DL 基础 | cs231n assignment 1
cs231n assignment 1
20210804 - 20210808。
总结
建立模型的步骤:
__init__(self)
;在注释中约定模型的参数超参数。- 写出【loss function】,
loss()
:要给出regularization_strength,如果给出label y就返回gradient。 - 用stochastic gradient descent写出
train()
。 - 写出
predict()
。
训练模型的步骤:
- 得到train、validation、predict的X和y,顺便得到它们的维度;
- 设置一堆超参数,开始训练,试出来哪些超参数更好。
矩阵求微分:
其中
KNN
思想
k是一个超参数。对于新给出的一个数据,找到离它【距离】最近的k个样本,用 这k个样本中数目最多的类别 来预测 这个数据的类别。
距离:L1距离/Manhattan距离,L2距离/Euclidean距离。
(L1距离与选择的坐标轴有关,而转动坐标轴对L2距离没有影响。因此如果坐标轴有特殊的意义,可以考虑L1距离,否则L2距离更自然一些。)
cross-validation
一般做法:我们会把数据分成3组:train,validation,test。在validation上试出最合适的超参数,然后我们就用这一组超参数对应的模型了。
交叉验证:把test拿出来,然后把其余的分成若干组。对于一组超参数,把每一组都拿出来做一次validation(用其余组训练模型),然后对模型在各个validation上的表现取平均值,根据这个平均值选超参数。
在小数据集上是有用的,但在深度学习中不常用。
编程细节
# 神仙高效矢量化代码 dists[i, j] = np.sqrt(np.sum(np.square(X[i] - self.X_train[j]))) # np是万能的 dists[i, :] = np.sqrt(np.sum(np.square(X[i] - self.X_train), axis = 1)) # 进阶版,axis=1: :::::: -> :,0::::::: -> ...... dists = np.sqrt( np.sum(X**2, axis = 1, keepdims = True) + np.sum(self.X_train**2, axis = 1, keepdims = True).T - 2*np.dot(X, self.X_train.T) ) # 一次得到!更高更妙的广播操作,keepdims用来保持二维特性
max_index = np.argsort(dists[i]) # argsort返回的是数组值从小到大的索引值
maxdir = {} # this is a dictionary sy = set(closest_y) # make it become set for s in sy: maxdir[s] = closest_y.count(s) y_pred[i] = int(max(maxdir, key = maxdir.get)) # 字典返回value最大的key
# Frobenius norm 可以用来检验两个矩阵是否相同 # 就是所有的difference平方和开根号 # 换句话说,把矩阵变成向量再求euclidean距离 difference = np.linalg.norm(dists - dists_one, ord='fro') print('Difference was: %f' % (difference, )) if difference < 0.001: print('Good! The distance matrices are the same') else: print('Uh-oh! The distance matrices are different')
SVM
思想
线性分类器:
x是3072*1的图片(列向量),W是10*3072的权重矩阵,b是10*1的bias列向量。
最后我们得到一个10*1的列向量,其中【第i行的元素】就是【W第i行】和【x】的内积(再加一个bias),内积即相似程度。W的第i行可以被看成与类别i对应的pattern。
代码中的预处理
- 算出mean,然后把每个数据都减去mean;
- 直接把mean作为bias,svm只对W进行优化。
multi-class svm loss
我们看除正确类别外的9个类别的得分:如果正确类别的得分高于该错误类别得分,高于它一个安全的bound(此处为1),loss是0,否则loss是【错误类别得分+bound-正确类别】。
正则项
λ是正则化强度。就是鼓励更简洁的模型,penalize the complexity of the model。
L2 regularization:
L1 regularization:
编程细节
# numpy真是魔法 mask = range(num_training, num_training + num_validation) X_val = X_train[mask]
如果【正确类别得分没有高于错误类别一个安全的bound】,求梯度的时候不仅要错误类别分数降低,还要正确类别分数升高。
# W是3072*10,X是100*3072 scores = X.dot(W) correct_class_score = scores[np.arange(num_train),y] scores_to_calc = scores - correct_class_score.reshape(-1, 1) + 1. # 想让矩阵变成只有一列(行数不知道多少),通过mat.reshape(-1,1) # 也就是所有分数减去正确分数再加1 scores_to_calc[scores_to_calc <= 0] = 0 loss = np.sum(scores) / num_train - 1 # 减去正确类别 scores_to_calc[scores_to_calc > 0] = 1 mask = np.array(scores_to_calc) # 数组深复制 mask[np.arange(num_train), y] = -np.sum(scores_to_calc, axis = 1) # 有多少个+1超过bound的错误类别分数,正确类别的loss梯度就要减多少次 dW = X.T.dot(mask) / num_train # Add regularization to the loss. loss += reg * np.sum(W * W) dW += 2 * reg * W
梯度下降法,是沿loss负梯度的方向向下走,所以是W -= learning_rage * grad
。
softmax
思想
softmax的loss function是这样的:
我们认为P是一个概率。给出样本
就是【类别k得分的exp】比上【各个类别得分的exp之和】。
损失函数就是【-log正确类别概率】,概率=1时loss=0,概率=0时loss=正无穷。
编程细节
X_train = np.reshape(X_train, (X_train.shape[0], -1)) # reshape,保留第一个维度,剩下全压缩到一个维度(-1)
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))]) # hstack,就是把两个矩阵水平靠着放在一起 # 等价于np.concatenate([ndarray数组], axis=1)
要想用np广播,就要在np.sum()
的时候加上keepdims=True
。
two layers net
思想
linear score function:
2-layer Neural Network:

非线性运算(如这里的max)很重要,否则线性堆叠在一起还是线性。
forward pass:先算h,再算s,再算loss。
backward pass:求loss的微分,先算dscore,再算db2、dW2、dh,通过dh再算dW1和db1。
epoch是什么
一个epoch表示把所有数据送入模型训练一遍的过程。
minibatch是为了算gradient快一些。
iterations_per_epoch = max(num_train / batch_size, 1)
,就是说我们要iterate几次才能完成一个epoch。
完成一个epoch之后,我们把learning_rate调低,learning_rate *= learning_rate_decay
。
编程细节
算loss的时候算的是N个example的mean,并且别忘了加regularization term。
算gradient的时候也别忘了加上正则项。
y_pred = np.argsort(self.loss(X),axis = 1)[:,-1] # argsort把元素从小到大排序,给我们排序好的下标。我们要得分最大的,因此[:,-1]
feathers
思想
feather engineering。
本文作者:MoonOut
本文链接:https://www.cnblogs.com/moonout/p/15114371.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步