Datawhale第八期——Task2设立计算图并自动计算
使用numpy实现梯度下降算法
import numpy as np
import matplotlib.pyplot as plt
def func(x):
return np.square(x)
def dfunc(x):
return 2*x
def main():
x=np.linspace(-1,1,100)
y=func(x)
eta=0.1#这是学习率(决定了参数移动到最优值的速度快慢)
theta=-1.0#第一个点
episilon=1e-8
while True:
gradient=dfunc(theta)
last_theta=theta
theta-=gradient*eta#对theta进行更新
if abs(func(theta)-func(last_theta))<episilon:
break
print(theta)
print(func(theta))
main()
使用pytorch实现梯度下降算法
import torch
x = torch.Tensor([0])#设定初始值
x.requires_grad_(True)
for epoch in range(epoches):
y=x*x
y.backward()#反向传播求梯度
eta=0.1#这是学习率(决定了参数移动到最优值的速度快慢)
x.data= x.data - eta*x.grad.data
# 在 PyTorch 中梯度如果不清零会积累((因为PyTorch是基于动态图的, 每迭代一次就会留下计算缓存, 到一下次循环时需要手动清楚缓存))
x.grad.data.zero_()