基于深层RNN的光谱分类问题研究
·
前言
RNN有多种形式,LSTM,GRU等等,这是在RNN每一个基本结构中改变RNN的形式,目前还有两种通过叠加RNN的层数来对数据进行分析的,如双向RNN和深层RNN,其中双向RNN,是认为转入数据与之前和之后的传入数据是相关的,深层RNN是针对于浅层RNN不等很好的提取数据中的抽象特征所提出的。
笔者最近在研究语音识别方向,简单的尝试了ctc与LSTM的结合,但是语音数据较少,笔者之前一直研究光谱分析方向,所以采用了深层RNN来对光谱数据进行分析。
深层RNN

如图所示这是一个摘自《TensorFlow 实战Google深度学习框架》的深层RNN的基本结构,从这幅图中可以看出深层RNN在纵向加深了网络,使之可以提取出更加抽象的特征。
代码实现
1 数据的读取
这一部分就不讲了,因为在前面的几篇博客中都有涉及。
2 网络搭建
def RNN(x,weights,biases):
lstm_cell=rnn.BasicLSTMCell
cell=tf.nn.rnn_cell.MultiRNNCell([lstm_cell(n_hidden) for _ in range(3)])
outputs,_=tf.nn.dynamic_rnn(cell,x,dtype=tf.float32)
return tf.matmul(outputs[:,-1,:],weights['out'])+biases['out']
这是一个非常简单的三层RNN
rnn.BasicLSTMCell的意思建立一个LSTM的基本单元
tf.nn.rnn_cell.MultiRNNCell相当于定义每一个隐藏层中多少个(n_hidden)LSTM的基本结构
tf.nn.dynamic_rnn他输出的结果维度是[batch_size,time,hidden_size]我们只关注最后的输出结果,outputs[:,-1,:],这一列。
完整代码
import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
matix=np.loadtxt("D:/深度学习/all_feature/15—class_label15_train80.txt")
matix1=np.loadtxt("D:/深度学习/all_feature/15—class_label15_test40.txt")
matix_3=matix.reshape(1200,1,1030)
matix1_3=matix1.reshape(631,1,1030)
print(matix1.shape)
training_rate=0.001
training_iters=100000
batch_size=128
display_step=10
n_input=1015
n_steps=1
n_hidden=128
n_classes=15
x=tf.placeholder("float",[None,n_steps,n_input])
y=tf.placeholder("float",[None,n_classes])
weights={'out':tf.Variable(tf.random_normal([n_hidden,n_classes]))}
biases={'out':tf.Variable(tf.random_normal([n_classes]))}
def RNN(x,weights,biases):
lstm_cell=rnn.BasicLSTMCell
cell=tf.nn.rnn_cell.MultiRNNCell([lstm_cell(n_hidden) for _ in range(3)])
outputs,_=tf.nn.dynamic_rnn(cell,x,dtype=tf.float32)
return tf.matmul(outputs[:,-1,:],weights['out'])+biases['out']
pred=RNN(x,weights,biases)
cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))
optimizer=tf.train.AdamOptimizer(learning_rate=training_rate).minimize(cost)
correct_pred=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuaracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
step=1
while step*batch_size<training_iters:
batch_x,batch_y=matix_3[:,:,:1015],matix[:,1015:]
sess.run(optimizer,feed_dict={x:batch_x,y:batch_y})
if step%display_step==0:
acc=sess.run(accuaracy,feed_dict={x:matix1_3[:,:,:1015],y:matix1[:,1015:]})
loss = sess.run(cost, feed_dict={x:matix1_3[:,:,:1015],y:matix1[:,1015:]})
print("Iter " + str(step * batch_size) + ", Raman Loss= " + \
"{:.6f}".format(loss) + ", Testing Accuracy= " + \
"{:.5f}".format(acc))
step+=1
更多推荐



所有评论(0)