侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

softmax及python实现过程解析

Python  /  管理员 发布于 7年前   232

相对于自适应神经网络、感知器,softmax巧妙低使用简单的方法来实现多分类问题。

  • 功能上,完成从N维向量到M维向量的映射
  • 输出的结果范围是[0, 1],对于一个sample的结果所有输出总和等于1
  • 输出结果,可以隐含地表达该类别的概率

softmax的损失函数是采用了多分类问题中常见的交叉熵,注意经常有2个表达的形式

  • 经典的交叉熵形式:L=-sum(y_right * log(y_pred)), 具体
  • 简单版本是: L = -Log(y_pred),具体

这两个版本在求导过程有点不同,但是结果都是一样的,同时损失表达的意思也是相同的,因为在第一种表达形式中,当y不是

正确分类时,y_right等于0,当y是正确分类时,y_right等于1。

下面基于mnist数据做了一个多分类的实验,整体能达到85%的精度。

'''softmax classifier for mnist created on 2019.9.28author: vince'''import mathimport loggingimport numpy import randomimport matplotlib.pyplot as pltfrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_setsfrom sklearn.metrics import accuracy_scoredef loss_max_right_class_prob(predictions, y):return -predictions[numpy.argmax(y)];def loss_cross_entropy(predictions, y):return -numpy.dot(y, numpy.log(predictions));'''Softmax classifierlinear classifier '''class Softmax:def __init__(self, iter_num = 100000, batch_size = 1):self.__iter_num = iter_num;self.__batch_size = batch_size;def train(self, train_X, train_Y):X = numpy.c_[train_X, numpy.ones(train_X.shape[0])];Y = numpy.copy(train_Y);self.L = [];#initialize parametersself.__weight = numpy.random.rand(X.shape[1], 10) * 2 - 1.0;self.__step_len = 1e-3; logging.info("weight:%s" % (self.__weight));for iter_index in range(self.__iter_num):if iter_index % 1000 == 0:logging.info("-----iter:%s-----" % (iter_index));if iter_index % 100 == 0:l = 0;for i in range(0, len(X), 100):predictions = self.forward_pass(X[i]);#l += loss_max_right_class_prob(predictions, Y[i]); l += loss_cross_entropy(predictions, Y[i]); l /= len(X);self.L.append(l);sample_index = random.randint(0, len(X) - 1);logging.debug("-----select sample %s-----" % (sample_index));z = numpy.dot(X[sample_index], self.__weight);z = z - numpy.max(z);predictions = numpy.exp(z) / numpy.sum(numpy.exp(z));dw = self.__step_len * X[sample_index].reshape(-1, 1).dot((predictions - Y[sample_index]).reshape(1, -1));#dw = self.__step_len * X[sample_index].reshape(-1, 1).dot(predictions.reshape(1, -1)); #dw[range(X.shape[1]), numpy.argmax(Y[sample_index])] -= X[sample_index] * self.__step_len;self.__weight -= dw;logging.debug("weight:%s" % (self.__weight));logging.debug("loss:%s" % (l));logging.info("weight:%s" % (self.__weight));logging.info("L:%s" % (self.L));def forward_pass(self, x):net = numpy.dot(x, self.__weight);net = net - numpy.max(net);net = numpy.exp(net) / numpy.sum(numpy.exp(net)); return net;def predict(self, x):x = numpy.append(x, 1.0);return self.forward_pass(x);def main():logging.basicConfig(level = logging.INFO,format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt = '%a, %d %b %Y %H:%M:%S');logging.info("trainning begin.");mnist = read_data_sets('../data/MNIST',one_hot=True)  # MNIST_data指的是存放数据的文件夹路径,one_hot=True 为采用one_hot的编码方式编码标签#load datatrain_X = mnist.train.images        #训练集样本validation_X = mnist.validation.images   #验证集样本test_X = mnist.test.images         #测试集样本#labelstrain_Y = mnist.train.labels        #训练集标签validation_Y = mnist.validation.labels   #验证集标签test_Y = mnist.test.labels         #测试集标签classifier = Softmax();classifier.train(train_X, train_Y);logging.info("trainning end. predict begin.");test_predict = numpy.array([]);test_right = numpy.array([]);for i in range(len(test_X)):predict_label = numpy.argmax(classifier.predict(test_X[i]));test_predict = numpy.append(test_predict, predict_label);right_label = numpy.argmax(test_Y[i]);test_right = numpy.append(test_right, right_label);logging.info("right:%s, predict:%s" % (test_right, test_predict));score = accuracy_score(test_right, test_predict);logging.info("The accruacy score is: %s "% (str(score)));plt.plot(classifier.L)plt.show();if __name__ == "__main__":main();

损失函数收敛情况

Sun, 29 Sep 2019 18:08:08 softmax.py[line:104] INFO trainning end. predict begin.Sun, 29 Sep 2019 18:08:08 softmax.py[line:114] INFO right:[7. 2. 1. ... 4. 5. 6.], predict:[7. 2. 1. ... 4. 8. 6.]Sun, 29 Sep 2019 18:08:08 softmax.py[line:116] INFO The accruacy score is: 0.8486 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    自适应线性神经网络Adaline的python实现详解
    下一条:
    python根据时间获取周数代码实例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客