<jupyter_start><jupyter_text>**Introduction to Apache MXNet - NDArray API, AutoGrad API, and Optimizer API**<jupyter_code>!pip install mxnet
from mxnet import ndarray as nda
# Create CPU array
arr_one = nda.ones((2, 2))
print(arr_one)
arr_x = nda.zeros((3, 5))
print(arr_x)
arr_y = nda.random_normal(0, 1, shape=(2,2))
print(arr_y)
arr_y.shape
arr_y.size
arr_y[0:2,]
arr_y[1,:]
arr_y[0,1]
from mxnet import ndarray as nda
arr_z=nda.random.randint(1,5,shape=(2,3))
print(arr_z,end="")
arr_y=nda.random.randint(1,5,shape=(2,3))
print(arr_y)
print("\n Transpose of arr_y:",arr_y.T)
print("\n Addition of arr_y and arr_z:",arr_y+arr_z)
print("\n Multiplication of arr_y and arr_z:",arr_y*arr_z)
arr_p = arr_z.asnumpy()
print(arr_p)
type(arr_p)
arr_k = nda.array(arr_p)
print(arr_k)
import mxnet as mx
from mxnet import ndarray as nda
from mxnet import autograd
var = nda.array([4])
var.attach_grad()
with autograd.record():
 res=(2*(var**3))+(4*var)
res.backward()
print(var.grad)
from mxnet import gluon as gl
from mxnet import optimizer
neu_network=gl.nn.Dense(1)
neu_network.initialize()
print(neu_network)
optim_nn=optimizer.SGD(learning_rate=0.01)
print(optim_nn)
nn_trainer=gl.Trainer(neu_network.collect_params(),optimizer=optim_nn)
print(nn_trainer)<jupyter_output>Dense(None -> 1, linear)
<mxnet.optimizer.optimizer.SGD object at 0x7efdfe8f9898>
<mxnet.gluon.trainer.Trainer object at 0x7efdd8a78be0><jupyter_text>**Practical Implementation of Neural Network with Apache MXNet**<jupyter_code>from mxnet import nd, autograd
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
iris_data="https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv"
df = pd.read_csv(iris_data, delimiter=',', header = 0)
print(df.shape)
print(df.head(10))
new_df=pd.get_dummies(df)
print(new_df.head(10))
train_data, test_data = train_test_split( new_df,
test_size=0.3, random_state=1)
print(train_data.shape)
print(test_data.shape)
features =['sepal_width','petal_length','petal_width','species_setosa','species_versicolor','species_virginica']
y_train = nd.array(train_data['sepal_length'])
X_train = nd.array(train_data[features])
y_test = nd.array(test_data['sepal_length'])
X_test = nd.array(test_data[features])

learn_rate = 0.02
epochs = 200
X_features = nd.array(X_train)
target_y = nd.array(y_train)
columns = X_features.shape[1]
weights = nd.random.normal(shape = [columns, 1])
bias = nd.random.normal(shape = 1)
paras = [weights,bias]
for x in paras: x.attach_grad()
def gradient_calc(paras,lr):
    for x in paras:
      x[:] = x - x.grad * lr
loss_data = []
for epoch in range(epochs):
  with autograd.record():
    loss=nd.mean((nd.dot(X_train, weights) + bias -y_train)**2)
loss.backward()
gradient_calc(paras, learn_rate)
print ("Epoch %s, Mean loss: %s" % (epoch,loss))
loss_data.append(loss.asscalar())
plt.figure(num=None,figsize=(10,8))
plt.plot(loss_data)
plt.xlabel('Epochs',fontsize=12)
plt.ylabel('Mean Loss',fontsize=12)
MSE = nd.mean(((nd.dot(X_test, weights) + bias) - y_test)**2)
print ("Mean Squared Error on Test Set: %s" % (MSE))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15098537825810554, 'fraction_numerical': 0.02256834075015893, 'mean_word_length': 7.069230769230769, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 11, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '578372', 'license': 'MIT', 'n_tokens_mistral': 1328, 'n_tokens_neox': 1292, 'n_words': 248, 'path': 'Chapter02/NeuralNetworkwithApacheMXNet.ipynb', 'repo_name': 'PacktPublishing/neural-network-programming-with-python', 'size': '3146'}