我一直在关注 YouTube 教程,让神经网络预测猫与狗的图像。本教程结束时没有展示如何对任何图像进行预测,我在尝试解决它时遇到了麻烦。 这是网络代码:
import numpy as np
import cv2
import os
import random
import matplotlib.pyplot as plt
import pickle
DIRECTORY = r'/content/drive/MyDrive/neural'
CATEGORIES = ['cats', 'dogs']
IMG_SIZE = 100
data = []
for category in CATEGORIES:
folder = os.path.join(DIRECTORY, category)
label = CATEGORIES.index(category)
for img in os.listdir(folder):
img_path = os.path.join(folder, img)
img_arr = cv2.imread(img_path)
img_arr = cv2.resize(img_arr, (IMG_SIZE, IMG_SIZE))
data.append([img_arr, label])
random.shuffle(data)
X = []
y=[]
for features, labels in data:
X.append(features)
y.append(labels)
X = np.array(X)
y = np.array(y)
X = X/255
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
model = Sequential()
model.add(Conv2D(64, (3,3), activation = 'relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3,3), activation = 'relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(128, input_shape = X.shape[1:], activation = 'relu'))
model.add(Dense(2, activation = 'softmax'))
model.compile(optimizer = 'adam', loss='sparse_categorical_crossentropy', metrics = ['accuracy'])
model.fit(X, y, epochs = 10, validation_split = 0.1)
以下是训练结果: 纪元 10/10 647/647 [==============================] - 58s 90ms/步 - 损失:0.0262 - 准确度:0.9917 - val_loss :1.4013 - val_accuracy:0.7630
现在这是我尝试用模型进行预测。
import numpy as np
import cv2
import keras
CATEGORIES = ['Cat', 'Dog']
def image(path):
img = cv2.imread(path)
new_arr = cv2.resize(img, (100, 100))
new_arr = np.array(new_arr)
new_arr = new_arr.reshape(-1, 100, 100, 3)
new_arr = new_arr/255
return new_arr
prediction = model.predict([image('/content/drive/MyDrive/neural/test/photo-1609779361684-8196b3a0abf1.jpg')])
print(CATEGORIES[prediction.argmax()])
我得到的结果是完全随机的。我认为问题在于调整我想要预测的图像的大小,但我尝试了不同的东西,我无法解决它。
当我尝试使用
TF 2.8
复制相同的代码时,这显示了正确的输出。
请检查: (模型训练 10 个 epoch 后)
Epoch 10/10
57/57 [==============================] - 1s 16ms/step - loss: 0.0551 - accuracy: 0.9822 - val_loss: 1.2132 - val_accuracy: 0.6900
<keras.callbacks.History at 0x7f2e6a61e290>
以及预测部分:
import numpy as np
import cv2
from tensorflow import keras
CATEGORIES = ['Cat', 'Dog']
def image(path):
img = cv2.imread(path)
new_arr = cv2.resize(img, (100, 100))
new_arr = np.array(new_arr)
new_arr = new_arr.reshape(-1, 100, 100, 3)
new_arr = new_arr/255
return new_arr
prediction = model.predict([image('/content/GoogleDrive/MyDrive/MY WORK/cats_and_dogs_filtered/validation/cats/cat.2000.jpg')])
print(CATEGORIES[prediction.argmax()])
或者可以使用:
img1=image('/content/GoogleDrive/MyDrive/MY WORK/cats_and_dogs_filtered/validation/cats/cat.2000.jpg')
prediction = model.predict(img1)
print(CATEGORIES[prediction.argmax()])
输出:
Cat
注意: 建议使用
tensorflow.keras
代替 keras
,如下所示:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
或者使用
from tensorflow import keras
导入keras
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense