6 python numpy list multidimensional-array tensorflow
这些帖子实际上有成千上万,但我还没有看到一个解决我确切问题的帖子.如果存在,请随时关闭.
我知道列表在Python中是可变的.因此,我们无法将列表存储为字典中的键.
我有以下代码(因为它无关紧要而遗漏了大量的代码):
with tf.Session() as sess:
sess.run(init)
step = 1
while step * batch_size < training_iterations:
for batch_x, batch_y in batch(train_x, train_y, batch_size):
batch_x = np.reshape(batch_x, (batch_x.shape[0],
1,
batch_x.shape[1]))
batch_x.astype(np.float32)
batch_y = np.reshape(batch_y, (batch_y.shape[0], 1))
batch_y.astype(np.float32)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
if step % display_step == 0:
# Calculate batch accuracy
acc = sess.run(accuracy,
feed_dict={x: batch_x, y: batch_y})
# Calculate batch loss
loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
print("Iter " + str(step*batch_size) +
", Minibatch Loss= " +
"{:.6f}".format(loss) + ", Training Accuracy= " +
"{:.5f}".format(acc))
step += 1
print("Optimization Finished!")
Run Code Online (Sandbox Code Playgroud)
train_x
是一个[batch_size, num_features]
numpy矩阵
train_y
是一个[batch_size, num_results]
numpy矩阵
我的图表中有以下占位符:
x = tf.placeholder(tf.float32, shape=(None, num_steps, num_input))
y = tf.placeholder(tf.float32, shape=(None, num_res))
Run Code Online (Sandbox Code Playgroud)
所以很自然地我需要转换我的train_x
并train_y
获得tensorflow期望的正确格式.
我这样做有以下几点:
batch_x = np.reshape(batch_x, (batch_x.shape[0],
1,
batch_x.shape[1]))
batch_y = np.reshape(batch_y, (batch_y.shape[0], 1))
Run Code Online (Sandbox Code Playgroud)
这个结果给了我两个numpy.ndarray
:
batch_x
尺寸[batch_size, timesteps, features]
batch_y
是尺寸的[batch_size, num_results]
如图所示.
现在,当我通过这些重新塑造时,numpy.ndarray
我得到TypeError: Unhashable type list
以下一行:
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
Run Code Online (Sandbox Code Playgroud)
这对我来说很奇怪,因为启动python:
import numpy as np
a = np.zeros((10,3,4))
{a : 'test'}
TypeError: unhashable type: 'numpy.ndarray`
Run Code Online (Sandbox Code Playgroud)
您可以看到我收到完全不同的错误消息.
在我的代码中,我对数据执行了一系列转换:
x = tf.transpose(x, [1, 0, 2])
x = tf.reshape(x, [-1, num_input])
x = tf.split(0, num_steps, x)
lstm_cell = rnn_cell.BasicLSTMCell(num_hidden, forget_bias=forget_bias)
outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)
列表出现的唯一位置是切片后,这会产生一个T
大小的张量列表rnn.rnn
.
我在这里完全失败了.我觉得我正盯着解决方案,我看不到它.有人可以帮我从这里出去吗?
谢谢!
小智 8
我觉得这里有点傻,但我相信别人会有这个问题.
上面的行tf.split
是列表中的结果是问题.
我没有将它们分成单独的函数,并直接修改x(如我的代码所示),并且从未更改过名称.因此,当代码运行时sess.run
,x不再是预期的张量占位符,而是图形中转换后的张量列表.
重命名每个转换x
解决了问题.
我希望这可以帮助别人.