人工神经网络
隐藏层神经元数目的经验法:
1:如果输入与输出层的大小相差很大,则隐藏层的神经元数目最好与输出层更接近
2:对于相对较小的输入层,隐藏神经元最好是输入层和输出层大小之和的三分之二,或者小于输入层大小的两倍
简单例子1:
这只是一个建大的例子,这种分类其实没有意义,但可以测试网络是否可以正常运行,在这段代码中,只提供了一个训练记录,它的类标签为5,这个网络会用来判断输入数据的类标签是否为5
import cv2
import numpy as np
ann = cv2.ml.ANN_MLP_create() #创建感知器
ann.setLayerSizes(np.array([9, 5, 9], dtype=np.uint8)) #设置拓扑结构 输入层 隐藏层 输出层的个数
ann.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP) #训练模式,采用反向传播方式 另外一种RPROP也是反向传播算法,这两种类型 只能在有监督学习中才可以设置
"""
train函数包含三个参数:
samples,layout和reponses
只有samples是必须设置的参数,另外两个为可选参数
只用了samples参数训练的统计模块,hi采用无监督学习算法,如果提供了layout和responses参数就是有监督学习
"""
ann.train(np.array([[1.2, 1.3, 1.9, 2.2, 2.3, 2.9, 3.0, 3.2, 3.3]], dtype=np.float32),
cv2.ml.ROW_SAMPLE,
np.array([[0,0,0,0,1,0,0,0,0]],
dtype=np.float32)
)
print (ann.predict(np.array([[1.4, 1.5, 1.2, 2., 2.5, 2.8, 3., 3.1, 3.8]], dtype=np.float32)))
输出:
(5.0, array([[-0.06419383, -0.13360272, -0.1681568 , -0.18708915, 0.0970564 ,
0.89237726, 0.05093023, 0.17537238, 0.13388439]], dtype=float32))
基于ANN的动物分类
假设输入统计量:体重,长度,牙齿,输入的都是无食用价值的数据,并且只考虑了训练数据集的大小/训练迭代系数。通过这些结果可以看到ANN对那些类产生了过拟合,因此,提高训练过程中输入的数据质量很重要。
每次运行的结果都不相同
import cv2
import numpy as np
from random import randint
animals_net = cv2.ml.ANN_MLP_create()
animals_net.setTrainMethod(cv2.ml.ANN_MLP_RPROP | cv2.ml.ANN_MLP_UPDATE_WEIGHTS)
animals_net.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM)
animals_net.setLayerSizes(np.array([3, 6, 4]))
animals_net.setTermCriteria(( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 ))
"""Input arrays
weight, length, teeth
"""
"""Output arrays
dog, eagle, dolphin and dragon
"""
def dog_sample():
return [randint(10, 20), 1, randint(38, 42)]
def dog_class():
return [1, 0, 0, 0]
def condor_sample():
return [randint(3,10), randint(3,5), 0]
def condor_class():
return [0, 1, 0, 0]
def dolphin_sample():
return [randint(30, 190), randint(5, 15), randint(80, 100)]
def dolphin_class():
return [0, 0, 1, 0]
def dragon_sample():
return [randint(1200, 1800), randint(30, 40), randint(160, 180)]
def dragon_class():
return [0, 0, 0, 1]
def record(sample, classification):
return (np.array([sample], dtype=np.float32), np.array([classification], dtype=np.float32))
records = []
"""
SAMPLES = 5000
for x in range(0, SAMPLES):
print "Samples %d/%d" % (x, SAMPLES)
animals_net.train(np.array([dog_sample()], dtype=np.float32), cv2.ml.ROW_SAMPLE, np.array([dog_class()], dtype=np.float32))
animals_net.train(np.array([condor_sample(