Why does the following PyTorch linear regression model only seem to fit the intercept…
Jump to turn (6)
- 1Why does the following PyTorch linear regression model only seem to fit the inte
- 2I tried those suggestions... You don't think it's a simple issue in my code some
- 3Hmm... so the input is already toy data, including fully below: X, y = datasets.
- 4Thank you! The main issue was lack of .view(-1) in loss = criterion(ypred.view(-
- 5So shapes were: ypred.shape,ytrain.shape torch.Size([80, 1]) torch.Size([80]). W
- 6This is still a bit odd... It looks like we converted ytrain to the same shape a
- User
Why does the following PyTorch linear regression model only seem to fit the intercept and how to correct it? import torch.nn as nn class LinearRegressionTorch(nn.Module): """Can use torch.autograd automatic differentiation for gradient updates""" def init(self, input_dim, output_dim=1): super().init() self.linear = nn.Linear(input_dim,output_dim)
codedef forward(self, X): return self.linear(X)model = LinearRegressionTorch(input_dim=X.shape[1])
Training loop
n_iters = 1000 criterion = nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr = 0.01) for _ in range(n_iters): y_pred = model(X) loss = criterion(y_pred,y_train) loss.backward() optimizer.step() optimizer.zero_grad()
with torch.no_grad(): predictions = model(X_test) print("predictions: ") print(predictions)
mse = mean_squared_error(y_test, predictions) print("MSE:", mse)
accu = r2_score(y_test, predictions) print("Accuracy:", accu) with torch.no_grad(): y_pred_line = model(X).detach().numpy() cmap = plt.get_cmap("viridis") fig = plt.figure(figsize=(8, 6)) m1 = plt.scatter(X_train.detach().numpy(), y_train.detach().numpy(), color=cmap(0.9), s=10) m2 = plt.scatter(X_test.detach().numpy(), y_test.detach().numpy(), color=cmap(0.5), s=10) plt.plot(X.detach().numpy(), y_pred_line, color="black", linewidth=2, label="Prediction") plt.show()