【Python实战】——神经网络识别手写数字(三)

简介: 【Python实战】——神经网络识别手写数字

【Python实战】——神经网络识别手写数字(二)+https://developer.aliyun.com/article/1506501

3 模型优化

3.1 调整神经元数量

3.1.1 每次epoch训练预测情况

  运行程序:

##更换隐藏神经元数量为50
epochs = 50
train_acc=[]
test_acc=[]
NN = NeuralNetwork(num_of_in_nodes = image_pixels, 
                   num_of_out_nodes = 10, 
                   num_of_hidden_nodes = 50,
                   learning_rate = 0.1)
for epoch in range(epochs):  
    print("epoch: ", epoch)
    for i in range(len(train_imgs)):
        NN.train(train_imgs[i], 
                 train_labels_one_hot[i])
  
    corrects, wrongs = NN.evaluate(train_imgs, train_labels)
    print("accuracy train: ", corrects / ( corrects + wrongs))
    train_acc.append(corrects / ( corrects + wrongs))
    corrects, wrongs = NN.evaluate(test_imgs, test_labels)
    print("accuracy: test", corrects / ( corrects + wrongs))
    test_acc.append(corrects / ( corrects + wrongs))

  运行结果:

epoch:  0
accuracy train:  0.93605
accuracy: test 0.935
epoch:  1
accuracy train:  0.95185
accuracy: test 0.9501
epoch:  2
accuracy train:  0.9570333333333333
accuracy: test 0.9526
epoch:  3
accuracy train:  0.9630833333333333
accuracy: test 0.9556
epoch:  4
accuracy train:  0.9640166666666666
accuracy: test 0.9556
epoch:  5
accuracy train:  0.9668333333333333
accuracy: test 0.957
epoch:  6
accuracy train:  0.96765
accuracy: test 0.957
epoch:  7
accuracy train:  0.9673166666666667
accuracy: test 0.9566
epoch:  8
accuracy train:  0.96875
accuracy: test 0.9559
epoch:  9
accuracy train:  0.97145
accuracy: test 0.957
epoch:  10
accuracy train:  0.974
accuracy: test 0.9579
epoch:  11
accuracy train:  0.9730666666666666
accuracy: test 0.9569
epoch:  12
accuracy train:  0.9730166666666666
accuracy: test 0.9581
epoch:  13
accuracy train:  0.9747666666666667
accuracy: test 0.959
epoch:  14
accuracy train:  0.9742166666666666
accuracy: test 0.9581
epoch:  15
accuracy train:  0.97615
accuracy: test 0.9596
epoch:  16
accuracy train:  0.9759
accuracy: test 0.9586
epoch:  17
accuracy train:  0.9773166666666666
accuracy: test 0.9596
epoch:  18
accuracy train:  0.9778833333333333
accuracy: test 0.9606
epoch:  19
accuracy train:  0.9789166666666667
accuracy: test 0.9589
epoch:  20
accuracy train:  0.9777333333333333
accuracy: test 0.9582
epoch:  21
accuracy train:  0.9774
accuracy: test 0.9573
epoch:  22
accuracy train:  0.9796166666666667
accuracy: test 0.9595
epoch:  23
accuracy train:  0.9792666666666666
accuracy: test 0.959
epoch:  24
accuracy train:  0.9804333333333334
accuracy: test 0.9591
epoch:  25
accuracy train:  0.9806
accuracy: test 0.9589
epoch:  26
accuracy train:  0.98105
accuracy: test 0.9596
epoch:  27
accuracy train:  0.9806833333333334
accuracy: test 0.9587
epoch:  28
accuracy train:  0.9809833333333333
accuracy: test 0.9595
epoch:  29
accuracy train:  0.9813333333333333
accuracy: test 0.9595

3.1.2 正确率绘图

  运行程序:

#正确率绘图
# matplotlib其实是不支持显示中文的 显示中文需要一行代码设置字体  
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.family'] = 'SimHei'  
plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)  
import matplotlib.pyplot as plt 
x=np.arange(1,31,1)
plt.title('神经元数量为50时正确率')
plt.plot(x, train_acc, color='green', label='训练集')
plt.plot(x, test_acc, color='red', label='测试集')
plt.legend() # 显示图例
plt.show()

  运行结果:

3.2 更换隐藏层层数

3.2.1 每次epoch训练预测情况

  运行程序:

#隐藏层层数为2
class NeuralNetwork:
    
    def __init__(self, 
                 num_of_in_nodes, #输入节点数
                 num_of_out_nodes, #输出节点数
                 num_of_hidden_nodes1,#隐藏第一层节点数
                 num_of_hidden_nodes2,#隐藏第二层节点数
                 learning_rate):#学习率
        self.num_of_in_nodes = num_of_in_nodes
        self.num_of_out_nodes = num_of_out_nodes
        self.num_of_hidden_nodes1 = num_of_hidden_nodes1
        self.num_of_hidden_nodes2 = num_of_hidden_nodes2
        self.learning_rate = learning_rate 
        self.create_weight_matrices()
    #初始为一个隐藏节点    
    def create_weight_matrices(self):#创建权重矩阵
       
        #A method to initialize the weight 
        #matrices of the neural network#一种初始化神经网络权重矩阵的方法
        
        rad = 1 / np.sqrt(self.num_of_in_nodes)  
        X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)  #形成指定分布
        self.weight_1 = X.rvs((self.num_of_hidden_nodes1, self.num_of_in_nodes)) #rvs:产生服从指定分布的随机数
        
        rad = 1 / np.sqrt(self.num_of_hidden_nodes1)
        X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
        self.weight_2 = X.rvs((self.num_of_hidden_nodes2, self.num_of_hidden_nodes1)) #rvs: 产生服从指定分布的随机数
        
        rad = 1 / np.sqrt(self.num_of_hidden_nodes2)
        X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
        self.weight_3 = X.rvs((self.num_of_out_nodes, self.num_of_hidden_nodes2)) #rvs: 产生服从指定分布的随机数
    def train(self, input_vector, target_vector):
        
        #input_vector and target_vector can 
        #be tuple, list or ndarray
      
        
        input_vector = np.array(input_vector, ndmin=2).T#输入
        target_vector = np.array(target_vector, ndmin=2).T#输出
        
        output_vector1 = np.dot(self.weight_1, input_vector) #隐藏层值
        output_hidden1 = activation_function(output_vector1)#删除不激活
        
        output_vector2 = np.dot(self.weight_2, output_hidden1)#输出
        output_hidden2 = activation_function(output_vector2)#删除不激活
        
        output_vector3 = np.dot(self.weight_3, output_hidden2)#输出
        output_network = activation_function(output_vector3)##删除不激活
        
        
        # calculate output errors:计算输出误差
        output_errors = target_vector - output_network
        
        # update the weights:更新权重
        tmp = output_errors * output_network * (1.0 - output_network)     
        self.weight_3 += self.learning_rate  * np.dot(tmp, output_hidden2.T)
        
        hidden1_errors = np.dot(self.weight_3.T, output_errors)
        
        tmp = hidden1_errors * output_hidden2 * (1.0 - output_hidden2)     
        self.weight_2 += self.learning_rate  * np.dot(tmp, output_hidden1.T)
        # calculate hidden errors:计算隐藏层误差
        hidden_errors = np.dot(self.weight_2.T, hidden1_errors)
        
        # update the weights:
        tmp = hidden_errors * output_hidden1 * (1.0 - output_hidden1)
        self.weight_1 += self.learning_rate * np.dot(tmp, input_vector.T)
        
    #测试集
    def run(self, input_vector):
        # input_vector can be tuple, list or ndarray
        input_vector = np.array(input_vector, ndmin=2).T
        
        output_vector = np.dot(self.weight_1, input_vector)
        output_vector = activation_function(output_vector)
        
        output_vector = np.dot(self.weight_2, output_vector)
        output_vector = activation_function(output_vector)
        
        output_vector = np.dot(self.weight_3, output_vector)
        output_vector = activation_function(output_vector)
        return output_vector
    #判别矩阵
    def confusion_matrix(self, data_array, labels):
        cm = np.zeros((10, 10), int)
        for i in range(len(data_array)):
            res = self.run(data_array[i])
            res_max = res.argmax()
            target = labels[i][0]
            cm[res_max, int(target)] += 1
        return cm    
     #精确度
    def precision(self, label, confusion_matrix):
        col = confusion_matrix[:, label]
        return confusion_matrix[label, label] / col.sum()
    #评估
    def evaluate(self, data, labels):
        corrects, wrongs = 0, 0
        for i in range(len(data)):
            res = self.run(data[i])
            res_max = res.argmax()
            if res_max == labels[i]:
                corrects += 1
            else:
                wrongs += 1
        return corrects, wrongs
        
##迭代30次
epochs = 30
train_acc=[]
test_acc=[]
NN = NeuralNetwork(num_of_in_nodes = image_pixels, 
                   num_of_out_nodes = 10, 
                   num_of_hidden_nodes1 = 100,
                   num_of_hidden_nodes2 = 100,
                   learning_rate = 0.1)
for epoch in range(epochs):  
    print("epoch: ", epoch)
    for i in range(len(train_imgs)):
        NN.train(train_imgs[i], 
                 train_labels_one_hot[i])
  
    corrects, wrongs = NN.evaluate(train_imgs, train_labels)
    print("accuracy train: ", corrects / ( corrects + wrongs))
    train_acc.append(corrects / ( corrects + wrongs))
    corrects, wrongs = NN.evaluate(test_imgs, test_labels)
    print("accuracy: test", corrects / ( corrects + wrongs))
    test_acc.append(corrects / ( corrects + wrongs))

  运行结果:

epoch:  0
accuracy train:  0.8972333333333333
accuracy: test 0.9005
epoch:  1
accuracy train:  0.8891833333333333
accuracy: test 0.8936
epoch:  2
accuracy train:  0.9146833333333333
accuracy: test 0.9182
epoch:  3
D:\ananconda\lib\site-packages\ipykernel_launcher.py:5: RuntimeWarning: overflow encountered in power
  """
accuracy train:  0.8974833333333333
accuracy: test 0.894
epoch:  4
accuracy train:  0.8924166666666666
accuracy: test 0.8974
epoch:  5
accuracy train:  0.91295
accuracy: test 0.914
epoch:  6
accuracy train:  0.9191166666666667
accuracy: test 0.9205
epoch:  7
accuracy train:  0.9117666666666666
accuracy: test 0.9162
epoch:  8
accuracy train:  0.9220333333333334
accuracy: test 0.9222
epoch:  9
accuracy train:  0.9113833333333333
accuracy: test 0.9112
epoch:  10
accuracy train:  0.9134333333333333
accuracy: test 0.911
epoch:  11
accuracy train:  0.9112166666666667
accuracy: test 0.9103
epoch:  12
accuracy train:  0.914
accuracy: test 0.9126
epoch:  13
accuracy train:  0.9206833333333333
accuracy: test 0.9214
epoch:  14
accuracy train:  0.90945
accuracy: test 0.9073
epoch:  15
accuracy train:  0.9225166666666667
accuracy: test 0.9287
epoch:  16
accuracy train:  0.9226
accuracy: test 0.9205
epoch:  17
accuracy train:  0.9239833333333334
accuracy: test 0.9202
epoch:  18
accuracy train:  0.91925
accuracy: test 0.9191
epoch:  19
accuracy train:  0.9223166666666667
accuracy: test 0.92
epoch:  20
accuracy train:  0.9113
accuracy: test 0.9084
epoch:  21
accuracy train:  0.9241666666666667
accuracy: test 0.925
epoch:  22
accuracy train:  0.9236333333333333
accuracy: test 0.9239
epoch:  23
accuracy train:  0.9301166666666667
accuracy: test 0.9259
epoch:  24
accuracy train:  0.9195166666666666
accuracy: test 0.9186
epoch:  25
accuracy train:  0.9200833333333334
accuracy: test 0.9144
epoch:  26
accuracy train:  0.9204833333333333
accuracy: test 0.9186
epoch:  27
accuracy train:  0.9288666666666666
accuracy: test 0.9259
epoch:  28
accuracy train:  0.9293
accuracy: test 0.9282
epoch:  29
accuracy train:  0.9254666666666667
accuracy: test 0.9242

3.2.2 正确率绘图

  运行程序:

#正确率绘图
# matplotlib其实是不支持显示中文的 显示中文需要一行代码设置字体  
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.family'] = 'SimHei'  
plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)  
import matplotlib.pyplot as plt 
x=np.arange(1,31,1)
plt.title('隐藏层数为2时正确率')
plt.plot(x, train_acc, color='green', label='训练集')
plt.plot(x, test_acc, color='red', label='测试集')
plt.legend() # 显示图例
plt.show()

  运行结果:

相关文章
|
15天前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。
|
16天前
|
机器学习/深度学习 人工智能 算法
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
宠物识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了37种常见的猫狗宠物种类数据集【'阿比西尼亚猫(Abyssinian)', '孟加拉猫(Bengal)', '暹罗猫(Birman)', '孟买猫(Bombay)', '英国短毛猫(British Shorthair)', '埃及猫(Egyptian Mau)', '缅因猫(Maine Coon)', '波斯猫(Persian)', '布偶猫(Ragdoll)', '俄罗斯蓝猫(Russian Blue)', '暹罗猫(Siamese)', '斯芬克斯猫(Sphynx)', '美国斗牛犬
97 29
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
|
16天前
|
小程序 开发者 Python
探索Python编程:从基础到实战
本文将引导你走进Python编程的世界,从基础语法开始,逐步深入到实战项目。我们将一起探讨如何在编程中发挥创意,解决问题,并分享一些实用的技巧和心得。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考。让我们一起开启Python编程的探索之旅吧!
41 10
|
16天前
|
机器学习/深度学习 人工智能 算法
深度学习入门:用Python构建你的第一个神经网络
在人工智能的海洋中,深度学习是那艘能够带你远航的船。本文将作为你的航标,引导你搭建第一个神经网络模型,让你领略深度学习的魅力。通过简单直观的语言和实例,我们将一起探索隐藏在数据背后的模式,体验从零开始创造智能系统的快感。准备好了吗?让我们启航吧!
42 3
|
17天前
|
存储 安全 网络安全
网络安全的盾与剑:漏洞防御与加密技术的实战应用
在数字化浪潮中,网络安全成为保护信息资产的重中之重。本文将深入探讨网络安全的两个关键领域——安全漏洞的防御策略和加密技术的应用,通过具体案例分析常见的安全威胁,并提供实用的防护措施。同时,我们将展示如何利用Python编程语言实现简单的加密算法,增强读者的安全意识和技术能力。文章旨在为非专业读者提供一扇了解网络安全复杂世界的窗口,以及为专业人士提供可立即投入使用的技术参考。
|
20天前
|
存储 缓存 监控
Docker容器性能调优的关键技巧,涵盖CPU、内存、网络及磁盘I/O的优化策略,结合实战案例,旨在帮助读者有效提升Docker容器的性能与稳定性。
本文介绍了Docker容器性能调优的关键技巧,涵盖CPU、内存、网络及磁盘I/O的优化策略,结合实战案例,旨在帮助读者有效提升Docker容器的性能与稳定性。
54 7
|
24天前
|
机器学习/深度学习 自然语言处理 语音技术
Python在深度学习领域的应用,重点讲解了神经网络的基础概念、基本结构、训练过程及优化技巧
本文介绍了Python在深度学习领域的应用,重点讲解了神经网络的基础概念、基本结构、训练过程及优化技巧,并通过TensorFlow和PyTorch等库展示了实现神经网络的具体示例,涵盖图像识别、语音识别等多个应用场景。
48 8
|
28天前
|
算法 Unix 数据库
Python编程入门:从基础到实战
本篇文章将带你进入Python编程的奇妙世界。我们将从最基础的概念开始,逐步深入,最后通过一个实际的项目案例,让你真正体验到Python编程的乐趣和实用性。无论你是编程新手,还是有一定基础的开发者,这篇文章都将为你提供有价值的信息和知识。让我们一起探索Python的世界吧!
|
29天前
|
并行计算 调度 开发者
探索Python中的异步编程:从基础到实战
在Python的世界里,异步编程是一种让程序运行更加高效、响应更快的技术。本文不仅会介绍异步编程的基本概念和原理,还将通过具体代码示例展示如何在Python中实现异步操作。无论你是初学者还是有经验的开发者,都能从中获益,了解如何运用这一技术优化你的项目。
|
29天前
|
数据处理 Python
探索Python中的异步编程:从基础到实战
在Python的世界中,“速度”不仅是赛车手的追求。本文将带你领略Python异步编程的魅力,从原理到实践,我们不单单是看代码,更通过实例感受它的威力。你将学会如何用更少的服务器资源做更多的事,就像是在厨房里同时烹饪多道菜而不让任何一道烧焦。准备好了吗?让我们开始这场技术烹饪之旅。
下一篇
DataWorks