首页 > 解决方案 > 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>.

这是为什么?

标签: pythontensorflow

解决方案


[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 中对张量进行索引和切片的更多信息。


推荐阅读