如何解决此错误?我尝试访问所有论坛以寻找答案来纠正此问题。
我在这里尝试使用keras进行多标签分类
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Input, Dense, Dropout, Embedding, LSTM, Flatten
from keras.models import Model
from keras.utils import to_categorical
from keras.callbacks import ModelCheckpoint
MAX_LENGTH = 500
tokenizer = Tokenizer()
tokenizer.fit_on_texts(df.overview.values)
post_seq = tokenizer.texts_to_sequences(df.overview.values)
post_seq_padded = pad_sequences(post_seq, maxlen=MAX_LENGTH)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(post_seq_padded, train_encoded, test_size=0.3)
vocab_size = len(tokenizer.word_index) + 1
inputs = Input(shape=(MAX_LENGTH, ))
embedding_layer = Embedding(vocab_size, 128, input_length=MAX_LENGTH)(inputs)
x = Dense(64, input_shape=(None,), activation='relu')(embedding_layer)
predictions = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=[inputs], outputs=predictions)
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
model.summary()
filepath="weights.hdf5"
checkpointer = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
history = model.fit(X_train, batch_size=64, y=to_categorical(y_train), verbose=1, validation_split=0.25, shuffle=True, epochs=10, callbacks=[checkpointer])
ValueError跟踪(最近一次通话)
<ipython-input-11-7fdc4bff9648> in <module>
2 checkpointer = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
3 history = model.fit(X_train, batch_size=64, y=to_categorical(y_train), verbose=1, validation_split=0.25,
**---->** 4 shuffle=True, epochs=10, callbacks=[checkpointer])
ValueError:检查目标时出错:预期density_3具有形状(500,4),但数组具有形状(4,2)
我希望输出形状为(500,3),但我得到的(4,2)却不匹配,无法继续进行操作。
答案 0 :(得分:0)
在将嵌入层的输出传递到密集层之前,尝试使其平坦,如下所示:
embedding_layer = Embedding(vocab_size, 128, input_length=MAX_LENGTH)(inputs)
flat_layer = Flatten()(embedding_layer)
x = Dense(64, activation='relu')(flat_layer)
答案 1 :(得分:0)
尝试一下
x = Dense(64, input_dim = 500, activation='relu')(embedding_layer)