简体   繁体   English

PyTorch 线性回归模型

[英]PyTorch linear regression model

I have a multivariate linear regression problem in which each data point looks like this:我有一个多元线性回归问题,其中每个数据点如下所示:

y_i = 3                             # Some integer between 0 and 20
X_i = [0.5, 80, 0.004, 0.5, 0.789]  # A 5 dimensional vector

I can train a simple linear model by using sklearn, something like:我可以使用 sklearn 训练一个简单的线性模型,例如:

from sklearn import linear_model
ols = linear_model.LinearRegression()
model = ols.fit(X, y)

This gets me an accuracy of ~55 % (a linear model is not suitable for the problem, but this is a baseline to demonstrate the feasibility of modelling the problem, and a way for me to learn PyTorch, having use TensorFlow previously).这使我的准确率达到了约 55%(线性模型不适合该问题,但这是证明对问题建模的可行性的基线,也是我学习 PyTorch 的一种方式,之前使用过 TensorFlow)。

When I try to train a linear model using PyTorch I am defining the model as:当我尝试使用 PyTorch 训练线性模型时,我将模型定义为:

class TwoLayerNet(torch.nn.Module):
    def __init__(self, D_in, D_out):

        super(TwoLayerNet, self).__init__()
        self.linear1 = torch.nn.Linear(D_in, D_out)

    def forward(self, x):

        y_pred = self.linear1(x)
        return y_pred

D_in, D_out = 5, 1
model = TwoLayerNet(D_in, D_out)

And training as:并训练为:

epochs = 10
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
for epoch in range(epochs):
    for n, batch in enumerate(batches):
        X = []
        y = []
        for values in batch:
            X.append(values[0])
            y.append(values[1])
        
        X = torch.from_numpy(np.asarray(X))
        y = torch.from_numpy(np.asarray(y))
        # Forward pass: Compute predicted y by passing x to the model
        optimizer.zero_grad()
        y_pred = model(X)
        # Compute and print loss
        loss = criterion(y_pred, y)
        if n % 100 == 99:
            print(n, loss.item())

        # Zero gradients, perform a backward pass, and update the weights.
        
        loss.backward()
        optimizer.step()

This is just some code from the PyTorch documentation which I have adjusted.这只是我调整过的 PyTorch 文档中的一些代码。 The current set up only achieves ~25%, no where near the accuracy that I would expect from the linear model.当前设置仅达到约 25%,远不及我对线性模型所期望的准确度。 Am I doing something incorrect in the model training wrt PyTorch?我在 PyTorch 的模型训练中做错了什么吗?

tam63, tam63,

you are missing activation function in the model definition.您在模型定义中缺少激活函数。 replace代替

y_pred = self.linear1(x)

with

y_pred =  F.relu(self.linear1(x))

there are few more things that may go wrong.还有一些事情可能会出错。 For instance (1) too low a learning rate, (2) too few layers (add one more).例如(1)学习率太低,(2)层太少(多加一层)。 If you are familiar with TF as you say, try same problem in TF and once you have good results - translate it into Pytorch with same network structure and same hyperparameters.如果你像你说的那样熟悉 TF,在 TF 中尝试同样的问题,一旦你有好的结果 - 将它转换成具有相同网络结构和相同超参数的 Pytorch。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM