【问题标题】:TypeError:预期的 CPU(得到 CUDA)
【发布时间】:2021-04-17 03:51:45
【问题描述】:
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)

我该如何解决这个错误?

【问题讨论】:

  • ##### 创建张量 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()
  • 请阅读如何create a minimal reproducible examplehow to ask 并使用edit 按钮来改进您的帖子。
  • 错误是:>>> X_train=torch.FloatTensor(X_train).cuda() Traceback(最近一次调用最后):文件“”,第 1 行,在 类型错误:预期的 CPU(得到 CUDA)
  • @VinothKumarS,你的 m/c 有 GPU 吗?您是否使用混合 CPU/GPU 类型执行任何操作?是pytorch GPU版本吗?显示完整的错误信息!
  • @anurag 是的,我的机器的 GPU 是 RTX 3070,它是 PyTorch GPU 版本。

标签: python pytorch gpu


【解决方案1】:

要将变量传输到 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)

【讨论】:

  • cuda:0 - 在此处将 0 更改为所需的 GPU 索引(如果您有多个 GPU)
  • 非常感谢先生!它现在可以工作了,你能解释一下为什么我们需要使用它吗?
  • 我不确定您的代码为什么不起作用,但是,根据here 的讨论,应该没有任何区别!另外,如果这解决了您的问题,请点赞/接受!
猜你喜欢
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
相关资源
最近更新 更多