愉快的学习就从翻译开始吧_Multivariate Time Series Forecasting with LSTMs in Keras_4_Define and Fit Model

In this section, we will fit an LSTM on the multivariate input data.

本章,我们将在多变量输入数据上拟合LSTM

First, we must split the prepared dataset into train and test sets. To speed up the training of the model for this demonstration, we will only fit the model on the first year of data, then evaluate it on the remaining 4 years of data. If you have time, consider exploring the inverted version of this test harness.

首先,我们必须将准备好的数据集分为训练和测试集。 为了加速此演示模型的培训,我们将只在第一年的数据上拟合模型,然后在剩余的4年数据中对其进行评估。 如果你有时间,可以考虑探索这个测试工具的倒置版本(意思就是四年训练,一年测试)。

The example below splits the dataset into train and test sets, then splits the train and test sets into input and output variables. Finally, the inputs (X) are reshaped into the 3D format expected by LSTMs, namely [samples, timesteps, features].

下面的例子将数据集分解为训练集和测试集,然后将训练集和测试集分解为输入和输出变量。 最后,输入(X)被重新整形为LSTM预期的3D格式,即[samples, timesteps, features]。

# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples timesteps features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

Running this example prints the shape of the train and test input and output sets with about 9K hours of data for training and about 35K hours for testing.

运行该示例,打印出训练和测试的输入输出集的形状,大约9k小时的数据用于训练,大约35k小时的数据用于测试

(8760, 1, 8) (8760,) (35039, 1, 8) (35039,)

Now we can define and fit our LSTM model.

现在我们可以定义和拟合我们的LSTM模型、

We will define the LSTM with 50 neurons in the first hidden layer and 1 neuron in the output layer for predicting pollution. The input shape will be 1 time step with 8 features.

我们将用第一个隐藏层50个神经元和输出层一个神经元定义LSTM来预测污染,输入格式将是8个特征的一个时间步

We will use the Mean Absolute Error (MAE) loss function and the efficient Adam version of stochastic gradient descent.

我们将使用平均绝对误差(MAE)损失函数和随机梯度下降的高效Adam版本。

The model will be fit for 50 training epochs with a batch size of 72. Remember that the internal state of the LSTM in Keras is reset at the end of each batch, so an internal state that is a function of a number of days may be helpful (try testing this).

该模型将适用于批量为72的50个训练时期。请记住,Keras中的LSTM的内部状态在每批次结束时被重置,因此一个多天函数的内部状态 也许更有帮助(尝试测试这个)(72不就是3天吗?这特么是说用更多的天数来做为一个batch吗?我特么就到现在都不明白重置状态到底指什么!)。

Finally, we keep track of both the training and test loss during training by setting the validation_data argument in the fit() function. At the end of the run both the training and test loss are plotted.

最后,我们通过在fit()函数中设置validation_data参数来跟踪训练期间的训练和测试损失。 在运行结束时,绘制训练和测试损失。

# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2,
                    shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

matplotlib.pyplot. legend ( *args**kwargs )

Places a legend on the axes.

To make a legend for lines which already exist on the axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:

ax.plot([1, 2, 3])
ax.legend(['A simple line'])

However, in order to keep the “label” and the legend element instance together, it is preferable to specify the label either at artist creation, or by calling the set_label() method on the artist:

line, = ax.plot([1, 2, 3], label='Inline label')
# Overwrite the label by calling the method.
line.set_label('Label via method')
ax.legend()

Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling legend() without any arguments and without setting the labels manually will result in no legend being drawn.

For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:

legend((line1, line2, line3), ('label1', 'label2', 'label3'))
Parameters:

loc : int or string or pair of floats, default: ‘upper right’

The location of the legend. Possible codes are:

Location StringLocation Code
‘best’0
‘upper right’1
‘upper left’2
‘lower left’3
‘lower right’4
‘right’5
‘center left’6
‘center right’7
‘lower center’8
‘upper center’9
‘center’10

Alternatively can be a 2-tuple giving x, y of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

bbox_to_anchor : matplotlib.transforms.BboxBase instance or tuple of floats

Specify any arbitrary location for the legend ibbox_transform coordinates (default Axes coordinates).

For example, to put the legend’s upper right hand corner in the center of the axes the following keywords can be used:

loc='upper right', bbox_to_anchor=(0.5, 0.5)

ncol : integer

The number of columns that the legend has. Default is 1.

prop : None or matplotlib.font_manager.FontProperties or dict

The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

Controls the font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.

numpoints : None or int

The number of marker points in the legend when creating a legend
e
ntry for a line/matplotlib.lines.Line2D. Default is None which will take the value from thelegend.numpoints rcParam.

scatterpoints : None or int

The number of marker points in the legend when creating a legend
e
ntry for a scatter plot/ matplotlib.collections.PathCollection. Default is None which will take the value from the legend.scatterpoints rcParam.

scatteryoffsets : iterable of floats

The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5]. Default [0.375, 0.5, 0.3125].

markerscale : None or int or float

The relative size of legend markers compared with the originally drawn ones. Default is None which will take the value from the legend.markerscale rcParam.

markerfirst : bool

if Truelegend marker is placed to the left of the legend label if Falselegend marker is placed to the right of the legend
l
abel

frameon : None or bool

Control whether the legend should be drawn on a patch (frame). Default is None which will take the value from the legend.frameon rcParam.

fancybox : None or bool

Control whether round edges should be enabled around the FancyBboxPatch which makes up the legend’s background. Default is None which will take the value from the legend.fancybox rcParam.

shadow : None or bool

Control whether to draw a shadow behind the legend.
Default is None which will take the value from the legend.shadow rcParam.

framealpha : None or float

Control the alpha transparency of the legend’s background. Default is None which will take the value from the legend.framealpha rcParam.

facecolor : None or “inherit” or a color spec

Control the legend’s background color. Default is None which will take the value from thelegend.facecolor rcParam. If "inherit", it will take the axes.facecolor rcParam.

edgecolor : None or “inherit” or a color spec

Control the legend’s background patch edge color. Default is None which will take the value from thelegend.edgecolor rcParam. If "inherit", it will take the axes.edgecolor rcParam.

mode : {“expand”, None}

If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend’s size).

bbox_transform : None or matplotlib.transforms.Transform

The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’transAxes transform will be used.

title : str or None

The legend’s title. Default is no title (None).

borderpad : float or None

The fractional whitespace inside the legend border. Measured in font-size units. Default is None which will take the value from the legend.borderpad rcParam.

labelspacing : float or None

The vertical space between the legend entries. Measured in font-size units. Default is None which will take the value from the legend.labelspacing rcParam.

handlelength : float or None

The length of the legend handles. Measured in font-size units. Default is None which will take the value from the legend.handlelength rcParam.

handletextpad : float or None

The pad between the legend handle and text. Measured in font-size units. Default is None which will take the value from the legend.handletextpad rcParam.

borderaxespad : float or None

The pad between the axes and legend border. Measured in font-size units. Default is None which will take the value from the legend.borderaxespad rcParam.

columnspacing : float or None

The spacing between columns. Measured in font-size units. Default is None which will take the value from the legend.columnspacing rcParam.

handler_map : dict or None

The custom dictionary mapping instances or types to a legend
h
andler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map().

Notes

Not all kinds of artist are supported by the legend command. See Legend guide for details.

Examples

(Source codepngpdf)

../_images/legend_demo7.png


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值