LSTM在Keras中:顺序API和函数式API的参数数量差异

使用顺序API

如果我使用Keras的顺序API创建一个LSTM,并使用以下代码:

from keras.models import Sequentialfrom keras.layers import LSTMmodel = Sequential()model.add(LSTM(2, input_dim=3))

那么

model.summary()

返回48个参数,这在这个Stack Overflow问题中被认为是正确的。

model.summary() with the Sequential API

快速详情:

input_dim = 3, output_dim = 2n_params = 4 * output_dim * (output_dim + input_dim + 1) = 4 * 2 * (2 + 3 + 1) = 48

使用函数式API

但是如果我使用以下代码通过函数式API做同样的事情:

from keras.models import Modelfrom keras.layers import Inputfrom keras.layers import LSTMinputs = Input(shape=(3, 1))lstm = LSTM(2)(inputs)model = Model(input=inputs, output=lstm)

那么

model.summary()

返回32个参数。

model.summary() with the Functional API

为什么会有这样的差异?


回答:

这种差异的原因是,当你向RNN层(包括LSTM层)传递input_dim=x时,意味着输入形状是(None, x),即有不同数量的时间步,每个时间步是一个长度为x的向量。然而,在函数式API的例子中,你指定shape=(3, 1)作为输入形状,这意味着有3个时间步,每个时间步有一个特征。因此参数数量将是:4 * output_dim * (output_dim + input_dim + 1) = 4 * 2 * (2 + 1 + 1) = 32,这正是模型摘要中显示的数字。

此外,如果你使用Keras 2.x.x版本,在为RNN层使用input_dim参数时,你会得到一个警告:

UserWarning: 递归层的input_diminput_length参数已被废弃。请改用input_shape

UserWarning: 将你的LSTM调用更新为Keras 2 API:LSTM(2, input_shape=(None, 3))

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中创建了一个多类分类项目。该项目可以对…

发表回复

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