import tensorflow as tf
import numpy as np
n_steps = 2 # 2个步长
n_input = 3 # 每步的输入维度是3
n_batch_size = 2 # 批次大小是2
# 两个样本的特征,2个步长,每步的输入维度是3
# 所提特征
feature = np.array([[1,2,3,4,5,6],[1,2,3,4,5,6]])
print feature
print feature.shape
# 变形是为了和下面tensorflow中的变量对应
refeature = feature.reshape(2,2,3)
print refeature
# 在tensorflow中定义的输入变量,用来接收数据,
# None不定的样本数据 n_steps个步长 n_input样本输入长度
x = tf.placeholder("float", [None, n_steps, n_input])
# 下面是2种方法,对样本特征数据,输入LSTM中
#'---------第1种方法:3个语句---------'
m = tf.transpose(x, [1, 0, 2])
n = tf.reshape(m, [-1, n_input])
p = tf.split(n, n_steps)
#'---------第2种方法:1个语句---------'
r = tf.unstack(x, n_steps, 1)
#'---------第3种方法:1个语句---------'
input3 = tf.unstack(tf.transpose(x, [1,0,2]))
sess = tf.InteractiveSession()
s = sess.run(p, feed_dict={x: refeature})
print '---------第1种方法:3个语句---------'
print s
t = sess.run(r, feed_dict={x: refeature})
print '---------第2种方法:1个语句---------'
print t
t3 = sess.run(input3, feed_dict={x: refeature})
print '---------第3种方法:1个语句---------'
print t3
解释:
第1步:原始特征:两个样本的特征值如下,代表是:批次大小是2,步长为2,则每步的输入值是3
[[1 2 3 4 5 6]
[1 2 3 4 5 6]]
第2步:变形,目的是为了和tensorflow定义的变量对应
代表:2个样本,每个样本2步,每一步的输入维度为3
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
第3步:按批次 一步一步送入LSTM,是向量
变形,向量中,第1个数据代表 该批次中所有样本的第1步,
第2个数据代表 该批次中所有样本的第2步,
[array([[ 1., 2., 3.],
[ 1., 2., 3.]], dtype=float32), array([[ 4., 5., 6.],
[ 4., 5., 6.]], dtype=float32)]