https://mxnet.incubator.apache.org/tutorials/basic/module.html

import logging
import random
logging.getLogger().setLevel(logging.INFO) import mxnet as mx
import numpy as np mx.random.seed(1234)
np.random.seed(1234)
random.seed(1234) # 准备数据
fname = mx.test_utils.download('https://s3.us-east-2.amazonaws.com/mxnet-public/letter_recognition/letter-recognition.data')
data = np.genfromtxt(fname=fname,delimiter=',')[:,1:]
label = np.array([ord(l.split(',')[0])-ord('A') for l in open(fname, 'r')]) batch_size = 32
ntrain = int(data.shape[0]*0.8) train_iter = mx.io.NDArrayIter(data[:ntrain,:],label[:ntrain],batch_size,shuffle=True)
val_iter = mx.io.NDArrayIter(data[ntrain:,:],label[ntrain:],batch_size) # 定义网络
net = mx.sym.Variable('data')
net = mx.sym.FullyConnected(net, name='fc1', num_hidden=64)
net = mx.sym.Activation(net, name='relu1', act_type="relu")
net = mx.sym.FullyConnected(net, name='fc2', num_hidden=26)
net = mx.sym.SoftmaxOutput(net, name='softmax')
mx.viz.plot_network(net, node_attrs={"shape":"oval","fixedsize":"false"}) # # 创建模块
mod = mx.mod.Module(symbol=net,
context=mx.cpu(),
data_names=['data'],
label_names=['softmax_label']) # # 中层接口
# # 训练模型
# mod.bind(data_shapes=train_iter.provide_data,label_shapes=train_iter.provide_label)
# mod.init_params(initializer=mx.init.Uniform(scale=.1))
# mod.init_optimizer(optimizer='sgd',optimizer_params=(('learning_rate',0.1),))
# metric = mx.metric.create('acc')
#
# for epoch in range(100):
# train_iter.reset()
# metric.reset()
# for batch in train_iter:
# mod.forward(batch,is_train=True)
# mod.update_metric(metric,batch.label)
# mod.backward()
# mod.update()
# print('Epoch %d,Training %s' % (epoch,metric.get())) # fit 高层接口
train_iter.reset()
mod = mx.mod.Module(symbol=net,
context=mx.cpu(),
data_names=['data'],
label_names=['softmax_label']) mod.fit(train_iter,
eval_data=val_iter,
optimizer='sgd',
optimizer_params={'learning_rate':0.1},
eval_metric='acc',
num_epoch=10) # 预测和评估
y = mod.predict(val_iter)
assert y.shape == (4000,26) # 评分
score = mod.score(val_iter,['acc'])
print("Accuracy score is %f"%(score[0][1]))
assert score[0][1] > 0.76, "Achieved accuracy (%f) is less than expected (0.76)" % score[0][1] # 保存和加载
# 构造一个回调函数保存检查点
model_prefix = 'mx_mlp'
checkpoint = mx.callback.do_checkpoint(model_prefix) mod = mx.mod.Module(symbol=net)
mod.fit(train_iter,num_epoch=5,epoch_end_callback=checkpoint) sym, arg_params, aux_params = mx.model.load_checkpoint(model_prefix, 3)
assert sym.tojson() == net.tojson() # assign the loaded parameters to the module
mod.set_params(arg_params, aux_params) mod = mx.mod.Module(symbol=sym)
mod.fit(train_iter,
num_epoch=21,
arg_params=arg_params,
aux_params=aux_params,
begin_epoch=3)
assert score[0][1] > 0.77, "Achieved accuracy (%f) is less than expected (0.77)" % score[0][1]

mxnet 神经网络训练和预测的更多相关文章

  1. 吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

    import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_dat ...

  2. 利用Matlab神经网络计算包预测近四天除湖北外新增确诊人数:拐点已现

    数据来源: 国家卫健委 已经7连降咯! 1.20-2.10图示(更新中): 神经网络训练并预测数据: clear %除湖北以外全国新增确诊病例数 2020.1.20-2.9 num=[5,44,62, ...

  3. ResNet网络的训练和预测

    ResNet网络的训练和预测 简介 Introduction 图像分类与CNN 图像分类 是指将图像信息中所反映的不同特征,把不同类别的目标区分开来的图像处理方法,是计算机视觉中其他任务,比如目标检测 ...

  4. 神经网络训练中的Tricks之高效BP(反向传播算法)

    神经网络训练中的Tricks之高效BP(反向传播算法) 神经网络训练中的Tricks之高效BP(反向传播算法) zouxy09@qq.com http://blog.csdn.net/zouxy09 ...

  5. mxnet的训练过程——从python到C++

    mxnet的训练过程--从python到C++ mxnet(github-mxnet)的python接口相当完善,我们可以完全不看C++的代码就能直接训练模型,如果我们要学习它的C++的代码,从pyt ...

  6. 神经网络训练tricks

    神经网络构建好,训练不出好的效果怎么办?明明说好的拟合任意函数(一般连续)(为什么?可以参考http://neuralnetworksanddeeplearning.com/),说好的足够多的数据(h ...

  7. tesorflow - create neural network+结果可视化+加速神经网络训练+Optimizer+TensorFlow

    以下仅为了自己方便查看,绝大部分参考来源:莫烦Python,建议去看原博客 一.添加层 def add_layer() 定义 add_layer()函数 在 Tensorflow 里定义一个添加层的函 ...

  8. TensorFlow实战第三课(可视化、加速神经网络训练)

    matplotlib可视化 构件图形 用散点图描述真实数据之间的关系(plt.ion()用于连续显示) # plot the real data fig = plt.figure() ax = fig ...

  9. Pytorch学习记录-torchtext和Pytorch的实例( 使用神经网络训练Seq2Seq代码)

    Pytorch学习记录-torchtext和Pytorch的实例1 0. PyTorch Seq2Seq项目介绍 1. 使用神经网络训练Seq2Seq 1.1 简介,对论文中公式的解读 1.2 数据预 ...

随机推荐

  1. jqgrid 各种方法参数的使用

    现在jqGrid对象 tableObj 一.获取选中的行 selected = tableObj.jqGrid('getGridParam', 'selrow'); if (selected == n ...

  2. wrqer

  3. mybatis学习之高级映射

    一对一映射查询 1.数据库执行脚本: /* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.7.11-log : Database - db_mybatis *** ...

  4. 数据库字段值为null利用setInc方法无法直接写入

    1.数据库字段值为null利用setInc方法无法直接写入,先判断是否为空,再写入. if($points->add($dataList)){ $user=M('cuser'); $null=$ ...

  5. CSS3之盒模型

    1. 什么是盒模型? css中的每个元素都是一个盒模型, 包括html body元素, 浏览器解析css的时候也会把每个元素看成一个盒子来解析. 盒模型具备的属性(存在的特点)有: content ( ...

  6. [ERROR] Failed to execute goal org.apache.maven.plugins:maven-dependency-plugin:2.8:unpack (unpack) on project sq-integral-web: Unable to find artifact.

    1.问题描述 项目maven打包报上述错误, 但是小伙伴运行好使. 2.问题解决 是idea工程编码(gbk)和项目编码(utf-8)不一致 idea->file->Other Setti ...

  7. 2018.10.26NOIP模拟赛解题报告

    心路历程 预计得分:\(100 + 100 + 70\) 实际得分:\(40 + 100 + 70\) 妈妈我又挂分了qwq..T1过了大样例就没管,直到临考试结束前\(10min\)才发现大样例是假 ...

  8. html 之 position用法

    引用: position的四个属性值: 1.relative2.absolute3.fixed4.static下面分别讲述这四个属性. <div id="parent"> ...

  9. PowerDesigner设置所有int主键自增脚本

    '*****************************************************************************dim model 'current mod ...

  10. 表格 滚动条 (tbody部分滚动)

    本文是从简书复制的, markdown语法可能有些出入, 想看"正版"和更多内容请关注 简书: 小贤笔记 html <table> <thead> < ...