如何将形状张量(36,)转换为(1,36)

2024-04-24 23:52:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对numpy还不熟悉,希望有人能帮我。你知道吗

代码是:

x = tf.placeholder(tf.float32 , [1 , 36])
# L is a list from a list of lists.
sess.run(rnn_model , {x : L})

错误是:

ValueError: Cannot feed value of shape (36,) for Tensor 'Placeholder:0', which has shape '(1, 36)'

我认为这是因为L是2D列表中的一个列表,python认为L必须是一个列列表。你知道吗

如何解决错误?你知道吗


Tags: ofrun代码fromnumpy列表istf
3条回答

您可以使用numpy来重塑list L,然后使用tf.convert_to_tensor()。你知道吗

示例

import numpy as np
import tensorflow as tf
print(tf.__version__)
print(np.__version__)

L = [i for i in range(36)]
La = np.array(L).reshape((1,len(L))).astype(np.float32)
Lt = tf.convert_to_tensor(La)
print(y)

输出

1.15.0
1.17.3
Tensor("Const_7:0", shape=(1, 36), dtype=float32)

您可以通过在所需位置使用None来使用花式索引来添加尺寸为1的额外维度。你知道吗

L[None, :]

或者

np.array(L)[None, :]

如果我不是一个疯子。你知道吗

可以使用np.expand_dims()将列表转换为列向量,如下所示:

sess.run(rnn_model , {x : np.expand_dims(L, axis=0)})

相关问题 更多 >