使用keras和tensorflow对卷积神经网络(CNN)的输入应该是什么?

时间:2018-01-23 17:45:56

标签: python keras

我正在尝试使用keras ad tensorflow作为后端来创建CNN模型。 下面是相同的代码..

无法理解它期待的输入......

import cv2,os
import glob
import numpy as np
from sklearn.utils import shuffle
from sklearn.cross_validation import train_test_split
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten

PATH = os.getcwd()
data_path = PATH + '/data1/cat/*.PNG'


files = glob.glob(data_path)
X_data = []
for myFile in files:
    image = cv2.imread (myFile)
    image_resize = cv2.resize(image,(128,128))
    X_data.append (image_resize)

image_data = np.array(X_data)
image_data = image_data.astype('float32')
image_data /= 255
print('X_data shape:', image_data.shape)



#Class ani labels
class_num = 2

total_Images = image_data.shape[0]
labels = np.ones((total_Images),dtype='int64')

labels[0:30] = 0
labels[31:] = 1


Y = to_categorical(labels,class_num)

#print(Y);



# Shuffle the dataset
x, y = shuffle(image_data, Y, random_state=2)
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)



input_shape = image_data[0].shape

#print(input_shape)

model = Sequential()

conv1 = Convolution2D(32,(3,3),padding='same',activation='relu')(input_shape)
conv2 = Convolution2D(32,(3,3),padding='same',activation='relu')(conv1)
pool_1 = MaxPooling2D(pool_size=(2,2))(conv2)
drop1 = Dropout(0.5)(pool_1)

conv3 = Convolution2D(64,(3,3),padding='same',activation='relu')(drop1)
conv4 = Convolution2D(64,(3,3),padding='same',activation='relu')(conv3)

pool_2 = MaxPooling2D(pool_size=(2,2))(conv4)
drop2 = Dropout(0.5)(pool_2)


flat = Flatten()(drop2)
hidden = Dense(64,activation='relu')(flat)
drop3 = Dropout(0.5)(hidden)
out = Dense(class_num,activation='softmax')(drop3)

model.compile(loss = 'categorical_crossentropy', optimizer= 'adam', metrics=['accuracy'])


model.fit(X_train,y_train,batch_size=16,nb_epoch=20, verbose=1, validation_data=(X_test,y_test))

model.evaluate(X_test,y_test,verbose=1)
Error: ValueError: Layer conv2d_1 was called with an input that isn't a 
symbolic tensor. Received type: <class 'tuple'>. Full input: [(128, 128,3)]. 
All inputs to the layer should be tensors.

1 个答案:

答案 0 :(得分:0)

您正尝试使用功能API和顺序模型,您需要先消除此行

model = Sequential()

然后,从functional API的文档中,我们添加了一个Input(channels,rows,columns)图层,并从X_train矩阵中填入大小值。

input_shape = Input()