PyTorch深度学习实践课程-梯度下降

梯度下降算法

进入anaconda命令控制台输入
pip install matplotlib
下载matplotlib


(base) C:\Users\hp>python
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 数据集
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = 1

# 正向传播
def forward(x):
    return x * w


# 计算损失
def cost(xs, ys):
    cost = 0
    for x, y in zip(xs, ys):
        y_pred = forward(x)
        cost += (y_pred - y) ** 2
    return cost/len(xs)


# 反向传播
def gradient(xs, ys):
    grad = 0
    for x, y in zip(xs, ys):
        grad += 2 * x * (x * w - y)
    return grad / len(xs)


# 开始训练
mse_list = []
for epoch in range(100):
    # 计算成本
    cost_val = cost(x_data, y_data)
    # 计算梯度
    grad_val = gradient(x_data, y_data)
    # 更新参数
    w = w - 0.01 * grad_val
    mse_list.append(cost_val)
    print("epoch=", epoch, "cost_val=", cost_val, "w=", w)

# 预测
print("x=4, y=", forward(4))

# 绘图
plt.plot(mse_list)
plt.xlabel("epoch")
plt.ylabel("cost")
plt.show()

运行结果
在这里插入图片描述

随机梯度下降算法复现

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 数据集
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = 1

# 正向传播
def forward(x):
    return x * w


# 计算损失
def loss(x, y):
    cost = 0
    y_pred = forward(x)
    cost += (y_pred - y) ** 2
    return cost


# 反向传播
def gradient(x, y):
    grad = 0
    grad += 2 * x * (x * w - y)
    return grad


# 开始训练
mse_list = []
for epoch in range(100):
    # 每次使用一个样本进行训练
    for x_val, y_val in zip(x_data, y_data):
        # 计算成本
        cost_val = loss(x_val, y_val)
        # 计算梯度
        grad_val = gradient(x_val, y_val)
        # 更新参数
        w = w - 0.01 * grad_val
    mse_list.append(cost_val)
    print("epoch=", epoch, "cost_val=", cost_val, "w=", w)

# 预测
print("x=4, y=", forward(4))

# 绘图
plt.plot(mse_list)
plt.xlabel("epoch")
plt.ylabel("cost")
plt.show()


运行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值