简体   繁体   English

在 keras 中使用 conv2d 层进行文本分类的维度误差

[英]Dimensional Error for text classification using conv2d layer in keras

I have a dataframe which I split into train and test set and the input shape for the train set is (4115,588).我有一个 dataframe ,我将其分为训练集和测试集,训练集的输入形状为 (4115,588)。 Now I want to create a neural network with Conv2D layers but face this error when I pass in the input shape arguement.现在我想创建一个带有 Conv2D 层的神经网络,但是当我传入输入形状参数时会遇到这个错误。 ValueError: Input 0 of layer sequential_8 is incompatible with the layer: : expected min_ndim=4, found ndim=3. ValueError:layersequential_8 的输入 0 与 layer 不兼容::预期 min_ndim=4,发现 ndim=3。 Full shape received: (None, 588, 1) I tried the following steps:收到的完整形状:(无,588,1)我尝试了以下步骤:

X_train = X_train.to_numpy()
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1],1))

model = Sequential()
model.add(Conv2D(128, kernel_size=(3,3), input_shape=(X_train.shape[0],588,1), 
activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(32, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

Can someone guide me on how to solve this error.有人可以指导我如何解决这个错误。 I am relatively new to this topic.我对这个话题比较陌生。

Conv2D expects input of shape, 4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (rows, cols, channels) if data_format='channels_last'. Conv2D 期望输入形状,4+D 张量,形状: batch_shape + (channels, rows, cols)如果 data_format='channels_first' 或 4+D 张量,形状: batch_shape + (rows, cols, channels)如果 data_format='channels_last '。

I tested your code with mnist dataset its working.我用 mnist dataset 测试了你的代码。 Working sample code工作示例代码

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
import tensorflow as tf

(X_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
#X_train = X_train.to_numpy()
#X_train = X_train.reshape((X_train.shape[0], X_train.shape[1],1))


model = tf.keras.Sequential()
model.add(Conv2D(128, kernel_size=(3,3), input_shape=(28,28,1), 
activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(32, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))


model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(),
              metrics=['accuracy'])
model.fit(X_train,
          y_train,
          batch_size=128,
          epochs=1,
          verbose=1)

Output Output

469/469 [==============================] - 137s 289ms/step - loss: -10766237696.0000 - accuracy: 0.1124

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM