qq_44720724
阿狸大傻子
采纳率0%
2021-02-26 01:03

用keras做简单的猫狗识别,但是最后有个 I错误,新手求求大家帮忙提提意见

import sys
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

#创建cnn网络模型
def define_cnn_model():
    #使用序列模型
    model=Sequential()
    #卷积层
    model.add(Conv2D(32,(3,3),activation="relu",padding="same",input_shape=(200,200,3)),)
    #最大池化层
    model.add(MaxPooling2D((2,2)),)
    #Flatten层
    model.add(Flatten())
    #全连接层
    model.add(Dense(128,activation="relu"))
    model.add(Dense(1,activation="sigmoid"))

    #编译模型
    opt=SGD(lr=0.001,momentum=0.9)
    model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['accuracy'])
    return model

#from keras.utils import plot_model
#model=define_cnn_model()
#plot_model(model,to_file='cnn_model.png',dpi=100,show_shapes=True,show_layer_names=True)

def train_cnn_model():
    #实例化模型
    model=define_cnn_model()
    #创建图片生成器
    datagen=ImageDataGenerator(rescale=1.0/255.0)
    train_path= "C:\\Users\\lenovo\\Desktop\\trainingdata"
    train_it=datagen.flow_from_directory(
               train_path,
               class_mode='binary',
               batch_size=64,
               target_size=(200,200))
    #训练模型
    model.fit(train_it,
              steps_per_epoch=len(train_it),
              epochs=1,
              verbose=1,
              )
    model.save('cat dog_model.h5')
train_cnn_model()

from keras.models import load_model
#修改模型位置
model_path='cat dog_model.h5'
model=load_model(model_path)

#定义一个函数,从测试文件夹内读取任意一张图片
import os,random
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

def read_random_image():
    folder = "C:\\Users\\lenovo\\Desktop\\dogcat\\"
    file_path = folder + random.choice(os.listdir(folder))
    pil_im=Image.open(file_path,'r')
    return pil_im

#预测图片的种类
def get_predict(pil_im,model):
    # 对图片进行缩放
    pil_im = pil_im.resize((200, 200))
    #将格式转化为numpy array格式
    array_im=np.asarray(pil_im)
    #对图片进行预测
    result=model.predict([[array_im]])
    if result[0][0]>0.5:
        print("预测结果是:狗")
    else:
        print("预测结果是:猫")

pil_im=read_random_image()
get_predict(pil_im,model)

 ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 200, 3),这个错误困扰了大半天了,求求大家帮个忙

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • qq_34124780 qq_34124780 2月前

    报错是指你输入网络的shape和网络的的输入不一样。比如网络只接受单通道的图片,你输入rgb彩色图。看报错你的

    input_shape应该是类似(batch_size,宽度,高度,通道),你却只输入三个,所以报错了

    点赞 1 评论 复制链接分享
  • qq_44720724 阿狸大傻子 2月前

     ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 200, 3) 这个错误,实在不知道怎么改了

     

    点赞 评论 复制链接分享

为你推荐