【发布时间】:2020-10-06 15:05:59
【问题描述】:
我正在为一个在链中使用 Keras 二进制分类器模型的多类问题构建一个链分类器。我有 17 个标签作为分类目标,X_train 的形状是 (111300,107),y_train 是 (111300,17)。训练后,我在预测方法中得到了以下错误;
*could not broadcast input array from shape (27839,1) into shape (27839)*
我的代码在这里:
def create_model():
input_size=length_long_sentence
embedding_size=128
lstm_size=64
output_size=len(unique_tag_set)
#----------------------------Model--------------------------------
current_input=Input(shape=(input_size,))
emb_current = Embedding(vocab_size, embedding_size, input_length=input_size)(current_input)
out_current=Bidirectional(LSTM(units=lstm_size))(emb_current )
#out_current = Reshape((1,2*lstm_size))(out_current)
output = Dense(units=1, activation= 'sigmoid')(out_current)
#output = Dense(units=1, activation='softmax')(out_current)
model = Model(inputs=current_input, outputs=output)
#-------------------------------compile-------------
model.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])
return model
model = KerasClassifier(build_fn=create_model, epochs=1,batch_size=256, shuffle = True, verbose = 1,validation_split=0.2)
chain=ClassifierChain(model, order='random', random_state=42)
history=chain.fit(X_train, y_train)
chain.classes_ 的结果如下:
[array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8),
array([0, 1], dtype=uint8)]
然后尝试预测测试数据:
Y_pred_chain = chain.predict(X_test)
这里有完整的错误跟踪:
109/109 [==============================] - 22s 202ms/step
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-34a25ad06cd4> in <module>()
----> 1 Y_pred_chain = chain.predict(X_test)
/usr/local/lib/python3.6/dist-packages/sklearn/multioutput.py in predict(self, X)
523 else:
524 X_aug = np.hstack((X, previous_predictions))
--> 525 Y_pred_chain[:, chain_idx] = estimator.predict(X_aug)
526
527 inv_order = np.empty_like(self.order_)
ValueError: could not broadcast input array from shape (27839,1) into shape (27839)
谁能帮忙解决这个错误?
【问题讨论】:
-
我会仔细检查 X_test 的形状。
-
X_test 的形状是 (27839, 107)。
-
训练结束后,能不能打印
chain.classes_并写出它的输出? -
我在主帖中添加了chain.classes_的输出。
-
这有点远,但我有一个类似的问题,我通过使用
np.array(X_test)作为输入解决了这个问题。我认为这与X_test的指针是否实际“控制”内存有关
标签: python keras scikit-learn multilabel-classification multiclass-classification