Softmax Regression练习

    在上篇博文(http://blog.csdn.net/freeliao/article/details/19424565)介绍了Softmax Regression的模型,现在来做下该模型在MNIST数据集上的识别练习(http://ufldl.stanford.edu/wiki/index.php/Exercise:Softmax_Regression)。MNIST数据集训练集由60000张28*28的图片组成,测试集由10000张同样大小的图片组成。

    这里的Softmax Regression没有隐含层,直接以图片的像素值作为输入,得到输出层,输出层有10个单元,每个单元代表输入属于该类别的概率。

回顾一下模型的损失函数和梯度:



    matlab实现过程中要注意用Vectorized的实现方式,尽量避免出现构造过大的矩阵,否则容易出现out of memory错误。


  实现结果准确率为92.640%。

softmaxExercise.m

%% CS294A/CS294W Softmax Exercise 

%  Instructions
%  ------------
% 
%  This file contains code that helps you get started on the
%  softmax exercise. You will need to write the softmax cost function 
%  in softmaxCost.m and the softmax prediction function in softmaxPred.m. 
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%  (However, you may be required to do so in later exercises)

%%======================================================================
%% STEP 0: Initialise constants and parameters
%
%  Here we define and initialise some constants which allow your code
%  to be used more generall
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python实现softmax regression(也称为多类别逻辑回归)可以使用NumPy库来进行数值计算。下面是一个简单的示例代码: ```python import numpy as np def softmax_regression(X, y, num_classes, learning_rate, num_iterations): num_features = X.shape[1] theta = np.zeros((num_features, num_classes)) for i in range(num_iterations): scores = np.dot(X, theta) exp_scores = np.exp(scores) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # 计算损失函数 loss = -np.log(probs[range(len(X)), y]) data_loss = np.sum(loss) / len(X) # 计算梯度 d_probs = probs d_probs[range(len(X)), y] -= 1 d_probs /= len(X) d_theta = np.dot(X.T, d_probs) # 更新参数 theta -= learning_rate * d_theta return theta # 示例数据 X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) y = np.array([0, 1, 2, 1]) # 调用softmax_regression函数进行训练 num_classes = len(np.unique(y)) learning_rate = 0.01 num_iterations = 1000 theta = softmax_regression(X, y, num_classes, learning_rate, num_iterations) print("训练得到的参数theta:") print(theta) ``` 这段代码实现了softmax regression的训练过程。首先,定义了一个softmax_regression函数,该函数接受输入特征矩阵X、标签向量y、类别数量num_classes、学习率learning_rate和迭代次数num_iterations作为参数。在函数内部,首先初始化参数theta为全零矩阵。然后,通过迭代更新参数theta,直到达到指定的迭代次数。在每次迭代中,计算得分矩阵scores、概率矩阵probs和损失函数loss。然后,计算梯度d_theta,并使用学习率更新参数theta。最后,返回训练得到的参数theta。 在示例数据部分,定义了一个简单的输入特征矩阵X和标签向量y。调用softmax_regression函数进行训练,并打印训练得到的参数theta。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值