python - 类型错误 : expected CPU (got CUDA)

标签 python pytorch gpu

import torch
torch.cuda.is_available()
torch.cuda.current_device()
torch.cuda.get_device_name(0)
torch.cuda.memory_reserved()
torch.cuda.memory_allocated()
torch.cuda.memory_allocated()
var1=torch.FloatTensor([1.0,2.0,3.0]).cuda()
var1
var1.device
import pandas as pd
df=pd.read_csv('diabetes.csv')
df.head()
df.isnull().sum()

import seaborn as sns
import numpy as np
df['Outcome']=np.where(df['Outcome']==1,"Diabetic","No Diabetic")
df.head()
sns.pairplot(df,hue="Outcome")
X=df.drop('Outcome',axis=1).values### independent features
y=df['Outcome'].values###dependent features
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)
y_train
进口火炬
将 torch.nn 导入为 nn
导入 torch.nn.functional 作为 F
X_train=torch.FloatTensor(X_train).cuda()
X_test=torch.FloatTensor(X_test).cuda()
y_train=torch.LongTensor(y_train).cuda()
y_test=torch.LongTensor(y_test).cuda()
当我运行此代码时,出现此错误:
Traceback (most recent call last):
  File "<stdin>", line 24, in <module>
TypeError: expected CPU (got CUDA)
我该如何解决这个错误?

最佳答案

要将变量传输到 GPU,请尝试以下操作:

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

X_train=torch.FloatTensor(X_train).to(device)
X_test=torch.FloatTensor(X_test).to(device)
y_train=torch.LongTensor(y_train).to(device)
y_test=torch.LongTensor(y_test).to(device)

关于python - 类型错误 : expected CPU (got CUDA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65679823/

相关文章:

python - 为什么在线性层之后使用 ReLu 激活时精度会降低

python - 为什么pytorch模型无法识别我定义的张量?

gpu - NVIDIA-SMI 失败,因为无法与 NVIDIA 驱动程序通信

python - 如何在每个月底运行 Celery 定期任务

python - 如何使用 Nose 抑制失败测试用例的痕迹?

python - 如何更新 zip 文件中的一个文件?

tensorflow - 更换gpu后我必须重新安装tensorflow吗?

python - 解析帝国时代游戏记录文件(.mgx)

tensorflow - 在强化学习中限制神经网络输出的最佳方法

image-processing - FFMPEG GPU 图像处理