本文介绍了检查输入时出错:预期conv2d_1_input具有4维,但数组的形状为(800,1000)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CNN进行情感分析我的代码将数据传递给convolution2D时,我的数据的形状为(1000,1000),这将向我抛出错误.我无法解决.我尝试下面的解决方案,但仍然面临问题.扩建CNN时,我收到了Keras的投诉,这些投诉对我来说是没有道理的.

i am trying to do sentimental analysis using CNNi my code my data has (1000,1000) shape when i pass the data to convolution2D it is throwing me an error. which i am not able to resolve.i tried below solution but still facing issue.When bulding a CNN, I am getting complaints from Keras that do not make sense to me.

我的代码在下面.

TfIdf = TfidfVectorizer(max_features=1000)
X = TfIdf.fit_transform(x.ravel())
Y = df.iloc[:,1:2].values


X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2,random_state=1)

classifier = Sequential()

classifier.add(Convolution2D(32, kernel_size=(3,3), input_shape=(1000, 1000, 1), activation = 'relu'))

classifier.add(MaxPooling2D(pool_size=(2,2)))

classifier.add(Flatten())

classifier.add(Dense(output_dim =  128, activation='relu'))

classifier.add(Dense(output_dim =  1, activation='sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

classifier.fit(X_train, Y_train, batch_size = 10, nb_epoch = 100, validation_data=(X_test,Y_test))

(loss,accuracy) = classifier.evaluate(X_test,Y_test, batch_size =10)

print(accuracy)

推荐答案

您的神经网络希望数据是四维的.尺寸为(samples, rows, columns, channels).您的输入数据似乎只是二维的.您需要添加第一个维度即样本,因为Keras希望在输入中获得更多样本.您可以通过以下方式将样本尺寸添加到当前输入矩阵中:

Your neural network expects the data to be four-dimensional. Dimensions are (samples, rows, columns, channels). Your input data seems to be only two-dimensional. You need to add the first dimension which is samples since Keras expect to get more samples at the input. You can add a dimension for samples to your current input matrix with

X = X[np.newaxis, ...]

它将为尺寸为1的样本添加第一维.您还需要为当前缺少的渠道添加维度,作为最后一个维度.

It will add the first dimension for samples which will have size 1.You also need to add the dimension for channels which is currently missing as the last dimension.

可以通过以下步骤在两个步骤中执行两项操作:

Both actions can be performed in one step with:

X = X[np.newaxis, ..., np.newaxis]

这篇关于检查输入时出错:预期conv2d_1_input具有4维,但数组的形状为(800,1000)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 22:06