博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
gluon 实现多层感知机MLP分类FashionMNIST
阅读量:6712 次
发布时间:2019-06-25

本文共 1970 字,大约阅读时间需要 6 分钟。

from mxnet import gluon,initfrom mxnet.gluon import loss as gloss, nnfrom mxnet.gluon import data as gdatafrom mxnet import nd,autogradimport gluonbook as gbimport sys# 读取数据# 读取数据mnist_train = gdata.vision.FashionMNIST(train=True)mnist_test = gdata.vision.FashionMNIST(train=False)batch_size = 256transformer = gdata.vision.transforms.ToTensor()if sys.platform.startswith('win'):    num_workers = 0else:    num_workers = 4# 小批量数据迭代器train_iter = gdata.DataLoader(mnist_train.transform_first(transformer),batch_size=batch_size,shuffle=True,num_workers=num_workers)test_iter = gdata.DataLoader(mnist_test.transform_first(transformer),batch_size=batch_size,shuffle=False,num_workers=num_workers)# 定义网络net = nn.Sequential()net.add(nn.Dense(256,activation='relu'),nn.Dense(10))net.initialize(init.Normal(sigma=0.01))# 损失函数loss = gloss.SoftmaxCrossEntropyLoss()trainer = gluon.Trainer(net.collect_params(),'sgd',{
'learning_rate':0.5})def accuracy(y_hat, y): return (y_hat.argmax(axis=1) == y.astype('float32')).mean().asscalar()def evaluate_accuracy(data_iter, net): acc = 0 for X, y in data_iter: acc += accuracy(net(X), y) return acc / len(data_iter)num_epochs = 5def train(net,train_iter,test_iter,loss,num_epochs,batch_size,params=None,lr=None,trainer=None): for epoch in range(num_epochs): train_l_sum = 0 train_acc_sum = 0 for X,y in train_iter: with autograd.record(): y_hat = net(X) l = loss(y_hat,y) l.backward() if trainer is None: gb.sgd(params,lr,batch_size) else: trainer.step(batch_size) train_l_sum += l.mean().asscalar() test_acc = evaluate_accuracy(test_iter,net) print('epoch %d,loss %.4f,test acc %.3f'%(epoch+1,train_l_sum / len(train_iter),test_acc))train(net,train_iter,test_iter,loss,num_epochs,batch_size,None,None,trainer)

转载于:https://www.cnblogs.com/TreeDream/p/10033557.html

你可能感兴趣的文章
Web服务之LNMMP架构及动静分离实现
查看>>
centos6.4搭建zabbix
查看>>
Nginx+Keepalived实现
查看>>
安装python的easy_install和pip
查看>>
android SQLite
查看>>
Apache for Load Banlance
查看>>
Sublime Text 2 快捷键用法大全
查看>>
放弃redis使用mongodb做任务队列支持增删改管理
查看>>
G口与S口的区别
查看>>
甲骨文拒绝SAP 2.72亿美元赔偿要求重审
查看>>
FLEX3中应用CSS完全详解手册
查看>>
Windows7添加usb3.0驱动
查看>>
模式——工程化实现及扩展(设计模式Java 版)
查看>>
如何干净的清除Slave同步信息
查看>>
Oracle动态采样学习
查看>>
借助开源工具高效完成Java应用的运行分析
查看>>
Transparent Huge Pages相关概念
查看>>
浅谈RAID和LVM
查看>>
初中高级LINUX运维所需具备技能
查看>>
从开发到测试
查看>>