-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcatvsdog.py
61 lines (55 loc) · 2.49 KB
/
catvsdog.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
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential, load_model
from keras.layers import Conv2D, Flatten, Dense, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from tensorflow.keras import optimizers
import os
train_dir = 'C:/Users/Lenovo/OneDrive/Desktop/model/dogvscat/train'
test_dir = 'C:/Users/Lenovo/OneDrive/Desktop/model/dogvscat/test'
model_path = 'model/catvsdog.h5'
if os.path.exists(model_path):
model = load_model(model_path)
print("Model loaded successfully.")
else:
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(224, 224), batch_size=20, class_mode='binary')
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(224, 224), batch_size=20, class_mode='binary')
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
MaxPooling2D(2, 2),
Conv2D(64, (3, 3), activation='relu'), MaxPooling2D(2, 2),
Conv2D(128, (3, 3), activation='relu'), MaxPooling2D(2, 2),
Conv2D(128, (3, 3), activation='relu'), MaxPooling2D(2, 2),
Flatten(), Dense(512, activation='relu'), Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(learning_rate=1e-3), metrics=['accuracy'])
model.fit(train_generator, steps_per_epoch=train_generator.samples // 20, epochs=10,
validation_data=test_generator, validation_steps=test_generator.samples // 20)
model.save(model_path)
def predict_image(img_path):
img = load_img(img_path, target_size=(224, 224))
img_array = img_to_array(img).reshape(1, 224, 224, 3) / 255.0
prediction = model.predict(img_array)
plt.imshow(img)
plt.axis('off')
plt.show()
print("Prediction:", "cat" if prediction < 0.5 else "dog")
while True:
img_path = input("Enter the path to an image (or type 'exit' to quit): ")
if img_path.lower() == 'exit':
print("Exiting the program.")
break
elif os.path.exists(img_path):
predict_image(img_path)
else:
print("Invalid path. Please try again.")