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

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

相关推荐
武汉唯众智创2 分钟前
边缘端部署 AI 心理分析:自研边缘主机跑通人脸 + 语音双模态推理,不用云端算力详解
人工智能·ai心理健康·校园心理健康·多模态推理·人脸情绪识别·语音情感分析·心理健康信息化平台
IT_陈寒7 分钟前
Python的线程池把我坑惨了,原来异步不是万能的
前端·人工智能·后端
水木流年追梦14 分钟前
大模型入门-大模型优化方法12-YaRN 长文本外推技术
人工智能·分布式·算法·正则表达式·prompt
Litluecat18 分钟前
2026年6月6日科技热点新闻
人工智能·科技·热点·每日
小旭952718 分钟前
Spring AI Alibaba 从入门到实战:一站式掌握企业级 AI 应用开发
java·人工智能·spring
tianxiaxue129 分钟前
企微如何使用AI生成推荐话术?
人工智能·企业微信
团象科技31 分钟前
梳理中小出海独立站落地阶段关于WordPress 海外主机的实操参考路径
人工智能·深度学习
朴马丁41 分钟前
构建日化数字创新平台:PLM如何融合AI、物联网数据,驱动智能研发与精准营销
人工智能·物联网·流程行业plm·日化行业
我不介意孤独41 分钟前
04-记忆系统为什么向量数据库不够用
数据库·人工智能·资源隔离·agent infra
小程故事多_801 小时前
从人工编写到自主迭代进化,SkillEvolver重构大模型智能体技能生成新范式
人工智能·重构