|
a |
|
b/xception.ipynb |
|
|
1 |
{ |
|
|
2 |
"cells": [ |
|
|
3 |
{ |
|
|
4 |
"cell_type": "code", |
|
|
5 |
"execution_count": 5, |
|
|
6 |
"id": "6b8fc951", |
|
|
7 |
"metadata": {}, |
|
|
8 |
"outputs": [ |
|
|
9 |
{ |
|
|
10 |
"name": "stdout", |
|
|
11 |
"output_type": "stream", |
|
|
12 |
"text": [ |
|
|
13 |
"Found 980 images belonging to 2 classes.\n", |
|
|
14 |
"Found 140 images belonging to 2 classes.\n", |
|
|
15 |
"Found 280 images belonging to 2 classes.\n" |
|
|
16 |
] |
|
|
17 |
}, |
|
|
18 |
{ |
|
|
19 |
"name": "stderr", |
|
|
20 |
"output_type": "stream", |
|
|
21 |
"text": [ |
|
|
22 |
"C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_33056\\3483214989.py:72: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n", |
|
|
23 |
" xception_history = xception_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])\n" |
|
|
24 |
] |
|
|
25 |
}, |
|
|
26 |
{ |
|
|
27 |
"name": "stdout", |
|
|
28 |
"output_type": "stream", |
|
|
29 |
"text": [ |
|
|
30 |
"Epoch 1/5\n", |
|
|
31 |
"30/30 [==============================] - 186s 6s/step - loss: 0.1842 - accuracy: 0.9462 - val_loss: 0.1311 - val_accuracy: 0.9219\n", |
|
|
32 |
"Epoch 2/5\n", |
|
|
33 |
"30/30 [==============================] - 193s 6s/step - loss: 0.0225 - accuracy: 0.9926 - val_loss: 0.1422 - val_accuracy: 0.9297\n", |
|
|
34 |
"Epoch 3/5\n", |
|
|
35 |
"30/30 [==============================] - 190s 6s/step - loss: 0.0069 - accuracy: 0.9989 - val_loss: 0.0426 - val_accuracy: 0.9922\n", |
|
|
36 |
"Epoch 4/5\n", |
|
|
37 |
"30/30 [==============================] - 192s 6s/step - loss: 0.0070 - accuracy: 0.9979 - val_loss: 0.0151 - val_accuracy: 0.9922\n", |
|
|
38 |
"Epoch 5/5\n", |
|
|
39 |
"30/30 [==============================] - 192s 6s/step - loss: 0.0016 - accuracy: 1.0000 - val_loss: 0.0074 - val_accuracy: 0.9922\n" |
|
|
40 |
] |
|
|
41 |
}, |
|
|
42 |
{ |
|
|
43 |
"name": "stderr", |
|
|
44 |
"output_type": "stream", |
|
|
45 |
"text": [ |
|
|
46 |
"C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_33056\\3483214989.py:74: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n", |
|
|
47 |
" xception_scores = xception_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n" |
|
|
48 |
] |
|
|
49 |
}, |
|
|
50 |
{ |
|
|
51 |
"name": "stdout", |
|
|
52 |
"output_type": "stream", |
|
|
53 |
"text": [ |
|
|
54 |
"Xception Test Loss: 0.012623521499335766\n", |
|
|
55 |
"Xception Test Accuracy: 0.9921875\n" |
|
|
56 |
] |
|
|
57 |
}, |
|
|
58 |
{ |
|
|
59 |
"name": "stderr", |
|
|
60 |
"output_type": "stream", |
|
|
61 |
"text": [ |
|
|
62 |
"C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_33056\\3483214989.py:85: UserWarning: `Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.\n", |
|
|
63 |
" xception_predictions = xception_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n" |
|
|
64 |
] |
|
|
65 |
}, |
|
|
66 |
{ |
|
|
67 |
"name": "stdout", |
|
|
68 |
"output_type": "stream", |
|
|
69 |
"text": [ |
|
|
70 |
"9/9 [==============================] - 11s 1s/step\n", |
|
|
71 |
"Xception Classification Report:\n", |
|
|
72 |
" precision recall f1-score support\n", |
|
|
73 |
"\n", |
|
|
74 |
" 0 0.99 1.00 0.99 140\n", |
|
|
75 |
" 1 1.00 0.99 0.99 140\n", |
|
|
76 |
"\n", |
|
|
77 |
" accuracy 0.99 280\n", |
|
|
78 |
" macro avg 0.99 0.99 0.99 280\n", |
|
|
79 |
"weighted avg 0.99 0.99 0.99 280\n", |
|
|
80 |
"\n" |
|
|
81 |
] |
|
|
82 |
} |
|
|
83 |
], |
|
|
84 |
"source": [ |
|
|
85 |
"# Importing necessary libraries\n", |
|
|
86 |
"import os\n", |
|
|
87 |
"import random\n", |
|
|
88 |
"import shutil\n", |
|
|
89 |
"import numpy as np\n", |
|
|
90 |
"import matplotlib.pyplot as plt\n", |
|
|
91 |
"from keras.preprocessing.image import ImageDataGenerator\n", |
|
|
92 |
"from keras.applications import VGG16, VGG19, ResNet50, InceptionV3, Xception\n", |
|
|
93 |
"from keras.models import Model\n", |
|
|
94 |
"from keras.layers import Dense, GlobalAveragePooling2D\n", |
|
|
95 |
"from keras.optimizers import Adam\n", |
|
|
96 |
"from keras.callbacks import ModelCheckpoint\n", |
|
|
97 |
"from sklearn.metrics import classification_report, confusion_matrix\n", |
|
|
98 |
"\n", |
|
|
99 |
"# Setting random seed for reproducibility\n", |
|
|
100 |
"np.random.seed(42)\n", |
|
|
101 |
"random.seed(42)\n", |
|
|
102 |
"\n", |
|
|
103 |
"# Define constants\n", |
|
|
104 |
"NUM_CLASSES = 2\n", |
|
|
105 |
"IMG_SIZE = (224, 224)\n", |
|
|
106 |
"BATCH_SIZE = 32\n", |
|
|
107 |
"TRAIN_DIR = 'train'\n", |
|
|
108 |
"VAL_DIR = 'val'\n", |
|
|
109 |
"TEST_DIR = 'test'\n", |
|
|
110 |
"TRAIN_SPLIT = 0.7\n", |
|
|
111 |
"VAL_SPLIT = 0.1\n", |
|
|
112 |
"TEST_SPLIT = 0.2\n", |
|
|
113 |
"test_samples = 280\n", |
|
|
114 |
"\n", |
|
|
115 |
"# Define the base directory where the image data is located\n", |
|
|
116 |
"BASE_DIR = r\"C:\\Users\\mohit\\Downloads\\DIP Assignment 2\\Data\"\n", |
|
|
117 |
"\n", |
|
|
118 |
"# Set the paths for training, validation, and test data\n", |
|
|
119 |
"TRAIN_DIR = os.path.join(BASE_DIR, 'train')\n", |
|
|
120 |
"VAL_DIR = os.path.join(BASE_DIR, 'val')\n", |
|
|
121 |
"TEST_DIR = os.path.join(BASE_DIR, 'test')\n", |
|
|
122 |
"\n", |
|
|
123 |
"# Load and preprocess the data\n", |
|
|
124 |
"train_datagen = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\n", |
|
|
125 |
"val_datagen = ImageDataGenerator(rescale=1./255)\n", |
|
|
126 |
"test_datagen = ImageDataGenerator(rescale=1./255)\n", |
|
|
127 |
"\n", |
|
|
128 |
"train_generator = train_datagen.flow_from_directory(TRAIN_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical')\n", |
|
|
129 |
"\n", |
|
|
130 |
"val_generator = val_datagen.flow_from_directory(VAL_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical')\n", |
|
|
131 |
"\n", |
|
|
132 |
"test_generator = test_datagen.flow_from_directory(TEST_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical',shuffle=False)\n", |
|
|
133 |
"\n", |
|
|
134 |
"# Define function for creating transfer learning models\n", |
|
|
135 |
"def create_transfer_model(base_model, num_classes):\n", |
|
|
136 |
" x = base_model.output\n", |
|
|
137 |
" x = GlobalAveragePooling2D()(x)\n", |
|
|
138 |
" x = Dense(1024, activation='relu')(x)\n", |
|
|
139 |
" predictions = Dense(num_classes, activation='softmax')(x)\n", |
|
|
140 |
" model = Model(inputs=base_model.input, outputs=predictions)\n", |
|
|
141 |
" return model\n", |
|
|
142 |
"\n", |
|
|
143 |
"# Define Xception model\n", |
|
|
144 |
"xception_base = Xception(include_top=False, weights='imagenet', input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))\n", |
|
|
145 |
"xception_model = create_transfer_model(xception_base, NUM_CLASSES)\n", |
|
|
146 |
"\n", |
|
|
147 |
"# Compile the models\n", |
|
|
148 |
"optimizer = Adam(learning_rate=0.0001)\n", |
|
|
149 |
"xception_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n", |
|
|
150 |
"\n", |
|
|
151 |
"# Define checkpoint callback to save the best model during training\n", |
|
|
152 |
"checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)\n", |
|
|
153 |
"\n", |
|
|
154 |
"xception_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n", |
|
|
155 |
"\n", |
|
|
156 |
"xception_history = xception_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])\n", |
|
|
157 |
"\n", |
|
|
158 |
"xception_scores = xception_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n", |
|
|
159 |
"print(\"Xception Test Loss:\", xception_scores[0])\n", |
|
|
160 |
"print(\"Xception Test Accuracy:\", xception_scores[1])\n", |
|
|
161 |
"\n", |
|
|
162 |
"# Get the number of test samples\n", |
|
|
163 |
"num_test_samples = test_generator.n\n", |
|
|
164 |
"\n", |
|
|
165 |
"# Calculate the number of steps for prediction\n", |
|
|
166 |
"num_prediction_steps = num_test_samples // test_generator.batch_size + 1\n", |
|
|
167 |
"\n", |
|
|
168 |
"# Generate predictions for all test samples\n", |
|
|
169 |
"xception_predictions = xception_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n", |
|
|
170 |
"\n", |
|
|
171 |
"# Convert predictions to class labels\n", |
|
|
172 |
"xception_predicted_labels = np.argmax(xception_predictions, axis=1)\n", |
|
|
173 |
"\n", |
|
|
174 |
"# Get true class labels\n", |
|
|
175 |
"true_labels = test_generator.classes\n", |
|
|
176 |
"\n", |
|
|
177 |
"# Calculate classification report\n", |
|
|
178 |
"xception_report = classification_report(true_labels, xception_predicted_labels)\n", |
|
|
179 |
"\n", |
|
|
180 |
"print(\"Xception Classification Report:\")\n", |
|
|
181 |
"print(xception_report)" |
|
|
182 |
] |
|
|
183 |
}, |
|
|
184 |
{ |
|
|
185 |
"cell_type": "code", |
|
|
186 |
"execution_count": 2, |
|
|
187 |
"id": "17422ece", |
|
|
188 |
"metadata": {}, |
|
|
189 |
"outputs": [ |
|
|
190 |
{ |
|
|
191 |
"ename": "NameError", |
|
|
192 |
"evalue": "name 'xception_model' is not defined", |
|
|
193 |
"output_type": "error", |
|
|
194 |
"traceback": [ |
|
|
195 |
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", |
|
|
196 |
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", |
|
|
197 |
"\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_10180\\1533048863.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mxception_history\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mxception_model\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtrain_generator\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0msteps_per_epoch\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mtrain_generator\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mn\u001b[0m \u001b[1;33m//\u001b[0m \u001b[0mtrain_generator\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mbatch_size\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mepochs\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;31m# Plot the training loss curve\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", |
|
|
198 |
"\u001b[1;31mNameError\u001b[0m: name 'xception_model' is not defined" |
|
|
199 |
] |
|
|
200 |
} |
|
|
201 |
], |
|
|
202 |
"source": [ |
|
|
203 |
"import matplotlib.pyplot as plt\n", |
|
|
204 |
"\n", |
|
|
205 |
"xception_history = xception_model.fit(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=3)\n", |
|
|
206 |
"\n", |
|
|
207 |
"# Plot the training loss curve\n", |
|
|
208 |
"plt.plot(xception_history.history['loss'])\n", |
|
|
209 |
"plt.title('xception Training Loss')\n", |
|
|
210 |
"plt.xlabel('Epoch')\n", |
|
|
211 |
"plt.ylabel('Loss')\n", |
|
|
212 |
"plt.show()" |
|
|
213 |
] |
|
|
214 |
}, |
|
|
215 |
{ |
|
|
216 |
"cell_type": "code", |
|
|
217 |
"execution_count": null, |
|
|
218 |
"id": "6641997c", |
|
|
219 |
"metadata": {}, |
|
|
220 |
"outputs": [], |
|
|
221 |
"source": [ |
|
|
222 |
"plt.plot(xception_history.history['accuracy'])\n", |
|
|
223 |
"plt.title('xception Training Accuracy')\n", |
|
|
224 |
"plt.xlabel('Epoch')\n", |
|
|
225 |
"plt.ylabel('Accuracy')\n", |
|
|
226 |
"plt.show()" |
|
|
227 |
] |
|
|
228 |
}, |
|
|
229 |
{ |
|
|
230 |
"cell_type": "code", |
|
|
231 |
"execution_count": null, |
|
|
232 |
"id": "e503a76d", |
|
|
233 |
"metadata": {}, |
|
|
234 |
"outputs": [], |
|
|
235 |
"source": [] |
|
|
236 |
} |
|
|
237 |
], |
|
|
238 |
"metadata": { |
|
|
239 |
"kernelspec": { |
|
|
240 |
"display_name": "Python 3 (ipykernel)", |
|
|
241 |
"language": "python", |
|
|
242 |
"name": "python3" |
|
|
243 |
}, |
|
|
244 |
"language_info": { |
|
|
245 |
"codemirror_mode": { |
|
|
246 |
"name": "ipython", |
|
|
247 |
"version": 3 |
|
|
248 |
}, |
|
|
249 |
"file_extension": ".py", |
|
|
250 |
"mimetype": "text/x-python", |
|
|
251 |
"name": "python", |
|
|
252 |
"nbconvert_exporter": "python", |
|
|
253 |
"pygments_lexer": "ipython3", |
|
|
254 |
"version": "3.9.16" |
|
|
255 |
} |
|
|
256 |
}, |
|
|
257 |
"nbformat": 4, |
|
|
258 |
"nbformat_minor": 5 |
|
|
259 |
} |