我们调用第三方的神经网络python组件继续进行更复杂的函数拟合,这次拟合一个比f(x)=sin(x)*0.6函数更复杂的函数f(x)=sin(x)*0.5+cos(x)*0.5
python代码如下
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#bp ann 函数拟合sin*0.5+cos*0.5
import neurolab as nl
import numpy as np
import matplotlib.pyplot as plt
isdebug=False
#x和d样本初始化
train_x =[]
d=[]
samplescount=1000
myrndsmp=np.random.rand(samplescount)
for yb_i in xrange(0,samplescount):
train_x.append([myrndsmp[yb_i]*4*np.pi-2*np.pi])
for yb_i in xrange(0,samplescount):
d.append(np.sin(train_x[yb_i])*0.5+np.cos(train_x[yb_i])*0.5)
myinput=np.array(train_x)
mytarget=np.array(d)
bpnet = nl.net.newff([[-2*np.pi, 2*np.pi]], [5, 1])
err = bpnet.train(myinput, mytarget, epochs=800, show=100, goal=0.02)
simd=[]
for xn in xrange(0,len(train_x)):
# print "====================="
# print u"样本:%f=> "%(train_x[xn][0])
simd.append(bpnet.sim([train_x[xn]])[0][0])
# print simd[xn]
# print u"--正确目标值--"
# print d[xn]
# print "====================="
temp_x=[]
temp_y=simd
temp_d=[]
i=0
for mysamp in train_x:
temp_x.append(mysamp[0])
temp_d.append(d[i][0])
i+=1
x_max=max(temp_x)
x_min=min(temp_x)
y_max=max(max(temp_y),max(d))+0.2
y_min=min(min(temp_y),min(d))-0.2
plt.xlabel(u"x")
plt.xlim(x_min, x_max)
plt.ylabel(u"y")
plt.ylim(y_min, y_max)
plt.title("http://blog.csdn.net/myhaspl" )
lp_x1 = temp_x
lp_x2 = temp_y
lp_d = temp_d
plt.plot(lp_x1, lp_x2, 'r*')
plt.plot(lp_x1,lp_d,'b*')
plt.show()
>>> runfile(r'I:\book_prog\ann_bpnhsincos1.py', wdir=r'I:\book_prog')
Epoch: 100; Error: 0.528978849953;
Epoch: 200; Error: 0.33336612138;
Epoch: 300; Error: 0.253337487331;
Epoch: 400; Error: 0.20472927421;
Epoch: 500; Error: 0.202153963051;
Epoch: 600; Error: 0.19900731385;
Epoch: 700; Error: 0.197426245762;
Epoch: 800; Error: 0.193607559472;
The maximum number of train epochs is reached
>>>
拟合效果为: