-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrocs_vs_snakes.py
83 lines (71 loc) · 3.19 KB
/
crocs_vs_snakes.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
import numpy as np
import matplotlib.pyplot as plt
import warnings
from keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
import tensorflow
seed = 1842
tensorflow.random.set_seed(seed)
np.random.seed(seed)
warnings.simplefilter('ignore')
image_data = ImageDataGenerator(rescale=1 / 255, validation_split=0.2)
train_dataset = image_data.flow_from_directory(batch_size=40,
directory='Train',
shuffle=True,
target_size=(300, 300),
subset="training",
class_mode='categorical')
validation_dataset = image_data.flow_from_directory(batch_size=40,
directory='Train',
shuffle=True,
target_size=(300, 300),
subset="validation",
class_mode='categorical')
image_test_data = ImageDataGenerator(rescale=1 / 255)
test_dataset = image_test_data.flow_from_directory(
directory='Test',
shuffle=False,
target_size=(300, 300),
class_mode=None)
model = keras.models.Sequential([
keras.layers.Conv2D(32, 3, activation='relu', input_shape=[300, 300, 3]),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(32, 3, activation='relu'),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(64, 3, activation='relu'),
keras.layers.MaxPooling2D(),
keras.layers.Dropout(0.3),
keras.layers.Flatten(),
keras.layers.Dense(1024, activation='relu'),
keras.layers.Dense(2, activation='softmax')])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
callback = keras.callbacks.EarlyStopping(monitor='val_loss',
patience=3,
restore_best_weights=True)
history = model.fit(train_dataset, epochs=20, validation_data=train_dataset, callbacks=callback)
loss, accuracy = model.evaluate(train_dataset)
print("Loss:", loss)
print("Accuracy:", accuracy)
prediction = model.predict(test_dataset, callbacks=callback)
predictions = []
for i in range(len(prediction)):
a = ("%.6f" % float(prediction[i][0]))
b = ("%.6f" % float(prediction[i][1]))
a = round(float(a)*100, 2)
b = round(float(b)*100, 2)
c = [a, b]
predictions.append(c)
print(predictions)
for i in range(len(prediction)):
photo = test_dataset
img = photo[0][i]
if predictions[i][0] < predictions[i][1]:
answer = 'На изображении Змея, точность:'
predict = predictions[i][1]
else:
answer = 'На изображении Крокодил, точность:'
predict = predictions[i][0]
plt.figure()
plt.imshow(img)
plt.title(f'{answer} {predict}%')
plt.show()