我希望您能够为回归构建一个玩具LSTM模型。这篇优秀的教程对于初学者来说已经太复杂了。
给定长度为
目标值应该是:
我们使用
给定长度为
time_steps
的序列,预测下一个值。考虑time_steps=3
和以下序列:array([
[[ 1.],
[ 2.],
[ 3.]],
[[ 2.],
[ 3.],
[ 4.]],
...
目标值应该是:
array([ 4., 5., ...
I define the following model:
# Network Parameters
time_steps = 3
num_neurons= 64 #(arbitrary)
n_features = 1
# tf Graph input
x = tf.placeholder("float", [None, time_steps, n_features])
y = tf.placeholder("float", [None, 1])
# Define weights
weights = {
'out': tf.Variable(tf.random_normal([n_hidden, 1]))
}
biases = {
'out': tf.Variable(tf.random_normal([1]))
}
#LSTM model
def lstm_model(X, weights, biases, learning_rate=0.01, optimizer='Adagrad'):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, time_steps, n_features)
# Required shape: 'time_steps' tensors list of shape (batch_size, n_features)
# Permuting batch_size and time_steps
input dimension: Tensor("Placeholder_:0", shape=(?, 3, 1), dtype=float32)
X = tf.transpose(X, [1, 0, 2])
transposed dimension: Tensor("transpose_41:0", shape=(3, ?, 1), dtype=float32)
# Reshaping to (time_steps*batch_size, n_features)
X = tf.reshape(X, [-1, n_features])
reshaped dimension: Tensor("Reshape_:0", shape=(?, 1), dtype=float32)
# Split to get a list of 'time_steps' tensors of shape (batch_size, n_features)
X = tf.split(0, time_steps, X)
splitted dimension: [<tf.Tensor 'split_:0' shape=(?, 1) dtype=float32>, <tf.Tensor 'split_:1' shape=(?, 1) dtype=float32>, <tf.Tensor 'split_:2' shape=(?, 1) dtype=float32>]
# LSTM cell
cell = tf.nn.rnn_cell.LSTMCell(num_neurons) #Or GRUCell(num_neurons)
output, state = tf.nn.dynamic_rnn(cell=cell, inputs=X, dtype=tf.float32)
output = tf.transpose(output, [1, 0, 2])
last = tf.gather(output, int(output.get_shape()[0]) - 1)
return tf.matmul(last, weights['out']) + biases['out']
我们使用
pred = lstm_model(x, weights, biases)
来实例化LSTM模型,得到以下结果:---> output, state = tf.nn.dynamic_rnn(cell=cell, inputs=X, dtype=tf.float32)
ValueError: Dimension must be 2 but is 3 for 'transpose_42' (op: 'Transpose') with input shapes: [?,1], [3]
1) 你知道问题是什么吗?
2) 把LSTM输出乘以权重会得到回归结果吗?
tf.transpose()
操作,但是维度置换(第二个参数)有三个值。我猜它来自于这一行,问题在于tf.nn.dynamic_rnn()
期望所有时间步都被打包到单个张量中。尝试删除tf.split()
并将原始的X
值传递给tf.nn.dynamic_rnn()
。 - mrrytime_steps
二维张量列表,但正确的输入应该是单个三维张量(而第一维应该是batch_size
而不是time_steps
,因此转置也不必要)。 - mrryn_output
xtarget_features
的矩阵,但我想这可能是一个 1x1 的矩阵,并且相当于使用标量进行tf.multiply()
运算,对吗? - mrry