1.softmax从零实现

from mxnet.gluon import data as gdata
from sklearn import datasets
from mxnet import nd,autograd
# 加载数据集
digits = datasets.load_digits()
features,labels = nd.array(digits['data']),nd.array(digits['target'])
print(features.shape,labels.shape)
labels_onehot = nd.one_hot(labels,10)
print(labels_onehot.shape)
(1797, 64) (1797,)
(1797, 10)
class softmaxClassifier:
def __init__(self,inputs,outputs):
self.inputs = inputs
self.outputs = outputs self.weight = nd.random.normal(scale=0.01,shape=(inputs,outputs))
self.bias = nd.zeros(shape=(1,outputs))
self.weight.attach_grad()
self.bias.attach_grad() def forward(self,x):
output = nd.dot(x,self.weight) + self.bias
return self._softmax(output) def _softmax(self,x):
step1 = x.exp()
step2 = step1.sum(axis=1,keepdims=True)
return step1 / step2 def _bgd(self,params,learning_rate,batch_size):
'''
批量梯度下降
'''
for param in params: # 直接使用mxnet的自动求梯度
param[:] = param - param.grad * learning_rate / batch_size def loss(self,y_pred,y):
return nd.sum((-y * y_pred.log())) / len(y) def dataIter(self,x,y,batch_size):
dataset = gdata.ArrayDataset(x,y)
return gdata.DataLoader(dataset,batch_size,shuffle=True) def fit(self,x,y,learning_rate,epoches,batch_size):
for epoch in range(epoches):
for x_batch,y_batch in self.dataIter(x,y,batch_size):
with autograd.record():
y_pred = self.forward(x_batch)
l = self.loss(y_pred,y_batch)
l.backward()
self._bgd([self.weight,self.bias],learning_rate,batch_size)
if epoch % 50 == 0:
y_all_pred = self.forward(x)
print('epoch:{},loss:{},accuracy:{}'.format(epoch+50,self.loss(y_all_pred,y),self.accuracyScore(y_all_pred,y))) def predict(self,x):
y_pred = self.forward(x)
return y_pred.argmax(axis=0) def accuracyScore(self,y_pred,y):
acc_sum = (y_pred.argmax(axis=1) == y.argmax(axis=1)).sum().asscalar()
return acc_sum / len(y)
sfm_clf = softmaxClassifier(64,10)
sfm_clf.fit(features,labels_onehot,learning_rate=0.1,epoches=500,batch_size=200)
epoch:50,loss:
[1.9941667]
<NDArray 1 @cpu(0)>,accuracy:0.3550361713967724
epoch:100,loss:
[0.37214527]
<NDArray 1 @cpu(0)>,accuracy:0.9393433500278241
epoch:150,loss:
[0.25443634]
<NDArray 1 @cpu(0)>,accuracy:0.9549248747913188
epoch:200,loss:
[0.20699367]
<NDArray 1 @cpu(0)>,accuracy:0.9588202559821926
epoch:250,loss:
[0.1799827]
<NDArray 1 @cpu(0)>,accuracy:0.9660545353366722
epoch:300,loss:
[0.1619963]
<NDArray 1 @cpu(0)>,accuracy:0.9677239844184753
epoch:350,loss:
[0.14888664]
<NDArray 1 @cpu(0)>,accuracy:0.9716193656093489
epoch:400,loss:
[0.13875261]
<NDArray 1 @cpu(0)>,accuracy:0.9738452977184195
epoch:450,loss:
[0.13058177]
<NDArray 1 @cpu(0)>,accuracy:0.9760712298274903
epoch:500,loss:
[0.12379646]
<NDArray 1 @cpu(0)>,accuracy:0.9777406789092933
print('预测结果:',sfm_clf.predict(features[:10]))
print('真实结果:',labels[:10])
预测结果:
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
<NDArray 10 @cpu(0)>
真实结果:
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
<NDArray 10 @cpu(0)>

2.使用mxnet实现softmax分类

from mxnet import gluon,nd,autograd,init
from mxnet.gluon import nn,trainer,loss as gloss,data as gdata
# 定义模型
net = nn.Sequential()
net.add(nn.Dense(10)) # 初始化模型
net.initialize(init=init.Normal(sigma=0.01)) # 损失函数
loss = gloss.SoftmaxCrossEntropyLoss(sparse_label=False) # 优化算法
optimizer = trainer.Trainer(net.collect_params(),'sgd',{'learning_rate':0.1}) # 训练
epoches = 500
batch_size = 200 dataset = gdata.ArrayDataset(features, labels_onehot)
data_iter = gdata.DataLoader(dataset,batch_size,shuffle=True)
for epoch in range(epoches):
for x_batch,y_batch in data_iter:
with autograd.record():
l = loss(net.forward(x_batch), y_batch).sum() / batch_size
l.backward()
optimizer.step(batch_size)
if epoch % 50 == 0:
y_all_pred = net.forward(features)
acc_sum = (y_all_pred.argmax(axis=1) == labels_onehot.argmax(axis=1)).sum().asscalar()
print('epoch:{},loss:{},accuracy:{}'.format(epoch+50,loss(y_all_pred,labels_onehot).sum() / len(labels_onehot),acc_sum/len(y_all_pred)))
epoch:50,loss:
[2.1232333]
<NDArray 1 @cpu(0)>,accuracy:0.24652198107957707
epoch:100,loss:
[0.37193483]
<NDArray 1 @cpu(0)>,accuracy:0.9410127991096272
epoch:150,loss:
[0.25408813]
<NDArray 1 @cpu(0)>,accuracy:0.9543683917640512
epoch:200,loss:
[0.20680156]
<NDArray 1 @cpu(0)>,accuracy:0.9627156371730662
epoch:250,loss:
[0.1799252]
<NDArray 1 @cpu(0)>,accuracy:0.9666110183639399
epoch:300,loss:
[0.16203885]
<NDArray 1 @cpu(0)>,accuracy:0.9699499165275459
epoch:350,loss:
[0.14899409]
<NDArray 1 @cpu(0)>,accuracy:0.9738452977184195
epoch:400,loss:
[0.13890252]
<NDArray 1 @cpu(0)>,accuracy:0.9749582637729549
epoch:450,loss:
[0.13076076]
<NDArray 1 @cpu(0)>,accuracy:0.9755147468002225
epoch:500,loss:
[0.1239901]
<NDArray 1 @cpu(0)>,accuracy:0.9777406789092933

从零和使用mxnet实现softmax分类的更多相关文章

  1. 从零和使用mxnet实现dropout

    需求: 从零和使用mxnet实现dropout 数据集: 使用load_digits()手写数字数据集 要求: 使用1个掩藏层n_hidden1 = 36,激活函数为relu,损失函数为softmax ...

  2. 学习笔记TF010:softmax分类

    回答多选项问题,使用softmax函数,对数几率回归在多个可能不同值上的推广.函数返回值是C个分量的概率向量,每个分量对应一个输出类别概率.分量为概率,C个分量和始终为1.每个样本必须属于某个输出类别 ...

  3. 从零和使用mxnet实现线性回归

    1.线性回归从零实现 from mxnet import ndarray as nd import matplotlib.pyplot as plt import numpy as np import ...

  4. 动手学深度学习7-从零开始完成softmax分类

    获取和读取数据 初始化模型参数 实现softmax运算 定义模型 定义损失函数 计算分类准确率 训练模型 小结 import torch import torchvision import numpy ...

  5. softmax分类算法原理(用python实现)

    逻辑回归神经网络实现手写数字识别 如果更习惯看Jupyter的形式,请戳Gitthub_逻辑回归softmax神经网络实现手写数字识别.ipynb 1 - 导入模块 import numpy as n ...

  6. gluon实现softmax分类FashionMNIST

    from mxnet import gluon,init from mxnet.gluon import loss as gloss,nn from mxnet.gluon import data a ...

  7. Keras 多层感知机 多类别的 softmax 分类模型代码

    Multilayer Perceptron (MLP) for multi-class softmax classification: from keras.models import Sequent ...

  8. tf.nn.softmax 分类

    tf.nn.softmax(logits,axis=None,name=None,dim=None) 参数: logits:一个非空的Tensor.必须是下列类型之一:half, float32,fl ...

  9. softmax实现cifar10分类

    将cifar10改成单一通道后,套用前面的softmax分类,分类率40%左右,想哭... .caret, .dropup > .btn > .caret { border-top-col ...

随机推荐

  1. 【linux】lvm扩展根分区

    lvm扩展根目录 1.lvm的基本概念 physical volume (PV) 通常是一快硬盘.相当于一个物理设备,磁盘空间物理卷PV. volume group (VG) 相当于LVM的卷组,属于 ...

  2. 在Button样式中添加EventSetter,理解路由事件

    XML <Window.Resources> <Style x:Key="ButtonStyle2" TargetType="{x:Type Butto ...

  3. JSONBuilder的用法

    一.JSONBuilder可以向文件中写入写入json字符串.如下面的例子: 1 public class Test 2 { 3 public static void main(String args ...

  4. Spring Security 入门—内存用户验证

    简介 作为 Spring 全家桶组件之一,Spring Security 是一个提供安全机制的组件,它主要解决两个问题: 认证:验证用户名和密码: 授权:对于不同的 URL 权限不一样,只有当认证的用 ...

  5. excel中统计COUNTIFS的值为0

    excel中统计COUNTIFS的值为0 个人认为是由于导出的文件里面的字符个数问题 使用 =COUNTIFS(H1:H175,"微信支付") 这个的结果居然是0,找了很多办法 于 ...

  6. winform子窗口与父窗口的交互-使用委托与事件

    实现子窗口与父窗口的交互,通过父窗口调用并控制子窗口,子窗口也能控制父窗口,使用委托和事件的方法,可以实现. 1.父窗口调用子窗口,并通过子窗口控制父窗口 新建工程,创建两个窗体    显示子窗体的代 ...

  7. HttpClient到底该不该using?

    HttpClient实例是否应该释放掉? 从源代码中可以的看到httpClient类最上层实现了IDisposable接口,看到该接口我们下意识就是要用using(自动释放)代码块包含起.或者自己手动 ...

  8. iOS开发使用Xcode的一些小技巧

    1.打开iOS项目 如果你当前目录下既有project又有workspace,你可以在终端使用命令“xed.”自动打开workspace,如果只有project,它会自动打开project. 2.清理 ...

  9. h5和native测试时的区别

    我们以往的APP是使用原生系统内核的,相当于直接在系统上操作,是我们传统意义上的软件,更加稳定 H5的APP先得调用系统的浏览器内核,相当于是在网页中进行操作,较原生APP稳定性稍差,似乎还没有百万级 ...

  10. Python3内建函数sorted

    排序算法 排序也是在程序中经常用到的算法.无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小.如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的 ...