Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查输入时出错:预期conv2d_1_输入具有形状(28,28,1),但获得具有形状(3,224,224)的数组_Python_Keras_Deep Learning_Convolutional Neural Network - Fatal编程技术网

Python 检查输入时出错:预期conv2d_1_输入具有形状(28,28,1),但获得具有形状(3,224,224)的数组

Python 检查输入时出错:预期conv2d_1_输入具有形状(28,28,1),但获得具有形状(3,224,224)的数组,python,keras,deep-learning,convolutional-neural-network,Python,Keras,Deep Learning,Convolutional Neural Network,我如何解决它? 我使用的代码如下所示 prediction = model.predict(np.expand_dims(file, axis = 0)) prediction = np.squeeze(prediction) index = np.where(prediction == 1)[0] number = (index - 1).item() print("predicted number for my image: ", number) 这是用于将图像转换为矢量的 import

我如何解决它? 我使用的代码如下所示

prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
这是用于将图像转换为矢量的

import cv2
import numpy as np

file = cv2.imread('17316.png')
file = cv2.resize(file, (224, 224))
file = cv2.cvtColor(file, cv2.COLOR_BGR2RGB)
file = np.array(file).reshape((1, 3, 224, 224))
print(file.shape[0])
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
这是我应用的卷积神经网络的一部分,它会导致错误我该怎么做,我该如何解决?请建议我修改代码,以便我能对我的数据集进行正确的预测

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)

从错误消息中可以明显看出,模型期望图像形状为(28,28,1)。所以,在将图像馈送到模型之前,尝试调整图像大小

file = cv2.imread('17316.png')
file = cv2.resize(file, (28, 28))
file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY)
file = file.reshape((-1, 28, 28,1))
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)

这将解决问题。

从错误消息中可以明显看出,模型期望图像形状为(28,28,1)。所以,在将图像馈送到模型之前,尝试调整图像大小

file = cv2.imread('17316.png')
file = cv2.resize(file, (28, 28))
file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY)
file = file.reshape((-1, 28, 28,1))
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)

这将解决问题。

可以发布您的完整代码吗?输入形状的值是多少?我想你应该把它设为(3224224)。显然,您的数据格式是channels\u first,默认格式是channels\u last。所以,我建议你们使用第一个卷积层

model.add(Conv2D(32, kernel_size = (3, 3),
                 activation = 'relu',
                 input_shape = (3, 224, 224), 
                 data_format = "channels_first")
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
更新:根据您的代码,以下操作应该可以工作,但可能不会产生您想要的结果。您正在mnist数据集上进行培训,该数据集需要28x28x1格式的图像,因此必须按照Mitiku的回答调整大小。我希望这有帮助

import keras
import cv2 
import numpy as np 
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten 
from keras.layers import Conv2D, MaxPooling2D 
from keras import backend as K 

batch_size = 128 
num_classes = 10 
epochs = 1 
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.load_data() 

if K.image_data_format() == 'channels_first': 
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) 
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) 
    input_shape = (1, img_rows, img_cols) 
else: 
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) 
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) 
    input_shape = (img_rows, img_cols, 1) 
    x_train = x_train.astype('float32')

x_test = x_test.astype('float32') 
x_train /= 255 
x_test /= 255 
print('x_train shape:', x_train.shape) 
print(x_train.shape[0], 'train samples') 
print(x_test.shape[0], 'test samples') 
y_train = keras.utils.to_categorical(y_train, num_classes) 
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential() 
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu',\
                 input_shape = input_shape))
model.add(Conv2D(64, (3, 3), activation='relu')) 
model.add(MaxPooling2D(pool_size=(2, 2))) 
model.add(Dropout(0.25)) 
model.add(Flatten()) 
model.add(Dense(128, activation='relu')) 
model.add(Dropout(0.5)) 
model.add(Dense(num_classes, activation='softmax')) 
model.compile(loss=keras.losses.categorical_crossentropy, \
              optimizer=keras.optimizers.Adadelta(), \
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, \
          verbose=1, validation_data=(x_test, y_test)) 
score = model.evaluate(x_test, y_test, verbose=0) 

print('Test loss:', score[0]) 
print('Test accuracy:', score[1]) 

file = cv2.imread('17316.png') 
file = cv2.resize(file, (28, 28))
file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY)
file = file.reshape((28, 28,1))

model.predict(np.expand_dims(file, axis = 0))
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
更新2: mnist数据集有10个类。你有一个二进制分类问题。输出将图像分类为类8,对应于数字7,因为mnist数据集类是从0到9的数字。我们必须知道类是如何编码的——这是特定于问题的。在这种情况下,要返回号码,可以执行以下操作:

prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)

最后一行返回prediction包含1的索引,由于索引从1开始,您可以从索引中减去1以获得与您的图像对应的数字。

请发布您的完整代码好吗?输入形状的值是多少?我想你应该把它设为(3224224)。显然,您的数据格式是channels\u first,默认格式是channels\u last。所以,我建议你们使用第一个卷积层

model.add(Conv2D(32, kernel_size = (3, 3),
                 activation = 'relu',
                 input_shape = (3, 224, 224), 
                 data_format = "channels_first")
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
更新:根据您的代码,以下操作应该可以工作,但可能不会产生您想要的结果。您正在mnist数据集上进行培训,该数据集需要28x28x1格式的图像,因此必须按照Mitiku的回答调整大小。我希望这有帮助

import keras
import cv2 
import numpy as np 
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten 
from keras.layers import Conv2D, MaxPooling2D 
from keras import backend as K 

batch_size = 128 
num_classes = 10 
epochs = 1 
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.load_data() 

if K.image_data_format() == 'channels_first': 
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) 
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) 
    input_shape = (1, img_rows, img_cols) 
else: 
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) 
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) 
    input_shape = (img_rows, img_cols, 1) 
    x_train = x_train.astype('float32')

x_test = x_test.astype('float32') 
x_train /= 255 
x_test /= 255 
print('x_train shape:', x_train.shape) 
print(x_train.shape[0], 'train samples') 
print(x_test.shape[0], 'test samples') 
y_train = keras.utils.to_categorical(y_train, num_classes) 
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential() 
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu',\
                 input_shape = input_shape))
model.add(Conv2D(64, (3, 3), activation='relu')) 
model.add(MaxPooling2D(pool_size=(2, 2))) 
model.add(Dropout(0.25)) 
model.add(Flatten()) 
model.add(Dense(128, activation='relu')) 
model.add(Dropout(0.5)) 
model.add(Dense(num_classes, activation='softmax')) 
model.compile(loss=keras.losses.categorical_crossentropy, \
              optimizer=keras.optimizers.Adadelta(), \
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, \
          verbose=1, validation_data=(x_test, y_test)) 
score = model.evaluate(x_test, y_test, verbose=0) 

print('Test loss:', score[0]) 
print('Test accuracy:', score[1]) 

file = cv2.imread('17316.png') 
file = cv2.resize(file, (28, 28))
file = cv2.cvtColor(file, cv2.COLOR_BGR2GRAY)
file = file.reshape((28, 28,1))

model.predict(np.expand_dims(file, axis = 0))
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)
更新2: mnist数据集有10个类。你有一个二进制分类问题。输出将图像分类为类8,对应于数字7,因为mnist数据集类是从0到9的数字。我们必须知道类是如何编码的——这是特定于问题的。在这种情况下,要返回号码,可以执行以下操作:

prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)

最后一行返回预测包含1的索引,当索引从1开始时,您可以从索引中减去1以获得与图像对应的数字。

导入keras导入cv2从keras导入numpy作为np。数据集从keras导入mnist。模型从keras导入顺序。图层导入密集,退出,从keras.layers导入Conv2D,从keras导入后端的MaxPoolig2D作为K批大小=128个类=10个时代=1个img列,img列=28,28(x列,y列),(x列,y列),(x列测试,y列测试)=mnist.加载数据(),如果K.图像数据格式()='channels\u first':x列=x列。重塑(x列形状[0],1,img列,img列,img列)x_测试=x_测试。重塑(x_测试。形状[0],1,img_行,img_列)输入_形状=(1,img_行,img_列)其他:x_列=x_列。重塑(x_列。形状[0],img_行,img_列,1)x_测试=x_测试。重塑(x_测试。形状[0],img_行,img_列,img_列,1)输入_形状=(img_行,img_列,img_列,imu列=32''x')x_test=x_test.astype('float32')x_train/=255 x_test/=255 print('x_train shape:',x_train.shape[0],'train samples')print(x_test.shape[0],'test samples')y_train=keras.utils.to_category(y_train,num classes)y_test=keras.utils.to_category(y_test,num classes)to_category(y_test,num classes)model=sequentical(y_test,num)model)model=(32,kernel_size=(3,3),activation='relu',input_shape=input_shape')model.add(Conv2D(64,(3,3),activation='relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(droot(0.25))model.add(flatte())model.add(flatte())model.add(densite(128,activation='relu'))model.add(droot(0.5))model.add(droot(droot(droot(0.5))model(den(loss=keras.loss.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['Accurance'])模型拟合(x_列,y_列,批次大小=批次大小,历代=历代,冗余=1,验证数据=(x_测试,y_测试)分数=模型。评估(x_测试,y_测试,冗余=0)打印('test loss:',分数[0])打印('test准确性:',分数[1])文件=cv2.imread('17316.png')file=cv2.resize(file,(224224))file=cv2.cvtColor(file,cv2.COLOR_BGR2RGB)file=np.array(file)。重塑((3224224))打印(file.shape[0])模型。预测(file)导入keras导入cv2从keras导入numpy作为np。数据集从keras导入mnist。模型从keras导入顺序。层从keras导入密集、脱落、展平。层从keras导入Conv2D,从keras导入后端MaxPoolig2D作为K批大小=128个num类=10个纪元=1个img列,img列=28,28(x列,y列),(x列,y列),(x列,y列)=mnist.load_data()如果K.image_data_format()='channels_first':x_train=x_train.shape[0],1,img列,img列)x_test=x_test.shape[0],1,img列,img列)输入_shape=(1,img列,img列)其他:x_train=x_列,重塑(x_train.shape[0],img列,img列,1)x_测试=x_测试。重塑(x_测试。形状[0],img_行,img_列,1)输入_形状=(img_行,img_列,1)x_列=x_列。astype('float32')x_测试=x_测试。astype('float32')x_列/=255 x_测试
prediction = model.predict(np.expand_dims(file, axis = 0))
prediction = np.squeeze(prediction)
index = np.where(prediction == 1)[0]
number = (index - 1).item()
print("predicted number for my image: ", number)