LSTM-预测概率

目录

1.已知知识

1.1LSTM

1.2.随机行走模型

2 问题描述

3 代码

3.1.数据准备

3.2.结果


1.已知知识

1.1LSTM

指长短期记忆人工神经网络。长短期记忆网络(LSTM,Long Short-Term Memory)是一种时间循环神经网络,是为了解决一般的RNN(循环神经网络)存在的长期依赖问题而专门设计出来的。

RNN:Recurrent Neural Network 循环神经网络的计算过程如下:

c^{N<t>}=tanh(W_c[c^{<t-1>},x^{<t>}]+b_c),

\Gamma _u=\sigma (w_u[c^{<t>},x^{<T>}]+b_u),

c^{<t>}=\Gamma _u*c^{N<t>}+{\color{Red} (1-\Gamma _u)}*c^{<t>},

a^{<t>}=c^{<t>},

在LSTM当中将{\color{Red} (1-\Gamma _u)}换成了\Gamma _f,而且,对a^{<t>}的更新也换成了\Gamma _o*tanh(c^{<t>})

墙裂推荐吴恩达的课程,图片来自他讲LSTM,非常清楚,LSTM的计算过程如下:

计算三个门的结果除了a^{<t-1>},x^{<t>}外还可以再加一个上次细胞状态c^{<t-1>} ,这个操作叫窥视连孔连接,peophole connection。

1.2.随机行走模型

用random walk model 得出概率的走向,下面这段代码可以玩一下。

__author__ = 'Administrator'
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

fig=plt.figure()

#time span
T=500
#drift factor飘移率
mu=0.00005
#volatility波动率
sigma=0.04
#t=0初试价
S0=np.random.random()
#length of steps
dt=1
N=round(T/dt)
t=np.linspace(0,T,N)

W=np.random.standard_normal(size=N)
print("W ",W.shape)
#W.shape=(500,)
#几何布朗运动过程
W=np.cumsum(W)*np.sqrt(dt)
X=(mu-0.5*sigma**2)*t+sigma*W
S=S0*np.exp(X)

fd=pd.DataFrame({'pro':S})
fd.to_csv('pic/random_walk.csv',sep=',',index=False)
plt.plot(t,S,lw=2)
plt.show()

2 问题描述

预测某个app在未来某个时间再次被打开的概率,其概率曲线用随机行走模型 random walk model 得出,数据大小都为0-1之间的小数,如果得出的图的取值不在【0,1】,多画几次~,因为每个动作都随机,很有可能会超过【0,1】这个范围。假设共500个分钟,先用70%的数据进行训练,打乱数据集后,再选取30%的数据进行测试,这样可以提高泛化能力。

配置:用cpu跑的,相当的慢了,使用keras

3 代码

import pandas as pd
import numpy as np
import keras
import matplotlib.pyplot as plt
#from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
test_num=500
train_times=1000
#random walk model to generate the probability tendency of task
def random_walk_model():
    fig=plt.figure()
    #time span
    T=500
    #drift factor飘移率
    mu=0.00005
    #volatility波动率
    sigma=0.04
    #t=0初试价
    S0=np.random.random()
    #length of steps
    dt=1
    N=round(T/dt)
    #generate 500 steps and collect it into t
    t=np.linspace(0,T,N)

    #W is standard normal list
    W=np.random.standard_normal(size=N)
    print("W ",W)
    #W.shape=(500,)
    #几何布朗运动过程,产生概率轨迹
    W=np.cumsum(W)*np.sqrt(dt)
    X=(mu-0.5*sigma**2)*t+sigma*W
    S=S0*np.exp(X)
    plt.plot(t,S,lw=2)
    plt.show()
    #save the probability tendency of picture
    fd=pd.DataFrame({'pro':S})
    fd.to_csv('pic/random_walk_model.csv',sep=',',index=False)
    plt.savefig('pic/random_data.png')
    return S
def random_test(sequence_length=5,split=0.7):

    #get the stored data by using pandas
    test_data = pd.read_csv('pic/random_walk_model.csv', sep=',',usecols=[0])
    #print("test_data:",test_data)

    #generate new test data for 2d
    test_data = np.array(test_data).astype('float64')
    #print('test_data:',test_data.shape)
    #test_data: (500, 1)

    #70% are used to be trained, the rest is used to be tested
    split_boundary = int(test_data.shape[0] * split)
    #print('split_boundary:',split_boundary)
    #split_boundary:350

    pro_test=np.linspace(split_boundary,test_data.shape[0],test_data.shape[0]-split_boundary)
    pro_x=np.linspace(1,split_boundary,split_boundary)
    plt.plot(pro_x,test_data[:split_boundary])
    plt.plot(pro_test,test_data[split_boundary:],'red')
    plt.legend(['train_data','test_data'])
    plt.xlabel('times')
    plt.ylabel('probability')
    plt.show()
    #print("test_data: ",test_data,test_data.shape),test_data.shape=(600,1),array to list format

    #generate 3d format of data and collect it
    data = []

    for i in range(len(test_data) - sequence_length - 1):
        data.append(test_data[i: i + sequence_length + 1])
    #print(len(data[0][0]),len(data[1]),len(data))
    #1 6 494
    reshaped_data = np.array(data).astype('float64')
    #print("reshaped_data:",reshaped_data.shape)
   #reshaped_data: (494, 6, 1)

    #random the order of test_data to improve the robustness
    np.random.shuffle(reshaped_data)
    #from n to n*5 are the training data collected in x, the n*6th is the true value collected in y
    x = reshaped_data[:, :-1]
    y = reshaped_data[:, -1]

    #print("x ",x.shape,"\ny ",y.shape)
    #x  (494, 5, 1) y  (494, 1)

    #train data
    train_x = x[: split_boundary]
    train_y = y[: split_boundary]
    #test data
    test_x = x[split_boundary:]
    test_y=y[split_boundary:]
    #print("train_y:",train_x.shape,"train_y:",train_y.shape,"test_x ",test_x.shape,"test_y",test_y.shape)
    #train_y: (350, 5, 1) train_y: (350, 1) test_x  (144, 5, 1) test_y (144, 1)
    return train_x, train_y, test_x, test_y

def build_model():
    # input_dim是输入的train_x的最后一个维度,相当于输入的神经只有1个——特征只有1个,train_x的维度为(n_samples, time_steps, input_dim)
    #如果return_sequences=True:返回形如(samples,timesteps,output_dim)的3D张量否则,返回形如(samples,output_dim)的2D张量
    #unit并不是输出的维度,而是门结构(forget门、update门、output门)使用的隐藏单元个数
    model = Sequential()
    #use rmsprop for optimizer
    rmsprop=keras.optimizers.RMSprop(lr=0.001, rho=0.9,epsilon=1e-08,decay=0.0)
    #build one LSTM layer
    model.add(LSTM(input_dim=1, units=1, return_sequences=False,use_bias=True,activation='tanh'))
    #model.add(LSTM(100, return_sequences=False,use_bias=True,activation='tanh'))

    #comiple this model
    model.compile(loss='mse', optimizer=rmsprop)#rmsprop
    return model

def train_model(train_x, train_y, test_x, test_y):
    #call function to build model
    model = build_model()

    try:
        #store this model to use its loss parameter
        history=model.fit(train_x, train_y, batch_size=20, epochs=train_times,verbose=2)
        #store the loss
        lossof_history=history.history['loss']

        predict = model.predict(test_x)
        predict = np.reshape(predict, (predict.size, ))
        #evaluate this model by returning a loss
        loss=model.evaluate(test_x,test_y)
        print("loss is ",loss)
    #if there is a KeyboardInterrupt error, do the following
    except KeyboardInterrupt:
        print("error of predict ",predict)
        print("error of test_y: ",test_y)

    try:
        #x1 is the xlabel to print the test value, there are 500 data,30% is for testing
        x1=np.linspace(1,test_y.shape[0],test_y.shape[0])
        #x1 is the xlabel to print the loss value, there are 500 data,70% is for training
        x2=np.linspace(1,train_times,train_times)
        fig = plt.figure(1)
        #print the predicted value and true value
        plt.title("test with rmsprop lr=0.01_")
        plt.plot(x1,predict,'ro-')
        plt.plot(x1,test_y,'go-')
        plt.legend(['predict', 'true'])
        plt.xlabel('times')
        plt.ylabel('propability')
        plt.savefig('pic/train_with_rmsprop_lr=0.01.png')
        #print the loss
        fig2=plt.figure(2)
        plt.title("loss lr=0.01")
        plt.plot(x2,lossof_history)
        plt.savefig('pic/train_with_rmsprop_lr=0.01_LOSS_.png')
        plt.show()
    #if the len(x1) is not equal to predict.shape[0] / test_y.shape[0] / len(x2) is not equal to lossof_history.shape[0],there will be an Exception
    except Exception as e:
        print("error: ",e)

if __name__ == '__main__':
    #random_walk_model() function is only used by once, because data are stored as pic/random_data.csv
    #random_walk_model()

    #prepare the right data format for LSTM
    train_x, train_y, test_x, test_y=random_test()
    #standard the format for LSTM input
    test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))
    #print("main: train_x.shape ",train_x.shape)
    #main: train_x.shape  (350, 5, 1)
    train_model(train_x, train_y, test_x, test_y)

细节

3.1.数据准备

def random_test(sequence_length=6,split=0.7):

在这个函数当中,将获取的数据处理为需要的三维的张量格式,在训练的时候

history=model.fit(train_x, train_y, batch_size=20, epochs=train_times,verbose=2)

train_x.shape=  (415, 6, 1)#600条数据,70%的训练数据,30%测试数据

最后使用的训练数据需要是这样的三维张量。

Question:600条的数据,70%用于训练,那么数据应该是420条,但是为什么是415?

Answer:在预处理数据之后,建立一层的LSTM:

model.add(LSTM(input_dim=1, units=50, return_sequences=False))

后台显示input_dim warning,找了下原因,要使用input_shape作为参数,input_shape为3维,参数为(Batch_size, Time_step, Input_Sizes)。

batch_size设置:batch_size为

在model.add(LSTM(input_shape(,,,), units=, return_sequences=))语句中定义在该语句中不定义batch_size,input_shape=(5,),这只定义了time_step,或者input_shape=(None,5,5),第一个参数定义为None
无法使用model.train_on_batch(),且在test时也需要有batch_size的数据可以调用train_on_batch()

time_step为时间序列的长度/语句的最大长度

input_sizes:每个时间点输入x的维度/语句的embedding的向量维度,本例题做概率预测,再次回忆LSTM的图,x(t)输入是一个概率值,那么input_sizes=1,即特征值只有一个

那这与数据415条的关系在哪呢?

注意默认的参数 sequence_length=6

这是数据的一部分:

'''
0.7586717205211277
0.6628550358816061
0.9184003785782959
0.09365662435769384
0.9791582266747239
0.8700739252039772
0.7924134549615585
0.3983410609045436
0.38988445126231197
0.8167186985712294
0.879351951255656
0.9468282424096985
0.7060727836006101
0.7650727081508003
0.3633755461129521
0.3489589275449808
'''
for i in range(len(test_data) - sequence_length - 1):
        data.append(test_data[i: i + sequence_length + 1])

在上面的语句作用就是

当i=0时,data.append(test[0:6]),一共循环594次,那么data的数据为

[[[0.75867172]
  [0.66285504]
  [0.91840038]
  [0.09365662]
  [0.97915823]
  [0.87007393]]

 [[0.66285504]
  [0.91840038]
  [0.09365662]
  [0.97915823]
  [0.87007393]
  [0.79241345]]

 [[0.91840038]
  [0.09365662]
  [0.97915823]
  [0.87007393]
  [0.79241345]
  [0.39834106]]

 ...
]

即 其步长为1,生成的data.shape=(594, 6, 1)= (seq_len, batch, input_size)

其中第一个参数表示数据个数,

第二个参数表示,观察dada的数据,步长为1(自己设定的),个数为6,进行划分,batch就是那个6

第三个参数:回忆上面讲的input_shape的input_size——>每个时间点输入x的维度/语句的embedding的向量维度,本例题做概率预测,再次回忆LSTM的图,x(t)输入是一个概率值,那么input_sizes=1,即特征值只有一个

3.2.结果

用于测试的30%的数据预测结果与真实结果如下

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值