A linear layer does not converge to the analytical solution

username: somnambWl
cooked: <p>Hello,</p>
<p>as far as I know, a single linear layer with a single output neuron should work completely the same as linear regression. I am trying to achieve this, but I had no success so far.</p>
<p>I have the following code for initialization and data loading:</p>
<pre><code class="lang-auto">import h5py
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
import numpy as np
import torch

torch.set_default_tensor_type('torch.DoubleTensor')

filename = '../kernels/A600-1.h5'

f = h5py.File(filename, 'r')
X_train = f['kernels/train_kernel'][:,:]
y_train = f['vectors/train_vector'][:]
X_test = f['kernels/test_kernel'][:,:]
y_test = f['vectors/test_vector'][:]
f.close()
</code></pre>
<p>Then I compute linear regression results with the following code:</p>
<pre><code class="lang-auto">lin_model = LinearRegression(fit_intercept=False)
lin_model.fit(X_train, y_train)
y_predicted = lin_model.predict(X_test)
error = mean_absolute_error(y_test, y_predicted)
print(error)
</code></pre>
<p>For learning with PyTorch Linear layer I use this code:</p>
<pre><code class="lang-auto">X2_train = torch.Tensor(X_train).double()
y2_train = torch.Tensor(y_train.reshape(-1,1)).double()
X2_test = torch.Tensor(X_test).double()
y2_test = torch.Tensor(y_test.reshape(-1,1)).double()
model = torch.nn.Linear(600, 1, bias=False)
model.double()
criterion = torch.nn.MSELoss(reduction='elementwise_mean')
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# optimizer = torch.optim.SGD(model.parameters(), lr=1e-8)
model.train()        
for epoch in range(int(1e6)):
    optimizer.zero_grad()   # Reset gradients
    model.zero_grad()   # Just to be sure
    y_predicted = model(X2_train)   # Forward pass: predict
    loss = criterion(y_predicted, y2_train)   # Forward pass: calculate the loss
    loss.backward()   # Backpropagation: calculate the gradients
    optimizer.step()   # Update the weights
    if epoch%1000==0:
        print('Epoch: {} - loss: {}'.format(epoch, loss.item()))
model.eval()
model.double()
y_predicted2 = model(X_test).detach().numpy()
error2 = mean_absolute_error(y_test, y_predicted2)
print(error2)
</code></pre>
<p>I have also tried to use LBFGS optimizer, the code is similar:</p>
<pre><code class="lang-auto">X2_train = torch.Tensor(X_train).double()
y2_train = torch.Tensor(y_train.reshape(-1,1)).double()
X2_test = torch.Tensor(X_test).double()
y2_test = torch.Tensor(y_test.reshape(-1,1)).double()
model = torch.nn.Linear(600, 1, bias=False)
model.double()
criterion = torch.nn.MSELoss(reduction='elementwise_mean')
optimizer = torch.optim.LBFGS(model.parameters(), lr=1.0, max_iter=1000, history_size=10000)
model.train()        
for epoch in range(int(3e2)):
    def closure():
        optimizer.zero_grad()   # Reset gradients
        model.zero_grad()   # Just to be sure
        y_predicted = model(X2_train)   # Forward pass: predict
        loss = criterion(y_predicted, y2_train)   # Forward pass: calculate the loss
        loss.backward()   # Backpropagation: calculate the gradients
        print('Epoch: {} - loss: {}'.format(epoch, loss.item()))
        return loss
    optimizer.step(closure)   # Update the weights
model.eval()
model.double()
y_predicted2 = model(X_test).detach().numpy()
error2 = mean_absolute_error(y_test, y_predicted2)
print(error2)
</code></pre>
<p>I am using 600 weights for each, LinearRegression and Linear layer, both with no bias (I tried also with bias on but with no significant improvement), so they should work completely the same. Both are learning from the same data, 600 samples.<br>
The analytical solution of LinearRegression has L1 test error 0.003666.<br>
The Adam optimizer just runs for ages without converging to an analytical solution. The LBFGS converges to the test error 0.039252, which is almost ten times higher.</p>
<p>It is also possible to check weights with:</p>
<pre><code class="lang-auto">print(lin_model.coef_)
for p in model.parameters():
    print(p)  
</code></pre>
<p>They are different as I would expect if they converged to different minima. However, this is just a linear regression, it is a convex problem, so it should converge to the exactly same weights.</p>
<p>Can you see where the problem is?</p>
<p>My PyTorch version is 0.4.1.post2.</p>
<p>I can also send you training data with which I achieved these results.</p>

username: albanD
cooked: <p>Hi,</p>
<p>Gradient descent is really bad for optimization <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=6" title=":slight_smile:" class="emoji" alt=":slight_smile:"><br>
In particular, you have a smooth convex function for which gd will have a bad convergence rate (one over t?). The original Adam does not always converge even in the convex case.<br>
For the gradient descent methods, precise tuning of learning rate (and use of momentum) might be necessary to converge fast enough.</p>
<p>I am less familiar with LBFGS so I’m not sure why it converges to a different point.</p>
<p>I don’t know how <code>LinearRegression</code> from sklearn works. But does it really just minimizes the average l2 difference? Doesn’t it contain some regularization? Why do you optimize the l2 and compare the final l1 norms?</p>

username: somnambWl
cooked: <p>Ah, I didn’t know this about Adam.<br>
I also tried a higher learning rate, but if it is higher than 1e-8 for SGD, it explodes. However, if it is this low, it could learn ages. I tried momentum as well. Actually, I can not think of something I haven’t tried yet.</p>
<p>The <code>X_train</code> is a kernel matrix and this code does the same as <code>LinearRegression</code>:</p>
<pre><code class="lang-auto">import numpy as np
import numpy.linalg as la
from sklearn.metrics import mean_absolute_error

alpha = np.dot(la.inv(X_train), y_train)
y_predicted3 = np.dot(X_test, alpha)
error3 = mean_absolute_error(y_test, y_predicted3)
print(error3)
</code></pre>
<p>There is no regularization. I tried to optimize L1, but as it is convex problem, I thought it would converge to the same result. I could have added a commented line with <code>L1Loss</code>, I tried it, but it did not converge to the analytical solution as well. I compare L1 errors because it is easier to see the physical meaning of the problem.</p>

username: albanD
cooked: <p>L1Loss and L2Loss are both convex, but they are two different functions, so optimizing one or the other will give different results !<br>
For example, considering a 1D problem without bias, if your samples are (input, output): (1, 0.5) and (2, 0). Then your loss function will look like this:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/4/4ab997b02f840d16e55ae3062e91d8f8be3f80fc.png" data-download-href="https://discuss.pytorch.org/uploads/default/4ab997b02f840d16e55ae3062e91d8f8be3f80fc" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/2X/4/4ab997b02f840d16e55ae3062e91d8f8be3f80fc_2_690x319.png" alt="image" data-base62-sha1="aF2XHGY965jd765wsAsJnSpzNKs" width="690" height="319" srcset="https://discuss.pytorch.org/uploads/default/optimized/2X/4/4ab997b02f840d16e55ae3062e91d8f8be3f80fc_2_690x319.png, https://discuss.pytorch.org/uploads/default/original/2X/4/4ab997b02f840d16e55ae3062e91d8f8be3f80fc.png 1.5x, https://discuss.pytorch.org/uploads/default/original/2X/4/4ab997b02f840d16e55ae3062e91d8f8be3f80fc.png 2x" data-dominant-color="F9F8F5"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">946×438 29.6 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
As you can see, the absolute value and the squared norm don’t have the minimum at the same point</p>
<p>It is surprising that you cannot use SGD with any value bigger than 1e-8. Maybe you want to normalize your dataset to avoid very bad conditioning that significantly impact simple gradient based methods.</p>

username: somnambWl
cooked: <p>Ok, but anyway <code>LinearRegression</code> is using L2 norm and I used it for the <code>Linear</code> layer too. So the conditions for both are the same and as such, they should have the same errors in the end.<br>
Even if I normalize the data, LBFGS has a different result. The maximum learning rate for SGD is in order 1e-3 and it could again learn for ages.</p>

username: somnambWl
cooked: <p>I think that the problem is in the data. It has a very high condition number. May it be the problem?<br>
If someone had encountered this problem, could you let me know, how did you solve it?<br>
I already tried rescaling input and output, but it did not help.</p>

username: beibin
cooked: <p>I think the problem is that the average of gradient is small in every batch, because you feed the whole dataset into the model and optimizer at one time.</p>
<p>I am not sure how large your dataset is. When the batch size is too large and the data is too noisy, the final gradient will be averaged to near zero. Then, the model will converge at an extremely slow rate.</p>
<p>Try to feed your data one by one to the model and optimizer. See what happens.</p>

username: Yao_Xuan
cooked: <p>Hi, Did you make any progress in this problem? I got the same problem. I am trying to use a one-layer  linear network to solve for a least square approximation problem. The result given by optimizer is ten times higher than the explicit expression. Did you finally find a good solution for this?</p>
<p>Thanks,<br>
Yao</p>

username: proxon
cooked: <p>I had similar problem on a dataset where the number of samples was just x10 the number of parameters. Data was noisy and optimization would get stuck producing good results only for the frequent samples. Decreasing the batch size helped as it allowed the optimizer to better explore parameters for the less-frequent samples as well.</p>
<p>I got good results with batches of size 1-2. This significantly increased duration of a single epoch, but I could reduce the number of iterations and arrive at much better solution than in the past.</p>

username: FariFteh
cooked: <p>I got stuck with this problem forever, and finally reducing the batch size to 2 helped to improve the performance. Thank you so much!!!<br>
I expect the model to achieve lower l2 loss though, do you have any other suggestions?</p>