- Python Deep Learning Cookbook
- Indra den Bakker
- 284字
- 2021-07-02 15:43:13
How to do it...
- To install MXNet on Ubuntu with GPU support, we can use the following command in the terminal:
pip install mxnet-cu80==0.11.0
For other platforms and non-GPU support, have a look at https://mxnet.incubator.apache.org/get_started/install.html.
- Next, we are ready to import mxnet in our Python environment:
import mxnet as mx
- We create some simple dummy data that we assign to the GPU and CPU:
import numpy as np
x_input = mx.nd.empty((1, 5), mx.gpu())
x_input[:] = np.array([[1,2,3,4,5]], np.float32)
y_input = mx.nd.empty((1, 5), mx.cpu())
y_input[:] = np.array([[10, 15, 20, 22.5, 25]], np.float32)
- We can easily copy and adjust the data. Where possible MXNet will automatically execute operations in parallel:
x_input
w_input = x_input
z_input = x_input.copyto(mx.cpu())
x_input += 1
w_input /= 2
z_input *= 2
- We can print the output as follows:
print(x_input.asnumpy())
print(w_input.asnumpy())
print(z_input.asnumpy())
- If we want to feed our data to a model, we should create an iterator first:
batch_size = 1
train_iter = mx.io.NDArrayIter(x_input, y_input, batch_size, shuffle=True, data_name='input', label_name='target')
- Next, we can create the symbols for our model:
X = mx.sym.Variable('input')
Y = mx.symbol.Variable('target')
fc1 = mx.sym.FullyConnected(data=X, name='fc1', num_hidden = 5)
lin_reg = mx.sym.LinearRegressionOutput(data=fc1, label=Y, name="lin_reg")
- Before we can start training, we need to define our model:
model = mx.mod.Module(
symbol = lin_reg,
data_names=['input'],
label_names = ['target']
)
- Let's start training:
model.fit(train_iter,
optimizer_params={'learning_rate':0.01, 'momentum': 0.9},
num_epoch=100,
batch_end_callback = mx.callback.Speedometer(batch_size, 2))
- To use the trained model for prediction we:
model.predict(train_iter).asnumpy()
We've shortly introduced the MXNet framework. In this introduction, we've demonstrated how easily one can assign variables and computations to a CPU or GPU and how to use the Symbol interface. However, there is much more to explore and the MXNet is a powerful framework for building flexible and efficient deep learning models.
推薦閱讀
- Learning Scala Programming
- C語(yǔ)言程序設(shè)計(jì)教程
- Python科學(xué)計(jì)算(第2版)
- Java高手真經(jīng)(高級(jí)編程卷):Java Web高級(jí)開發(fā)技術(shù)
- VSTO開發(fā)入門教程
- 游戲程序設(shè)計(jì)教程
- R Data Analysis Cookbook(Second Edition)
- Swift Playgrounds少兒趣編程
- NoSQL數(shù)據(jù)庫(kù)原理
- Java并發(fā)編程之美
- 從零開始學(xué)Android開發(fā)
- 嵌入式Linux C語(yǔ)言程序設(shè)計(jì)基礎(chǔ)教程
- 微前端設(shè)計(jì)與實(shí)現(xiàn)
- C語(yǔ)言從入門到精通
- Mastering ArcGIS Server Development with JavaScript