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

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

相关推荐
阿童木写作1 分钟前
跨境图片翻译工具多合一,批量图片视频字幕翻译加智能抠图
人工智能·python·音视频·语音识别
科技之门2 分钟前
AI3D从建模到贴图、绑骨和动画的完整流程怎么做?V2Fun完整工作流指南
人工智能·3d·贴图
宇宙第一小趴菜3 分钟前
二、机器学习的应用领域和发展史
人工智能·机器学习
前端开发江鸟9 分钟前
我写过 MCP Server,却一直以为 MCP 只有 Tool
人工智能
天国梦31 分钟前
自习室智能化升级避坑指南:天学网AI智习室方案实测与选型建议
大数据·人工智能
阿里云云原生1 小时前
可用性从 99.9% 跃升至 99.995%:畅捷通如何用 AI 重塑运维底座?
运维·网络·人工智能
ZhengEnCi1 小时前
MoE(Mixture of Experts,混合专家模型)深度解析:从路由机制到专家专业化的迷思
人工智能
shxjnpl1 小时前
Qwen3-ASR 从 PyTorch 迁移到 vLLM:一次信创环境下的推理路径改造实录
人工智能·pytorch·vllm
阿童木写作2 小时前
Python实现Temu图片批量翻译自动化教程
运维·人工智能·python·自动化
冬奇Lab3 小时前
代码库知识库系列(06):把调用图编码进 Embedding——结构增强有效,但不够
人工智能