# 用BP人工神经网络识别手写数字——《Python也可以》

def convert_to_bw(im):

im = im.convert("L")

im.save("sample_L.bmp")

im = im.point(lambda x: WHITE if x > 196 else BLACK)

im = im.convert('1')

im.save("sample_1.bmp")

return im

def split(im):

assert im.mode == '1'

result = []

w, h = im.size

xs = [0, 23, 57, 77, 106, 135, 159, 179, 205, 228, w]

ys = [0, 22, 60, 97, 150, h]

for i, x in enumerate(xs):

if i + 1 >= len(xs):

break

for j, y in enumerate(ys):

if j + 1 >= len(ys):

break

box = (x, y, xs[i+1], ys[j+1])

t = im.crop(box).copy()

box = box + ((i + 1) % 10, )

# save_32_32(t, 'num_%d_%d_%d_%d_%d'%box)

result.append((normalize_32_32(t, 'num_%d_%d_%d_%d_%d'%box), (i + 1) % 10))

return result

0 0 4 4 4 2 0 0 0 0 0 0 0 0 2 4 0 0 4 4 4 2 0 0 0 0 0 0 0 0 2 4 2 2 4 4 2 1 0 0 0 0 0 0 1 2 3 4 4 4 4 4 0 0 0 0 0 0 0 0 2 4 4 4 4 4 4 4 0 0 0 0 0 0 0 0 2 4 4 4 4 4 0 0 0 0 0 0 0 0 0 0 2 4 4 4 4 4 0 0 0 0 0 0 0 0 0 0 2 4 4 4 4 4 0 0 0 0 0 0 0 4 4 4 4 4 4 4 4 4 0 0 0 0 0 0 0 4 4 4 4 4 4 4 4 4 2 2 2 2 2 2 2 4 4 2 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 0 2 4 4 4 2 2 2 2 4 3 2 2 2 2 2 0 2 4 4 4 0 0 0 0 4 2 0 0 0 0 0 0 2 4 4 4 0 0 0 0 4 2 0 0 0 0 0 0 2 4 4 4 0 0 0 0 0 0 0 0 0 0 0 0 2 4 4 4 0 0 0 0 0 0 0 0 0 0 0 0 2 4 4 4

f = open('train.data', 'wt')

print >>f, len(result), 256, 10

for input, output in result:

print >>f, input

print >>f, output

BP神经网络

connectionRate = 1

learningRate = 0.008

desiredError = 0.001

maxIterations = 10000

iterationsBetweenReports = 100

inNum= 256

hideNum = 64

outNum=10

class NeuNet(neural_net):

def __init__(self):

neural_net.__init__(self)

neural_net.create_standard_array(self,(inNum, hideNum, outNum))

def train_on_file(self,fileName):

neural_net.train_on_file(self,fileName,maxIterations,iterationsBetweenReports,desiredError)

if __name__ == "__main__":

ann = NeuNet()

ann.train_on_file("train.data")

ann.save("number_char_recognize2.net")

if __name__ == "__main__":

ann = NeuNet()

ann.create_from_file("number_char_recognize.net")

for k, v in data.iteritems():

k = string_to_list(k)

v = string_to_list(v)

result = ann.run(k)

print euclidean_distance(v, result)

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180206A1D4G200?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-12-05

2021-12-05

2021-12-05

2021-12-05

2021-12-05

2021-12-05

2018-05-23

2018-04-18

2021-12-05

2021-12-05

2021-12-05

2021-12-05