sgd Momentum Vanilla SGD RMSprop adam等优化算法在寻找 简单感知器回归中的 的应用
关于优化参数的函数 可以看博文
(2条消息) sgd Momentum Vanilla SGD RMSprop adam等优化算法在寻找 简单logistic分类中的 的应用_tcuuuqladvvmm454的博客-CSDN博客
L2正则化
动量参数改进
其他
1 关于l1正则化
迭代次数小的时候,损失很严重
对应迭代100次,l2正则化效果特别好
代码
import torch
import matplotlib.pyplot as plt
import os
import random
import numpy as np
os.environ['KMP_DUPLICATE_LIB_OK']='True'
tezhneg=4
n_data = torch.ones(150, tezhneg) # 数据的基本形态
x1 = torch.normal(2 * n_data, 1) # shape=(50, 2)
y1 = torch.zeros(150) # 类型0 shape=(50, 1)
x2 = torch.normal(-2 * n_data, 1) # 类型1 shape=(50, 1)
y2 = torch.ones(150) # 类型1 shape=(50, 1)
# 注意 x, y 数据的数据形式一定要像下面一样 (torch.cat 是合并数据)
x = torch.cat((x1, x2), 0).type(torch.FloatTensor)
y = torch.cat((y1, y2), 0).type(torch.FloatTensor)
#plt.figure
#plt.scatter(x[:, 1].numpy(), y.numpy(), 1)
#plt.show()
#plt.scatter(x[:, 0].numpy(), y.numpy(), 1)
#plt.show()
plt.scatter(x[:, 0].numpy(), x[:, 1].numpy(), 1)
plt.show()
num_inputs=x.shape[0]
w = torch.tensor(np.random.normal(0, 0.01, ( tezhneg,1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
features=x
labels=y
batch_size=30
num_inputs = tezhneg
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples)) # [0, 1, …, 998, 999]
random.shuffle(indices) # 样本的读取顺序是随机的
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # 最后一次可能不足一
#个batch
yield features.index_select(0, j), labels.index_select(0, j)
ww=w
bb=b
def linreg(X, w, b):
return torch.mm(X, w) + b
#ww=linreg(x, w, b).shape
def squared_loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2#+w**2/2
def sgd(params, lr, batch_size):##改进的动量因子
for param in params:
#print('param=',param,'\nparam.grad=',param.grad,'\nparam.data=',param.data)
v=0
dongliang=0.8
v=(dongliang*v+lr * param.grad)/ batch_size
param.data -= v#lr * param.grad / batch_size # 注意这里更改param时用的param.data
lr = 0.03
num_epochs = 10
net = linreg
loss = squared_loss
loss1=[]
for epoch in range(num_epochs): # 训练模型一共需要num_epochs个迭代周期
# 在每一个迭代周期中,会使用训练数据集中所有样本一次
for X, y in data_iter(batch_size, features, labels): # x和y分别是小批量样本的特征和标签
#batch_size
l = loss(net(X, w, b), y)+sum(w**2)###L2正则化
l=l.sum() # l是有关小批量X和y的损失
l.backward() # 小批量的损失对模型参数求梯度
sgd([w, b], lr, batch_size) # 使用小批量随机梯度下降迭代模型参数
w.grad.data.zero_() # 梯度清零
b.grad.data.zero_()
#print('w=',w[0],'b=',b)
train_l = loss(net(features, w, b), labels)
loss1.append(train_l.mean().item())
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
yy=(net(features, w, b) )
yy1=labels
#print(ww, '\n', w)
#print(bb, '\n', b)
plt.figure()
plt.subplot(311)
plt.plot(loss1,'-r*')
#plt.show()
plt.subplot(313)
plt.plot(yy.detach().numpy(),'-',label='yuce')
plt.plot(yy1.detach().numpy(),'-',label='real')
plt.legend()
plt.title('dongliang+L2zhengzehua regress')
plt.show()