【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()

  运行结果:

相关文章
|
9天前
|
Python
Python中的异步编程:使用asyncio和aiohttp实现高效网络请求
【10月更文挑战第34天】在Python的世界里,异步编程是提高效率的利器。本文将带你了解如何使用asyncio和aiohttp库来编写高效的网络请求代码。我们将通过一个简单的示例来展示如何利用这些工具来并发地处理多个网络请求,从而提高程序的整体性能。准备好让你的Python代码飞起来吧!
26 2
|
7天前
|
数据采集 机器学习/深度学习 人工智能
Python编程入门:从基础到实战
【10月更文挑战第36天】本文将带你走进Python的世界,从基础语法出发,逐步深入到实际项目应用。我们将一起探索Python的简洁与强大,通过实例学习如何运用Python解决问题。无论你是编程新手还是希望扩展技能的老手,这篇文章都将为你提供有价值的指导和灵感。让我们一起开启Python编程之旅,用代码书写想法,创造可能。
|
5天前
|
机器学习/深度学习 人工智能 算法
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
垃圾识别分类系统。本系统采用Python作为主要编程语言,通过收集了5种常见的垃圾数据集('塑料', '玻璃', '纸张', '纸板', '金属'),然后基于TensorFlow搭建卷积神经网络算法模型,通过对图像数据集进行多轮迭代训练,最后得到一个识别精度较高的模型文件。然后使用Django搭建Web网页端可视化操作界面,实现用户在网页端上传一张垃圾图片识别其名称。
25 0
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
|
8天前
|
机器学习/深度学习 数据可视化 数据处理
Python数据科学:从基础到实战
Python数据科学:从基础到实战
16 1
|
9天前
|
机器学习/深度学习 JSON API
Python编程实战:构建一个简单的天气预报应用
Python编程实战:构建一个简单的天气预报应用
23 1
|
4天前
|
数据采集 存储 数据处理
探索Python中的异步编程:从基础到实战
【10月更文挑战第39天】在编程世界中,时间就是效率的代名词。Python的异步编程特性,如同给程序穿上了一双翅膀,让它们在执行任务时飞得更高、更快。本文将带你领略Python异步编程的魅力,从理解其背后的原理到掌握实际应用的技巧,我们不仅会讨论理论基础,还会通过实际代码示例,展示如何利用这些知识来提升你的程序性能。准备好让你的Python代码“起飞”了吗?让我们开始这场异步编程的旅程!
13 0
|
8天前
|
并行计算 数据挖掘 大数据
Python数据分析实战:利用Pandas处理大数据集
Python数据分析实战:利用Pandas处理大数据集
|
文字识别 开发工具 Python
Python编程:通过百度文字识别提取表格数据
Python编程:通过百度文字识别提取表格数据
222 0
Python编程:通过百度文字识别提取表格数据
|
4天前
|
机器学习/深度学习 人工智能 TensorFlow
人工智能浪潮下的自我修养:从Python编程入门到深度学习实践
【10月更文挑战第39天】本文旨在为初学者提供一条清晰的道路,从Python基础语法的掌握到深度学习领域的探索。我们将通过简明扼要的语言和实际代码示例,引导读者逐步构建起对人工智能技术的理解和应用能力。文章不仅涵盖Python编程的基础,还将深入探讨深度学习的核心概念、工具和实战技巧,帮助读者在AI的浪潮中找到自己的位置。
|
4天前
|
机器学习/深度学习 数据挖掘 Python
Python编程入门——从零开始构建你的第一个程序
【10月更文挑战第39天】本文将带你走进Python的世界,通过简单易懂的语言和实际的代码示例,让你快速掌握Python的基础语法。无论你是编程新手还是想学习新语言的老手,这篇文章都能为你提供有价值的信息。我们将从变量、数据类型、控制结构等基本概念入手,逐步过渡到函数、模块等高级特性,最后通过一个综合示例来巩固所学知识。让我们一起开启Python编程之旅吧!