图像线性分类
机器学习:数据驱动的方式
- 收集图像数据和标签
- 使用机器学习的方法训练分类器
- 在新的图像上评估分类器
Nearest Neighbor Classifier
距离公式
L1距离
d
1
(
I
1
,
I
2
)
=
∑
p
∣
I
1
p
−
I
2
p
∣
d_1(I_1,I_2) = \sum_p|I_1^p - I_2^p|
d1(I1,I2)=∑p∣I1p−I2p∣
import numpy asnp
class NearestNeighbor:
def __inti__(self):
pass
def train(self,X,y):
"""X is N x D where each row is an example. Y is 1-dimension od size N"""
# memorize training data
self.Xtr = x
self.Ytr = y
def predict(self, X):
"""X is N xD where each row is an example we wish to predice lable for """
num_test = X.shape[0]
Ypre = np.zeros(num_test, dtype = self.Yter.dtype)
# For each test image ,find cloest train image ,predict label of nearst image
for i in xrang(num_test):
# find the nearest training image to the i'th test image
distances = np.sum(np.abs(self.Xter - X[i,:]),axis=1)
min_index = np.argmin(distances)
Ypred[i] = self.Ytr[min_index]
return Ypred
上面的算法有一点不好,训练是O(1)的复杂度, 预测是O(N)的复杂度。
K-Nearest Neighbor
增加了一个投票过程,选取最接近的K个图像,然后投票,选则投票数组多的一个类别
马汉顿距离的结果和坐标轴相关,欧拉距离和与坐标轴无关
Hyperparameters 超参数
- k的取多少效果最好
- 用那种距离公式最好
- 一般需要验证集用来选择超参数
- 一般在小数据集上使用交叉验证
k-NN 和 pixel distance 从来不用
- 像素距离标准并不一定能反应相关信息
- 维度爆炸,随着维度的增加,分类性能从增加到减少,因为纬度越高,数据越稀疏,导致过拟合
线性分类
假如说每张图像都只有4个像素,又有三个类别 猫/ 狗 / 船
b 是一个偏移量,如果说我们的数据中有更多的狗,狗这一分类的 b 可能会比较大
另:w 和 b 可以组成一个 m+1 维的向量, 可以构成一个 m维空间的平面
w
0
x
0
+
w
1
x
1
+
.
.
.
+
w
m
x
m
+
b
=
0
w_0x_0 +w_1x_1+...+w_mx_m+b=0
w0x0+w1x1+...+wmxm+b=0
选个一个好的参数矩阵 W
- 定义损失函数
- 优化,损失函数的值
总的loss可以是所有样本loss的均值
多分类 SVM loss