当前位置: 代码网 > 科技>人工智能 > 【ZYNQ7020_mnist】神经网络在FPGA上的部署实现

【ZYNQ7020_mnist】神经网络在FPGA上的部署实现

2024年08月02日 人工智能 我要评论
目前的神经网络并不适合在低功耗处理器上进行训练,但是在fpga中单纯用于任务处理还是有点搞头的。本项目即实现了最最简单网络模型在FPGA上用于识别最最简单手写数字的tiny级任务。从零开始将神经网络部署到FPGA(ZYNQ7020)。

项目流程说明

目前的神经网络并不适合在低功耗处理器上进行训练,但是在fpga中单纯用于任务处理还是有点搞头的。。本项目即实现了最最简单网络模型在fpga上用于识别最最简单手写数字的tiny级任务。

一、生成预先计划的图片数据文件

从网络下载的mnist数据集包括两个csv数据文件,训练集和测试集,需要将其转换为所需的数据文件供ps端加载。

  1. 原始文件 :网络下载的mnist数据集包括两个csv数据文件,训练集和测试集。每个文件中的每一行有785个数据,第一列为标记,之后的是784个0~255之间的像素值;
  2. 需要用数据处理程序读取源文件的某一行并生成 具有特定分隔符 的数据文件;
  3. 仅作为测试用,一个文件只保存一幅图像数据即可,可以随机多生成几个文件,一是防止网络模型识别错误的小概率事件发生,二是相互对照便于比较ps端程序的稳定性;
  4. 数据均转化为0~1之间的浮点数,每个数据为4字节;
  5. 示例程序中使用python脚本读取csv文件,随机生成了5个数据文件。上代码:
import csv
import random

def normalize_pixel_value(value):
    """normalize the pixel value to be between 0 and 1."""
    return float(value) / 255.0

def read_random_row_from_csv(file_path):
    """read a random row between 1 and 10 from the csv file and return as a list of normalized floats, excluding the first value."""
    with open(file_path, newline='') as csvfile:
        reader = list(csv.reader(csvfile))
        random_row_index = random.randint(1, 10) - 1  # randomly select a row index between 0 and 9 (corresponding to rows 1 to 10)
        random_row = reader[random_row_index]  # get the selected row
        normalized_data = [normalize_pixel_value(value) for value in random_row[1:]]  # skip the first value and normalize the rest
        return normalized_data

def write_data_to_file(file_path, data):
    """write the data to a file with ',\n\r' as the separator."""
    with open(file_path, 'w') as file:
        for value in data:
            file.write(f"{value},\n\r")

def main():
    # read a random row between 1 and 10 from src.csv
    normalized_data = read_random_row_from_csv('data/mnist_test.csv')

    # write the normalized data to b.dat
    write_data_to_file('out/a05.dat', normalized_data)

if __name__ == "__main__":
    main()

二、搭建模型,训练神经网络,得到权重参数

  1. 搭建的神经网络为两个隐藏层、一个输入层、一个输出层,均为全连接网络层线性层,即y = a * x + b
  2. 输入层节点数为784,隐藏层节点数为6432,输出层节点数为10
  3. 共有3个网络权重文件和3个偏置数据文件,在网络训练完成后需要各个单独保存
  4. 这6个网络数据文件需要固化在pl端的ip核中;
  5. 示例程序中使用python脚本实现了上述功能。上代码:
# importing necessary libraries
import numpy
import scipy.special
import matplotlib.pyplot

# defining the neural network class
class neuralnetwork:

    # initializing the neural network
    def __init__(self, inputnodes, hiddennodes1, hiddennodes2, outputnodes, learningrate):
        self.inodes = inputnodes
        self.hnodes1 = hiddennodes1
        self.hnodes2 = hiddennodes2
        self.onodes = outputnodes
        self.lr = learningrate
        
        # weight initialization
        self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes1, self.inodes))
        self.whh = numpy.random.normal(0.0, pow(self.hnodes1, -0.5), (self.hnodes2, self.hnodes1))
        self.who = numpy.random.normal(0.0, pow(self.hnodes2, -0.5), (self.onodes, self.hnodes2))

        # bias initialization
        self.bih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes1, 1))
        self.bhh = numpy.random.normal(0.0, pow(self.hnodes1, -0.5), (self.hnodes2, 1))
        self.bho = numpy.random.normal(0.0, pow(self.hnodes2, -0.5), (self.onodes, 1))

        # activation function is the sigmoid function
        self.activation_function = lambda x: scipy.special.expit(x)

    # training the neural network
    def train(self, inputs_list, targets_list):
        inputs = numpy.array(inputs_list, ndmin=2).t
        targets = numpy.array(targets_list, ndmin=2).t

        hidden_inputs1 = numpy.dot(self.wih, inputs) + self.bih
        hidden_outputs1 = self.activation_function(hidden_inputs1)

        hidden_inputs2 = numpy.dot(self.whh, hidden_outputs1) + self.bhh
        hidden_outputs2 = self.activation_function(hidden_inputs2)

        final_inputs = numpy.dot(self.who, hidden_outputs2) + self.bho
        final_outputs = self.activation_function(final_inputs)

        output_errors = targets - final_outputs
        hidden_errors2 = numpy.dot(self.who.t, output_errors)
        hidden_errors1 = numpy.dot(self.whh.t, hidden_errors2)

        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)),
                                        numpy.transpose(hidden_outputs2))
        self.bho += self.lr * numpy.sum(output_errors * final_outputs * (1.0 - final_outputs), axis=1, keepdims=true)
        
        self.whh += self.lr * numpy.dot((hidden_errors2 * hidden_outputs2 * (1.0 - hidden_outputs2)),
                                        numpy.transpose(hidden_outputs1))
        self.bhh += self.lr * numpy.sum(hidden_errors2 * hidden_outputs2 * (1.0 - hidden_outputs2), axis=1, keepdims=true)
        
        self.wih += self.lr * numpy.dot((hidden_errors1 * hidden_outputs1 * (1.0 - hidden_outputs1)),
                                        numpy.transpose(inputs))
        self.bih += self.lr * numpy.sum(hidden_errors1 * hidden_outputs1 * (1.0 - hidden_outputs1), axis=1, keepdims=true)

    # querying the neural network
    def query(self, inputs_list):
        inputs = numpy.array(inputs_list, ndmin=2).t
        hidden_inputs1 = numpy.dot(self.wih, inputs) + self.bih
        hidden_outputs1 = self.activation_function(hidden_inputs1)

        hidden_inputs2 = numpy.dot(self.whh, hidden_outputs1) + self.bhh
        hidden_outputs2 = self.activation_function(hidden_inputs2)

        final_inputs = numpy.dot(self.who, hidden_outputs2) + self.bho
        final_outputs = self.activation_function(final_inputs)

        return final_outputs

    # method to save weights and biases to file
    def save_parameters(self, filename_prefix):
        numpy.savetxt(f"out/{filename_prefix}_wih.dat", self.wih, delimiter=",", newline=",\n\r")
        numpy.savetxt(f"out/{filename_prefix}_whh.dat", self.whh, delimiter=",", newline=",\n\r")
        numpy.savetxt(f"out/{filename_prefix}_who.dat", self.who, delimiter=",", newline=",\n\r")
        numpy.savetxt(f"out/{filename_prefix}_bih.dat", self.bih, delimiter=",", newline=",\n\r")
        numpy.savetxt(f"out/{filename_prefix}_bhh.dat", self.bhh, delimiter=",", newline=",\n\r")
        numpy.savetxt(f"out/{filename_prefix}_bho.dat", self.bho, delimiter=",", newline=",\n\r")


def main():
    input_nodes = 784
    hidden_nodes1 = 64
    hidden_nodes2 = 32
    output_nodes = 10
    learning_rate = 0.16
    n = neuralnetwork(input_nodes, hidden_nodes1, hidden_nodes2, output_nodes, learning_rate)

    training_data_file = open("data/mnist_train.csv", 'r')
    training_data_list = training_data_file.readlines()
    training_data_file.close()

    epochs = 15
    for e in range(epochs):
        for record in training_data_list:
            all_values = record.split(',')
            inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
            targets = numpy.zeros(output_nodes) + 0.01
            targets[int(all_values[0])] = 0.99
            n.train(inputs, targets)

    # save the weights and biases after training
    n.save_parameters("mnist")

    test_data_file = open("data/mnist_test.csv", 'r')
    test_data_list = test_data_file.readlines()
    test_data_file.close()

    scorecard = []
    for record in test_data_list:
        all_values = record.split(',')
        correct_label = int(all_values[0])
        inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
        outputs = n.query(inputs)
        label = numpy.argmax(outputs)
        scorecard.append(1 if label == correct_label else 0)

    scorecard_array = numpy.asarray(scorecard)
    print("performance = ", scorecard_array.sum() / scorecard_array.size)


if __name__ == "__main__":
    main()

三、hls设计

  1. 加载训练好的神经网络数据文件,可以在代码中添加预编译: #inculde 文件 指令,hls支持。。。
  2. hls需要用 c++ 代码实现线性层和激活层的运算,主要为for循环
  3. 添加约束和优化指令,主要是指定输入输出端口为bram总线型;最好关闭一些for循环的流水线,否则dsp资源不够用;
  4. 编写测试文件对源文件进行调试,减少返工。。
  5. 示例程序中上述功能测试已经过运行验证 。hls测试结果

四、vivado设计

  1. 导入生成的ip核,正点原子的板卡不要忘了修改makefile文件;
  2. 需要用到的外设有 ddr、uart、sd ,另外再添加上bram控制器和生成器,然后添加自定义的网络模型ip核,ip核不用更改内部参数设置,分配合适的地址和空间即可;
  3. 分析综合布局布线生成bit文件并导出硬件平台信息;
  4. 示例程序中上述功能测试已经过运行验证。

五、vitis设计

  1. 导入硬件平台信息,导入板级包支持fat系统文件操作;
  2. 编写c代码源文件,主要是从sd卡读取图片信息,然后送入网络模型入口,然后从网络模型出口处读取数据,经过串口打印显示;
  3. 注意内存地址的读写容易出问题从而陷入异常无限循环无法自拔。。
  4. 示例程序中上述功能测试已经过运行验证,其识别效果并不稳定,时好时坏,暂未解决。。。。(不过可以肯定的是pl的ip核是有用的,基本目的已经达成。)
  5. 后续可优化的部分还有,额,很多很多,如果有哪位大佬有相关的优化想法和方法或者相关问题的解决方案,还望一起交流啊~,先谢了

程序说明

本文所使用的源代码和模型结构大部分基于这篇文章进行微调(换了个马甲):

参考贴文链接:: 如何从零开始将神经网络移植到fpga(zynq7020)加速

本项目代码已经发布到github,若需要请自取,链接地址 ::zynq7020_mnist 项目文件

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com