尝试将双向层连接到LSTM层以进行多类分类时,层bidirectional与层不兼容

我在处理一个多类分类问题,为了好玩,我想尝试不同的模型。我找到了一篇博客,它使用LSTM进行分类,我试图调整我的模型以使其工作。

这是我的模型:

  from tensorflow import keras  from tensorflow.keras.models import Sequential  from tensorflow.keras.layers import Dense, Dropout, Activation, Bidirectional, LSTM  from tensorflow.keras.optimizers import SGD, Adam   x_train_shape = X_train.shape[1]  model = Sequential()  model.add(Dense(x_train_shape, activation='tanh', input_dim=x_train_shape))  # model.add(Dropout(0.2))  model.add(Bidirectional(LSTM(32)))    # model.add(Dense(x_train_shape, activation='tanh'))  # model.add(Dense(x_train_shape, activation='tanh'))  model.add(Dense(len(labels), activation='softmax'))  model.compile(loss='categorical_crossentropy',                optimizer="adam", metrics=['accuracy', 'TopKCategoricalAccuracy', 'FalsePositives'])  model.fit(X_train, y_train, epochs=500, batch_size=200)

它返回以下错误:

ValueError: Input 0 of layer bidirectional_5 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 109]

如果我取消注释LSTM下的Dense层并注释掉LSTM,模型就能工作,所以这肯定与LSTM行有关。

如何将LSTM层连接到Dense层以进行多类分类?


回答:

尝试在Dense层周围添加一个TimeDistributed层。这里有一个使用虚假数据的例子:

from tensorflow import kerasimport numpy as npfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import *X_train = np.random.rand(100, 1, 10)y_train = np.random.randint(0, 10, 100)y_train = keras.utils.to_categorical(y_train)assert X_train.ndim == 3model = Sequential()model.add(TimeDistributed(Dense(10), input_shape=(X_train.shape[1:])))model.add(Bidirectional(LSTM(8)))model.add(Dense(8, activation='tanh'))model.add(Dense(8, activation='tanh'))model.add(Dense(y_train.shape[-1], activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer="adam")history = model.fit(X_train, y_train, epochs=1, batch_size=8)
Train on 100 samples  8/100 [=>............................] - ETA: 0s - loss: 2.2984 80/100 [=======================>......] - ETA: 0s - loss: 2.2863100/100 [==============================] - 0s 950us/sample - loss: 2.2984

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注