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

2022-11-02 15:14:39 浏览数 (1)

运行程序如下:

代码语言:javascript复制
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()

代码语言:javascript复制
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()即可

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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180596.html原文链接:https://javaforall.cn

0 人点赞