“微信公众号”

一、回归预测要实现的问题

这次我们会使用RNN来进行回归(Regression)的训练,使用自己创建的sin曲线预测一条cos曲线。如下图所示,我们用蓝色的sin曲线预测红色的cos曲线。

二、回归预测要实现的效果

经过RNN的回归训练,我们的网络预测结果和真实结果的一个比对图,如下所示。

三、网络结构展示

四、代码展示

#conding:utf-8

'''
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
Run this script on tensorflow r0.10. Errors appear when using lower versions.
'''

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# define super-parameters
BATCH_START = 0 # 建立batch data时候的index
TIME_STEPS = 20 # backpropagation through time 的 time_steps
BATCH_SIZE = 50
INPUT_SIZE = 1 # sin 数据输入size
OUTPUT_SIZE = 1 # cos数据输出size
CELL_SIZE = 10 # RNN的hidden unit size
LR = 0.006 # learning rate

# 数据生成
def get_batch():
    global BATCH_START,TIME_STEPS
    # xs shape(50batch,20steps)
    xs = np.arange(BATCH_START,BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE,TIME_STEPS)) /(10 * np.pi)
    seq = np.sin(xs)
    res = np.cos(xs)
    BATCH_START += TIME_STEPS
    # plt.plot(xs[0,:],res[0,:],'r',xs[0,:],seq[0,:],'b--')
    # plt.show()
    # returned seq, res and xs:shape(batch,step,input)
    return [seq[:,:,np.newaxis],res[:,:,np.newaxis],xs]

# 定义LSTMRNN的主体结构
class LSTMRNN(object):
    # __init__作用:对类LSTMRNN的实例进行初始化
    def __init__(self,n_steps,input_size,output_size,cell_size,batch_size):
        # 设置步长
        self.n_steps = n_steps
        # 输入数据的维度
        self.input_size = input_size
        # 输出数据的维度
        self.output_size = output_size
        # 隐层LSTM的个数
        self.cell_size = cell_size
        # batch大小
        self.batch_size = batch_size
        # 定义输入输出数据变量
        with tf.name_scope("inputs"):
            self.xs = tf.placeholder(tf.float32,[None,n_steps,input_size],name="xs")
            self.ys = tf.placeholder(tf.float32,[None,n_steps,output_size],name="ys")
        # 定义输入层
        with tf.variable_scope("in_hidden"):
            self.add_input_layer()
        # 定义LSTM层
        with tf.variable_scope("LSTM_cell"):
            self.add_cell()
        # 定义输出层
        with tf.variable_scope("out_hidden"):
            self.add_output_layer()
        # 计算代价函数
        with tf.name_scope("cost"):
            self.compute_cost()
        with tf.name_scope("train"):
            self.train_op = tf.train.AdamOptimizer(LR).minimize(self.cost)

    def add_input_layer(self,):
        l_in_x = tf.reshape(self.xs,[-1,self.input_size],name="2_2D") # (batch*n_step,in_size)
        #  Ws (in_size,cell_size)
        Ws_in = self._weight_variable([self.input_size,self.cell_size])
        # bs(cell_size,)
        bs_in = self._bias_variable([self.cell_size,])
        # l_in_y = (batch * n_steps,cell_size)
        with tf.name_scope("Wx_plus_b"):
            l_in_y = tf.matmul(l_in_x,Ws_in) + bs_in
        # reshape l_in_y ==> (batch,n_steps,cell_size)
        self.l_in_y = tf.reshape(l_in_y,[-1,self.n_steps,self.cell_size],name="2_3D")

    def add_cell(self):
        # state_is_tuple=true保存长时记忆
        lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size,forget_bias=1.0,state_is_tuple=True)
        with tf.name_scope("initial_state"):
            self.cell_init_state = lstm_cell.zero_state(self.batch_size,dtype=tf.float32)
        self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(lstm_cell,self.l_in_y,initial_state=self.cell_init_state,time_major=False)

    def add_output_layer(self):
        # shape = (batch*steps,cell_size)
        l_out_x = tf.reshape(self.cell_outputs,[-1,self.cell_size],name="2_2D")
        Ws_out = self._weight_variable([self.cell_size,self.output_size])
        bs_out = self._bias_variable([self.output_size,])
        # shape = (batch * steps,output_size)
        with tf.name_scope("Wx_plus_b"):
            self.pred = tf.matmul(l_out_x,Ws_out) + bs_out

    def compute_cost(self):
        losses = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
            [tf.reshape(self.pred,[-1],name="reshape_pred")],
            [tf.reshape(self.ys,[-1],name="reshape_target")],
            [tf.ones([self.batch_size * self.n_steps],dtype=tf.float32)],
            average_across_timesteps = True,
            softmax_loss_function = self.ms_error,
            name = "losses"
        )
        with tf.name_scope("average_cost"):
            self.cost = tf.div(
                tf.reduce_sum(losses,name="losses_sum"),
                self.batch_size,
                name="average_cost"
            )
            tf.summary.scalar("cost",self.cost)

    def ms_error(self,y_target,y_pre):
        return tf.square(tf.sub(y_target,y_pre))

    def _weight_variable(self,shape,name="weights"):
        initializer = tf.random_normal_initializer(mean=0.,stddev=1.,)
        return tf.get_variable(shape=shape,initializer=initializer,name=name)

    def _bias_variable(self,shape,name="biases"):
        initializer = tf.constant_initializer(0.1)
        return tf.get_variable(name=name,shape=shape,initializer=initializer)

if __name__=="__main__":
    # 搭建LSTMRNN模型
    model = LSTMRNN(TIME_STEPS,INPUT_SIZE,OUTPUT_SIZE,CELL_SIZE,BATCH_SIZE)
    sess = tf.Session()
    merged = tf.summary.merge_all()
    writer = tf.summary.FileWriter("logs",sess.graph)
    sess.run(tf.global_variables_initializer())
    # relocate to the local dir and run this line to view it on Chrome (http://0.0.0.0:6006/):
    # $ tensorboard --logdir='logs'
    plt.ion()  # 设置连续plot
    plt.show()

    # 训练200次
    for i in range(200):
        seq,res,xs = get_batch() # 提取batch data
        if i == 0:
            # 初始化data
            feed_dic = {
                model.xs:seq,
                model.ys:res,
            }
        else:
            feed_dic = {
                model.xs: seq,
                model.ys: res,
                model.cell_init_state:state #保持state的连续性
            }
        # 训练
        _,cost,state,pred = sess.run(
            [model.train_op,model.cost,model.cell_final_state,model.pred],
           feed_dict=feed_dic)

        # plotting
        plt.plot(xs[0,:],res[0].flatten(),'r',xs[0,:],pred.flatten()[:TIME_STEPS],'b--')
        plt.ylim((-1.2,1.2))
        plt.draw()
        plt.pause(0.3) # 每0.3s刷新一次

        # 打印cost结果
        if i % 2 == 0:
            print("cost:",round(cost,4))
            result = sess.run(merged,feed_dic)
            writer.add_summary(result,i)

Reference:

【1】莫烦的视频:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-09-RNN3/

【2】莫烦的视频:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-10-RNN4/

【3】莫烦视频源码地址:https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf20_RNN2.2/full_code.py

【4】Tensorflow的BPTT形式理解:http://r2rt.com/styles-of-truncated-backpropagation.html

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐