Closed khyatibhuva closed 3 years ago
we are getting 88% accuracy on 93 classes on testing database
Also upload the relevant files of this version here.
from tensorflow.keras import *
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from keras.applications.mobilenet import MobileNet, preprocess_input
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
IMAGE_SIZE = [227, 227]
model =MobileNet(input_shape= [227,227, 3], weights='imagenet', include_top=False)
"""
for layer in vgg.layers[:16]:
layer.trainable = False
"""
for layer in model.layers[:-23]:
layer.trainable = False
folders = glob('/content/drive/MyDrive/Colab Notebooks/Project/Cars196/training/*')
"""
layer_dict = dict([(layer.name, layer) for layer in model.layers])
conv_output = model.get_layer("block5_conv1").output
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
kernel_regularizer=tf.keras.regularizers.l2(0.01),
name='block5_conv2')(conv_output)
x = layers.Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv3')(x)
x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
x = Flatten()(x)
prediction = Dense(len(folders), activation='softmax')(x)
model = Model(inputs=model.input, outputs=prediction)
"""
"""
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
x = global_average_layer(model)
x = tf.keras.layers.Dropout(0.2)(x)
"""
x = Flatten()(model.layers[-6].output)
prediction = Dense(len(folders), activation='softmax')(x)
model = Model(inputs = model.input, outputs = prediction)
model.summary()
adam=tf.keras.optimizers.Adam(
learning_rate=1e-5,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
decay = 0.0
)
model.compile(
loss='categorical_crossentropy',
optimizer="adam",
metrics=['accuracy']
)
#model.load_weights('/content/drive/MyDrive/Colab Notebooks/Project/sample/previews.data-00000-of-00001.hdf5')
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
#rescale = 1./255,
rotation_range = 0,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/Project/Cars196/training',
target_size = (227, 227),
batch_size = 256,
class_mode = 'categorical',
shuffle=True)
test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/Project/Cars196/testing',
target_size = (227, 227),
batch_size = 256,
class_mode = 'categorical',
shuffle=True)
checkpoint_filepath = '/content/drive/MyDrive/Colab Notebooks/Project/sample/./weights.{epoch:02d}.hdf5'
callback = [tf.keras.callbacks.EarlyStopping(monitor='loss', patience=4,mode = 'auto', restore_best_weights=False),
tf.keras.callbacks.CSVLogger('traininglog.csv', separator=",", append=False),
tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss",factor=0.1, patience=2, mode="auto",min_delta=0.0001,min_lr=0),
tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_filepath, save_weights_only=True,monitor='val_accuracy',mode='max',save_best_only=True),
]
r = model.fit(
training_set,
validation_data=test_set,
epochs=100,
steps_per_epoch=len(training_set),
validation_steps=len(test_set),
callbacks = [callback]
)
#Visualizing the results.
plt.plot(r.history['loss'], label='train loss')
plt.plot(r.history['val_loss'], label='val loss')
plt.legend()
plt.show()
plt.plot(r.history['accuracy'], label='train acc')
plt.plot(r.history['val_accuracy'], label='val acc')
plt.legend()
plt.show()
import tensorflow as tf
from keras.models import load_model
model.save('New_model.h5')
model.save('/content/drive/MyDrive/Colab Notebooks/Project/Cars196/New_model_95_classes.h5')
model.evaluate(test_set)`
This model is giving good accuracy and we are going to further improve it
Above model is giving 88.87% accuracy.
Noted.
Try to strike a balance between increasing number of cars and current accuracy.