Skip to content

Instantly share code, notes, and snippets.

View kevakba's full-sized avatar
🎯
Focusing

Kevin Akbari kevakba

🎯
Focusing
View GitHub Profile
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
import matplotlib.pyplot as plt
from tensorflow.keras import layers
import matplotlib.image as mpimg
import pathlib
dataset_path = "C:/Users/ADMIN/Desktop/Project/1"
data_dir = pathlib.Path(dataset_path)
train_dir = os.path.join(data_dir, 'train')
val_dir = os.path.join(data_dir, 'val')
batch_size=30
img_height=200
img_width=200
image_gen_train = ImageDataGenerator(
rescale=1./255,
rotation_range=45,
width_shift_range=.15,
height_shift_range=.15,
horizontal_flip=True,
zoom_range=0.5
)
image_gen_val = ImageDataGenerator(rescale=1./255)
val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,
directory=val_dir,
target_size=(img_width,img_height), color_mode='grayscale',
class_mode='sparse')
model = tf.keras.Sequential()
model.add(Conv2D(16, 3, padding='same', activation='relu', input_shape=(img_width,img_height, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, 3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, 3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
epochs = 20
history = model.fit_generator(
train_data_gen,
steps_per_epoch=int(np.ceil(train_data_gen.n / float(batch_size))),
epochs=epochs,
validation_data=val_data_gen,
validation_steps=int(np.ceil(val_data_gen.n / float(batch_size)))
)
Epoch 1/20
48/48 [==============================] - 15s 320ms/step - loss: 1.9151 - accuracy: 0.2396 - val_loss: 1.6345 - val_accuracy: 0.3139
Epoch 2/20
48/48 [==============================] - 15s 314ms/step - loss: 1.4954 - accuracy: 0.3917 - val_loss: 1.3522 - val_accuracy: 0.4722
Epoch 3/20
48/48 [==============================] - 16s 330ms/step - loss: 1.1761 - accuracy: 0.5528 - val_loss: 1.1349 - val_accuracy: 0.5389
Epoch 4/20
48/48 [==============================] - 16s 339ms/step - loss: 0.8542 - accuracy: 0.6958 - val_loss: 0.6563 - val_accuracy: 0.7194
Epoch 5/20
48/48 [==============================] - 16s 340ms/step - loss: 0.6892 - accuracy: 0.7417 - val_loss: 0.7053 - val_accuracy: 0.7472
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')