Python 如何在pytorch中包含一个属性,让用户决定是否使用GPU?
我是Python和pytorch的初学者,我为没有说清楚或没有使用正确的术语而道歉 我正在尝试编写一个线性回归类,它允许用户决定是否要在GPU上运行模型 以下是我用一种相当愚蠢的方式编写的代码Python 如何在pytorch中包含一个属性,让用户决定是否使用GPU?,python,class,pytorch,gpu,Python,Class,Pytorch,Gpu,我是Python和pytorch的初学者,我为没有说清楚或没有使用正确的术语而道歉 我正在尝试编写一个线性回归类,它允许用户决定是否要在GPU上运行模型 以下是我用一种相当愚蠢的方式编写的代码 class LinearRegression(): def __init__(self, dtype = torch.float64): self.dtype = dtype self.bias = None self.weight = None
class LinearRegression():
def __init__(self, dtype = torch.float64):
self.dtype = dtype
self.bias = None
self.weight = None
def fit(self, x, y, std = None, device = "cuda"):
if x.dtype is not self.dtype:
x = x.type(dtype = self.dtype)
if y.dtype is not self.dtype:
y = y.type(dtype = self.dtype)
#let the user decide whether they want it to be standardized
if std == True:
mean = torch.mean(input = x, dim=0).to(device)
sd = torch.std(input = x, dim=0).to(device)
x = x.to(device)
x = (x-mean)/sd
u = torch.ones(size = (x.size()[0], 1), dtype = self.dtype).to(device)
x_design = torch.cat([u, x], dim = 1).to(device)
y = y.to(device)
parameter = torch.inverse(
torch.transpose(x_design, dim0=0, dim1=1) @ x_design).to(device) @ \
torch.transpose(x_design, dim0=0, dim1=1).to(device) @ y
self.bias = parameter[0, 0]
self.weight = parameter[1:, 0]
return self
基本上,我只是在每个张量中添加了.to(device),以便在用户希望使用的设备上运行它。
但是,我相信有更好的方法可以做到这一点,也许在\uuu int\uuu
中包含一些内容
我不知道如何更有效地编写它,这样我就不必在任何时候添加新函数时都包含.to(设备)