import torch from torch.autograd import Variable from sklearn import datasets from torch import nn X = [[i, i] for i in range(0, 10)] Y = [[i[0]*2, i[0]*i[0]] for i in X] X_train = Variable(torch.Tensor(X).float()) Y_train = Variable(torch.Tensor(Y).float()) #X_test = torch.Tensor(X_test).float() class simpleNet(nn.Module): def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim): super(simpleNet, self).__init__() self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1), nn.BatchNorm1d(n_hidden_1), nn.ReLU(True)) self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2), nn.BatchNorm1d(n_hidden_2), nn.Sigmoid()) self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, 20), nn.BatchNorm1d(20), nn.Sigmoid()) self.layer4 = nn.Sequential(nn.Linear(20, out_dim)) def forward(self, x): x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) return x model = simpleNet(2, 100, 50, 2) loss_func = nn.MSELoss() opt = torch.optim.Adam(model.parameters(), lr=0.1) loss_count = [] for epoch in range(1): for i in range(1000): batch_x = X_train # torch.Size([128, 1, 28, 28]) batch_y = Y_train # torch.Size([128]) out = model(batch_x) # torch.Size([128,10]) # 获取损失 loss = loss_func(out, batch_y) # 使用优化器优化损失 opt.zero_grad() # 清空上一步残余更新参数值 loss.backward() # 误差反向传播,计算参数更新值 opt.step() # 将参数更新值施加到net的parmeters上 loss_count.append(loss) print('{}:\t'.format(i), loss.item()) torch.save(model, r'C:\Users\Administrator\PycharmProjects\data\cnn') print(Y) print(model(X_train))
基于pytorch多标记实例,实现自动对两个未知数的求和与求积
最新推荐文章于 2023-08-18 11:43:08 发布