跟着别人写了一个关于VGG16预测猫跟狗的代码
前面无论是训练集准确率还是测试集准确率都是100%,但是后面从网上随意下载猫或者狗的照片进行预测都是猫,目前甚至没找到出现狗的预测答案,就算是采用训练集或者测试集里狗的图片预测答案仍是猫,可以问问各位同学我的代码到底哪错了吗,非常谢谢,代码如下
from keras.api.preprocessing.image import load_img,img_to_array
from keras.api.applications.vgg16 import VGG16
from keras.api.applications.vgg16 import preprocess_input
import numpy as np
img_path='1.jpg'
img=load_img(img_path,target_size=(224,224))
img=img_to_array(img)
model_vgg=VGG16(weights='imagenet',include_top=False)
x=np.expand_dims(img,axis=0)
x=preprocess_input(x)
type(img)
features=model_vgg.predict(x)
features=features.reshape(1,7*7*512)
print(x.shape)
def modelProcess(img_path,model):
img=load_img(img_path,target_size=(224,224))
img=img_to_array(img)
x=np.expand_dims(img,axis=0)
x=preprocess_input(x)
x_vgg=model.predict(x)
x_vgg=x_vgg.reshape(1,25088)
return x_vgg
import os
folder="D:/乌龟的学习/kagglecatsanddogs_5340/PetImages/cat1"
dirs=os.listdir(folder)
img_path=[]
for i in dirs:
if os.path.splitext(i)[1] == '.jpg':
img_path.append(i)
img_path=[folder+'//'+i for i in img_path]
features1=np.zeros([len(img_path),25088])
for i in range(len(img_path)):
feature_i=modelProcess(img_path[i],model_vgg)
print('preprocessed:',img_path[i])
features1[i]=feature_i
folder="D:/乌龟的学习/kagglecatsanddogs_5340/PetImages/dog1"
dirs=os.listdir(folder)
img_path=[]
for i in dirs:
if os.path.splitext(i)[1] == '.jpg':
img_path.append(i)
img_path=[folder+'//'+i for i in img_path]
features2=np.zeros([len(img_path),25088])
for i in range(len(img_path)):
feature_i=modelProcess(img_path[i],model_vgg)
print('preprocessed:',img_path[i])
features2[i]=feature_i
print(features1.shape,features2.shape)
y1=np.zeros(300)
y2=np.zeros(300)
X=np.concatenate((features1,features2),axis=0)
y=np.concatenate((y1,y2),axis=0)
y=y.reshape(-1,1)
print(X.shape,y.shape)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=50)
print(X_train.shape,X_test.shape,X.shape)
from keras.models import Sequential
from keras.layers import Dense
model=Sequential()
model.add(Dense(units=10,activation='relu',input_dim=25088))
model.add(Dense(units=1,activation='sigmoid'))
model.summary()
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(X_train,y_train,epochs=100)
from sklearn.metrics import accuracy_score
prediction0=model.predict(X_train)
y_train_predict=np.argmax(prediction0,axis=1)
accuracy_train=accuracy_score(y_train,y_train_predict)
print(accuracy_train)
prediction2=model.predict(X_test)
y_test_predict=np.argmax(prediction2,axis=1)
accuracy_test=accuracy_score(y_test,y_test_predict)
print(accuracy_test)
img_path='dog1.jpg'
img=load_img(img_path,target_size=(224,224))
img=img_to_array(img)
x=np.expand_dims(img,axis=0)
x=preprocess_input(x)
features1=model_vgg.predict(x)
features1=features1.reshape(1,7*7*512)
prediction1=model.predict(features1)
print(prediction1)