不用重复造轮子,我们可以直接使用多层感知器的库,目前多层感知器的库较多,我们选择纯python库实现的神经网络库-neurolab,该库基于LGPL协议,下载地址 为:
https://code.google.com/p/neurolab/
我们用这个库训练我们前面的非线性分类的例子
>>> import neurolab as nl
>>> train_x = [[4,11],[7,340],[10,95],[3,29],[7,43],[5,128]]
>>> input=np.array(train_x)
>>> d =[[1],[0],[1],[0],[1],[0]]
>>> target=np.array(d)
>>> target
array([[1],
[0],
[1],
[0],
[1],
[0]])
>>> input
array([[ 4, 11],
[ 7, 340],
[ 10, 95],
[ 3, 29],
[ 7, 43],
[ 5, 128]])
>>> net = nl.net.newff([[3, 10], [11, 400]], [5, 1])
>>> err = net.train(input, target, show=15)
Epoch: 15; Error: 0.326594518922;
Epoch: 30; Error: 0.0242485565317;
The goal of learning is reached
训练完毕后,我们验证一下,效果不错
>>> net.sim([[3, 10]])
array([[ 0.99999326]])
>>> net.sim([[9, 80]])
array([[ 0.89054486]])
>>> net.sim([[6.5,272]])
array([[ 0.05707987]])
>>> net.sim([[10,80]])
array([[ 0.9448553]])
>>> net.sim([[5,125]])
array([[ 0.12198103]])
>>> net.sim([[5,100]])
array([[ 0.18880761]])
>>>
可以设定一个硬限幅函数,以0.5为一个阈值,超过这个阈值返回1,否则返回0