mxnet 手写数字识别的例子

前面写了一些关于mxnetAPI的,现在给出一个github上mxnet的一个例子

import os,  sys
from utils import get_data

import mxnet as mx
import numpy as np
import logging
# 创建计算图
data = mx.symbol.Variable('data')
fc1 = mx.symbol.FullyConnected(data, name='fc1', num_hidden=128)
act1 = mx.symbol.Activation(fc1, name='relu1', act_type="relu")
fc2 = mx.symbol.FullyConnected(act1, name = 'fc2', num_hidden = 64)
act2 = mx.symbol.Activation(fc2, name='relu2', act_type="relu")
fc3 = mx.symbol.FullyConnected(act2, name='fc3', num_hidden=10)
# print(fc3)  这时候只是一个符号
softmax = mx.symbol.SoftmaxOutput(fc3, name = 'softmax')

n_epoch = 2
batch_size = 100
# 加载数据
basedir = os.path.dirname(__file__)
get_data.get_mnist(os.path.join(basedir, "data"))

train_dataiter = mx.io.MNISTIter(
        image=os.path.join(basedir, "data", "train-images-idx3-ubyte"),
        label=os.path.join(basedir, "data", "train-labels-idx1-ubyte"),
        data_shape=(784,),
        batch_size=batch_size, shuffle=True, flat=True, silent=False, seed=10)

val_dataiter = mx.io.MNISTIter(
        image=os.path.join(basedir, "data", "t10k-images-idx3-ubyte"),
        label=os.path.join(basedir, "data", "t10k-labels-idx1-ubyte"),
        data_shape=(784,),
        batch_size=batch_size, shuffle=True, flat=True, silent=False)

################################################################################
# Intermediate-level API
################################################################################
#传入symbol,创建模型
mod = mx.mod.Module(softmax)
# bind
mod.bind(data_shapes=train_dataiter.provide_data, label_shapes=train_dataiter.provide_label)
# 模型初始化参数
mod.init_params()
# 模型的优化器和学习率
mod.init_optimizer(optimizer_params={'learning_rate':0.01, 'momentum': 0.9})
# 建立模型评价的选择
metric = mx.metric.create('acc')

for i_epoch in range(n_epoch):
    for i_iter, batch in enumerate(train_dataiter):
        # 前向计算
        mod.forward(batch)
        # 更新
        mod.update_metric(metric, batch.label)
        # 后向
        mod.backward()
        # 再更新
        mod.update()

    for name, val in metric.get_name_value():
        print('epoch %03d: %s=%f' % (i_epoch, name, val))
    # 每训练一次,参数都会更新,所以评价也得更新,所以要先重置
    metric.reset()
    train_dataiter.reset()

展开阅读全文

没有更多推荐了,返回首页