Python使用gluon/mxnet模块实现的mnist手写数字识别功能完整示例

时间:2021-05-22

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

import gluonbook as gbfrom mxnet import autograd,nd,init,gluonfrom mxnet.gluon import loss as gloss,data as gdata,nn,utils as gutilsimport mxnet as mxnet = 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.5batch_size=256ctx = 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 = 30def 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程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章