Deeplearning 笔记:梯度法

4. Deep Learning From Scratch

4.4 梯度法

通过梯度法求函数最小值时,参数的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# coding: utf-8
import numpy as np
import matplotlib.pylab as plt
from gradient_2d import numerical_gradient

#计算函数f值最小时,x的值
def gradient_descent(f, init_x, lr=0.01, step_num=100):
x = init_x #初始值
x_history = [] #定义一个空的列表

for i in range(step_num):
x_history.append( x.copy() ) #拷贝x的值后,就不会随着原x的变化而变化

grad = numerical_gradient(f, x) #求梯度值(斜率), 得到一个二维数组
x -= lr * grad #沿梯度变化的方向减少,函数值相应的减少

return x, np.array(x_history) #返回最后x的值以及他的变化轨迹


def function_2(x):
return x[0]**2 + x[1]**2

init_x = np.array([-3.0, 4.0])

lr = 0.1
step_num = 20
x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)

plt.plot( [-5, 5], [0,0], '--b')
plt.plot( [0,0], [-5, 5], '--b')
plt.plot(x_history[:,0], x_history[:,1], 'o')

plt.xlim(-3.5, 3.5)
plt.ylim(-4.5, 4.5)
plt.xlabel("X0")
plt.ylabel("X1")
plt.show()

后记:

1.在书中求函数的极小值,但是我觉得这样是不对的,因为gradient_descent返回的值是x和它的历史记录, 而不是f(x)的值。所以应该是f(x)取最小时,x的值。

2.另外在运行这个代码的时候遇到一个问题,matplotlib的某一个模块找不到了。之前也出现过这样类似的情况,是因为杀毒软件把一些模块给屏蔽掉了,到软件中找的这些模块,把模块返回原来的位置,再添加信任就可以了。但是这次没有在杀毒软件中找到,所以就用pip卸载了matplotlib然后在重装就可以了。