当我运行以下代码时
import tensorflow as tf
def compute_area(sides):
a = sides[:, 0]
b = sides[:, 1]
c = sides[:, 2]
# Heron formula
s = (a + b + c) * 0.5
area_sq = s * (s - a) * (s - b) * (s - c)
return tf.sqrt(area_sq)
with tf.Session() as sess:
area = compute_area(tf.constant([5.0, 3.0, 7.1]))
result = sess.run(area)
print(result)
我收到以下错误
ValueError: Index out of range using input dim 1; input has only 1 dims for 'strided_slice' (op: 'StridedSlice') with input shapes: [3], [2], [2], [2] and with computed input tensors: input[3] = <1 1>.
那是为什么?
答案 0 :(得分:1)
[5.0, 3.0, 7.1]
是一个向量,它是一维张量。无法使用矩阵的语法对向量进行切片或索引,例如使用[:, 0]
,但要访问向量的第一个元素,您需要(简单地)使用[0]
。因此,您的代码将按以下方式工作
import tensorflow as tf
def compute_area(sides):
a, b, c = sides[0], sides[1], sides[2]
# Heron formula
s = (a + b + c) * 0.5
area_sq = s * (s - a) * (s - b) * (s - c)
return tf.sqrt(area_sq)
with tf.Session() as sess:
area = compute_area(tf.constant([5.0, 3.0, 7.1]))
result = sess.run(area)
print(result)
(在TensorFlow官方文章中有关张量的“ Referring to tf.Tensor slices ”部分中,您具有有关在TensorFlow中索引和切片张量的更多信息。