<jupyter_start><jupyter_text>importing libraries<jupyter_code>import matplotlib.pyplot as plt
import numpy as np

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
tf.config.list_physical_devices('GPU')
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
print(tf.__version__)
!nvidia-smi
img_size = (300, 300)
batch_size = 32
directory = r'C:/Users/utkar/Desktop/ML/tensorflow/image classification/CovidDataset'

ds_train = tf.keras.preprocessing.image_dataset_from_directory(directory,
                                                              labels='inferred',
                                                              label_mode='int',
                                                              color_mode="grayscale",
                                                              batch_size=batch_size,
                                                              image_size=img_size,
                                                              shuffle=True,
                                                              seed=123,
                                                              validation_split=0.2,
                                                              subset="training",
                                                              )

ds_validation = tf.keras.preprocessing.image_dataset_from_directory(directory,
                                                              labels='inferred',
                                                              label_mode='int',
                                                              color_mode="grayscale",
                                                              batch_size=batch_size,
                                                              image_size=img_size,
                                                              shuffle=True,
                                                              seed=123,
                                                              validation_split=0.2,
                                                              subset="validation",
                                                              )
class_names = ds_train.class_names
print(class_names)
plt.figure(figsize=(10, 10))
a = 0
b1 = np.random.randint(0, 76)
for images, labels in ds_train.take(b1):
    for i in range(9):
        plt.subplot(3, 3, 1+i)
        #print(images[i].numpy())
        plt.imshow(images[i].numpy().astype("uint8"), cmap='gray')
        plt.title(class_names[labels[i]])
        plt.axis("off")
    break
            
plt.show()
for img_batch, labels_batch in ds_train:
    print(img_batch.shape)
    print(labels_batch.shape)
    break
num_classes = 2

model = Sequential([
    layers.experimental.preprocessing.Rescaling(1./255, input_shape=(300, 300, 1)),
    layers.Conv2D(16, 3, padding='same', activation=tf.nn.relu, strides=1),
    layers.MaxPool2D(pool_size=(2, 2)),
    layers.Dropout(0.4),
    layers.Conv2D(64, 3, padding='same', activation='relu', strides=2),
    #layers.MaxPool2D(pool_size=(2, 2)),
    layers.Dropout(0.4),
    #layers.Conv2D(256, 3, padding='same', activation='relu'),
    #layers.MaxPool2D(pool_size=(2, 2)),
    #layers.Dropout(0.4),
    layers.Conv2D(256, 3, padding='same', activation='relu', strides=2),
    layers.Dropout(0.4),
    layers.MaxPool2D(pool_size=(2, 2)),
    layers.Conv2D(512, 3, padding='same', activation='relu'),
    layers.MaxPool2D(pool_size=(2, 2)),
    layers.Dropout(0.4),
    layers.Flatten(),
    layers.Dense(32, activation='relu'),
    layers.Dropout(0.4),
    layers.Dense(256, activation='relu'),
    layers.Dropout(0.4),
    layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.summary()
epochs = 40
training = model.fit(
    ds_train,
    validation_data=ds_validation,
    epochs=epochs
)
#model = keras.models.load_model("nn.h5")
acc = training.history['accuracy']
val_acc = training.history['val_accuracy']

loss = training.history['loss']
val_loss = training.history['val_loss']

epochs_range = range(epochs)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
a = 0
b = 0
c = 0
for images, labels in ds_validation:
    c += 1
    for i in range(32):
        prediction = model.predict(images)
        score = tf.nn.softmax(prediction[i])
        if class_names[np.argmax(score)] == class_names[labels[i]]:
            #print(("yes"))
            a += 1
        else: b += 1
    if c == 15:
        break
print(a)
print(b)
print(100*(a/(a+b)))
        
path_to_model = r'C:/Users/utkar/Desktop/ML/tensorflow/image classification/ctscan.tf'
tf.keras.models.save_model(
    model,
    path_to_model,
    overwrite=True,
    include_optimizer=True,
    save_format=None,
    signatures=None,
    options=None,
    save_traces=True
)<jupyter_output>INFO:tensorflow:Assets written to: C:/Users/utkar/Desktop/ML/tensorflow/image classification/ctscan.tf\assets
StarcoderdataJupyterStructuredCleanDedup