'function' object has no attribute `dim

Malte5768: <p>So i just started learning programming and i wanted to try out a really simple NN which i then made with help of a  YT video.Which means that this code is a 100 percent copied… for what ever reason i get that error message and i dont know how to fix it <img src="https://discuss.pytorch.org/images/emoji/apple/confused.png?v=9" title=":confused:" class="emoji" alt=":confused:"></p>
<p>import torch<br>
import torch.nn as nn<br>
import torch.nn.functional as F<br>
from torch.autograd import Variable<br>
import torch.optim as optim</p>
<p>class MeinNetz(nn.Module):</p>
<pre><code>def __init__(self):              
    super(MeinNetz, self).__init__()
    self.lin1 = nn.Linear(10, 10)
    self.lin2 = nn.Linear(10, 10)

def forward(self, x):
    x = F.relu(self.lin1(x)) 
    x = self.lin2(x)
    return x

def num_flat_features(self,x):
    size = x.size()[1:]          
    num = 1
    for i in size:
        num *= i
        return num
</code></pre>
<p>netz = MeinNetz()</p>
<p>for i in range (100):<br>
x = [1,0,0,0,1,0,0,0,1,1]<br>
target = Variable(torch.Tensor([x for _ in range(10)]))</p>
<pre><code>out = netz(input)

x= [0,1,1,1,0,1,1,1,0,0]
target = Variable(torch.Tensor([x for _ in range(10)]))
criterion = nn.MSELoss()  
loss = criterion(out,target)
print(loss)

netz.zero_grad()
loss.backward()  
optimizer = optim.SGD(netz.parameters(), lr=0.01)
optimizer.step()
</code></pre>
<p>This is my Error:</p>
<p>Traceback (most recent call last):</p>
<p>File “”, line 1, in <br>
runfile(‘G:/Erstes NN(6.11.19).py’, wdir=‘G:’)</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\spyder_kernels\customize\spydercustomize.py”, line 827, in runfile<br>
execfile(filename, namespace)</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\spyder_kernels\customize\spydercustomize.py”, line 110, in execfile<br>
exec(compile(f.read(), filename, ‘exec’), namespace)</p>
<p>File “G:/Erstes NN(6.11.19).py”, line 43, in <br>
out = netz(input)</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\modules\module.py”, line 489, in <strong>call</strong><br>
result = self.forward(*input, **kwargs)</p>
<p>File “G:/Erstes NN(6.11.19).py”, line 24, in forward<br>
x = F.relu(self.lin1(x)) <span class="hashtag">#letzes</span> mus hier immer ein return sein#</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\modules\module.py”, line 489, in <strong>call</strong><br>
result = self.forward(*input, **kwargs)</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\modules\linear.py”, line 67, in forward<br>
return F.linear(input, self.weight, self.bias)</p>
<p>File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\functional.py”, line 1350, in linear<br>
if input.dim() == 2 and bias is not None:</p>
<p>AttributeError: ‘function’ object has no attribute ‘dim’</p>

KFrank: <p>Hi Malte!</p>
<aside class="quote no-group quote-modified" data-username="Malte5768" data-post="1" data-topic="61199" data-full="true">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/malte5768/48/17785_2.png" class="avatar"> Malte5768:</div>
<blockquote>
<p>This is my Error:</p>
<p>Traceback (most recent call last):<br>
…<br>
File “G:/Erstes NN(6.11.19).py”, line 43, in <br>
out = netz(input)<br>
…<br>
File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\functional.py”, line 1350, in linear<br>
if input.dim() == 2 and bias is not None:</p>
<p>AttributeError: ‘function’ object has no attribute ‘dim’</p>
</blockquote>
</aside>
<p>Your problem is that (in your code) <code>input</code> is not defined – or, more<br>
precisely, it is defined by python to be a function.  (This kind of thing is<br>
a common source of errors in weakly-type languages such as python.)</p>
<p>Python’s <code>input</code> function doesn’t have a <code>dim</code> attribute, hence the<br>
error.</p>
<p>Here are some results from a python session that illustrate this:</p>
<pre><code class="lang-plaintext">&gt;&gt;&gt; type (input)
&lt;class 'builtin_function_or_method'&gt;
&gt;&gt;&gt; input.dim()
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: 'builtin_function_or_method' object has no attribute 'dim'
&gt;&gt;&gt; import torch
&gt;&gt;&gt; input = torch.randn (3, 4)
&gt;&gt;&gt; type (input)
&lt;class 'torch.FloatTensor'&gt;
&gt;&gt;&gt; input.dim()
2
</code></pre>
<p>When the python session first starts, <code>input</code> exists and is defined by<br>
python to be a ‘builtin_function_or_method’.</p>
<p>Then I <code>import torch</code> and assign a tensor to <code>input</code>.  (Python is very<br>
permissive – you are allowed to assign things to variable names that<br>
are used for python builtins.)  Now <code>input</code> is a ‘torch.FloatTensor’, and<br>
you can happily call its <code>dim()</code> method.</p>
<p>Note, <code>input</code> in:</p>
<pre><code class="lang-plaintext">File “G:/Erstes NN(6.11.19).py”, line 43, in
out = netz(input)
</code></pre>
<p>and in:</p>
<pre><code class="lang-plaintext">File “E:\Programmieren\Anaconda\lib\site-packages\torch\nn\functional.py”, line 1350, in linear
if input.dim() == 2 and bias is not None:
</code></pre>
<p>are not, in general, the same thing.  They just happen to be labelled<br>
with the same character string.</p>
<p>In the first case, <code>input</code> is whatever it is when you call <code>netz(input)</code>,<br>
namely the python builtin.  In the second case it is the name of an<br>
argument to a function inside of functional.py.  In your situation, it<br>
<em>is</em> the same as the first <code>input</code> because it was passed as an<br>
argument through a series of functions until it gets to that line of<br>
code in functional.py that actually tries to do something with it, at<br>
which point python discovers that it isn’t what you thought it was.</p>
<p>(In pytorch, “input” is often used as the name of the tensor that<br>
is passed to a model.  You could argue that pytorch shouldn’t be<br>
using names of python builtins for these sorts of things, but that<br>
ship has long since sailed.)</p>
<p>How to fix it?  You need to pass some kind of sensible data to your<br>
model.  If you copied your code from a tutorial, either the tutorial<br>
is buggy, or you missed copying the part of the code where “input”<br>
is defined to be something meaningful for training the model.</p>
<p>Good luck.</p>
<p>K. Frank</p>

Malte5768: <p>Thank you very much mate <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:">  im gonna try that out tomorrow <img src="https://discuss.pytorch.org/images/emoji/apple/smiley.png?v=9" title=":smiley:" class="emoji" alt=":smiley:"></p>

RowanG1: <p>Did you get this right? I am trying to use the forward method of pytorch after creating a fastai model, and it throws the same error.</p>

ptrblck: <p>Could you check which operation throws this error as shown in the stacktrace and make sure you are not hitting the same issue as described by <a class="mention" href="/u/kfrank">@KFrank</a>?</p>

RowanG1: <p>Found solution:</p><aside class="onebox stackexchange" data-onebox-src="https://stackoverflow.com/questions/70537717/trace-script-for-pytorch-ml-model-to-deploy-on-mobile">
  <header class="source">

      <a href="https://stackoverflow.com/questions/70537717/trace-script-for-pytorch-ml-model-to-deploy-on-mobile" target="_blank" rel="noopener nofollow ugc">stackoverflow.com</a>
  </header>

  <article class="onebox-body">
      <a href="https://stackoverflow.com/users/5208205/rowan-gontier" target="_blank" rel="noopener nofollow ugc">
    <img alt="Rowan Gontier" src="https://graph.facebook.com/10153498190017246/picture?type=large" class="thumbnail onebox-avatar" width="201" height="200">
  </a>

<h4>
  <a href="https://stackoverflow.com/questions/70537717/trace-script-for-pytorch-ml-model-to-deploy-on-mobile" target="_blank" rel="noopener nofollow ugc">Trace script for pytorch ML model to deploy on mobile</a>
</h4>

<div class="tags">
  <strong>fast-ai</strong>
</div>

<div class="date">
  asked by
  
  <a href="https://stackoverflow.com/users/5208205/rowan-gontier" target="_blank" rel="noopener nofollow ugc">
    Rowan Gontier
  </a>
  on <a href="https://stackoverflow.com/questions/70537717/trace-script-for-pytorch-ml-model-to-deploy-on-mobile" target="_blank" rel="noopener nofollow ugc">11:36PM - 30 Dec 21 UTC</a>
</div>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>