目录
SVD是在机器学习领域广泛应用的算法,它不光可以用于降维算法中的特征分解,还可以用于推荐系统,以及自然语言处理等领域。本篇博客将介绍如何使用SVD对深度模型中全连接层(fully-connected layer)进行压缩。此外,我将以cifar10为例,用caffe进行实现。
一. SVD(奇异值分解)的原理
SVD的原理在网上能找到很多资料,这里不再赘述。推荐一篇博客: link.
二. 用SVD压缩深度模型中的全连接层
以cifar10为例,打开caffe/examples/cifar10/cifar10_quick_train_test.prototxt
,可以看到最后两个全连接层ip1和ip2
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool3"
top: "ip1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 64
weight_filler {
type: "gaussian"
std: 0.1
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 10
weight_filler {
type: "gaussian"
std: 0.1
}
bias_filler {
type: "constant"
}
}
}
根据ip1和ip2的num_output
,我们可以看出,ip1有64个神经元,ip2有10个神经元。也就是说在ip2这一层的权重矩阵W,其shape为(10, 64),根据SVD公式,
式子来自此博客link.
我们可以对权重矩阵W进行奇异值分解。代码如下:
import numpy as np
#假设此时W已经从模型提取出来了
U, s, V = np.linalg.svd(W)
print("U.shape:{}".format(U.shape),
"s.shape:{}".format(s.shape),
"V.shape:{}".format(V.shape