import torch.nn as nn
N, D_in, H, D_out = 64,1000,100,10
#随机创建一些训练数据
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
class TwoLayerNet(torch.nn.Module):
def init(self, D_in, H, D_out):
super(TwoLayerNet, self).init()
self.Linear1 = torch.nn.Linear(D_in, H, bias=False)
self.Linear2 = torch.nn.Linear(H, D_out, bias=False)
def forward(self, x):
    y_pred = self.linear2(self.linear1(x).clamp(min=0))
    return y_pred

model = TwoLayerNet(D_in, H, D_out)
loss_fn = nn.MSELoss(reduction=‘sum’)
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)
for it in range(500):
Forward pass
y_pred = model(x)
# compute loss
loss = loss_fn(y_pred, y)  # computation graph
print(it, loss.item())

optimizer.zero_grad()
# Backward pass
loss.backward()

# update model parameters
optimizer.step()

ModuleAttributeError Traceback (most recent call last)
in
24 for it in range(500):
25 # Forward pass
—> 26 y_pred = model(x)
27
28 # compute loss
E:\anaconda3\envs\sbw\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
725 result = self._slow_forward(*input, **kwargs)
726 else:
→ 727 result = self.forward(*input, **kwargs)
728 for hook in itertools.chain(
729 _global_forward_hooks.values(),
in forward(self, x)
14
15 def forward(self, x):
—> 16 y_pred = self.linear2(self.linear1(x).clamp(min=0))
17 return y_pred
18
E:\anaconda3\envs\sbw\lib\site-packages\torch\nn\modules\module.py in getattr(self, name)
776 if name in modules:
777 return modules[name]
→ 778 raise ModuleAttributeError("’{}’ object has no attribute ‘{}’".format(
779 type(self).name, name))
780
ModuleAttributeError: ‘TwoLayerNet’ object has no attribute ‘linear2’