DDR爱好者之家 Design By 杰米

本文实例讲述了Python使用gluon/mxnet模块实现的mnist手写数字识别功能。分享给大家供大家参考,具体如下:

import gluonbook as gb
from mxnet import autograd,nd,init,gluon
from mxnet.gluon import loss as gloss,data as gdata,nn,utils as gutils
import mxnet as mx
net = nn.Sequential()
with net.name_scope():
  net.add(
    nn.Conv2D(channels=32, kernel_size=5, activation='relu'),
    nn.MaxPool2D(pool_size=2, strides=2),
    nn.Flatten(),
    nn.Dense(128, activation='sigmoid'),
    nn.Dense(10, activation='sigmoid')
  )
lr = 0.5
batch_size=256
ctx = mx.gpu()
net.initialize(init=init.Xavier(), ctx=ctx)
train_data, test_data = gb.load_data_fashion_mnist(batch_size)
trainer = gluon.Trainer(net.collect_params(),'sgd',{'learning_rate' : lr})
loss = gloss.SoftmaxCrossEntropyLoss()
num_epochs = 30
def train(train_data, test_data, net, loss, trainer,num_epochs):
  for epoch in range(num_epochs):
    total_loss = 0
    for x,y in train_data:
      with autograd.record():
        x = x.as_in_context(ctx)
        y = y.as_in_context(ctx)
        y_hat=net(x)
        l = loss(y_hat,y)
      l.backward()
      total_loss += l
      trainer.step(batch_size)
    mx.nd.waitall()
    print("Epoch [{}]: Loss {}".format(epoch, total_loss.sum().asnumpy()[0]/(batch_size*len(train_data))))
if __name__ == '__main__':
  try:
    ctx = mx.gpu()
    _ = nd.zeros((1,), ctx=ctx)
  except:
    ctx = mx.cpu()
  ctx
  gb.train(train_data,test_data,net,loss,trainer,ctx,num_epochs)

更多关于Python相关内容可查看本站专题:《Python数学运算技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米