cs231n作业1——Softmax

参考文章:cs231n assignment1------softmax

Softmax

softmax其实和SVM差别不大,两者损失函数不同,softmax就是把各个类的得分转化成了概率。

损失函数:

python 复制代码
def softmax_loss_naive(W, X, y, reg):
    loss = 0.0
    dW = np.zeros_like(W)
    num_classes = W.shape[1]
    num_train = X.shape[0]
    for i in range(num_train):
        scores = X[i].dot(W)                # 矩阵点乘:第 i 张照片在各类别上的得分
        scores -= np.max(scores)            # 减去最大得分,减小计算量
        correct_class_score = scores[y[i]]  # 接下来三行是损失函数的计算
        exp_sum = np.sum(np.exp(scores))
        loss += -correct_class_score + np.log(exp_sum) # np.log()以e为底
        for j in range(num_classes):
            if j == y[i]:
                dW[:, y[i]] += (np.exp(scores[y[i]])/exp_sum-1)*X[i]
            else:
                dW[:, j] += np.exp(scores[j])/exp_sum*X[i]    
    
    loss /= num_train                      # 求平均损失
    loss += reg * np.sum(W * W)            # 损失加上正则化惩罚
    dW /= num_train                        # 求平均梯度
    dW += 2.0*reg*W

    return loss, dW

用向量法实现 Softmax

python 复制代码
def softmax_loss_vectorized(W, X, y, reg):
    loss = 0.0
    dW = np.zeros_like(W)

    num_classes = W.shape[1]
    num_train = X.shape[0]
    scores = X.dot(W)                                                  # N*C 的矩阵
    scores -= np.max(scores, axis=1, keepdims=True)                    # 减去每行(每张图片对于每一类)的最大值
    correct_class_score = scores[range(num_train),y]
    exp_sum = np.sum(np.exp(scores), axis=1, keepdims=True)            # 按行求和,并保持为二维(列向量)
    loss = -np.sum(correct_class_score) + np.sum(np.log(exp_sum))      # 损失函数公式并求和
    loss = loss/num_train + reg * np.sum(W * W)
    
    med = np.exp(scores)/exp_sum         # 对于j!=yi的情况,dw=np.exp(scores[j])/exp_sum*X[i]
    med[range(num_train),y] -= 1         # 对于j=yi的情况,dw=(np.exp(scores[j])/exp_sum-1)*X[i]
    dW = X.T.dot(med)                    # 最后同时乘以 X[i]
    dW /= num_train
    dW += 2.0*reg*W

    return loss, dW

之后用随机梯度下降法优化损失函数,最后进行超参数的选择。

相关推荐
宿州派大星20 分钟前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
风娜1 小时前
IT 疑难杂症诊疗室:从现象到根因的系统排查方法论
人工智能·github
碧海银沙音频科技研究院1 小时前
炬芯ATS3089X手表的HFP通话不自动路由到设备BT的问题解决
网络·人工智能·嵌入式硬件·算法
承渊政道1 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
howdoyoudo2026062 小时前
AI审计手记 #28:从“暂停训练”到“切断联网”——AI安全控制手段的极限升级
大数据·人工智能·安全·ai·语言模型
colman wang2 小时前
人工智能课程(配套AIMA(Artificial Intelligence: A Modern Approach))
人工智能
LinXunFeng6 小时前
Draw Things 换装 LoRA 实战:用 Silo 秒装,同一提示词对比出图
人工智能·开源·aigc
xiaohaiAIgeo6 小时前
【2026年】通风柜自动门安全吗?联锁逻辑与防夹设计
人工智能·安全·科普知识
像风一样自由20206 小时前
52.Docker部署大模型应用从本地开发到服务化运行
运维·人工智能·docker·容器·大模型·智能体