我正在尝试将一维稀疏向量传递给Tensorflow:
import tensorflow as tf
import numpy as np
x = tf.sparse_placeholder(tf.float32)
y = tf.sparse_reduce_sum(x)
with tf.Session() as sess:
indices = np.array([0, 1], dtype=np.int64)
values = np.array([1.5, 3.0], dtype=np.float32)
shape = np.array([2], dtype=np.int64)
print(sess.run(y, feed_dict={
x: tf.SparseTensorValue(indices, values, shape)}))
此代码抛出以下错误:
ValueError: Cannot feed value of shape (2,) for Tensor u'Placeholder_2:0', which has shape '(?, ?)'
我的形状错了吗?
答案 0 :(得分:1)
指数的大小应为(2,1)
。因此,将索引更改为:indices = np.array([[0], [1]], dtype=np.int64)
。以下代码有效:
x = tf.sparse_placeholder(tf.float32)
y = tf.sparse_reduce_sum(x)
with tf.Session() as sess:
indices = np.array([[0], [1]], dtype=np.int64)
values = np.array([1.5, 3.0], dtype=np.float32)
shape = np.array([2], dtype=np.int64)
print(sess.run(y, feed_dict={
x: tf.SparseTensorValue(indices, values, shape)}))
#Output
#4.5