叮当物联

如何使用神经网络实现基本的数学运行(乘法、除法、加法、减法)

一、乘法

import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
%matplotlib inline


class LineNet(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_out):
        super(LineNet, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.predict = torch.nn.Linear(n_hidden, n_out)
        
    def forward(self,x):
        x = F.relu(self.hidden(x))
        x = F.sigmoid(self.predict(x))
        return x
    
net = LineNet(2,100,1)
print(net)


# optimizer = torch.optim.SGD(net.parameters(),lr = 0.5)
optimizer = torch.optim.SGD(net.parameters(), lr = 10)
loss_func = torch.nn.MSELoss()

for t in range(1000):
    prediction = net(x)
    loss = loss_func(prediction, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if t%200 == 0:
        print(f"\nt = {t}=======output weight:======\n",net.predict.weight)
        print(f"\nt={t}=======output weight grad:======\n",net.predict.weight.grad)
        print(f"loss={loss.data.item()}")

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »