import mxnet as mx
import numpy as np
from mxnet import autograd, nd
from mxnet import gluon
from mxnet import init
from mxnet.gluon import nn
from mxnet.gluon import data as gdata
from mxnet.gluon import loss as gloss
def linearRegression():
# define data format
input_dim = 2
input_num = 100
# prepare label data
true_w = [3, -2.5]
true_b = 7.6
x_label = nd.random.normal(shape=(input_num, input_dim))
y_label = true_w[0] * x_label[:, 0] + true_w[1] * x_label[:, 1] + true_b
# load input data
batch_size = 10
dataset = gdata.ArrayDataset(x_label, y_label)
data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)
# define net(model)
net = nn.HybridSequential() # make it hybrid to optimize computing
net.add(nn.Dense(1))
net.initialize()
# loss and optimize functions
loss = gloss.L2Loss()
optimize_method = "sgd"
learning_rate = 0.03
trainer = gluon.Trainer(net.collect_params(), optimize_method, {"learning_rate": learning_rate})
# train
num_epoch = 20
for epoch in range(0, num_epoch):
for x, y in data_iter:
with autograd.record():
temp_loss = loss(net(x), y)
temp_loss.backward()
trainer.step(batch_size)
print ("epoch %d, loss %f" % (epoch, loss(net(x_label), y_label).mean().asnumpy()))
# the trained parameters
print (net[0].weight.data(), net[0].bias.data())
net.save("linearRegression", iteration)
# test the model
x_test = nd.array([[3, 5], [6, 10], [13, 7]])
#net.save(x_test, data_iter * num_epoch)
# export net json and param
net.hybridize()
# Please first call block.hybridize() and then run forward with this block at least once before calling export.
net(x_label)
net.export("simple_net", num_epoch)
def testLinearRegression():
# define net(model)
#net = nn.HybridSequential() # make it hybrid to optimize computing
#net.add(nn.Dense(1))
#net.initialize()
# define test data
batch_size = 1
num_batch = 5
eval_data = np.array([[3, 5], [6,10], [13, 7]])
eval_label = np.zeros(len(eval_data)) # just need to be the same length, empty is ok
eval_iter = mx.io.NDArrayIter(eval_data, eval_label, batch_size, shuffle=False)
# load model
sym, arg_params, aux_params = mx.model.load_checkpoint("simple_net", 20) # load with net name and epoch num
mod = mx.mod.Module(symbol=sym, context=mx.cpu(), data_names=["data"], label_names=[]) # label can be empty
mod.bind(for_training=False, data_shapes=[("data", (1, 2))]) # data shape, 1 x 2 vector for one test data record
mod.set_params(arg_params, aux_params)
# predict
predict_stress = mod.predict(eval_iter, num_batch)
print (predict_stress) # you can transfer to numpy array
def main():
#linearRegression()
testLinearRegression()
if __name__ == "__main__":
main()