题解:AT_birthday0410_x
cxyMOI
·
2024-07-07 19:19:47
·
题解
求值是简单的,只需得到表达式。这是一个单行不定长文本识别问题,下面将使用一个有 4564 个float参数的神经网络模型解决这道题。模型是 CRNN+CTC 模型[^1]的简化版本。
我在测试集上验证 了(多次提交并根据评测结果调整超参数和模型结构)。
模型结构
模型依次含有如下层:
输入是一个 W\times65 的矩阵,每个元素是 0 或 1 。
一个卷积层,包含 8 个 4\times4 卷积核,ReLu激活。
一个池化层,大小为 2\times2 。
一个卷积层,包含 8 个 3\times3\times8 卷积核,ReLu激活。
一个池化层,大小为 2\times2 。
一个卷积层,包含 4 个 3\times3\times8 卷积核,ReLu激活。
一个池化层,大小为 2\times2 。池化层输出 4 个 \frac{W}{8}\times8 的矩阵。
一个双向 RNN 层,32 维输入,17 维输出,24 维隐藏状态。
一个 CTC 层。
下面简单介绍神经网络。
神经网络
神经网络是一种机器学习程序或模型,它以类似于人脑的方式做出决策,通过使用模仿生物神经元协同工作方式的过程来识别现象、权衡利弊并得出结论。
每个神经网络都由多个节点层或人工神经元组成 – 一个输入层、一个或多个隐藏层和一个输出层。每个节点都与其他节点相连,具有一个关联的权重和阈值。如果任何单个节点的输出高于指定的阈值,那么该节点将被激活,并将数据发送到网络的下一层。否则,不会将数据传递到网络的下一层。
神经网络依靠训练数据来学习并随着时间的推移提高其准确性。一旦对其准确性进行微调,它们就会成为计算机科学和人工智能领域的强大工具,使我们能够高速对数据进行分类和聚类。与人类专家的人工识别相比,人工智能进行语音识别或图像识别只需几分钟,而人工识别则需要几小时。神经网络最著名的例子之一就是 Google 的搜索算法。
神经网络有时被称为人工神经网络 (ANN) 或模拟神经网络 (SNN)。它们是机器学习的一个子集,是深度学习模型的核心。[^2]
神经网络是带有一些参数的函数,训练时根据数据和标签调整网络中的参数,从而使网络可以拟合目标函数。
例如在本题中,函数的输入是图像,输出是表达式。训练结束后,网络应该能根据图像正确预测表达式。
神经网络可以视为一个有向无环图(计算图),其中每一个节点是一个数(可能是参数/输入/输出/中间结果),每一条边是一种运算。神经网络按照拓扑序依次计算每个节点的值。网络通常由很多层组成,预测时依次计算网络的每一层,每一层的输出就是下一层的输入。这种情况下计算图是每一层的计算图的拼接。
梯度下降
为了调整参数使得网络尽可能拟合目标函数,首先需要定义“拟合的错误程度”。用一个数即 loss 函数的值表示它。loss 函数有很多种定义方式。
这样问题就转化为使函数 \mathrm{loss}(a_1,...,a_n) 尽量小。由于网络非常复杂,不可能精确求解。求近似最小值的基本方法是梯度下降:首先求出全部的 \frac{\partial\mathrm{loss}}{\partial a_i} ,然后对每个 a_i ,令 a_i\leftarrow a_i-\eta\frac{\partial \mathrm{loss}}{\partial a_i} ,其中 \eta 是学习率。实际训练时会对这个方法进行一些优化。
反向传播
为了求出 \frac{\partial\mathrm{loss}}{\partial a_i} ,利用全微分和链式法则:
假设在计算图中 a_i 连向 b_1,...,b_k 。则有
\frac{\partial\mathrm{loss}}{\partial a_i}=\sum_{i=1}^k\frac{\partial\mathrm{loss}}{\partial b_i}\frac{\partial b_i}{\partial a_i}
由于计算图中每条边都是一些简单的运算,所以 \frac{\partial b_i}{\partial a_i} 容易求,只需要求出 \frac{\partial\mathrm{loss}}{\partial b_i} 。按照计算图的拓扑序(即神经网络的计算顺序)的相反方向 dp 即可,因此称为反向传播。
模型介绍
激活函数
神经网络中大部分的计算都是关于输入的线性变换,但线性变换的复合仍然是线性的。为了防止网络退化为线性,会在网络中加入非线性的激活函数层,将激活函数作用于每一个输入上。常用激活函数有 ReLU、tanh 等。
CNN
卷积神经网络(Convolutional Neural Networks, CNN)通常由若干卷积层和池化层组成(最后可能还有一个全连接层)。
卷积层的参数包括若干卷积核及偏置。这一层会将图像分别与每个卷积核进行卷积,然后分别加上对应的偏置。最后将激活函数作用于卷积结果。本文的 CNN 网络采用 ReLU 函数 \mathrm{ReLU}(x)=\max(0,x) 。
池化层将一个区域内的所有数替换为一个数,用于缩小图像大小以及扩大卷积核的作用范围。最大池化比较常用,把这些数换成最大值。在本文的网络中,池化层将 64\times W 的矩阵变为 8\times\frac W8 的矩阵,其中每个数代表原矩阵中对应范围的最大值。
两个或多个 CNN 网络堆叠时,下一层的每个输出是上一层的每个输出分别被卷积后对应相加之和。
由于接下来是 CNN 或 RNN,CRNN 网络中 CNN 没有全连接层。
RNN
正常应该在这里用多层双向 LSTM。考虑到代码长度限制了参数量,并且本题的场景不需要长距离信息,用更简单的普通双向 RNN 代替。
循环神经网络(Recurrent Neural Network, RNN)的输入是一个序列,输出是和输入等长的序列。RNN 用于处理第 i 个输出和第 i 个附近的(比如第 i\pm1 个)输入有关,而不是只和第 i 个输入有关的问题。例如在本题中一个字符宽度是 38 ,而一个输入只包含宽度为 8 的范围内的信息,所以使用 RNN。
本文的模型中 RNN 使用 tanh 激活函数。为了传递附近的信息,RNN 含有隐藏状态 h_i ,其中编码了第 i 个输入时网络获取的信息。在本文的网络中,h_i 是一个长度为 32 的向量。设 a_i 是输入,b_i 是输出,具体的计算方法为:
h_{i+1}=\tanh(Wh_i+Ua_i+b)
b_i=Vh_i
其中 U,V,W 都是矩阵,b 是向量,它们的值是需要学习的参数。f(一个向量) 表示对这个向量的每个元素进行 f 得到的结果。
softmax
softmax 层对 RNN 的输出进行归一化。RNN 输出的第 t 个向量 (a_{t,1},a_{t,2},...,a_{t,n}) 被归一化为 (y_{t,1},y_{t,2},...,y_{t,n})=(\frac{e^{a_1}}{e^{a_1}+...+e^{a_n}},\frac{e^{a_2}}{e^{a_1}+...+e^{a_n}},...,\frac{e^{a_n}}{e^{a_1}+...+e^{a_n}}) 。y_{t,k} 可以看作第 t 个输出是字符 k 的概率。
CTC
联结主义时间分类算法(Connectionist Temporal Classification, CTC) [^3]是一种算法,用于解决不定长序列的对齐问题。对 CTC 的介绍可以参看[^4]。在 CRNN 中,一个字符变为多个输出,例如3*3-4可能被识别为333**33---44。合并相邻的相同字符可以部分解决这个问题,但1+22会被识别为1+2。为了解决这个问题,CTC 引入了空白字符,用于分隔相邻字符。
定义解码函数 \mathcal B:L'^T\mapsto L^{\le T} ,其中 L 是字符集,L'=L\cup\{b\} (b 表示空白字符),T 是输入长度:先删去相邻的相同字符,然后删去空白。例如 \mathcal B(b3b**333--bb4)=3*3-4 ,\mathcal B(11b++2b2)=1+22 。
定义 CTC loss 为 RNN 的输出解码后得到正确结果的概率的对数的相反数 -\log{p(\bold l|\bold x)} ,其中 \bold l 是正确标签,\bold x 是 softmax 的输出。显然有
p(\bold l|\bold x)=\sum_{\mathcal B(\pi)=\bold l}p(\pi|\bold x)=\sum_{\mathcal B(\pi)=\bold l}\prod_{t=1}^Ty_{t,\pi_t}
其中 \pi\in L'^T 是一个可能的序列。
要计算 loss 和 loss 关于各个 y_{t,i} 的偏导数。
考虑 dp。首先在 \bold l 的每两个字符间和首尾插入一个空白字符,得到的字符串记为 \bold l' 。如果 \bold l=3*3-4 ,那么 \bold l'=b3b*b3b-4b 。定义
\alpha_t(s)=\sum_{\substack{\mathcal B(\pi_{1:t})=\mathcal B(\bold l'_{1:s})\\\pi_t=\bold l'_s}}\prod_{t'=1}^ty_{t',\pi_{t'}}
容易证明有递推关系
$$
\begin{aligned}
\alpha_t(s)=
\begin{cases}
(\alpha_{t-1}(s)+\alpha_{t-1}(s-1))y_{t,\bold l'_s}&\bold l'_s=\bold l'_{s-2}\\
(\alpha_{t-1}(s)+\alpha_{t-1}(s-1)+\alpha_{t-1}(s-2))y_{t,\bold l'_s}&\text{otherwise}
\end{cases}
\end{aligned}
$$
于是可以 $O(T^2)$ 计算 $\alpha$ 在各个 $t$ 和 $s$ 上的值。显然 $p(\bold l|\bold x)=\alpha_T(2T)+\alpha_T(2T+1)$。
定义
$$\beta_t(s)=\sum_{\substack{\mathcal B(\pi_{t:T})=\mathcal B(\bold l'_{s:2T+1})\\\pi_t=\bold l'_s}}\prod_{t'=t}^Ty_{t',\pi_{t'}}$$
对 $\beta$ 有类似的递推关系。
不难看出 $\alpha_t(s)$ 和 $\beta_t(s)$ 都是关于 $y_{t,\bold l'_s}$ 的正比例函数,并且 $p(\bold l|\bold x)=\sum_{s=1}^{2T+1}\frac{\alpha_t(s)\beta_t(s)}{y_{t,\bold l'_s}}$ 对任意 $t$ 恒成立。于是有 $\frac{\partial p(\bold l|\bold x)}{\partial y_{t,k}}=\sum_{\bold l'_s=k}\frac{\alpha_t(s)\beta_t(s)}{y_{t,k}^2}$,再根据 $\frac{\partial(-\log{p(\bold l|\bold x))}}{\partial y_{t,k}}=\frac{\partial(-\log{p(\bold l|\bold x))}}{\partial p(\bold l|\bold x)}\frac{\partial p(\bold l|\bold x)}{\partial y_{t,k}}=-\frac1{p(\bold l|\bold x)}\frac{\partial p(\bold l|\bold x)}{\partial y_{t,k}}$ 就算出了 loss 关于 $y_{t,k}$ 的偏导数。
# 实现
注意到 Atcoder 的评测环境中没有常用的深度学习库,因此用`c++`实现上述模型。
## 头文件和常量
```cpp
#include <array>
#include <cmath>
#include <iostream>
#include <random>
#include <ranges>
#include <stack>
#include <string>
#include <vector>
const int height=65,width_of_char=38,num_of_chars=16;
const std::array<std::string,height> char_image_list[num_of_chars]={/*复制 https://img.atcoder.jp/data/other/birthday0410/X_umekomi.txt 到这里*/};
const char char_list[num_of_chars+1]={'0','1','2','3','4','5','6','7','8','9','(',')','+','-','*','/','?'};
```
## 参数
```cpp
std::mt19937 gen(3407);
class ARG{
public:
float x;
ARG()=default;
explicit ARG(float x_):x(x_){}
};
class GRAD_ARG:public ARG{
public:
float x_grad;
GRAD_ARG()=default;
explicit GRAD_ARG(float x_):ARG(x_),x_grad(0){}
};
class BP_ARG:public GRAD_ARG{
public:
static constexpr float eps=1e-8,beta_m=0.9,beta_v=0.999;
float m,v,grad_sum,bmk,bvk;
BP_ARG():GRAD_ARG(std::normal_distribution<float>(0,0.1)(gen)),m(0),v(0),bmk(1),bvk(1){};
BP_ARG(float x):GRAD_ARG(x),m(0),v(0),bmk(1),bvk(1){};
void learn(float learning_rate){
m=beta_m*m+(1-beta_m)*grad_sum;
v=beta_v*v+(1-beta_v)*grad_sum*grad_sum;
bmk*=beta_m;
bvk*=beta_v;
x-=learning_rate*m/((1-bmk)*(eps+std::sqrt(v/(1-bvk))));
}
};
template<typename T>
concept IS_ARG=requires(T& t){t.x;};
template<typename T>
concept WITH_GRAD=requires(T& t){t.x_grad;};
template<typename T>
concept WITH_BP=requires(T& t,float l){t.learn(l);};
template<typename T1,typename T2>
concept CAN_TRAIN=IS_ARG<T1>&&WITH_GRAD<T1>&&IS_ARG<T2>&&WITH_BP<T2>;
```
* 随机数种子设为`3407`是因为[^5]。
* 使用 Adam 优化器。
* 参数初始化为均值 $0$,标准差 $0.1$ 的正态分布。
* `grad_sum`保存一个 batch 中的梯度之和。
## 参数保存
```cpp
const char used_chars[93]="!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~";
std::string to_s(float x){
bool f=x<0;
x=std::abs(x);
x=std::ldexp(x,18);
int y;
if(x<1){
y=static_cast<int>(x*16928);
}else{
if(x>=(1<<22)){
x=4194303.75f;
}
x=std::frexp(x,&y)*2-1;
y=y*16928+static_cast<int>(x*16928);
}
y=y*2+f;
std::string res="";
for(int i=0;i<3;i++){
res+=used_chars[y%92];
y/=92;
}
return res;
}
template<IS_ARG T>
std::string to_s(T* a,int n){
std::string res="";
for(int i=0;i<n;i++){
res+=to_s(a[i].x);
}
return res;
}
float from_s(std::string_view s){
int y=0;
for(int i=2;i>=0;i--){
y*=92;
y+=s[i]-33-(s[i]>'"')-(s[i]>'\\');
}
bool f=y%2;
y/=2;
float x;
if(y<16928){
x=(static_cast<float>(y)+0.5)/16928;
}else{
x=std::ldexp(1+(static_cast<float>(y%16928)+0.5)/16928,y/16928-1);
}
return std::ldexp((f?-x:x),-18);
}
template<IS_ARG T>
void from_s(T* a,std::string_view s){
for(int i=0;i<s.size();i+=3){
a[i/3].x=from_s(s.substr(i,3));
}
}
```
* 假设所有参数都在 $(-16,16)$ 中。
* 用 $3$ 个字符保存一个参数。
## 训练数据生成
```cpp
class IMAGE{
using IMAGE_TO_TRANSFORM=std::vector<std::pair<float,float>>;
using IMAGE_FOR_NET=std::array<std::vector<std::array<GRAD_ARG,height>>,1>;
std::vector<bool> v[height];
void append(IMAGE img,int pad){
pad=(pad<0)?0:pad;
for(int i=0;i<height;i++){
v[i].insert(v[i].end(),img.v[i].begin(),img.v[i].end());
v[i].insert(v[i].end(),pad,0);
}
}
public:
IMAGE()=default;
explicit IMAGE(const std::array<std::string,height>& char_img){
for(int i=0;i<height;i++){
v[i].resize(width_of_char);
for(int j=0;j<width_of_char;j++){
v[i][j]=(char_img[i][j]=='#');
}
}
}
explicit IMAGE(const auto& pixel_set){
auto [min_i,max_i]=std::ranges::minmax(pixel_set|std::views::transform([](const auto& p){return p.first;}));
auto [min_j,max_j]=std::ranges::minmax(pixel_set|std::views::transform([](const auto& p){return p.second;}));
int shift_i=(-min_i+5>height-1-max_i-5)?0:std::uniform_int_distribution<int>(-min_i+5,height-1-max_i-5)(gen);
int shift_j=-min_j;
for(int i=0;i<height;i++){
v[i].resize(max_j+1+shift_j);
}
for(auto p:pixel_set){
int i,j;
std::tie(i,j)=p;
if(static_cast<unsigned int>(i+shift_i)<height){
v[i+shift_i][j+shift_j]=1;
}
}
}
IMAGE_FOR_NET to_net(){
IMAGE_FOR_NET res;
res[0].resize(v[0].size());
for(int i=0;i<height;i++){
for(int j=0;j<v[i].size();j++){
res[0][j][i].x=v[i][j];
}
}
return res;
}
static std::vector<int> random_vector(int R=3,int L=200){
std::uniform_int_distribution<> u(R,L),c(0,15);
int l=u(gen);
std::vector<int> res(l);
for(int i=0;i<l;i++){
res[i]=c(gen);
}
return res;
}
explicit IMAGE(std::vector<int> data){
std::uniform_real_distribution<float> Md(0.9,1),Mhd(0.8,1),Mwd(0.8,1),Rd(-25,25),Sxd(-0.2,0.2),Syd(-0.2,0.2);
int padl=std::discrete_distribution<int>({1,2,1,2,3,5,3,7,6,5,1})(gen)+1;
for(int i=0;i<height;i++){
v[i].resize(padl);
}
for(int i=0;i<data.size();i++){
float M=Md(gen),Mh=Mhd(gen),Mw=Mwd(gen),R=Rd(gen)*M_PI/180,Sx=Sxd(gen),Sy=Syd(gen);
IMAGE img(char_image_list[data[i]]);
std::vector<std::pair<int,int>> pixel_set;
for(int p=-50;p<50;p++){
for(int q=-30;q<30;q++){
float x=p,y=q;
std::tie(x,y)=std::make_tuple(x+Sy*y,y+Sx*x);
std::tie(x,y)=std::make_tuple(x/(1-Sx*Sy),y/(1-Sx*Sy));
std::tie(x,y)=std::make_tuple(x*std::cos(R)-y*std::sin(R),x*std::sin(R)+y*std::cos(R));
std::tie(x,y)=std::make_tuple(x/M/Mh,y/M/Mw);
auto [m,n]=std::make_tuple(std::lround(x+height/2),std::lround(y+width_of_char/2));
if(0<=m&&m<height&&0<=n&&n<img.v[0].size()){
if(img.v[m][n]){
pixel_set.push_back(std::make_pair(p,q));
}
}
}
}
img=IMAGE(pixel_set);
if(i+1<data.size()){
append(img,static_cast<int>(std::normal_distribution<float>(19.7,3.08)(gen)));
}else{
append(img,std::discrete_distribution<int>({1,2,2,3,4,5,8,7,2,1})(gen)+10);
}
}
std::uniform_real_distribution<float> u(0,1);
float p=std::uniform_real_distribution<float>(0.04,0.06)(gen);
for(int i=0;i<height;i++){
for(int j=0;j<v[i].size();j++){
if(u(gen)<p){
v[i][j]=!v[i][j];
}
}
}
}
};
```
* `IMAGE::random_vector`生成随机字符串。
* 代码中看起来奇怪的概率分布是统计 $30\le t<50$ 号点的输入数据(这些数据可以在题目描述中的链接里下载)得到的。
* 生成数据的参数比题目中会产生更大的变形,但到训练后期会改成题目中的参数(具体内容在“模型训练”一节)。
* 使用向后映射和最近邻插值计算变形后的图像。
## CNN
```cpp
template<IS_ARG T1,IS_ARG T2,int depth,int input_height,int conv_num,int conv_size,int pad,int pool_size>
class CNN{
static const int conv_res_height=input_height+2*pad+1-conv_size;
static const int pool_res_height=conv_res_height/pool_size;
static float activation_func(float x){
return (x>0)?x:0;
}
static float activation_func_deriv(float x){
return (x>0)?1:0;
}
T2 weight[conv_num][depth][conv_size][conv_size];
T2 bias[conv_num];
std::vector<std::array<T1,conv_res_height>> convolution_res[conv_num];
std::vector<std::array<T1,input_height+2*pad>> input[depth];
void padding(const auto& in){
for(int c=0;c<depth;c++){
input[c].resize(in[c].size()+2*pad);
for(int i=0;i<pad;i++){
input[c][i].fill(T1(0));
input[c][in[c].size()+i+pad].fill(T1(0));
}
for(int i=0;i<in[c].size();i++){
for(int j=0;j<pad;j++){
input[c][i+pad][j].x=0;
input[c][i+pad][j+input_height+pad].x=0;
}
for(int j=0;j<input_height;j++){
input[c][i+pad][j+pad]=in[c][i][j];
}
}
}
}
void convolution(const auto& in){
padding(in);
int conv_res_width=input[0].size()+1-conv_size;
for(int i=0;i<conv_num;i++){
convolution_res[i].resize(conv_res_width);
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
convolution_res[i][j][k].x=bias[i].x;
}
}
for(int c=0;c<depth;c++){
std::array<std::array<float,conv_size>,conv_size> wgt;
for(int x=0;x<conv_size;x++){
for(int y=0;y<conv_size;y++){
wgt[x][y]=weight[i][c][x][y].x;
}
}
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
float cvr=0;
for(int x=0;x<conv_size;x++){
for(int y=0;y<conv_size;y++){
cvr+=input[c][j+x][k+y].x*wgt[x][y];
}
}
convolution_res[i][j][k].x+=cvr;
}
}
}
}
}
void activate(){
for(int i=0;i<conv_num;i++){
int conv_res_width=convolution_res[i].size();
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
convolution_res[i][j][k].x=activation_func(convolution_res[i][j][k].x);
}
}
}
}
void pool(){
for(int i=0;i<conv_num;i++){
const int conv_res_width=convolution_res[i].size();
const int filled_width=(conv_res_width+pool_size-1)/pool_size;
convolution_res[i].resize(filled_width*pool_size);
result[i].resize(filled_width);
for(int j=conv_res_width;j<filled_width*pool_size;j++){
convolution_res[i][j].fill(T1(0));
}
for(int j=0;j<filled_width;j++){
result[i][j].fill(T1(0));
for(int x=0;x<pool_size;x++){
for(int k=0;k<pool_res_height;k++){
for(int y=0;y<pool_size;y++){
if(convolution_res[i][j*pool_size+x][k*pool_size+y].x>result[i][j][k].x){
result[i][j][k].x=convolution_res[i][j*pool_size+x][k*pool_size+y].x;
}
}
}
}
}
}
}
void bp_padding(auto& in)requires CAN_TRAIN<T1,T2>{
for(int c=0;c<depth;c++){
for(int i=0;i<in[c].size();i++){
for(int j=0;j<input_height;j++){
in[c][i][j].x_grad=input[c][i+pad][j+pad].x_grad;
}
}
}
}
void bp_convolution(auto& in)requires CAN_TRAIN<T1,T2>{
int conv_res_width=input[0].size()+1-conv_size;
for(int i=0;i<conv_num;i++){
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
bias[i].x_grad+=convolution_res[i][j][k].x_grad;
}
}
for(int c=0;c<depth;c++){
std::array<std::array<T1,conv_size>,conv_size> wgt;
for(int x=0;x<conv_size;x++){
for(int y=0;y<conv_size;y++){
wgt[x][y].x=weight[i][c][x][y].x;
wgt[x][y].x_grad=weight[i][c][x][y].x_grad;
}
}
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
float cvg=convolution_res[i][j][k].x_grad;
for(int x=0;x<conv_size;x++){
for(int y=0;y<conv_size;y++){
wgt[x][y].x_grad+=input[c][j+x][k+y].x*cvg;
input[c][j+x][k+y].x_grad+=wgt[x][y].x*cvg;
}
}
}
}
for(int x=0;x<conv_size;x++){
for(int y=0;y<conv_size;y++){
weight[i][c][x][y].x_grad=wgt[x][y].x_grad;
}
}
}
}
bp_padding(in);
}
void bp_activate()requires CAN_TRAIN<T1,T2>{
for(int i=0;i<conv_num;i++){
int conv_res_width=convolution_res[i].size();
for(int j=0;j<conv_res_width;j++){
for(int k=0;k<conv_res_height;k++){
convolution_res[i][j][k].x_grad*=activation_func_deriv(convolution_res[i][j][k].x);
}
}
}
}
void bp_pool()requires CAN_TRAIN<T1,T2>{
for(int i=0;i<conv_num;i++){
int conv_res_width=convolution_res[i].size();
int filled_width=(conv_res_width+pool_size-1)/pool_size;
for(int j=0;j<filled_width;j++){
for(int x=0;x<pool_size;x++){
for(int k=0;k<pool_res_height;k++){
for(int y=0;y<pool_size;y++){
if(convolution_res[i][j*pool_size+x][k*pool_size+y].x>=result[i][j][k].x){
convolution_res[i][j*pool_size+x][k*pool_size+y].x_grad=result[i][j][k].x_grad;
}
}
}
}
}
}
}
void clear_grad()requires CAN_TRAIN<T1,T2>{
for(int i=0;i<conv_num;i++){
for(int c=0;c<depth;c++){
for(int j=0;j<conv_size;j++){
for(int k=0;k<conv_size;k++){
weight[i][c][j][k].x_grad=0;
}
}
}
bias[i].x_grad=0;
for(auto& j:convolution_res[i]){
for(auto& a:j){
a.x_grad=0;
}
}
}
for(auto& c:input){
for(auto& j:c){
for(auto& k:j){
k.x_grad=0;
}
}
}
}
public:
std::array<std::vector<std::array<T1,pool_res_height>>,conv_num> result;
CNN()=default;
CNN(std::string_view s){
from_s(&weight[0][0][0][0],s.substr(0,3*conv_num*depth*conv_size*conv_size));
from_s(&bias[0],s.substr(3*conv_num*depth*conv_size*conv_size,3*conv_num));
}
std::string to_str(){
return to_s(&weight[0][0][0][0],conv_num*depth*conv_size*conv_size)+to_s(&bias[0],conv_num);
}
void forward_propagation(const auto& in){
convolution(in);
activate();
pool();
}
void apply_to_all_bp_arg(const auto& f){
for(int i=0;i<conv_num;i++){
for(int c=0;c<depth;c++){
for(int j=0;j<conv_size;j++){
for(int k=0;k<conv_size;k++){
f(weight[i][c][j][k]);
}
}
}
f(bias[i]);
}
}
void backward_propagation(auto& in)requires CAN_TRAIN<T1,T2>{
clear_grad();
bp_pool();
bp_activate();
bp_convolution(in);
apply_to_all_bp_arg([](T2& x){x.grad_sum+=x.x_grad;});
}
};
```
* 在图像周围填充`0`。
* 用合理的顺序循环,并且将常用的数据提前取出,这样可以提高缓存命中率从而加速卷积。
## RNN
```cpp
template<IS_ARG T1,IS_ARG T2,int depth,int input_size,int state_size,int output_size>
class RNN{
static float activation_func(float x){
return std::tanh(x);
}
static float activation_func_deriv(float x){
return 1-x*x;
}
T2 input_weight[2][state_size][depth][input_size];
T2 state_weight[2][state_size][state_size];
T2 state_bias[2][state_size];
T2 full_connect_weight[2][state_size][output_size];
std::vector<std::array<T1,state_size>> state[2];
void rnn_one_layer(int flag,int i,std::array<std::vector<std::array<T1,input_size>>,depth>& input){
int b=1-2*flag;
state[flag][i+b].fill(T1(0));
for(int j=0;j<state_size;j++){
for(int c=0;c<depth;c++){
for(int k=0;k<input_size;k++){
state[flag][i+b][j].x+=input_weight[flag][j][c][k].x*input[c][i-flag][k].x;
}
}
for(int k=0;k<state_size;k++){
state[flag][i+b][j].x+=state_weight[flag][j][k].x*state[flag][i][k].x;
}
state[flag][i+b][j].x+=state_bias[flag][j].x;
state[flag][i+b][j].x=activation_func(state[flag][i+b][j].x);
for(int k=0;k<output_size;k++){
result[i-flag][k].x+=state[flag][i+b][j].x*full_connect_weight[flag][j][k].x;
}
}
}
void bp_rnn_one_layer(int flag,int i,std::array<std::vector<std::array<T1,input_size>>,depth>& input)requires CAN_TRAIN<T1,T2>{
int b=1-2*flag;
for(int j=0;j<state_size;j++){
for(int k=0;k<output_size;k++){
full_connect_weight[flag][j][k].x_grad+=result[i-flag][k].x_grad*state[flag][i+b][j].x;
state[flag][i+b][j].x_grad+=result[i-flag][k].x_grad*full_connect_weight[flag][j][k].x;
}
state[flag][i+b][j].x_grad*=activation_func_deriv(state[flag][i+b][j].x);
for(int c=0;c<depth;c++){
for(int k=0;k<input_size;k++){
input_weight[flag][j][c][k].x_grad+=state[flag][i+b][j].x_grad*input[c][i-flag][k].x;
input[c][i-flag][k].x_grad+=state[flag][i+b][j].x_grad*input_weight[flag][j][c][k].x;
}
}
for(int k=0;k<state_size;k++){
state_weight[flag][j][k].x_grad+=state[flag][i+b][j].x_grad*state[flag][i][k].x;
state[flag][i][k].x_grad+=state[flag][i+b][j].x_grad*state_weight[flag][j][k].x;
}
state_bias[flag][j].x_grad+=state[flag][i+b][j].x_grad;
}
}
void clear_grad()requires CAN_TRAIN<T1,T2>{
for(int i:{0,1}){
for(int j=0;j<state_size;j++){
for(int c=0;c<depth;c++){
for(auto& k:input_weight[i][j][c]){
k.x_grad=0;
}
}
for(auto& k:state_weight[i][j]){
k.x_grad=0;
}
state_bias[i][j].x_grad=0;
for(auto& k:full_connect_weight[i][j]){
k.x_grad=0;
}
}
for(auto& j:state[i]){
for(auto& k:j){
k.x_grad=0;
}
}
}
}
public:
std::vector<std::array<T1,output_size>> result;
RNN()=default;
RNN(std::string_view s){
from_s(&input_weight[0][0][0][0],s.substr(0,6*state_size*depth*input_size));
from_s(&state_weight[0][0][0],s.substr(6*state_size*depth*input_size,6*state_size*state_size));
from_s(&state_bias[0][0],s.substr(6*state_size*(depth*input_size+state_size),6*state_size));
from_s(&full_connect_weight[0][0][0],s.substr(6*state_size*(depth*input_size+state_size+1),6*state_size*output_size));
}
std::string to_str(){
return
to_s(&input_weight[0][0][0][0],2*state_size*depth*input_size)
+to_s(&state_weight[0][0][0],2*state_size*state_size)
+to_s(&state_bias[0][0],2*state_size)
+to_s(&full_connect_weight[0][0][0],2*state_size*output_size);
}
void forward_propagation(std::array<std::vector<std::array<T1,input_size>>,depth>& input){
result.resize(input[0].size());
for(auto& i:result){
i.fill(T1(0));
}
state[0].resize(input[0].size()+1);
state[0][0].fill(T1(0));
for(int i=0;i<input[0].size();i++){
rnn_one_layer(0,i,input);
}
state[1].resize(input[0].size()+1);
state[1][input[0].size()].fill(T1(0));
for(int i=input[0].size();i>0;i--){
rnn_one_layer(1,i,input);
}
}
void apply_to_all_bp_arg(const auto& f){
for(int i:{0,1}){
for(int j=0;j<state_size;j++){
for(int c=0;c<depth;c++){
for(auto& k:input_weight[i][j][c]){
f(k);
}
}
for(auto& k:state_weight[i][j]){
f(k);
}
f(state_bias[i][j]);
for(auto& k:full_connect_weight[i][j]){
f(k);
}
}
}
}
void backward_propagation(std::array<std::vector<std::array<T1,input_size>>,depth>& input)requires CAN_TRAIN<T1,T2>{
clear_grad();
for(int c=0;c<depth;c++){
for(auto& i:input[c]){
for(auto& j:i){
j.x_grad=0;
}
}
}
for(int i=input[0].size()-1;i>=0;i--){
bp_rnn_one_layer(0,i,input);
}
for(int i=1;i<=input[0].size();i++){
bp_rnn_one_layer(1,i,input);
}
apply_to_all_bp_arg([](T2& x){x.grad_sum+=x.x_grad;});
}
};
```
* 各数组的第一个下标为`0`表示正向 RNN,为`1`表示反向 RNN。
* $(\tanh x)'=1-(\tanh x)^2$。
## CTC
```cpp
template<IS_ARG T1,IS_ARG T2,int input_size>
class CTC{
std::vector<std::vector<float>> alpha_hat;
std::vector<std::vector<float>> beta_hat;
std::vector<int> l;
std::vector<std::array<float,input_size>> log_of_res;
float sum,max_x;
int L,T;
static float log_sum_exp(float a,float b){
if(std::isinf(a)&&std::isinf(b)){
return -HUGE_VALF;
}
return std::max(a,b)+std::log(1+std::exp(-std::abs(a-b)));
}
void softmax(std::vector<std::array<T1,input_size>>& input){
log_of_res.resize(input.size());
for(int i=0;i<input.size();i++){
sum=0;
max_x=input[i][0].x;
for(T1& j:input[i]){
if(j.x>max_x){
max_x=j.x;
}
}
for(int j=0;j<=num_of_chars;j++){
log_of_res[i][j]=input[i][j].x-max_x;
input[i][j].x=std::exp(log_of_res[i][j]);
sum+=input[i][j].x;
}
for(int j=0;j<=num_of_chars;j++){
log_of_res[i][j]-=std::log(sum);
input[i][j].x/=sum;
}
}
}
float bp_ctc_loss(std::vector<int>&data,std::vector<std::array<T1,input_size>>& input)requires CAN_TRAIN<T1,T2>{
L=data.size()*2+1,T=input.size();
alpha_hat.assign(T,std::vector<float>(L,-HUGE_VALF));
beta_hat.assign(T,std::vector<float>(L,-HUGE_VALF));
l.assign(L,num_of_chars);
for(int i=0;i<L;i++){
if(i%2==1){
l[i]=data[i/2];
}
}
float loss=0;
alpha_hat[0][0]=log_of_res[0][l[0]];
alpha_hat[0][1]=log_of_res[0][l[1]];
for(int t=1;t<T;t++){
alpha_hat[t][0]=alpha_hat[t-1][0]+log_of_res[t][l[0]];
alpha_hat[t][1]=log_sum_exp(alpha_hat[t-1][0],alpha_hat[t-1][1])+log_of_res[t][l[1]];
for(int s=2;s<L;s++){
alpha_hat[t][s]=log_sum_exp(alpha_hat[t-1][s],alpha_hat[t-1][s-1]);
if(!(l[s]==l[s-2])){
alpha_hat[t][s]=log_sum_exp(alpha_hat[t][s],alpha_hat[t-1][s-2]);
}
alpha_hat[t][s]+=log_of_res[t][l[s]];
}
}
beta_hat[T-1][L-1]=log_of_res[T-1][l[L-1]];
beta_hat[T-1][L-2]=log_of_res[T-1][l[L-2]];
for(int t=T-2;t>=0;t--){
beta_hat[t][L-1]=beta_hat[t+1][L-1]+log_of_res[t][l[L-1]];
beta_hat[t][L-2]=log_sum_exp(beta_hat[t+1][L-1],beta_hat[t+1][L-1])+log_of_res[t][l[L-2]];
for(int s=L-3;s>=0;s--){
beta_hat[t][s]=log_sum_exp(beta_hat[t+1][s],beta_hat[t+1][s+1]);
if(!(l[s]==l[s+2])){
beta_hat[t][s]=log_sum_exp(beta_hat[t][s],beta_hat[t+1][s+2]);
}
beta_hat[t][s]+=log_of_res[t][l[s]];
}
}
loss-=log_sum_exp(alpha_hat[T-1][L-1],alpha_hat[T-1][L-2]);
return loss;
}
void bp_softmax(std::vector<std::array<T1,input_size>>& input)requires CAN_TRAIN<T1,T2>{
for(int t=0;t<T;t++){
float Z=alpha_hat[t][0]+beta_hat[t][0]-log_of_res[t][l[0]];
for(int s=1;s<L;s++){
Z=log_sum_exp(Z,alpha_hat[t][s]+beta_hat[t][s]-log_of_res[t][l[s]]);
}
for(int k=0;k<=num_of_chars;k++){
input[t][k].x_grad=-HUGE_VALF;
}
for(int s=0;s<L;s++){
input[t][l[s]].x_grad=log_sum_exp(input[t][l[s]].x_grad,alpha_hat[t][s]+beta_hat[t][s]);
}
for(int k=0;k<=num_of_chars;k++){
input[t][k].x_grad-=log_of_res[t][k]+Z;
input[t][k].x_grad=-std::exp(input[t][k].x_grad);
}
}
for(auto& i:input){
for(auto& j:i){
j.x_grad+=j.x;
}
}
}
public:
std::vector<int> result;
void forward_propagation(std::vector<std::array<T1,input_size>>& input){
int l=input_size;
result.clear();
for(int i=0;i<input.size();i++){
float max_p=-1;
int opt_j=input_size;
for(int j=0;j<input_size;j++){
if(input[i][j].x>max_p){
opt_j=j;
max_p=input[i][j].x;
}
}
if(opt_j!=input_size-1&&opt_j!=l){
result.push_back(opt_j);
}
l=opt_j;
}
softmax(input);
}
float backward_propagation(std::vector<int>&data,std::vector<std::array<T1,input_size>>& input)requires CAN_TRAIN<T1,T2>{
float loss=bp_ctc_loss(data,input);
bp_softmax(input);
return loss;
}
};
```
* 由于精度问题,采用 LSE 技巧:存储对数而非原值。例如`alpha_hat`是 $\log\alpha_t(s)$,`beta_hat`同理。原来的`0`用`-HUGE_VALF`表示。
* `log_sum_exp(a,b)`返回 $\log(e^a+e^b)$。
* `softmax`函数原地进行 softmax。`input`变为 softmax 结果,`log_of_res`是结果的对数。
* `forward_propagation`选取每个位置上概率最大的字符并计算 $\mathcal B$ 的结果。
## 模型
```cpp
template<IS_ARG T1,IS_ARG T2>
class CRNN_CTC_MODEL{
public:
CNN<T1,T2,1,65,8,4,1,2> cnn1;
CNN<T1,T2,8,32,8,3,1,2> cnn2;
CNN<T1,T2,8,16,4,3,1,2> cnn3;
RNN<T1,T2,4,8,24,num_of_chars+1> rnn;
CTC<T1,T2,num_of_chars+1> ctc;
float tot_loss;
int correct_predict;
void forward_propagation(auto& input){
cnn1.forward_propagation(input);
cnn2.forward_propagation(cnn1.result);
cnn3.forward_propagation(cnn2.result);
rnn.forward_propagation(cnn3.result);
ctc.forward_propagation(rnn.result);
}
void train_one_sample(auto& input,std::vector<int> data)requires CAN_TRAIN<T1,T2>{
forward_propagation(input);
float loss=ctc.backward_propagation(data,rnn.result);
tot_loss+=loss;
rnn.backward_propagation(cnn3.result);
cnn3.backward_propagation(cnn2.result);
cnn2.backward_propagation(cnn1.result);
cnn1.backward_propagation(input);
if(ctc.result==data){
correct_predict++;
}
}
void apply_to_all_bp_arg(const auto& f){
cnn1.apply_to_all_bp_arg(f);
cnn2.apply_to_all_bp_arg(f);
cnn3.apply_to_all_bp_arg(f);
rnn.apply_to_all_bp_arg(f);
}
CRNN_CTC_MODEL()=default;
CRNN_CTC_MODEL(std::string cnn1_str,std::string cnn2_str,std::string cnn3_str,std::string rnn_str):cnn1(cnn1_str),cnn2(cnn2_str),cnn3(cnn3_str),rnn(rnn_str){}
void train(int batchs,auto data_gen,float learning_rate=0.001,int batch_size=8)requires CAN_TRAIN<T1,T2>{
correct_predict=0;
tot_loss=0;
std::cout<<"[>";
for(int i=0;i<batchs;i++){
apply_to_all_bp_arg([](T2& x){x.grad_sum=0;});
for(int j=0;j<batch_size;j++){
std::vector<int> data=data_gen();
auto input=IMAGE(data).to_net();
train_one_sample(input,data);
}
apply_to_all_bp_arg([=](T2& x){x.grad_sum/=batch_size;if(std::abs(x.x)>=16){x.x=(x.x>0)?15.99999905f:-15.99999905f;}x.learn(learning_rate);});
for(int t=static_cast<int>(i*100/batchs);t<static_cast<int>((i+1)*100/batchs);t++){
std::cout<<"\b=>"<<std::flush;
}
}
std::cout<<"\b] loss: "<<tot_loss/batch_size/batchs<<", acc: "<<static_cast<float>(correct_predict)/batch_size/batchs<<std::endl;
}
void print_model(){
std::cout
<<"const std::string cnn1_arg=\""<<cnn1.to_str()
<<"\";\nconst std::string cnn2_arg=\""<<cnn2.to_str()
<<"\";\nconst std::string cnn3_arg=\""<<cnn3.to_str()
<<"\";\nconst std::string rnn_arg=\""<<rnn.to_str()<<"\";\n";
}
};
```
* 由于最后只能输出绝对值不小于 $16$ 的参数,每次训练完成后将绝对值太大的参数改小。
* 每次输出进度条、loss、准确率。
* `print_model`输出定义四个表示模型参数的常量字符串的语句。
## 计算
```cpp
int prec(char op){
switch(op){
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
}
return 0;
}
int apply_op(int a,int b,char op){
switch(op){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
return 0;
}
int eval(std::string exp){
std::stack<int> numbers;
std::stack<char> operators;
for(int i=0;i<exp.length();i++){
if(std::isdigit(exp[i])){
int val=0;
while(i<exp.length()&&std::isdigit(exp[i])){
val=val*10+exp[i]-'0';
i++;
}
i--;
numbers.push(val);
}else if(exp[i]=='('){
operators.push(exp[i]);
}else if(exp[i]==')'){
while(!operators.empty() && operators.top() !='('){
int val2=numbers.top();
numbers.pop();
int val1=numbers.top();
numbers.pop();
char op=operators.top();
operators.pop();
numbers.push(apply_op(val1,val2,op));
}
if(!operators.empty())
operators.pop();
}else{
while(!operators.empty()&&prec(operators.top())>=prec(exp[i])){
int val2=numbers.top();
numbers.pop();
int val1=numbers.top();
numbers.pop();
char op=operators.top();
operators.pop();
numbers.push(apply_op(val1, val2, op));
}
operators.push(exp[i]);
}
}
while(!operators.empty()){
int val2=numbers.top();
numbers.pop();
int val1=numbers.top();
numbers.pop();
char op=operators.top();
operators.pop();
numbers.push(apply_op(val1, val2, op));
}
return numbers.top();
}
```
* 用两个栈计算表达式。
# 训练过程
## 第一步
用上述的数据生成和训练参数训练模型。
```cpp
int main(){
CRNN_CTC_MODEL<GRAD_ARG,BP_ARG> model;
for(int i=0;i<1024;i++){
std::cout<<"epoch "<<i+1<<"/1024"<<std::endl;
std::cout<<"max len: 3"<<std::endl;
model.train(45,[]()->auto{return IMAGE::random_vector(1,3);});
std::cout<<"max len: 50"<<std::endl;
model.train(90,[]()->auto{return IMAGE::random_vector(1,50);});
std::cout<<"max len: 200"<<std::endl;
model.train(75,[]()->auto{return IMAGE::random_vector(1,200);});
}
model.print_model();
return 0;
}
```
编译运行程序,得到一个[模型](https://www.luogu.com.cn/paste/cdmtfixv)。这个模型对上述参数生成的数据的准确率超过 $98\%$。它可以获得 $488$ 分。
")
## 第二步
按照题目描述生成数据,用这些数据微调模型。
具体地,将第一步得到的[模型](https://www.luogu.com.cn/paste/cdmtfixv)复制到`int main(){}`前,然后作如下更改:
* 将`IMAGE::IMAGE()`中`std::uniform_real_distribution<float> Md(0.9,1),Mhd(0.8,1),Mwd(0.8,1),Rd(-25,25),Sxd(-0.2,0.2),Syd(-0.2,0.2);`改为`std::uniform_real_distribution<float> Md(0.9,1),Mhd(0.9,1),Mwd(0.9,1),Rd(-15,15),Sxd(-0.1,0.1),Syd(-0.1,0.1);`
* 删除`IMAGE::IMAGE()`中的`float p=std::uniform_real_distribution<float>(0.04,0.06)(gen);`,将`if(u(gen)<p){`改为`if(u(gen)<0.05){`
* 将`CRNN_CTC_MODEL::train(...)`中`...,float learning_rate=0.001,...`改为`...,float learning_rate=0.00001,...`
* 将`main`中`CRNN_CTC_MODEL<GRAD_ARG,BP_ARG> model;`改为`CRNN_CTC_MODEL<GRAD_ARG,BP_ARG> model(cnn1_arg,cnn2_arg,cnn3_arg,rnn_arg);`
* 将`main`中两处`1024`改为`8`
编译运行程序,得到一个新的模型。
## 第三步
将第二步得到的模型复制到程序中,并且删除不必要的代码,得到[最终提交的代码](https://www.luogu.com.cn/paste/yjx4wch3)。它可以通过此题。
[^1]:<https://arxiv.org/pdf/1507.05717>
[^2]:<https://www.ibm.com/cn-zh/topics/neural-networks>
[^3]:<https://www.cs.toronto.edu/~graves/icml_2006.pdf>
[^4]:<https://distill.pub/2017/ctc/>
[^5]:<https://arxiv.org/abs/2109.08203>