类型错误:只有单个元素的整数张量才能转换为索引

问题描述 投票:0回答:2
n_inc = torch.tensor(1)
theta = torch.tensor(0.6109)
phi = torch.tensor(0)
k0 = torch.tensor(6.2832)


kinc = k0*n_inc*[torch.sin(theta)*torch.cos(phi),
                 torch.sin(theta)*torch.sin(phi), 
                 torch.cos(theta)]
print(kinc)

当我运行代码时,它显示以下错误消息-

TypeError:只能转换单个元素的整数张量 到索引

谁能帮我解决这个问题?

感谢@Hamza 指出错误。该代码正在使用

Numpy
运行。还没有找到任何直接的方法来做到这一点
PyTorch

'''

import numpy as np
import torch

theta = 0.6109
phi = 0.0
k0 = 6.2832
n_inc = 1.0

kinc = k0*n_inc*np.array([np.sin(theta)*np.cos(phi), 
                          np.sin(theta)*np.sin(phi), 
                          np.cos(theta)])
kinc = torch.tensor(kinc)
print(kinc)

'''

python python-3.x pytorch
2个回答
0
投票

假设您知道,当您将一个列表与一个数字相乘时,该列表会以与该数字相等的时间重复。这个数字应该是整数,否则你会得到你的错误:

torch.tensor(0.6109)*[torch.sin(theta)*torch.cos(phi), #<--- it throws an error
                 torch.sin(theta)*torch.sin(phi), 
                 torch.cos(theta)]

如果要重复列表,只需将列表与整数张量相乘,而不是浮点张量。

如果要将整数张量乘以列表中的每个元素。您应该只将列表转换为 NumPy 数组:

kinc = k0*n_inc*np.array([torch.sin(theta)*torch.cos(phi), #<- NumPy array not a list
                 torch.sin(theta)*torch.sin(phi), 
                 torch.cos(theta)])

您不需要将 sin 和 cos 转换为 NumPy 类型。


0
投票

使用

torch.stack([np.sin(theta)*np.cos(phi),
                 np.sin(theta)*np.sin(phi), 
                 np.cos(theta)], dim= 0)

直接将 Torch Tensor 列表堆叠到新的 Torch Tensor。

© www.soinside.com 2019 - 2024. All rights reserved.