前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >机器学习-10-神经网络python实现-鸢尾花分类

机器学习-10-神经网络python实现-鸢尾花分类

作者头像
用户2225445
发布2024-05-05 08:25:43
1670
发布2024-05-05 08:25:43
举报
文章被收录于专栏:IT从业者张某某IT从业者张某某

总结

本系列是机器学习课程的系列课程,主要介绍基于python实现神经网络。

参考

机器学习-10-神经网络python实现-从零开始

本门课程的目标

完成一个特定行业的算法应用全过程:

懂业务+会选择合适的算法+数据处理+算法训练+算法调优+算法融合

+算法评估+持续调优+工程化接口实现

机器学习定义

关于机器学习的定义,Tom Michael Mitchell的这段话被广泛引用: 对于某类任务T性能度量P,如果一个计算机程序在T上其性能P随着经验E而自我完善,那么我们称这个计算机程序从经验E中学习

从零构建神经网络

手写数据集MNIST介绍

mnist_dataset

MNIST数据集是一个包含大量手写数字的集合。 在图像处理领域中,它是一个非常受欢迎的数据集。 经常被用于评估机器学习算法的性能。 MNIST是改进的标准与技术研究所数据库的简称。 MNIST 包含了一个由 70,000 个 28 x 28 的手写数字图像组成的集合,涵盖了从0到9的数字。

本文通过神经网络基于MNIST数据集进行手写识别。

代码读取数据集MNIST

导入库

代码语言:javascript
复制
import numpy
import matplotlib.pyplot

读取mnist_train_100.csv

代码语言:javascript
复制
# open the CSV file and read its contents into a list
data_file = open("mnist_dataset/mnist_train_100.csv", 'r')
data_list = data_file.readlines()
data_file.close()

查看数据集的长度

代码语言:javascript
复制
# check the number of data records (examples)
len(data_list)
# 输出为 100

查看一条数据,这个数据是手写数字的像素值

代码语言:javascript
复制
# show a dataset record
# the first number is the label, the rest are pixel colour values (greyscale 0-255)
data_list[1]

输出为:

需要注意的是,这个字符串的第一个字为真实label,比如

代码语言:javascript
复制
data_list[50]

输出为:

这个输出看不懂,因为这是一个很长的字符串,我们对其进行按照逗号进行分割,然后输出为28*28的,就能看出来了

代码语言:javascript
复制
# take the data from a record, rearrange it into a 28*28 array and plot it as an image
all_values = data_list[50].split(',')
num=0
for i in all_values[1:]:
    num = num +1
    print("%-3s"%(i),end=' ')
    if num==28:
        num = 0
        print('',end='\n')

输出为:

通过用图片的方式查看

代码语言:javascript
复制
# take the data from a record, rearrange it into a 28*28 array and plot it as an image
all_values = data_list[50].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28,28))
matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')

输出为:

这个像素值为0-255,对其进行归一化操作

代码语言:javascript
复制
# scale input to range 0.01 to 1.00
scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
# print(scaled_input)
scaled_input

输出为:

构建一个包含十个输出的标签

代码语言:javascript
复制
#output nodes is 10 (example)
onodes = 10
targets = numpy.zeros(onodes) + 0.01
targets[int(all_values[0])] = 0.99
# print(targets)
targets

输出为:

神经网络实现

导入库

代码语言:javascript
复制
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# library for plotting arrays
import matplotlib.pyplot

神经网络实现

代码语言:javascript
复制
# neural network class definition
# 神经网络类定义
class neuralNetwork:
    
    
    # initialise the neural network
    # 初始化神经网络
    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
        # set number of nodes in each input, hidden, output layer
        # 设置每个输入、隐藏、输出层的节点数
        self.inodes = inputnodes
        self.hnodes = hiddennodes
        self.onodes = outputnodes
        
        # link weight matrices, wih and who
        # weights inside the arrays are w_i_j, where link is from node i to node j in the next layer
        # w11 w21
        # w12 w22 etc 
        # 链接权重矩阵,wih和who
        # 数组内的权重w_i_j,链接从节点i到下一层的节点j
        # w11 w21
        # w12 w22 等等
        self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
        self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))

        # learning rate 学习率
        self.lr = learningrate
        
        # activation function is the sigmoid function
        # 激活函数是sigmoid函数
        self.activation_function = lambda x: scipy.special.expit(x)
        
        pass

    
    # train the neural network
    # 训练神经网络
    def train(self, inputs_list, targets_list):
        # convert inputs list to 2d array
        # 将输入列表转换为2d数组
        inputs = numpy.array(inputs_list, ndmin=2).T
        targets = numpy.array(targets_list, ndmin=2).T
        
        # calculate signals into hidden layer
        # 计算输入到隐藏层的信号
        hidden_inputs = numpy.dot(self.wih, inputs)
        # calculate the signals emerging from hidden layer
        # 计算从隐藏层输出的信号
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # calculate signals into final output layer
        # 计算最终输出层的信号
        final_inputs = numpy.dot(self.who, hidden_outputs)
        # calculate the signals emerging from final output layer
        # 计算从最终输出层输出的信号
        final_outputs = self.activation_function(final_inputs)
        
        # output layer error is the (target - actual)
        # 输出层误差是(目标 - 实际)
        output_errors = targets - final_outputs
        # hidden layer error is the output_errors, split by weights, recombined at hidden nodes
        # 隐藏层误差是输出层误差,按权重分解,在隐藏节点重新组合
        hidden_errors = numpy.dot(self.who.T, output_errors) 
        
        # update the weights for the links between the hidden and output layers
        # 更新隐藏层和输出层之间的权重
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
        
        # update the weights for the links between the input and hidden layers
        # 更新输入层和隐藏层之间的权重
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
        
        pass

    
    # query the neural network
    # 查询神经网络
    def query(self, inputs_list):
        # convert inputs list to 2d array
        # 将输入列表转换为2d数组
        inputs = numpy.array(inputs_list, ndmin=2).T
        
        # calculate signals into hidden layer
        # 计算输入到隐藏层的信号
        hidden_inputs = numpy.dot(self.wih, inputs)
        # calculate the signals emerging from hidden layer
        # 计算从隐藏层输出的信号
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # calculate signals into final output layer
        # 计算最终输出层的信号
        final_inputs = numpy.dot(self.who, hidden_outputs)
        # calculate the signals emerging from final output layer
        # 计算从最终输出层输出的信号
        final_outputs = self.activation_function(final_inputs)
        
        return final_outputs

定义参数,并初始化神经网络

代码语言:javascript
复制
# number of input, hidden and output nodes
input_nodes = 784
hidden_nodes = 200
output_nodes = 10

# learning rate
learning_rate = 0.1

# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
n # <__main__.neuralNetwork at 0x2778590e5e0>

查看数据集

代码语言:javascript
复制
# load the mnist training data CSV file into a list
training_data_file = open("mnist_dataset/mnist_train.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
len(training_data_list) # 60001
# 其中第1行为列名 ,后面需要去掉,只保留后60000条

开始训练,该步骤需要等待一会,才能训练完成

代码语言:javascript
复制
# train the neural network
# 训练神经网络
# epochs is the number of times the training data set is used for training
# epochs次数,循环训练5次
epochs = 5

for e in range(epochs):
    # go through all records in the training data set
    # 每次取60000条数据,剔除列名
    for record in training_data_list[1:]:
        # split the record by the ',' commas
        # 用逗号分割
        all_values = record.split(',')
        # scale and shift the inputs
        # 对图像的像素值进行归一化操作
        inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
        # create the target output values (all 0.01, except the desired label which is 0.99)
        # 创建一个包含十个输出的向量,初始值为0.01
        targets = numpy.zeros(output_nodes) + 0.01
        # all_values[0] is the target label for this record
        # 对 label的 位置设置为0.99
        targets[int(all_values[0])] = 0.99
        # 开始训练
        n.train(inputs, targets)
        pass
    pass

查看训练后的权重

代码语言:javascript
复制
n.who.shape # (10, 200)
n.who

输出为:

代码语言:javascript
复制
n.wih.shape # ((200, 784)
n.wih

输出为:

查看测试集

代码语言:javascript
复制
# load the mnist test data CSV file into a list
test_data_file = open("mnist_dataset/mnist_test.csv", 'r')
test_data_list = test_data_file.readlines()
test_data_file.close()
len(test_data_list) # 10001
# 其中第1行为列名 ,后面需要去掉,只保留后10000条

预测测试集

代码语言:javascript
复制
# test the neural network
# 测试网络
# scorecard for how well the network performs, initially empty
# 计算网络性能,初始为空
scorecard = []

# go through all the records in the test data set
# 传入所有的测试集
for record in test_data_list[1:]:
    # split the record by the ',' commas
    # 使用逗号分割
    all_values = record.split(',')
    # correct answer is first value
    # 获取当前的测试集的label
    correct_label = int(all_values[0])
    # scale and shift the inputs
    # 归一化操作
    inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
    # query the network
    # 对测试集进行预测
    outputs = n.query(inputs)
    # the index of the highest value corresponds to the label
    # 获取输出中最大的概率的位置
    label = numpy.argmax(outputs)
    # append correct or incorrect to list
    # 按照预测的正确与否分别填入1和0
    if (label == correct_label):
        # network's answer matches correct answer, add 1 to scorecard
        # 答案匹配正确,输入1
        scorecard.append(1)
    else:
        # network's answer doesn't match correct answer, add 0 to scorecard
        # 答案不匹配,输入0
        scorecard.append(0)
        pass
    
    pass

计算网络性能

代码语言:javascript
复制
# calculate the performance score, the fraction of correct answers
scorecard_array = numpy.asarray(scorecard)
print ("performance = ", scorecard_array.sum() / scorecard_array.size)
# performance =  0.9725

输出为:

performance = 0.9725

基于神经网络实现鸢尾花数据集
代码语言:javascript
复制
# 使用sklearn分割数据
#导入数据集模块
from sklearn import datasets
#分别加载iris和digits数据集
iris_dataset = datasets.load_iris()  #鸢尾花数据集

print(iris_dataset.keys())
# dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])
iris_dataset.data[0]

# array([5.1, 3.5, 1.4, 0.2])
代码语言:javascript
复制
#output nodes is 10 (example)
onodes = 3
targets = numpy.zeros(onodes) + 0.01

targets

targets[int(iris_dataset.target[0])] = 0.99
# print(targets)
targets

# 0.99 0.01 0.01
代码语言:javascript
复制
# number of input, hidden and output nodes
input_nodes = 4
hidden_nodes = 20
output_nodes = 3

# learning rate
learning_rate = 0.1

# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
n # <__main__.neuralNetwork at 0x2778590e5e0>

# 鸢尾花分类
# 3.2 1.67 0.8 0.54  0
代码语言:javascript
复制
# train the neural network
# 训练神经网络
# epochs is the number of times the training data set is used for training
# epochs次数,循环训练5次
epochs = 100

for e in range(epochs):
    # go through all records in the training data set
    # 每次取60000条数据,剔除列名
    print("\n epochs------->",e)
    num = 0
    data_list = len(iris_dataset.data[:])
    nc = 0
    for record,label in zip(iris_dataset.data[:],iris_dataset.target[:]):
        # split the record by the ',' commas
        # 用逗号分割
        # scale and shift the inputs
        # 对图像的像素值进行归一化操作
        inputs = numpy.asfarray(record)
        # create the target output values (all 0.01, except the desired label which is 0.99)
        # 创建一个包含十个输出的向量,初始值为0.01
        targets = numpy.zeros(output_nodes) + 0.01
        # all_values[0] is the target label for this record
        # 对 label的 位置设置为0.99
        targets[int(label)] = 0.99
        # 开始训练
        n.train(inputs, targets)
        num +=1 
        
        nc = nc+1
        if num %10==0:
            print("\r epochs {} 当前进度为 {}".format(e,num/data_list),end="")
        pass
    pass
代码语言:javascript
复制
inputs= numpy.asfarray([5.1, 3.5, 1.4, 0.2])
outputs = n.query(inputs)
# the index of the highest value corresponds to the label
# 获取输出中最大的概率的位置
label = numpy.argmax(outputs)
label
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-05-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总结
  • 参考
  • 本门课程的目标
  • 机器学习定义
  • 从零构建神经网络
    • 手写数据集MNIST介绍
      • 代码读取数据集MNIST
        • 神经网络实现
          • 基于神经网络实现鸢尾花数据集
          相关产品与服务
          腾讯云服务器利旧
          云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档


          http://www.vxiaotou.com