暂无分类
暂无标签
发布于2020-04-23 19:30 阅读(827) 评论(0) 点赞(0) 收藏(3)
0
1
2
3
4
这里用黄金分割法求解
b-a | ||||||||
---|---|---|---|---|---|---|---|---|
1 | 2 | – | – | 8 | – | – | 6 | |
4 | ||||||||
– | – | – | – | – | – | – | – | – |
18 | ||||||||
19 |
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
#目标函数
def function(x):
y = x**2 - 7 * x + 10
return y
#黄金分割法
def GoldenBorder(a, b, accuracy):
x1 = a + 0.382*(b - a)
x2 = a + 0.618*(b - a)
fx1 = function(x1)
fx2 = function(x2)
print( "a=", a,"x1=", x1, "x2=", x2 , ",b=", b,",f(x1)=",fx1, ",f(x2)=", fx2, )
if fx1 < fx2:
a = a
b = x2
else:
a = x1
b = b
accuracy = b - a
print("NewRange[", a, ", ",b,"]","accuracy=", b-a)
return a, b ,accuracy
a = 2
b = 8
value = []
accuracy = b - a
epoch = 0
accuracies = []
ys = []
epoches=[]
xs = []
while accuracy > 0.001:
epoch += 1
print("-"*100)
print("Epoch:",epoch)
a, b, accuracy = GoldenBorder(a, b, accuracy)
accuracies.append(accuracy)
ys.append(function( a + (b - a) / 2 ))
epoches.append(epoch)
xs.append(a + (b - a) / 2)
x = a + (b - a) / 2
y = function(x)
print("-"*100)
print("最优点:x*=", x,",f(x*)=", y)
plt.title(' Golden Section Search ')
plt.subplot(2,1,1)
plt.plot(epoches,accuracies, ":o", label = 'accuracy', color="blue")
xticks(np.linspace(0,19,20,endpoint=True))
plt.ylabel('f(x)')
plt.legend()
plt.subplot(2,1,2)
plt.plot(ys, "-.o", label = 'f(x)', color="red")
xticks(np.linspace(0,19,20,endpoint=True))
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend()
plt.show()
X = np.linspace(3, 4, 20)
Epoch = np.linspace(0, 19,20)
X, Epoch= np.meshgrid(X, Epoch)
Y = X**2 - X * 7 + 10
fig = plt.figure(figsize = ((8,6)))
ax = fig.gca(projection='3d')
ax.plot_surface(Epoch ,X , Y, color="yellow", alpha=0.5)
ax.plot(epoches ,xs , ys,"-.o",color="blue")
xticks(np.linspace(0,19,20,endpoint=True))
ax.set_xlabel('epoch') #设置坐标轴标签
ax.set_ylabel('x')
ax.set_zlabel(' f(x) ')
plt.show()
!
原文链接:https://blog.csdn.net/weixin_44560088/article/details/105694069
0
1
2
3
4
5
6
7
8
9
作者:9384vfnv
链接: https://www.pythonheidong.com/blog/article/339728/594ad37fffc2de081b7c/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系z452as@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!