【问题标题】:Assign torch.cuda.FloatTensor分配 torch.cuda.FloatTensor
【发布时间】:2023-04-10 23:37:02
【问题描述】:

我想知道如何执行以下代码,但现在使用 pytorch, 其中 dtype = torch.cuda.FloatTensor。有代码直接python(使用numpy):

import numpy as np
import random as rand
xmax, xmin = 5, -5
pop = 30
x = (xmax-xmin)*rand.random(pop,1)
y = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)  
best = x[indexmin]

这是我的尝试:

import torch
dtype = torch.cuda.FloatTensor 
def fit (position):
    return  position**2
def main():
    pop = 30
    xmax, xmin = 5, -5
    x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best = x[indexmin]
    print(best)  

我将变量最好定义为索引等于 indexmin 的 x 值的最后一部分不起作用。我在这里做错了什么。

出现以下消息:

RuntimeError: expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405

【问题讨论】:

  • 嘿!我无法重现该错误。我在另一个 pytorch 版本上,它运行得很好。你能从终端运行conda list | grep pytorch 吗?
  • @cleros 谢谢! 抱歉,我发布了错误的代码 import torch dtype = torch.cuda.FloatTensor def fit (x): return x2 def main(): pop = 30 xmax, xmin = 5 , -5 x = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin y = fit(x) [miny, indexmin] = torch.min(y,0) best = x[ indexmin] print(best) main() 这是给我错误的代码。 **2) 当我运行 grep pytorch 时:'grep' 不被识别为内部或外部命令、可运行程序或批处理文件。

标签: numpy gpu pytorch


【解决方案1】:

以上代码在 pytorch 0.2 中运行良好。让我分析您的代码,以便您找出问题所在。

x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
y = fit(x)

这里,xy 是形状为 30x1 的二维张量。在下一行:

[miny, indexmin] = torch.min(y,0)

返回的张量miny 是一个形状为30x1 的二维张量,indexmin 是一个大小为1 的一维张量。所以,当你执行时:

best = x[indexmin]

它(可能)给出错误(在旧的 pytorch 版本中)因为x 是形状为30x1 的二维张量,而indexmin 是大小为1 的一维张量。要解决此错误,您只需执行以下操作:

best = x.squeeze()[indexmin] # x.squeeze() returns a 1d tensor of size `30`

请注意,形状为30x1 的二维张量与大小为30 的一维张量相同。所以,你可以如下修改你的程序。

import torch
dtype = torch.cuda.FloatTensor 
def main():
    pop, xmax, xmin = 30, 5, -5
    x= (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y = torch.pow(x, 2)
    minz, indexmin = y.min(0)
    best = x[indexmin]
    print(best)

main()

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-07-18
    相关资源
    最近更新 更多