2021-10-03

这篇博客探讨了sgd、Momentum、VanillaSGD、RMSprop和Adam等优化算法在简单感知器回归问题中的应用。通过L2正则化的引入,展示了在不同迭代次数下,这些优化算法如何影响模型的训练效果。博主通过代码实现了一个简单的Logistic回归模型,并用可视化的方式展示了优化算法与正则化结合后的训练过程和预测结果。
摘要由CSDN通过智能技术生成

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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值