TypeError: can‘t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory fi

TypeError: can‘t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory fiRuntimeError:Expectedobjectoftypetorch.cuda.FloatTensorbutfoundtypetorch.FloatTensorforargument#4’mat1’意思是:如果想把CUDAtensor格式的数据改成numpy时,需要先将其转换成cpufloat-tensor随后再转到numpy格式。numpy不能读取CU…

运行程序如下:

import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import matplotlib.pyplot as plt


class LinearRegression(nn.Module):
    def __init__(self):
        super(LinearRegression,self).__init__()
        self.linear = nn.Linear(1,1)
    def forward(self, x):
        out = self.linear(x)
        return out
x_train = np.array([[3.3],[4.4],[5.5],[6.710],[6.93],[4.168],[9.779],[6.182],[7.59],[2.167],[7.042],[10.791],[5.313],[7.997],[3.1]],dtype=np.float32)
y_train = np.array([[1.7],[2.76],[2.09],[3.19],[1.694],[1.573],[3.366],[2.596],[2.53],[1.221],[2.827],[3.465],[1.65],[2.904],[1.3]],dtype=np.float32)
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
num_epochs = 1000
if torch.cuda.is_available():
    print("GPU1")
    model = LinearRegression().cuda()
else:
    print("CPU1")
    model = LinearRegression()

criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=1e-3)


for epoch in  range(num_epochs):
    if torch.cuda.is_available():
        print('GPU2')
        inputs = Variable(x_train).cuda()
        target = Variable(y_train).cuda()
    else:
        print("CPU2")
        inputs = Variable(x_train)
        target = Variable(y_train)
    # forward
    out = model(inputs)
    loss = criterion(out,target)
    # backward
    optimizer.zero_grad()  # 梯度归零
    loss.backward()   # 反向传播
    optimizer.step()  # 更新参数
    # if (epoch+1) % 20 ==0:
    #     print('Epoch[{}/{}], loss:{:,6f}'.format(epoch+1,num_epochs,loss.data[0]))


model.eval()

predict = model(Variable(x_train.cuda()))  
predict = predict.data.numpy()
plt.plot(x_train.numpy(),y_train.numpy(),'ro',label='Original data')
plt.plot(x_train.numpy(),predict,label='Fitting Line')
plt.show()

这行报错:predict = predict.data.numpy()

TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

意思是:如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式。 numpy不能读取CUDA tensor 需要将它转化为 CPU tensor
predict.data.numpy() 改为predict.data.cpu().numpy()即可

今天的文章TypeError: can‘t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory fi分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/11099.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注