-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageClassificationExample.py
102 lines (70 loc) · 2.44 KB
/
imageClassificationExample.py
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
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
print('Using TensorFlow version', tf.__version__)
# This is the dataset, load the data
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print('x_train shape:', x_train.shape)
print('y_train shape:', y_train.shape)
print('x_test shape:', x_test.shape)
print('y_test shape:', y_test.shape)
from matplotlib import pyplot as plt
# Show an example data object
plt.imshow(x_train[0], cmap='binary')
plt.show()
print(y_train[0])
print(set(y_train))
from tensorflow.keras.utils import to_categorical
# Modify the outputs to be a 10-dimensional vector (containing categories)
y_train_encoded = to_categorical(y_train)
y_test_encoded = to_categorical(y_test)
print('y_train_encoded shape:', y_train_encoded.shape)
print('y_test_encoded shape:', y_test_encoded.shape)
print(y_train_encoded[0])
import numpy as np
x_train_reshaped = np.reshape(x_train, (60000, 784))
x_test_reshaped = np.reshape(x_test, (10000, 784))
print('x_train_reshaped shape:', x_train_reshaped.shape)
print('x_test_reshaped shape:', x_test_reshaped.shape)
print(set(x_train_reshaped[0]))
x_mean = np.mean(x_train_reshaped)
x_std = np.std(x_train_reshaped)
epsilon = 1e-10
x_train_norm = (x_train_reshaped - x_mean) / (x_std + epsilon)
x_test_norm = (x_test_reshaped - x_mean) / (x_std + epsilon)
print(set(x_train_norm[0]))
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(128, activation='relu', input_shape=(784,)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(
optimizer='sgd',
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.summary()
model.fit(x_train_norm, y_train_encoded, epochs=3)
loss, accuracy = model.evaluate(x_test_norm, y_test_encoded)
print('Test set accuracy:', accuracy * 100)
preds = model.predict(x_test_norm)
print('Shape of preds:', preds.shape)
plt.figure(figsize=(12, 12))
start_index = 0
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.grid(False)
plt.xticks([])
plt.yticks([])
pred = np.argmax(preds[start_index + i])
gt = y_test[start_index + i]
col = 'g'
if pred != gt:
col = 'r'
plt.xlabel('i={}, pred={}, gt={}'.format(start_index + i, pred, gt), color=col)
plt.imshow(x_test[start_index + i], cmap='binary')
plt.show()
plt.plot(preds[8])
plt.show()