作者:不会游泳的小饼儿 | 来源:互联网 | 2022-12-08 12:09
我正在使用Keras的Functional API(使用TensorFlow后端)培训具有多个输出层的文本情感分类模型.该模型将Keras预处理API的hashing_trick()函数生成的Numpy散列值数组作为输入,并使用Numpy二进制单热标签数组列表作为其目标,根据Keras规范训练具有多个输出的模型(请参阅fit()的文档:https://keras.io/models/model/).
这是模型,没有大多数预处理步骤:
textual_features = hashing_utility(filtered_words) # Numpy array of hashed values(training data)
label_list = [] # Will eventually contain a list of Numpy arrays of binary one-hot labels
for index in range(one_hot_labels.shape[0]):
label_list.append(one_hot_labels[index])
weighted_loss_value = (1/(len(filtered_words))) # Equal weight on each of the output layers' losses
weighted_loss_values = []
for index in range (one_hot_labels.shape[0]):
weighted_loss_values.append(weighted_loss_value)
text_input = Input(shape = (1,))
intermediate_layer = Dense(64, activation = 'relu')(text_input)
hidden_bottleneck_layer = Dense(32, activation = 'relu')(intermediate_layer)
keras.regularizers.l2(0.1)
output_layers = []
for index in range(len(filtered_words)):
output_layers.append(Dense(2, activation = 'sigmoid')(hidden_bottleneck_layer))
model = Model(inputs = text_input, outputs = output_layers)
model.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy', metrics = ['accuracy'], loss_weights = weighted_loss_values)
model.fit(textual_features, label_list, epochs = 50)
以下是此模型产生的错误跟踪培训的要点:
ValueError:检查目标时出错:期望dense_3具有形状(2,)但是得到了具有形状的数组(1,)
1> sdcbr..:
您的numpy arrays
(用于输入和输出)都应包含一个批次尺寸。如果您的标签当前为shape (2,)
,则可以对其进行重塑以包括如下的批次尺寸:
label_array = label_array.reshape(1, -1)