无法使用CNN模型获取输出

时间:2020-07-13 10:31:18

标签: machine-learning deep-learning lstm cnn

我正在尝试在此数据集上使用cnn-lstm模型。我已将此数据集存储在名为df的数据框中。此数据集中总共有11列,但我在这里仅提及9列。所有列都只有数字值

Area     book_hotel  votes  location    hotel_type  Total_Price   Facilities   Dine      rate
6             0        0      1           163          400             22        7        4.4
19            1        2      7           122          220             28        11       4.6


X=df.drop(['rate'],axis=1) 
Y=df['rate']

x_train, x_test, y_train, y_test = train_test_split(np.asarray(X), np.asarray(Y), test_size=0.33, shuffle= True)

x_train具有形状(3350,10)和 x_test的形状为(1650,10)

# The known number of output classes.
num_classes = 10

# Input image dimensions
input_shape = (10,)

# Convert class vectors to binary class matrices. This uses 1 hot encoding.
y_train_binary = keras.utils.to_categorical(y_train, num_classes)
y_test_binary = keras.utils.to_categorical(y_test, num_classes)

x_train = x_train.reshape(3350, 10,1)
x_test = x_test.reshape(1650, 10,1)





input_layer = Input(shape=(10, 1))
conv1 = Conv1D(filters=32,
               kernel_size=8,
               strides=1,
               activation='relu',
               padding='same')(input_layer)
lstm1 = LSTM(32, return_sequences=True)(conv1)
output_layer = Dense(1, activation='sigmoid')(lstm1)
model = Model(inputs=input_layer, outputs=output_layer)

model.summary()
model.compile(loss='mse',optimizer='adam')

最后,当我尝试使用输入来拟合模型

 model.fit(x_train,y_train)

ValueError                                Traceback (most recent call last)
<ipython-input-170-4719cf73997a> in <module>()
----> 1 model.fit(x_train,y_train)

2 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    133                         ': expected ' + names[i] + ' to have ' +
    134                         str(len(shape)) + ' dimensions, but got array '
--> 135                         'with shape ' + str(data_shape))
    136                 if not check_batch_axis:
    137                     data_shape = data_shape[1:]

ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (3350, 1)

有人可以帮助我解决此错误

1 个答案:

答案 0 :(得分:2)

我在您的代码中看到了一些问题...

最后一个维度输出必须等于类数,并且对于多类任务,您需要应用softmax激活:Dense(num_classes, activation='softmax')

您必须在最后一个lstm单元格中设置return_sequences=False,因为您需要2D输出而不是3D

您必须使用categorical_crossentropy作为具有一热编码目标的损失函数

这里是一个完整的虚拟示例...

num_classes = 10
n_sample = 1000
X = np.random.uniform(0,1, (n_sample,10,1))
y = tf.keras.utils.to_categorical(np.random.randint(0,num_classes, n_sample))

input_layer = Input(shape=(10, 1))
conv1 = Conv1D(filters=32,
               kernel_size=8,
               strides=1,
               activation='relu',
               padding='same')(input_layer)
lstm1 = LSTM(32, return_sequences=False)(conv1)
output_layer = Dense(num_classes, activation='softmax')(lstm1)

model = Model(inputs=input_layer, outputs=output_layer)

model.compile(loss='categorical_crossentropy',optimizer='adam')
model.fit(X,y, epochs=5)