c++ commited on
Commit
20792d5
·
verified ·
1 Parent(s): 73618f7

Upload 5 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ best_weights.hdf5 filter=lfs diff=lfs merge=lfs -text
37
+ RPS_Model.hdf5 filter=lfs diff=lfs merge=lfs -text
RPS_Model.hdf5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14728323d0ac51a38b137351c5bd10f5135a23229ba6a913fbdac332f0a09e92
3
+ size 165984992
RPS_Part2_VGG16.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from keras_preprocessing import image
6
+ from matplotlib import pyplot as plt
7
+
8
+ # Part 2
9
+ # a) The tested image is to be supplied via the arguments list
10
+ # b) visualisation of the supplied image with the prediction score and predicted label
11
+
12
+ # Loading the pre-trained model/best saved weight and perform Prediction
13
+ # model = tf.keras.models.load_model('../Rock_Paper_Scissors_VGG16/RPS_Model.hdf5')
14
+ model = tf.keras.models.load_model('../Rock_Paper_Scissors_VGG16/best_weights.hdf5')
15
+ img_width, img_height = 224, 224
16
+
17
+
18
+ # Predict function
19
+ def predict_image(image_input, model):
20
+ if image_input is None or image_input == '':
21
+ print("Invalid type")
22
+ return None
23
+ # putting the images in an array
24
+ img_array = image.img_to_array(image_input)
25
+ processed_img = tf.reshape(img_array, shape=[1, img_width, img_height, 3])
26
+
27
+ # It uses the model to predict the class probabilities for the processed image.
28
+ predict_proba = np.max(model.predict(processed_img)[0])
29
+ # It identifies the predicted class index and its corresponding label.
30
+ predict_class = np.argmax(model.predict(processed_img))
31
+
32
+ # Map predicted class index to label
33
+ class_labels = ['Paper', 'Rock', 'Scissors']
34
+ predict_label = class_labels[predict_class]
35
+
36
+ # It plots the input image with its predicted class label and displays the image without axis ticks.
37
+ plt.figure(figsize=(4, 4))
38
+ plt.imshow(img)
39
+ plt.axis('off')
40
+ plt.title(f'Predicted Class: {predict_label}')
41
+ plt.show()
42
+
43
+ # Print prediction result and probability
44
+ print("\nImage prediction result:", predict_label)
45
+ print("Probability:", round(predict_proba * 100, 2), "%")
46
+ print('\n')
47
+
48
+
49
+ # asking the user for their desired folder location
50
+ if __name__ == "__main__":
51
+ image_path = ''
52
+ if len(sys.argv) != 2:
53
+ image_path = input("Enter the path to the image file: ")
54
+ if input() == '':
55
+ image_path = '../rps/test'
56
+ # it collects 21 random images from the folder
57
+ for filename in os.listdir(image_path)[0:20]:
58
+ filepath = os.path.join(image_path, filename)
59
+ # it sends the images and loaded model to prediction function
60
+ img = image.load_img(filepath, target_size=(img_width, img_height))
61
+ predict_image(img, model)
RPS_Part3_VGG16.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import tensorflow as tf
6
+ from keras_preprocessing import image
7
+
8
+ # Part 3
9
+ # a) Read two images of hand signs provided as script arguments
10
+ # b) Predict the labels of the two images
11
+ # c) Output which image won the rock, paper, scissor game
12
+
13
+ # Loading the pre-trained model/best saved weight and perform Prediction
14
+ # vgg16_model = tf.keras.models.load_model('../Rock_Paper_Scissors_VGG16/RPS_Model.hdf5')
15
+ vgg16_model = tf.keras.models.load_model('../Rock_Paper_Scissors_VGG16/best_weights.hdf5')
16
+ img_width, img_height = 224, 224
17
+ # Define labels and Image addresses
18
+ class_labels = ['paper', 'rock', 'scissors']
19
+ folder_path = '../rps/test'
20
+
21
+
22
+ # Get a random Image from Folder
23
+ def selectRandomPicture(folder_path):
24
+ files = os.listdir(folder_path)
25
+ image_files = [file for file in files if file.lower().endswith(('.png', '.jpg', '.jpeg'))]
26
+ random_photo = random.choice(image_files)
27
+ return os.path.join(folder_path, random_photo)
28
+
29
+
30
+ # Function to load and preprocess images
31
+ def load_and_preprocess_image(image_path):
32
+ img = image.load_img(image_path, target_size=(img_width, img_height))
33
+ img_array = image.img_to_array(img)
34
+ img_array /= 255.0 # Normalize pixel values
35
+
36
+ return img_array
37
+
38
+
39
+ # A simple condition/rules to decide who’s the winner
40
+ def whos_winner(first_image, second_image):
41
+ winner = ''
42
+ if first_image == second_image:
43
+ winner = "Tie!!"
44
+
45
+ elif (first_image == 'rock' and second_image == 'scissors' or
46
+ first_image == 'scissors' and second_image == 'rock'):
47
+ winner = "Rock wins"
48
+
49
+ elif (first_image == 'rock' and second_image == 'paper' or
50
+ first_image == 'paper' and second_image == 'rock'):
51
+ winner = "Paper wins"
52
+
53
+ elif (first_image == 'paper' and second_image == 'scissors' or
54
+ first_image == 'scissors' and second_image == 'paper'):
55
+ winner = "Scissors wins"
56
+
57
+ return winner
58
+
59
+
60
+ # Read and preprocess the images and put 2 images in separate variables
61
+ image1 = load_and_preprocess_image(selectRandomPicture(folder_path))
62
+ image2 = load_and_preprocess_image(selectRandomPicture(folder_path))
63
+
64
+ # Predict the labels of the images
65
+ images = np.array([image1, image2])
66
+ predictions = vgg16_model.predict(images)
67
+ predicted_classes = np.argmax(predictions, axis=1)
68
+
69
+ firs_img = class_labels[predicted_classes[0]]
70
+ sec_img = class_labels[predicted_classes[1]]
71
+
72
+ # Plot the images
73
+ plt.figure(figsize=(8, 5))
74
+ plt.subplot(1, 2, 1)
75
+ plt.imshow(image1)
76
+ plt.title(class_labels[predicted_classes[0]])
77
+ plt.axis('off')
78
+ # Plot/Display the last result
79
+ plt.subplot(1, 2, 2)
80
+ plt.imshow(image2)
81
+ plt.title(class_labels[predicted_classes[1]])
82
+ plt.axis('off')
83
+ plt.tight_layout()
84
+ plt.suptitle(f'{whos_winner(firs_img, sec_img)}!')
85
+ plt.show()
86
+
87
+ print(f'The winner is:{whos_winner(firs_img, sec_img)}')
Rock_Paper_Scissors_VGG16.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from keras import applications, Sequential
4
+ from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
5
+ from keras.layers import Dense, Dropout, Flatten, BatchNormalization
6
+ from keras.optimizers import Adam, SGD
7
+ from keras.preprocessing.image import ImageDataGenerator
8
+ from keras.regularizers import l2
9
+ from matplotlib import pyplot as plt
10
+ from sklearn.metrics import classification_report, confusion_matrix
11
+
12
+ # Part 1
13
+ # a) visualized samples from the dataset, i.e.: rock, paper, scissors hand signs
14
+ # with the appropriate labels
15
+ # b) summary of the model architecture in a form of a plot or text
16
+ # c) model accuracy evaluation plot after the training concludes
17
+ # d) model loss evaluation plot after the training concludes
18
+
19
+
20
+ # Image directory's and defining the dimensions & Batch size as well as epochs
21
+ base_dir = '../rps'
22
+ train_dir = os.path.join(base_dir, 'train')
23
+ valid_dir = os.path.join(base_dir, 'validation')
24
+ BATCH_SIZE = 32
25
+ EPOCHS = 7
26
+ img_width, img_height = 224, 224
27
+ # Define L2 regularization coefficient to prevent overfitting
28
+ l2_reg = 0.00001
29
+
30
+ # Optimization + Learning rate variables
31
+ opt = Adam(learning_rate=1e-4)
32
+ opt1 = Adam(learning_rate=2e-4)
33
+ opt2 = Adam(learning_rate=0.0001)
34
+ opt3 = SGD(learning_rate=1e-4, momentum=0.99)
35
+
36
+ # Preparing the Train/Validation and Augmentation Data
37
+ train_datagen = ImageDataGenerator(
38
+ rescale=1.0 / 255,
39
+ rotation_range=90,
40
+ zoom_range=0.1,
41
+ width_shift_range=0.2,
42
+ height_shift_range=0.2,
43
+ shear_range=0.2,
44
+ # horizontal_flip=True,
45
+ vertical_flip=True,
46
+ brightness_range=(0.2, 1),
47
+ fill_mode='nearest',
48
+ validation_split=0.2)
49
+
50
+ train_generator = train_datagen.flow_from_directory(
51
+ train_dir,
52
+ shuffle=True,
53
+ target_size=(img_width, img_height),
54
+ batch_size=BATCH_SIZE,
55
+ class_mode='categorical',
56
+ subset='training')
57
+
58
+ # a) Visualize samples from the dataset
59
+ class_names = ['paper', 'rock', 'scissors']
60
+ images, labels = train_generator.next()
61
+ plt.figure(figsize=(10, 10))
62
+ for i in range(9):
63
+ plt.subplot(3, 3, i + 1)
64
+ label_index = np.argmax(labels[i])
65
+ plt.title('Label: ' + class_names[label_index])
66
+ plt.imshow(images[i])
67
+ plt.tight_layout()
68
+ plt.axis('off')
69
+ plt.show()
70
+
71
+ validation_datagen = ImageDataGenerator(rescale=1.0 / 255)
72
+ validation_generator = validation_datagen.flow_from_directory(
73
+ valid_dir,
74
+ target_size=(img_width, img_height),
75
+ batch_size=BATCH_SIZE,
76
+ class_mode='categorical')
77
+
78
+ # -------Callbacks-------------#
79
+ # It'll save the best trained weight
80
+ checkpoint = ModelCheckpoint(
81
+ filepath='best_weights.hdf5',
82
+ monitor='val_loss',
83
+ verbose=1,
84
+ save_best_only=True,
85
+ mode='min',
86
+ save_weights_only=False
87
+ )
88
+ # Early stop = in case of high Validation Loss
89
+ early_stop = EarlyStopping(
90
+ monitor='val_loss',
91
+ min_delta=0.001,
92
+ patience=5,
93
+ verbose=1,
94
+ mode='auto'
95
+ )
96
+ # Defining a learning rate reduction callback when its necessary it'll reduce
97
+ # the learning rate when its necessary
98
+ lr_reduction = ReduceLROnPlateau(
99
+ monitor='val_loss',
100
+ factor=0.2,
101
+ patience=2,
102
+ verbose=1,
103
+ mode='auto',
104
+ cooldown=1,
105
+ min_lr=0.000001
106
+ )
107
+ callbacks = [checkpoint, early_stop, lr_reduction]
108
+
109
+ # Load the pre-trained VGG16 model without the top layer
110
+ base_model = applications.VGG16(weights='imagenet', include_top=False, pooling='max',
111
+ input_shape=(img_width, img_height, 3))
112
+
113
+ # Freeze the pre-trained layers from 0-14,
114
+ # so they are not updated during training
115
+ for layer in base_model.layers[:10]:
116
+ layer.trainable = False
117
+ # b) summary of base model
118
+ base_model.summary()
119
+
120
+ # Adding custom layers on top of VGG16
121
+ model = Sequential()
122
+ model.add(base_model)
123
+ model.add(Flatten())
124
+ model.add(Dense(512, activation='relu', kernel_regularizer=l2(l2_reg)))
125
+ model.add(BatchNormalization())
126
+ model.add(Dropout(0.3))
127
+ model.add(Dense(3, activation='softmax', kernel_regularizer=l2(l2_reg)))
128
+ # b) summary of model
129
+ model.summary()
130
+
131
+ # Compile the model
132
+ model.compile(optimizer=opt,
133
+ loss='categorical_crossentropy',
134
+ metrics=['accuracy'])
135
+
136
+ # Finally we train the model with our desired adjustments
137
+ history = model.fit(
138
+ train_generator,
139
+ epochs=EPOCHS,
140
+ callbacks=callbacks,
141
+ validation_data=validation_generator)
142
+
143
+
144
+ # Plotting the Models 'accuracy' & 'loss'
145
+ def eval_plot(history):
146
+ plt.figure(figsize=(14, 5))
147
+
148
+ # Accuracy plot
149
+ plt.subplot(1, 2, 1)
150
+ acc = history.history['accuracy']
151
+ val_acc = history.history['val_accuracy']
152
+ epochs = range(len(acc))
153
+ acc_plot, = plt.plot(epochs, acc, 'r')
154
+ val_acc_plot, = plt.plot(epochs, val_acc, 'b')
155
+ plt.title('Training and Validation Accuracy')
156
+ plt.legend([acc_plot, val_acc_plot], ['Training Accuracy', 'Validation Accuracy'])
157
+
158
+ # Loss plot
159
+ plt.subplot(1, 2, 2)
160
+ loss = history.history['loss']
161
+ val_loss = history.history['val_loss']
162
+ epochs = range(len(loss))
163
+ loss_plot, = plt.plot(epochs, loss, 'r')
164
+ val_loss_plot, = plt.plot(epochs, val_loss, 'b')
165
+ plt.title('Training and Validation Loss')
166
+ plt.legend([loss_plot, val_loss_plot], ['Training Loss', 'Validation Loss'])
167
+ plt.tight_layout()
168
+ plt.show()
169
+
170
+
171
+ # Evaluate the Process to find out how well the model has been trained
172
+ def evaluate(model):
173
+ num_of_test_samples = len(validation_generator.filenames)
174
+
175
+ y_pred = model.predict(validation_generator, num_of_test_samples // BATCH_SIZE + 1)
176
+ y_pred = np.argmax(y_pred, axis=1)
177
+ print('\nConfusion Matrix\n')
178
+ print(confusion_matrix(validation_generator.classes, y_pred))
179
+ print('\n\nClassification Report\n')
180
+ target_names = ['Paper', 'Rock', 'Scissors']
181
+ print(classification_report(validation_generator.classes, y_pred, target_names=target_names))
182
+
183
+
184
+ eval_plot(history)
185
+ evaluate(model)
186
+ model.save('../Rock_Paper_Scissors_VGG16/RPS_Model.hdf5')
best_weights.hdf5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf61b1d4dad01b6cc0ed83fc6b4aa8167540e9fadcdafda8a765eb56bda7ca85
3
+ size 165984992