C++从零实现简单深度神经网络(基于OpenCV)

代码地址如下:
http://www.demodashi.com/demo/11138.html

一、准备工作

  • 需要准备什么环境

需要安装有Visual Studio并且配置了OpenCV。能够使用OpenCV的core模块。
使用者需要有基本的C++编程基础。

  • 本例子实现什么功能

本例实现了简单的深度神经网络,基于OpenCV的矩阵类Mat。程序实现了BP算法,支持创建和训练多层神经网络,支持loss可视化。支持模型的保存和加载。

二、示例代码

新建和初始化一个神经网络的过程非常简单,像下面这样:

	//Set neuron number of every layer
	vector<int> layer_neuron_num = { 784,100,10 };

	// Initialise Net and weights
	Net net;
	net.initNet(layer_neuron_num);
	net.initWeights(0, 0., 0.01);
	net.initBias(Scalar(0.5));

训练神经网络也很容易,下面是一个例子。训练完之后可以保存模型

#include"../include/Net.h"
//<opencv2\opencv.hpp>

using namespace std;
using namespace cv;
using namespace liu;

int main(int argc, char *argv[])
{
	//Set neuron number of every layer
	vector<int> layer_neuron_num = { 784,100,10 };

	// Initialise Net and weights
	Net net;
	net.initNet(layer_neuron_num);
	net.initWeights(0, 0., 0.01);
	net.initBias(Scalar(0.5));

	//Get test samples and test samples 
	Mat input, label, test_input, test_label;
	int sample_number = 800;
	get_input_label("data/input_label_1000.xml", input, label, sample_number);
	get_input_label("data/input_label_1000.xml", test_input, test_label, 200, 800);

	//Set loss threshold,learning rate and activation function
	float loss_threshold = 0.5;
	net.learning_rate = 0.3;
	net.output_interval = 2;
	net.activation_function = "sigmoid";

	//Train,and draw the loss curve(cause the last parameter is ture) and test the trained net
	net.train(input, label, loss_threshold, true);
	net.test(test_input, test_label);

	//Save the model
	net.save("models/model_sigmoid_800_200.xml");

	getchar();
	return 0;
}

加载训练过的模型然后直接使用就更加方便了。

#include"../include/Net.h"
//<opencv2\opencv.hpp>

using namespace std;
using namespace cv;
using namespace liu;

int main(int argc, char *argv[])
{
	//Get test samples and the label is 0--1
	Mat test_input, test_label;
	int sample_number = 200;
	int start_position = 800;
	get_input_label("data/input_label_1000.xml", test_input, test_label, sample_number, start_position);

	//Load the trained net and test.
	Net net;
	net.load("models/model_sigmoid_800_200.xml");
	net.test(test_input, test_label);

	getchar();
	return 0;
}

三、文件结构

  • 文件结构
    下载后文件如下:
  • 包含了例子所用的数据(data)
  • 示例程序(examples)
  • 头文件(include)
  • 示例程序训练的模型(models)
  • 实现源代码(src)
    文件结构

四、运行效果

这是以部分minist数据测试的效果图。同时还能实时输出loss值。


C++从零实现简单深度神经网络(基于OpenCV)

代码地址如下:
http://www.demodashi.com/demo/11138.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

posted on   demo例子集  阅读(841)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示