Keras入门——(6)长短期记忆网络LSTM(三)

参考:

https://blog.csdn.net/u012735708/article/details/82769711

https://zybuluo.com/hanbingtao/note/581764

http://blog.sina.com.cn/s/blog_afc8730e0102xup1.html

https://blog.csdn.net/qq_30638831/article/details/80060045

执行代码:

import pandas as pd
from datetime import datetime
from matplotlib import pyplot
from sklearn.preprocessing import LabelEncoder,MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from numpy import concatenate
from math import sqrt

# load data
def parse(x):
    return datetime.strptime(x, ‘%Y %m %d %H‘)

def read_raw():
    dataset = pd.read_csv(‘C:/Users/cf_pc/Documents/jupyter/data/PRSA_data_2010.1.1-2014.12.31.csv‘,  parse_dates = [[‘year‘, ‘month‘, ‘day‘, ‘hour‘]], index_col=0, date_parser=parse)
    dataset.drop(‘No‘, axis=1, inplace=True)
    # manually specify column names
    dataset.columns = [‘pollution‘, ‘dew‘, ‘temp‘, ‘press‘, ‘wnd_dir‘, ‘wnd_spd‘, ‘snow‘, ‘rain‘]
    dataset.index.name = ‘date‘
    # mark all NA values with 0
    dataset[‘pollution‘].fillna(0, inplace=True)
    # drop the first 24 hours
    dataset = dataset[24:]
    # summarize first 5 rows
    print(dataset.head(5))
    # save to file
    dataset.to_csv(‘C:/Users/cf_pc/Documents/jupyter/data/pollution.csv‘)

def drow_pollution():
    dataset = pd.read_csv(‘C:/Users/cf_pc/Documents/jupyter/data/pollution.csv‘, header=0, index_col=0)
    values = dataset.values
    # specify columns to plot
    groups = [0, 1, 2, 3, 5, 6, 7]
    i = 1
    # plot each column
    pyplot.figure(figsize=(10,10))
    for group in groups:
        pyplot.subplot(len(groups), 1, i)
        pyplot.plot(values[:, group])
        pyplot.title(dataset.columns[group], y=0.5, loc=‘right‘)
        i += 1
    pyplot.show()

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
     # convert series to supervised learning
        n_vars = 1 if type(data) is list else data.shape[1]
        df = pd.DataFrame(data)
        cols, names = list(), list()
        # input sequence (t-n, ... t-1)
        for i in range(n_in, 0, -1):
            cols.append(df.shift(i))
            names += [(‘var%d(t-%d)‘ % (j+1, i)) for j in range(n_vars)]
        # forecast sequence (t, t+1, ... t+n)
        for i in range(0, n_out):
            cols.append(df.shift(-i))
            if i == 0:
                names += [(‘var%d(t)‘ % (j+1)) for j in range(n_vars)]
            else:
                names += [(‘var%d(t+%d)‘ % (j+1, i)) for j in range(n_vars)]
        # put it all together
        agg = pd.concat(cols, axis=1)
        agg.columns = names
        # drop rows with NaN values
        if dropnan:
            agg.dropna(inplace=True)
        return agg

def cs_to_sl():
    # load dataset
    dataset = pd.read_csv(‘C:/Users/cf_pc/Documents/jupyter/data/pollution.csv‘, header=0, index_col=0)
    values = dataset.values
    # integer encode direction
    encoder = LabelEncoder()
    values[:,4] = encoder.fit_transform(values[:,4])
    # ensure all data is float
    values = values.astype(‘float32‘)
    # normalize features
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled = scaler.fit_transform(values)
    # frame as supervised learning
    reframed = series_to_supervised(scaled, 1, 1)
    # drop columns we don‘t want to predict
    reframed.drop(reframed.columns[[9,10,11,12,13,14,15]], axis=1, inplace=True)
    print(reframed.head())
    return reframed,scaler

def train_test(reframed):
    # 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)
    return train_X,train_y,test_X,test_y

def fit_network(train_X,train_y,test_X,test_y,scaler):
    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()
    # make a prediction
    yhat = model.predict(test_X)
    test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
    # invert scaling for forecast
    inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
    inv_yhat = scaler.inverse_transform(inv_yhat)
    inv_yhat = inv_yhat[:,0]
    # invert scaling for actual
    inv_y = scaler.inverse_transform(test_X)
    inv_y = inv_y[:,0]
    # calculate RMSE
    rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
    print(‘Test RMSE: %.3f‘ % rmse)

if __name__ == ‘__main__‘:
    drow_pollution()
    reframed,scaler = cs_to_sl()
    train_X,train_y,test_X,test_y = train_test(reframed)
    fit_network(train_X,train_y,test_X,test_y,scaler)

返回信息:

   var1(t-1)  var2(t-1)  var3(t-1)  var4(t-1)  var5(t-1)  var6(t-1)  1   0.129779   0.352941   0.245902   0.527273   0.666667   0.002290
2   0.148893   0.367647   0.245902   0.527273   0.666667   0.003811
3   0.159960   0.426471   0.229508   0.545454   0.666667   0.005332
4   0.182093   0.485294   0.229508   0.563637   0.666667   0.008391
5   0.138833   0.485294   0.229508   0.563637   0.666667   0.009912   

   var7(t-1)  var8(t-1)   var1(t)
1   0.000000        0.0  0.148893
2   0.000000        0.0  0.159960
3   0.000000        0.0  0.182093
4   0.037037        0.0  0.138833
5   0.074074        0.0  0.109658
(8760, 1, 8) (8760,) (35039, 1, 8) (35039,)
WARNING:tensorflow:From C:\3rd\Anaconda2\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From C:\3rd\Anaconda2\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Train on 8760 samples, validate on 35039 samples
Epoch 1/50
 - 2s - loss: 0.0578 - val_loss: 0.0562
Epoch 2/50
 - 1s - loss: 0.0413 - val_loss: 0.0563
Epoch 3/50
 - 1s - loss: 0.0254 - val_loss: 0.0454
Epoch 4/50
 - 1s - loss: 0.0179 - val_loss: 0.0388
Epoch 5/50
 - 1s - loss: 0.0158 - val_loss: 0.0237
Epoch 6/50
 - 1s - loss: 0.0149 - val_loss: 0.0175
Epoch 7/50
 - 1s - loss: 0.0148 - val_loss: 0.0163
Epoch 8/50
 - 1s - loss: 0.0147 - val_loss: 0.0160
Epoch 9/50
 - 1s - loss: 0.0148 - val_loss: 0.0155
Epoch 10/50
 - 1s - loss: 0.0147 - val_loss: 0.0151
Epoch 11/50
 - 1s - loss: 0.0146 - val_loss: 0.0148
Epoch 12/50
 - 1s - loss: 0.0147 - val_loss: 0.0145
Epoch 13/50
 - 1s - loss: 0.0146 - val_loss: 0.0143
Epoch 14/50
 - 1s - loss: 0.0146 - val_loss: 0.0143
Epoch 15/50
 - 1s - loss: 0.0145 - val_loss: 0.0141
Epoch 16/50
 - 1s - loss: 0.0145 - val_loss: 0.0144
Epoch 17/50
 - 1s - loss: 0.0147 - val_loss: 0.0140
Epoch 18/50
 - 1s - loss: 0.0145 - val_loss: 0.0140
Epoch 19/50
 - 1s - loss: 0.0145 - val_loss: 0.0138
Epoch 20/50
 - 1s - loss: 0.0145 - val_loss: 0.0138
Epoch 21/50
 - 1s - loss: 0.0144 - val_loss: 0.0138
Epoch 22/50
 - 1s - loss: 0.0145 - val_loss: 0.0138
Epoch 23/50
 - 1s - loss: 0.0146 - val_loss: 0.0137
Epoch 24/50
 - 1s - loss: 0.0144 - val_loss: 0.0137
Epoch 25/50
 - 1s - loss: 0.0144 - val_loss: 0.0137
Epoch 26/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 27/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 28/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 29/50
 - 1s - loss: 0.0145 - val_loss: 0.0137
Epoch 30/50
 - 1s - loss: 0.0145 - val_loss: 0.0136
Epoch 31/50
 - 1s - loss: 0.0144 - val_loss: 0.0137
Epoch 32/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 33/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 34/50
 - 1s - loss: 0.0145 - val_loss: 0.0136
Epoch 35/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 36/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 37/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 38/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 39/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 40/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 41/50
 - 1s - loss: 0.0143 - val_loss: 0.0135
Epoch 42/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 43/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 44/50
 - 1s - loss: 0.0144 - val_loss: 0.0135
Epoch 45/50
 - 1s - loss: 0.0144 - val_loss: 0.0137
Epoch 46/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 47/50
 - 1s - loss: 0.0143 - val_loss: 0.0135
Epoch 48/50
 - 1s - loss: 0.0144 - val_loss: 0.0136
Epoch 49/50
 - 1s - loss: 0.0143 - val_loss: 0.0135
Epoch 50/50
 - 1s - loss: 0.0144 - val_loss: 0.0134

Test RMSE: 4.401

参考:

https://www.cnblogs.com/tianrunzhi/p/7825671.html

https://www.cnblogs.com/king-lps/p/7846414.html

https://www.cnblogs.com/datablog/p/6127000.html

https://www.cnblogs.com/charlotte77/p/5622325.html

https://www.cnblogs.com/bawu/p/7701810.html

原文地址:https://www.cnblogs.com/ratels/p/11186636.html

时间: 2024-11-08 23:06:07

Keras入门——(6)长短期记忆网络LSTM(三)的相关文章

如何预测股票分析--长短期记忆网络(LSTM)

在上一篇中,我们回顾了先知的方法,但是在这个案例中表现也不是特别突出,今天介绍的是著名的l s t m算法,在时间序列中解决了传统r n n算法梯度消失问题的的它这一次还会有令人杰出的表现吗? 长短期记忆(Long Short-Term Memory) 是具有长期记忆能力的一种时间递归神经网络(Recurrent Neural Network). 其网络结构含有一个或多个具有可遗忘和记忆功能的单元组成.它在1997年被提出用于解决传统RNN(Recurrent Neural Network) 的

【DL-4】长短期记忆网络(LSTM)

目录 背景 从RNN到LSTM LSTM 的核心思想 LSTM前向传播算法 LSTM 的变体 一.背景 由于RNN梯度消失的问题,因此很难处理长序列的数据,大牛们对RNN的机构做了改进,得到了RNN的特例长短期记忆网络LSTM(Long Short-Term Memory)和其它变形,可以从结构上避免常规RNN的梯度消失. 举个例子:长期依赖(Long-Term Dependencies)问题 假设我们试着去预测"I grew up in France... I speak fluent Fre

(转)零基础入门深度学习(6) - 长短时记忆网络(LSTM)

无论即将到来的是大数据时代还是人工智能时代,亦或是传统行业使用人工智能在云上处理大数据的时代,作为一个有理想有追求的程序员,不懂深度学习(Deep Learning)这个超热的技术,会不会感觉马上就out了?现在救命稻草来了,<零基础入门深度学习>系列文章旨在讲帮助爱编程的你从零基础达到入门级水平.零基础意味着你不需要太多的数学知识,只要会写程序就行了,没错,这是专门为程序员写的文章.虽然文中会有很多公式你也许看不懂,但同时也会有更多的代码,程序员的你一定能看懂的(我周围是一群狂热的Clean

deep_learning_LSTM长短期记忆神经网络处理Mnist数据集

1.RNN(Recurrent Neural Network)循环神经网络模型 详见RNN循环神经网络:https://www.cnblogs.com/pinard/p/6509630.html 2.LSTM(Long Short Term Memory)长短期记忆神经网络模型 详见LSTM长短期记忆神经网络:http://www.cnblogs.com/pinard/p/6519110.html 3.LSTM长短期记忆神经网络处理Mnist数据集 1 2 3 4 5 6 7 8 9 10 11

网络编程模型及网络编程三要素

网络模型 计算机网络之间以何种规则进行通信,就是网络模型研究问题. 网络模型一般是指 OSI(Open SystemInterconnection开放系统互连)参考模型 TCP/IP参考模型 网络模型7层概述: 1.物理层:主要定义物理设备标准,如网线的接口类型.光纤的接口类型.各种传输介质的传输速率等.它的主要作用是传输比特流(就是由1.0转化为电流强弱来进行传输,到达目的地后在转化为1.0,也就是我们常说的数模转换与模数转换).这一层的数据叫做比特. 2. 数据链路层:主要将从物理层接收的数

keras 入门整理 如何shuffle,如何使用fit_generator

keras入门参考网址: 中文文档教你快速建立model keras不同的模块-基本结构的简介-类似xmind整理 Keras的基本使用(1)--创建,编译,训练模型 keras分类应用里的人脸预测kaggle: 根据人脸预测年龄性别和情绪 人脸表情分类与识别:opencv人脸检测+Keras情绪分类(四) 数据量大无法载入时,节约内存model.fit_generator: keras 大数据的训练,迭代载入内存 1 def generate_arrays_from_file(path):  

网络编程三素概述

1.1网络编程概述计算机网络 ●是指将地理位置不同的具有独立功能的多 台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统 网络编程●在网络通信协议下, 实现网络互连的不同计算机上运行的程序间可以进行数据交换 网络编程三要素 IP地址●要想让网络中的计算 机能够互相通信,必须为每台计算机指定一个标识号, 通过这个标识号来指定要接收数据的计算机和识别发送的计算机,而IP地址就是这个标识号.也就是设备的标识 端口●网

Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 联系方式:[email protected] [系列]Android系列之网络:(持续更新) Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据) Android系列之网络(二)----HTTP请求头与响应头 Android

iOS网络编程(三) 异步加载及缓存图片----&gt;SDWebImage

@SDWebImage提供一个UIImageView的类别以支持加载来自网络的远程图片.具有缓存管理.异步下载.同一个URL下载次数控制和优化等特征. @SDWebImage的导入1.https://github.com/rs/SDWebImage 下载SDWebImage开源包2.将类包拖入工程,再导入MapKit.framework.ImageIO.framework两个框架3.SDWebImage是支持ARC的,在MRC的工程中要注意,可参考MRC工程配置ARC4.注意:SDWebImag