network.h 使用指南(精简版)
下载库:network_h.7z
简介
基于 C++14 的仅头文件的神经网络库。
计算加速基于 OpenMP 和 AVX256 指令集,目前仅支持 CPU,和微软的 amp.h 加速矩阵乘法(GPU,但需要在 VS 下编译且加速效果似乎不好)。
使用 DEV-C++ 可编译。
自动反向传播
头文件 auto_dao.h,命名空间 auto_dao。
定义了自动求导的三维数组类型 val3d,数据按 d*h*w 储存。
val3d 成员变量:
d,h,w:三维大小;a,da:数据、数据对应的偏导;
val3d 成员函数:
- 四则运算重载(一对一运算,要求数组形状相同);
- 构造函数:传入
d,h,w,自动初始化(统一的值 or 数组中一一对应的值); reshape:修改d,h,w,但不能改变d*h*w(不改变储存的数据,仅改变读写映射方式);toshape:创建一个新的数组,d',h',w'给定,且a'_{i,j,k}=a_{i\text{ mod }d,j\text{ mod }h,k\text{ mod }w} ;dcat:将两个数组按照d这一维拼接,分别占用[0,d_x-1] 和[d_x,d_x+d_y-1] ;backward:将此处的偏导反向传播下去;
每次计算都会新开空间,需要调用 auto_dao::init 来释放现有的所有 val3d 的空间。
每次反向传播前需调用 auto_dao::init_backward 来初始化现有的所有 val3d。
预设优化器
头文件:Optimizer\*.h
命名规则:全大写命名。
统一变量:
m:权重数量,初始为0 ,用于传入网络层级的init函数;
统一函数:
init:初始化参数;build:分配权重、偏导储存空间;_wei(),_tmp():获取权重数组、偏导数组的起始地址,用于传入网络层级的build函数;init_backward:清空累计的偏导;flush:利用当前累计的偏导更新权重;delthis:释放空间;
参数命名规则和主流的神经网络库大致相同。
预设网络层级(单层算子)
头文件:Layers\*.h
命名规则:全大写命名。
统一函数:
init:初始化算子参数;build:为算子分配权重、偏导储存空间,并初始化权重(没有权重的层算子就没有该函数);operator():传入一个val3d,返回一个val3d,表示在传入的对象上应用该算子;save/load:保存到文件流中、从文件流中读取;delthis:释放空间;
参数命名规则和主流的神经网络库大致相同,init 的第一个参数 int &m 传入的是权重数量的计数器,一般传入 优化器的成员变量 m;build 的两个 float* 参数传入的分别是权重存储起始地址、偏导存储起始地址。
自动保存/读取器
定义宏 ENABLE_AUTO_SL 以启用。
在用户定义的神经网络类中,将优化器的声明放置于所有层级声明的前面,并且不能有多个优化器。
在优化器声明前加上 AUTO_SL_BEG 关键字,在所有层级声明的末尾加上 AUTO_SL_BEG 关键字。
将会自动定义类的两个成员函数 save 和 load。
例子:
class network
{
AUTO_SL_BEG
ADAM opt;
FC fc1,fc2,fc3;
CONV c1,c2;
AUTO_SL_END
}test;
使用 test.save(path) 和 test.load(path,Batch_Size) 以保存到文件或从文件中读取。
其它头文件
fast_calc.h:快速矩阵乘法相关;file_io.h:文件读写相关;defines.h:公共部分,定义、链接;network.h:库入口;
基于 MNIST 的例子
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <chrono>
#define ENABLE_OPENMP 0
#define THREAD_NUM 6
#define ENABLE_AUTO_SL 0
#include "./network_h/network.h"
using namespace std;
const int HEI = 28, WID = 28;
const int N = HEI * WID, Q = 10;
const int T = 60000, TESTT = 10000;
const int Batch_Size = 60, total_batch = 5000, calctme = 5;
struct NETWORK
{
AUTO_SL_BEG
ADAM opt;
CONV c1;
BN b1;
LEAKY_RELU a1;
POOLING p1;
CONV c2;
BN b2;
LEAKY_RELU a2;
POOLING p2;
FC fc1;
BIAS bi1;
LEAKY_RELU a3;
FC fc2;
BIAS bi2;
SIGMOID a4;
AUTO_SL_END
float in[Batch_Size * N];
val3d out;
inline void init()
{
opt.init(Batch_Size,0.001);
c1.init(opt.m,Batch_Size,(SHAPE3D){1,28,28},8,{3,3},{1,1},{1,1},0);
b1.init(opt.m,Batch_Size,(SHAPE3D){8,28,28});
a1.init(Batch_Size,8*28*28);
p1.init(Batch_Size,(SHAPE3D){8,28,28},{2,2});
c2.init(opt.m,Batch_Size,(SHAPE3D){8,14,14},16,{3,3},{1,1},{1,1},0);
b2.init(opt.m,Batch_Size,(SHAPE3D){16,14,14});
a2.init(Batch_Size,16*14*14);
p2.init(Batch_Size,(SHAPE3D){16,14,14},{2,2});
fc1.init(opt.m,Batch_Size,16*7*7,128);
bi1.init(opt.m,Batch_Size,(SHAPE3D){128,1,1});
a3.init(Batch_Size,128);
fc2.init(opt.m,Batch_Size,128,10);
bi2.init(opt.m,Batch_Size,(SHAPE3D){10,1,1});
a4.init(Batch_Size,10);
opt.build();
float *wei=opt._wei(),*tmp=opt._tmp();
c1.build(wei,tmp),b1.build(wei,tmp);
c2.build(wei,tmp),b2.build(wei,tmp);
fc1.build(wei,tmp),bi1.build(wei,tmp);
fc2.build(wei,tmp,INIT_XAVIER),bi2.build(wei,tmp);
}
inline void forward(bool test)
{
auto_dao::init(Batch_Size,test);
val3d x(1,28,28,in);
x=c1(x),x=b1(x),x=a1(x),x=p1(x);
x=c2(x),x=b2(x),x=a2(x),x=p2(x);
x=fc1(x),x=bi1(x),x=a3(x);
x=fc2(x),x=bi2(x),x=a4(x);
out=x;
}
inline void backward()
{
opt.init_backward();
auto_dao::init_backward();
out.backward();
opt.flush();
}
};
float casin[T + 5][N + 5];
int casans[T + 5];
float outs[Batch_Size * Q];
float total_loss;
NETWORK brn;
inline float lossfunc(float out[], float rout[], float dout[])
{
float res = 0;
for (int i = 0; i < Batch_Size * Q; i++)
{
res += 0.5 * (out[i] - rout[i]) * (out[i] - rout[i]);
dout[i] = out[i] - rout[i];
}
return res;
}
void train()
{
int cins = 0, couts = 0;
for (int tme = 1; tme <= Batch_Size; tme++)
{
int cas = (rand() * (RAND_MAX + 1) + rand()) % T + 1;
for (int i = 0; i < N; i++) brn.in[cins++] = casin[cas][i];
for (int i = 0; i < Q; i++) outs[couts++] = casans[cas] == i;
}
brn.forward(false);
total_loss+=lossfunc(brn.out.a,outs,brn.out.da)/Batch_Size;
brn.backward();
}
inline bool test(int cas)
{
for (int i = 0; i < N; i++) brn.in[i] = casin[cas][i];
brn.forward(true);
int mxid = 0;
for (int i = 1; i < Q; i++) if (brn.out.a[i] > brn.out.a[mxid]) mxid = i;
return mxid == casans[cas];
}
int main()
{
printf("模式选择:\n");
printf("[1] 加载 AI 并测试\n");
printf("[2] 训练 AI(最好的 AI 模型将会保存到 .\\best.ai)\n");
int mode;
scanf("%d", &mode);
system("cls");
string imgpath = "./data/MNIST/img",
anspath = "./data/MNIST/ans",
testimgpath = "./data/MNIST/testimg",
testanspath = "./data/MNIST/testans";
printf("\n训练图片文件:%s\n", imgpath.c_str());
printf("训练答案文件:%s\n", anspath.c_str());
printf("评估图片文件:%s\n", testimgpath.c_str());
printf("评估答案文件:%s\n", testanspath.c_str());
printf("加载配置文件完成\n\n");
if (mode == 1)
{
printf("请输入之前保存的 AI 路径\n");
string path;
cin >> path;
brn.load(path,Batch_Size);
printf("加载用于模型评估的测试数据中...\n");
FILE* fimg, * fans;
fimg = fopen(testimgpath.c_str(), "rb");
if (fimg == NULL)
{
puts("加载测试图片数据失败\n");
system("pause");
return -1;
}
fans = fopen(testanspath.c_str(), "rb");
if (fans == NULL)
{
puts("加载测试答案数据失败\n");
system("pause");
return -1;
}
fseek(fimg, 16, SEEK_SET);
fseek(fans, 8, SEEK_SET);
unsigned char* img = new unsigned char[N + 5];
for (int cas = 1; cas <= TESTT; cas++)
{
fread(img, 1, N, fimg);
for (int i = 0; i < N; i++) casin[cas][i] = img[i] / (float)255;
unsigned char num;
fread(&num, 1, 1, fans);
casans[cas] = num;
}
delete[] img;
fclose(fimg), fclose(fans);
printf("加载数据完成\n\n");
printf("开始模型评估...\n");
int tot = 0;
for (int i = 1; i <= TESTT; i ++) tot += test(i);
printf("模型评估完成,正确率:%.2f%%\n\n", (float)tot / TESTT * 100);
system("pause");
}
else
{
printf("加载数据中...\n");
FILE* fimg, * fans;
fimg = fopen(imgpath.c_str(), "rb");
if (fimg == NULL)
{
puts("加载图片数据失败\n");
system("pause");
return -1;
}
fans = fopen(anspath.c_str(), "rb");
if (fans == NULL)
{
puts("加载答案数据失败\n");
system("pause");
return -1;
}
fseek(fimg, 16, SEEK_SET);
fseek(fans, 8, SEEK_SET);
unsigned char* img = new unsigned char[N + 5];
for (int cas = 1; cas <= T; cas++)
{
fread(img, 1, N, fimg);
for (int i = 0; i < N; i++) casin[cas][i] = img[i] / (float)255;
unsigned char num;
fread(&num, 1, 1, fans);
casans[cas] = num;
}
delete[] img;
fclose(fimg), fclose(fans);
printf("加载数据完成\n\n");
brn.init();
total_loss = 0;
printf("开始训练...\n\n");
auto start = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= total_batch; i++)
{
train();
if (i % calctme == 0)
{
total_loss /= (float)calctme;
printf("[%.2f%%] 训练了 %d 组样本,平均 loss %f\n", i / (float)total_batch * 100, i * Batch_Size, total_loss);
total_loss = 0;
}
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count();
printf("\n训练完成!共训练 %d ms,模型已保存到 best.ai\n\n",(int)duration);
brn.save("best.ai");
printf("加载用于模型评估的测试数据中...\n");
fimg = fopen(testimgpath.c_str(), "rb");
if (fimg == NULL)
{
puts("加载测试图片数据失败\n");
system("pause");
return -1;
}
fans = fopen(testanspath.c_str(), "rb");
if (fans == NULL)
{
puts("加载测试答案数据失败\n");
system("pause");
return -1;
}
fseek(fimg, 16, SEEK_SET);
fseek(fans, 8, SEEK_SET);
img = new unsigned char[N + 5];
for (int cas = 1; cas <= TESTT; cas++)
{
fread(img, 1, N, fimg);
for (int i = 0; i < N; i++) casin[cas][i] = img[i] / (float)255;
unsigned char num;
fread(&num, 1, 1, fans);
casans[cas] = num;
}
delete[] img;
fclose(fimg), fclose(fans);
printf("加载数据完成\n\n");
printf("开始模型评估...\n");
int tot = 0;
for (int i = 1; i <= TESTT; i ++) tot += test(i);
printf("模型评估完成,正确率:%.2f%%\n\n", (float)tot / TESTT * 100);
system("pause");
}
return 0;
}