2017-11-13 8 views
0

.할당 torch.cuda.FloatTensor 내가 다음 코드, <strong>을하지만 지금 pytorch, DTYPE = torch.cuda.FloatTensor</strong>를 사용하는 방법을 알고 싶습니다

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) 

마지막 부분 나는 인덱스 x의 값으로 변수 최선을 정의

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] 

이 그것을 할 내 시도는 다음과 같습니다 (NumPy와 사용) 코드 직선 파이썬이있다 indexmin과 동일합니다. 작동하지 않습니다. 내가 여기서 잘못하고있는 것은 무엇인가.

다음 messenge가 나타납니다

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

안녕하세요! 오류를 재현 할 수 없습니다. 나는 다른 pytorch 버전에있어, 그리고 그것은 잘 실행됩니다. 당신은'conda list | grep pytorch' 터미널에서? – cleros

+0

@cleros 고마워요! ** 죄송하지만 잘못된 코드 ** 수입 토치 DTYPE = torch.cuda.FloatTensor 데프 맞게 (x)를 게시 한 : 반환 X ** 2 데프 주() : 팝업 = 30 XMAX를 , xmin = 5, -5 x = (xmax-xmin) * torch.rand (pop, 1) .type (dtype) + xmin y = fit (x) [miny, indexmin] = torch.min , 0) 최고 = x [색인] 인쇄 (최고) 주() 이 오류는 저에게 오류 코드입니다. ** 2) ** grep pytorch를 실행하면 'grep'이 (가) 내부 또는 외부 명령 실행 가능 프로그램 또는 배치 파일로 인식되지 않습니다. – Johnny

답변

0

위의 코드는 pytorch 0.2에서 잘 작동합니다. 문제를 식별 할 수 있도록 코드를 분석하겠습니다. 여기

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

, xy 형상 30x1의 2D 텐서이다. 다음 줄에 :

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

반환 텐서 miny 모양 30x1의 2 차원 텐서이며 indexmin 크기 1의 1 차원 텐서이다. 그래서, 때 당신은 실행 : x 모양 30x1의 2 차원 텐서이며 indexmin 크기 1의 1 차원 텐서이기 때문에이 (아마도) (구 pytorch 버전) 오류를 제공

best = x[indexmin] 

. 이 오류를 해결하려면, 당신은 단순히 수행 할 수 있습니다

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

, 30x1 크기 30의 1 차원 텐서와 동일 형태의 2 차원 텐서을 유의하시기 바랍니다. 따라서 다음과 같이 프로그램을 수정할 수 있습니다.

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() 
+0

내 친구 너무 많이 고맙습니다! 그것은 작동합니다! – Johnny