乌龟杀猪了 2024-11-10 00:08 采纳率: 0%
浏览 1

pythonVGG16算法

跟着别人写了一个关于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)
  • 写回答

1条回答 默认 最新

  • 无疆76 2024-11-10 00:09
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    您的代码整体上是合理的,但是可能存在一些问题导致模型在预测新的猫狗照片时表现不佳。我会根据您提供的代码进行一些分析和建议:

    1. 训练数据的问题: 确保您的训练数据(从cat1dog1文件夹中的图片)是充足的并且具有代表性。如果数据量不够或者分布不均,模型可能无法正确学习猫和狗的特征。此外,确认这些图片已经正确地预处理和标注。
    2. 模型结构的问题: 您使用了一个简单的全连接层(Dense层)作为分类器。尽管这是一个常见的方法,但对于特定的任务和数据集,可能不是最佳选择。您可以尝试更复杂的网络结构或调整参数以提高性能。
    3. 过拟合问题: 由于您在训练集上的准确率是100%,这可能意味着模型在某种程度上过拟合了训练数据。这可能导致在未见过的数据(如测试集或您下载的新照片)上表现不佳。您可以尝试使用更复杂的模型结构、增加数据多样性、使用正则化等方法来避免过拟合。
    4. 类别不平衡: 如果猫和狗的图片数量差异很大,模型可能会偏向于数量较多的类别。您可以使用再采样技术或设置适当的损失函数来平衡类别。
    5. 特征提取: 您使用了VGG16的预训练权重进行特征提取,这是一个很好的起点。但确保您的输入图片经过了正确的预处理(例如,归一化、剪裁等),以确保与预训练模型的输入一致。此外,确认您的图片大小是适应模型的大小(在这里是224x224)。
    6. 测试集预测: 在使用模型进行预测之前,确保您的测试集图片也经过了相同的预处理步骤,并且与训练时使用的预处理方式一致。
    7. 随机预测: 由于您使用了单一的Dense层进行分类,模型可能对于输入图像的微小变化非常敏感。这可能解释了为什么某些预测总是返回猫的结果。尝试增加模型的复杂性或使用不同的模型结构可能会改善这种情况。

    为了改进模型性能,您可以尝试上述建议中的一种或多种方法。此外,还可以考虑使用更复杂的模型结构(如卷积神经网络中的残差连接或其他高级技术),调整超参数(如学习率、批次大小等),或使用数据增强来增加训练数据的多样性。

    评论

报告相同问题?

问题事件

  • 修改了问题 11月10日
  • 创建了问题 11月10日