python - ValueError:使用输入暗淡 1 的索引超出范围;输入对于 strided_slice 只有 1 个暗淡
问题描述
当我运行以下代码时
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>.
这是为什么?
解决方案
[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)
在“引用 tf.Tensor 切片”部分(有关张量的 TensorFlow 官方文章),您可以了解有关在 TensorFlow 中对张量进行索引和切片的更多信息。
推荐阅读
- java - 使用 docx4j 将可见背景图片设置为 docx 文档
- vb.net - 以给定的时间间隔获取两个日期之间的所有时间
- blockchain - 通过 rpc 从 Remix 连接到本地区块链时出错
- java - 如何检查Java中的While条件中是否有任何线程(CompletableFuture)未完成?
- android - 在 Android 中使用 Gson 从通知数据中解析嵌套的 JSON 数组
- c# - Expression.Call 嵌套函数
- c++ - 指向从多个基类继承的派生类的基指针
- swift - Swift - 视觉格式语言 - 如何制作多行和多列
- python - 无法获取解开地图上某些点的所有名称
- mongodb - 在 Spring Data 中消除编译类的歧义