-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodel.py
More file actions
136 lines (87 loc) · 3.17 KB
/
Copy pathmodel.py
File metadata and controls
136 lines (87 loc) · 3.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# -*- coding: utf-8 -*-
"""Image Classification_Model .ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1B6wD5obNzREeLZuvzPvpph_2JCX5eHxx
# **Image Classification Model By Mirza Yasir Abdullah Baig**
## **Step No: 1 Importing Some Important Libraries**
"""
import tensorflow as tf
from tensorflow.keras import datasets, models, layers
import matplotlib.pyplot as plt
import numpy as np
"""## **Step No: 2 Training the Model**"""
(X_train, y_train), (X_test, y_test) = datasets.cifar10.load_data()
"""## **Step No: 3 Checking the Data Shape**"""
X_test.shape
X_train.shape
y_train.shape
y_train[:5]
"""## **Step No: 4 Converting the 2D Array in to 1D Array**"""
# ci==onvert 2 day array in 1d
y_train = y_train.reshape(-1,)
y_train[:5]
y_test = y_test.reshape(-1,)
classes = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
def plot_sample(X, y, index):
plt.figure(figsize=(15,2))
plt.imshow(X[index])
plt.xlabel(classes[y[index]])
"""## **Step No: 5 Plotting the Images**"""
plot_sample(X_train, y_train, 5)
plot_sample(X_train, y_train, 501)
X_train = X_train/255.0
X_test = X_test/255.0
"""## **Step No: 6 Training The Model**"""
ann = models.Sequential([
layers.Flatten(input_shape=(32,32,3)),
layers.Dense(3000, activation='relu'),
layers.Dense(1000, activation='relu'),
layers.Dense(10, activation='softmax')
])
ann.compile(optimizer='SGD',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
ann.fit(X_train, y_train, epochs=5)
"""## **Step No: 7 Classification Report**"""
from sklearn.metrics import confusion_matrix, classification_report
import numpy as np
# Predictions on test set
y_pred = ann.predict(X_test) # shape (10000, num_classes)
y_pred_classes = [np.argmax(element) for element in y_pred]
print('Classification report:\n', classification_report(y_test, y_pred_classes))
import seaborn as sn
plt.figure(figsize=(14,7))
sn.heatmap(y_pred, annot=True)
plt.xlabel('Predicted')
plt.ylabel('Truth')
plt.title('Confusion Matrix')
plt.show()
cnn = models.Sequential([
layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax') # 10 classes for CIFAR-10
])
cnn.compile(optimizer = 'adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
cnn.fit(X_train, y_train, epochs = 10)
cnn.evaluate(X_test, y_test)
y_pred = cnn.predict(X_test)
y_pred[:5]
"""## **Step No 8: Testing The Model**"""
y_classes = [np.argmax(element) for element in y_pred]
y_classes[:5]
y_test[:5]
plot_sample(X_test, y_test, 60)
plot_sample(X_test, y_test, 100)
classes[y_classes[100]]
"""# **Step No 9: Saving The Model**"""
cnn.save("cifar10_cnn_model.keras") # recommended format
from tensorflow.keras.models import load_model
loaded_cnn = load_model("cifar10_cnn_model.keras")
loaded_cnn.evaluate(X_test, y_test)