Anaconda环境配置+梯度下降法实例与改进

极简版Anaconda开发环境配置

1、下载安装python
官方下载
2、下载安装Anaconda
官方下载
3、新建开发环境、安装jupyter-notebook
在终端输入配置
配置:conda create -n env_name
配置:conda activate env_name

梯度下降实例

用梯度下降算法求 y=x1**2+3*x2**2的最小值

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
import matplotlib.pyplot as plt
#设定以下超参数
rate=0.0001 #学习率
threshold=0.00000001 #迭代判定门限

x1=10
x2=8
y0=x1**2+3*x2**2
dev=y0
res_value=[]
i=0 #变量初始化

while((abs(dev)>threshold)and(i<10000)):
x1=x1-2*x1*rate
x2=x2-6*x2*rate
ytmp=x1**2+3*x2**2
dev=ytmp-y0
y0=ytmp
res_value.append(dev)
i=i+1
print(i,x1,x2,y0)
print(i,x1,x2,y0)

plt.plot(res_value)
plt.show()

换个复杂的例子:用梯度下降法求y=-(sin(x1)-5sin(2x2))*2+x1*2+x2*2+x1-x2最小值

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
import numpy as np
import matplotlib.pyplot as plt

rate=0.001 #学习率
threshold=0.00000001 #迭代判定门限

#变量初始化
x1=-2
x2=1
y0=-(np.sin(x1)-5*np.sin(2*x2))**2+x1**2+x2**2+x1-x2
dev=y0
res_value=[]
i=0

while((abs(dev)>threshold)and(i<10000)):
x1=x1-rate*(-2*(np.sin(x1)-5*np.sin(2*x2))*np.cos(x1)+2*x1+1)
x2=x2-rate*(20*(np.sin(x1)-5*np.sin(2*x2))*np.cos(2*x2)+2*x2-1)
ytmp=-(np.sin(x1)-5*np.sin(2*x2))**2+x1**2+x2**2+x1-x2
dev=ytmp-y0 #计算2次迭代偏差
y0=ytmp
res_value.append(dev)
i=i+1
print(i,x1,x2,y0)
print(i,x1,x2,y0)

plt.plot(res_value)
plt.show()
#总结,有多个极值点时,初始点取值很敏感(运气成分),梯度下降法存在的问题
#解决办法,利用多个初始值,找到最小极小值
#怎么做:设置一个随机步长,跳出搜索域

针对上述问题改进的梯度下降算法

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
38
39
40
41
42
import numpy as np
import matplotlib.pyplot as plt
import random

rate=0.001 #学习率
threshold=0.00000001 #迭代判定门限

#变量初始化
x1=20
x2=30
y0=-(np.sin(x1)-5*np.sin(2*x2))**2+x1**2+x2**2+x1-x2
dev=y0
res_value=[]
minx1_value=[]
minx2_value=[]
miny_value=[]
i=0

while((abs(x1)<50)and(abs(x2)<50)and(i<100000)):
x1=x1-rate*(-2*(np.sin(x1)-5*np.sin(2*x2))*np.cos(x1)+2*x1+1)
x2=x2-rate*(20*(np.sin(x1)-5*np.sin(2*x2))*np.cos(2*x2)+2*x2-1)
ytmp=-(np.sin(x1)-5*np.sin(2*x2))**2+x1**2+x2**2+x1-x2
dev=ytmp-y0 #计算2次迭代偏差
if(abs(dev)<threshold):#搜索到极小值点,强制跳出当前极小值
miny_value.append(ytmp)
minx1_value.append(x1)
minx2_value.append(x2) #保存当前极值点信息
x1=x1+random.randint(-5,5)#跳出极小值点
x2=x2+random.randint(-5,5)
y0=ytmp
res_value.append(dev)
i=i+1
minindex=miny_value.index(min(miny_value))#获取最小值所在的位置
print("x1:",minx1_value[minindex])
print("x2:",minx2_value[minindex])
print(min(miny_value))

plt.figure(1)
plt.plot(res_value)
plt.figure(2)
plt.plot(miny_value)
plt.show()
0%