CS231n assignment1笔记

KNN

no_loop计算dists矩阵:
参考KNN中no-loop矩阵乘法代码

损失函数

在这里插入图片描述

Numpy中ndim、shape、dtype、astype的用法
Python numpy函数:hstack()、vstack()、stack()、dstack()、vsplit()、concatenate()

SVM

    for i in range(num_train):
        scores = X[i].dot(W)    #第i个训练集在10个维度上的数值
        correct_score = scores[y[i]]   #真实数值
        for j in range(num_att):
            if j == y[i]:
                continue
            margin = scores[j] - correct_score + 1 # note delta = 1
            if margin > 0:    #如果差距>1则计入误差
                loss += margin
                dW[:,j]+=X[i].T        ##通过求导得到
                dW[:,y[i]] += -X[i].T 

这里的优化参见下图cs231n官方笔记
在这里插入图片描述

这里import怎么用

Softmax

在这里插入图片描述
分子常常较大,在分式的分子和分母都乘以一个常数C
在这里插入图片描述
通常将C设为 log   C = − max ⁡ j f j \textbf{log C}=-\max_jf_j log C=maxjfj使得每项最大值为0
在这里插入图片描述
这里的 log = ln \textbf{log}=\textbf{ln} log=ln

    for i in range(num_train):
        scores = X[i].dot(W)
        # to keep numerical calculate stablly,minus maximum
        scores -= np.max(scores)
        exp_scores = np.exp(scores)
        prob = exp_scores / np.sum(exp_scores)
        for j in range(num_classes):
            if j == y[i]:
                correct_class_prob = prob[j]
                correct_class_logprob = -np.log(correct_class_prob)
                loss += correct_class_logprob
                dW[:,j] += (correct_class_prob - 1) * X[i,:]
            # 之前else没加,硬是找不出来这个bug
            else: 
                dW[:,j] += prob[j] * X[i,:]

上边代码为求softmax loss的梯度
下面为梯度推导
在这里插入图片描述
在这里插入图片描述

    loss /= num_train 
    loss += 0.5 * reg *np.sum(W * W)

    dW /= num_train
    dW += reg * W

dw就是lossw求导,代码中dwloss上下对应

    scores = scores - np.max(scores,axis=1).reshape(-1,1)

上式代码用来提高计算中的数值稳定
在这里插入图片描述
参考链接
cs231n官方笔记(知乎翻译版)
softmax损失函数推导参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值