TypeError: tanh(): argument 'input' (position 1) must be Tensor, not int

xursbn: <p>Hello everyone. I am a new Python programmer, even newer at PyTorch and Machine Learning.</p>
<p>I have an assignment that asks me to approximate the sine function using neural netwroks (very introductory stuff)</p>
<p>In the assignment, the following code is given:</p>
<pre><code class="lang-auto">import numpy as np
import matplotlib.pyplot as plt
import torch 

N = 200
# creates the x vector with N values between -2 and 2
x = (np.random.rand(N)*4)-2
# creates the y vector
y = np.sin(2*x)
plt.plot(x,y,'xb')
plt.grid('both')
plt.axis([-3,3,-2,2]);

nTraining = int(0.7*N) # puts 70% of the data for training
x_train = np.array(x[0:nTraining],dtype=np.float32)
x_train = x_train.reshape(-1,1)

y_train = np.array(y[0:nTraining],dtype=np.float32)
y_train = y_train.reshape(-1,1)

x_test = np.array(x[nTraining:],dtype=np.float32)
x_test = x_test.reshape(-1,1)

y_test = np.array(y[nTraining:],dtype=np.float32)
y_test = y_test.reshape(-1,1)
</code></pre>
<p>This is the part of the assignment that I’m supposed to make, and I’ve done the following:</p>
<pre><code class="lang-auto">learningRate=0.01
nInputs = 1
nHidden = 4
nOutput = 1
model = torch.nn.Sequential(
    torch.nn.Linear(nInputs, nHidden),
    torch.tanh(nHidden),
    torch.nn.Linear(nHidden, nOutput)
    ) 
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
print(model)
</code></pre>
<p>The <code>nHidden</code> value is set at “4” but it has no real meaning there. I’ve used it like that because it was like that on previous examples, but I’m supposed to change it.</p>
<p>Basically what I need is to create a neural network that approximates the sine function. The assignment suggests me to use the Hyperbolic Tangent function as an activating function to the hidden layers. I’ve tried doing that, but the following is shown:</p>
<pre><code class="lang-auto">TypeError                                 Traceback (most recent call last)

&lt;ipython-input-75-18fd3bb85735&gt; in &lt;module&gt;()
      5 model = torch.nn.Sequential(
      6     torch.nn.Linear(nInputs, nHidden),
----&gt; 7     torch.tanh(nHidden),
      8     torch.nn.Linear(nHidden, nOutput)
      9     ) 

TypeError: tanh(): argument 'input' (position 1) must be Tensor, not int
</code></pre>
<p>I understand what is being said to me, I can’t pass an integer to the tanh function, as it’s expecting a Tensor. The question is, how do I addapt the nHidden value in this code to be a Tensor?</p>
<p>After setting up everything, I’m supposed to run the following code:</p>
<pre><code class="lang-auto">def train_model(nEpochs = 10):
  errors=[]
  for epoch in range(nEpochs):
    if torch.cuda.is_available():
      inputs = torch.tensor(x_train).to('cuda')
      targets = torch.tensor(y_train).to('cuda')
    else:
      inputs = torch.tensor(x_train) 
      targets = torch.tensor(y_train)    
    optimizer.zero_grad()
    outputs = model(inputs)
    loss = criterion(outputs, targets)
    loss.backward() 
    optimizer.step()
    errors.append(loss.item())
    if(not epoch%100):
      print('Epoch:' + str(epoch) + ' errors: ' + str(loss.item()))
  return errors
  
errors = train_model(800) 
plt.plot(errors)
plt.show()
</code></pre>
<p>And the error should be below 0.05, but the most I can get is 0.27.</p>
<p>Can someone please give me any tips or something as to how I’m supposed to do that?</p>
<p>Thank you for the help in advance!</p>

AlphaBetaGamma96: <p>Replace,</p>
<aside class="quote no-group" data-username="xursbn" data-post="1" data-topic="154980">
<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/xursbn/48/50837_2.png" class="avatar"> xursbn:</div>
<blockquote>
<pre><code class="lang-auto">model = torch.nn.Sequential(
    torch.nn.Linear(nInputs, nHidden),
    torch.tanh(nHidden),
    torch.nn.Linear(nHidden, nOutput)
    ) 
</code></pre>
</blockquote>
</aside>
<p>with,</p>
<pre><code class="lang-auto">model = torch.nn.Sequential(
    torch.nn.Linear(nInputs, nHidden),
    torch.nn.Tanh(),
    torch.nn.Linear(nHidden, nOutput)
    )
</code></pre>
<p>And it should work</p>

xursbn: <p>(post deleted by author)</p>

xursbn: <p>That worked! Can’t believe it was that easy. Thank you very much.</p>