Tensorflow--正弦序列预测

来源:互联网 发布:windows android 编辑:程序博客网 时间:2024/05/16 04:58

Tensorflow对RNN模型的基础结构单元RNN单元和LSTM模型的基础结构单元LSTM单元提供了实现和封装,使用Tensorflow可以轻松的实现一个序列预测模型。
在这里以正弦序列预测为例学习.
运行环境是ubuntu14.04+tensorflow0.10+python2.7.
详细注释过程见代码

#coding=utf-8#Tensorflow实现正弦序列预测import randomimport numpy as nplength=10   #正弦序列长度为10def build_data(n):  #构造2000个序列长度为n的正弦序列,前1500个作为训练集,后500个作为测试集    xs=[]    ys=[]    for i in range(2000):        k=random.uniform(1,50)        x=[[np.sin(k+j)] for j in range(0,n)]        y=[np.sin(k+n)]        xs.append(x)        ys.append(y)    train_x=np.array(xs[0:1500])    train_y=np.array(ys[0:1500])    test_x=np.array(xs[1500:])    test_y=np.array(ys[1500:])    return train_x,train_y,test_x,test_ytrain_x,train_y,test_x,test_y=build_data(length)print train_x.shape,train_y.shape,test_x.shape,test_y.shapeimport tensorflow as tftime_step_size=lengthvector_size=1batch_size=10test_size=10#使用placeholder声明输入占位符,第一个维度是batch_size,None表示任意,从第二个维度开始才是特征维度X=tf.placeholder("float",[None,length,vector_size]) #[batch_size,time_step_size,vector_size]Y=tf.placeholder("float",[None,1])#声明参数变量W=tf.Variable(tf.random_normal([10,1],stddev=0.01)) #随机正态分布tensorB=tf.Variable(tf.random_normal([1],stddev=0.01))#构建RNN和LSTM计算图def seq_predict_model(X,w,b,time_step_size,vector_size):    X=tf.transpose(X,[1,0,2]) #[time_step_size,batch_size,vector_size]    X=tf.reshape(X,[-1,vector_size]) #[time_step_size*batch_size,vector_size]    X=tf.split(0,time_step_size,X)  #把X分为time_step份,array[time_step],[batch_size,vector_size]    #RNN    cell=tf.nn.rnn_cell.BasicRNNCell(num_units=10)    initial_state=tf.zeros([batch_size,cell.state_size])    outputs,_states=tf.nn.rnn(cell,X,initial_state=initial_state)    #LSTM    # cell=tf.nn.rnn_cell.BasicLSTMCell(num_units=10,forget_bias=1.0,state_is_tuple=True)    # outputs,_states=tf.nn.rnn(cell,X,dtype=tf.float32)    return tf.matmul(outputs[-1],w)+b,cell.state_sizepred_y,_=seq_predict_model(X,W,B,time_step_size,vector_size)#声明代价函数loss=tf.square(tf.sub(Y,pred_y))#加入优化算法train_op=tf.train.GradientDescentOptimizer(0.001).minimize(loss)    #梯度下降算法#构造训练迭代过程并预测测试数据结果with tf.Session() as sess:    #初始化所有变量,必须最先执行    tf.initialize_all_variables().run()    #以下为训练迭代,迭代50轮    for i in range(50):        for end in range(batch_size,len(train_x),batch_size):            begin=end-batch_size            x_value=train_x[begin:end]            y_value=train_y[begin:end]            #通过session.run接口触发执行            sess.run(train_op,feed_dict={X:x_value,Y:y_value})            test_indices=np.arange(len(test_x)) #在训练的过程中开始测试            np.random.shuffle(test_indices)            test_indices=test_indices[0:test_size]            x_value=test_x[test_indices]            y_value=test_y[test_indices]            val_loss=np.mean(sess.run(loss,feed_dict={X:x_value,Y:y_value}))    #使用均方差作为代价函数            print 'Run %s'%i,val_loss

小结:第一次接触tensorflow,在python也不熟悉的情况下,通过一个简单的例子了解一下使用tensorflow进行深度学习的过程,为之后的项目和研究打基础。

阅读全文
0 0
原创粉丝点击