我正在使用Keras的Functional API(使用TensorFlow后端)训练具有多个输出层的文本情感分类模型。该模型将Keras预处理API的hashing_trick()函数产生的哈希值的Numpy数组作为输入,并根据Keras规范使用二进制一键式标签的Numpy数组的 list 作为其目标。用于训练具有多个输出的模型(请参见此处的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:检查目标时出错:预期density_3的形状为(2,),但数组的形状为(1,)
答案 0 :(得分:4)
您的numpy arrays
(用于输入和输出)应包含批处理维度。如果您的标签当前为(2,)
形状,则可以对其进行重塑以包括如下的批次尺寸:
label_array = label_array.reshape(1, -1)
答案 1 :(得分:1)
我用过
iris <- transform(iris, Species.r=relevel(Species, ref="virginica"))
安装
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
我改变了损失,对我有用。