Skip to content

Instantly share code, notes, and snippets.

View Akash-Rawat's full-sized avatar

Akash Rawat Akash-Rawat

View GitHub Profile
@Akash-Rawat
Akash-Rawat / ModelSelection.py
Last active October 2, 2023 07:52
Selecting a Pre-trained Model
import torch
import torch.nn as nn
import torchvision.models as models
base_model = models.resnet18(pretrained=True)
num_Genders = len(image_datasets.classes)
num_ftrs = base_model.fc.in_features
base_model.fc = nn.Linear(num_ftrs, num_Genders)
@Akash-Rawat
Akash-Rawat / DataPrep.py
Last active October 2, 2023 07:46
Data Preparation
import torch
import torchvision
from torchvision import transforms
data_transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
results = neuralnetwork_cnn.evaluate(test_images, verbose=0)
print(" Test Loss: {:.5f}".format(results[0]))
print("Test Accuracy: {:.2f}%".format(results[1] * 100))
Test Loss: 0.06885
Test Accuracy: 99.53%
fig, ax = plt.subplots(figsize=(20, 6))
pd.DataFrame(history.history).iloc[:, :-1].plot(ax=ax)
history = neuralnetwork_cnn.fit_generator(
generator=train_images, validation_data=test_images,
callbacks=[es, ckpt, rlp], epochs = 50,
)
Epoch 00027: ReduceLROnPlateau reducing learning rate to 1.0000000656873453e-06.
261/261 [==============================] - 8s 30ms/step - loss: 0.0076 - acc: 0.9996 - val_loss: 0.0074 - val_acc: 0.9998
Epoch 28/50
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 64, 64, 4) 112
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 32, 32, 4) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 32, 32, 8) 136
_________________________________________________________________
def cnn(image_size, num_classes):
classifier = Sequential()
classifier.add(Conv2D(4, (3, 3), input_shape=image_size, activation='relu', padding='same'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(8, (2, 2), activation='relu', padding='same'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(num_classes, activation = 'softmax'))
classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
return classifier
train_generator = ImageDataGenerator(
preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input,
validation_split=0.2
)
test_generator = tf.keras.preprocessing.image.ImageDataGenerator(
preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input
)
train_images = train_generator.flow_from_dataframe(
dataframe=train_df,
fig, axes = plt.subplots(nrows=3, ncols=5, figsize=(15, 7),
subplot_kw={'xticks': [], 'yticks': []})
for i, ax in enumerate(axes.flat):
ax.imshow(plt.imread(train_df.Filepath[i]))
ax.set_title(train_df.Label[i]).set_color('white')
plt.tight_layout()
plt.show()
train="SPORT_1/train"
test="SPORT_1/test"
filepaths_train = list(glob.glob(train+'/**/*.jpg'))
filepaths_test = list(glob.glob(test+'/**/*.jpg'))
def proc_img(filepath):
""" Create a DataFrame with the filepath and the labels of the pictures
"""