MXNet Sample

MXNet Sample

  1. import pickle
  2. import numpy as np
  3.  
  4. def cos_curve(x):
  5.     return 0.25 * np.sin(2 * x * np.pi + 0.5 * np.pi) + 0.5
  6.  
  7. np.random.seed(123)
  8. samples = []
  9. labels = []
  10.  
  11. sample_density = 50
  12. for i in range(sample_density):
  13.     x1, x2 = np.random.random(2)
  14.  
  15.     bound = cos_curve(x1)
  16.  
  17.     if bound - 0.1 < x2 <= bound + 0.1:
  18.         continue
  19.     else:
  20.         samples.append((x1, x2))
  21.  
  22.         if x2 > bound:
  23.             labels.append(1)
  24.         else:
  25.             labels.append(0)
  26.  
  27. with open('data.pkl', 'wb') as f:
  28.     pickle.dump((samples, labels), f)
  29.  
  30. import matplotlib.pyplot as plt
  31.  
  32. for i, sample in enumerate(samples):
  33.     plt.plot(sample[0], sample[1], 'o' if labels[i] else '^',
  34.              mec='r' if labels[i] else 'b',
  35.              mfc='none',
  36.              markersize=10)
  37. x1 = np.linspace(0, 1)
  38. plt.plot(x1, cos_curve(x1), 'k--')
  39. plt.show()
  40.  
  41. #
  42.  
  43. import numpy as np
  44. import mxnet as mx
  45.  
  46. data = mx.sym.Variable('data')
  47.  
  48. fc1 = mx.sym.FullyConnected(data=data, name='fc1', num_hidden=2)
  49.  
  50. sigmoid1 = mx.sym.Activation(data=fc1, name='sigmoid1', act_type='sigmoid')
  51.  
  52. fc2 = mx.sym.FullyConnected(data=sigmoid1, name='fc2', num_hidden=2)
  53.  
  54. mlp = mx.sym.SoftmaxOutput(data=fc2, name='softmax')
  55.  
  56. shape = {'data': (2,)}
  57. mlp_dot = mx.viz.plot_network(symbol=mlp, shape=shape)
  58. mlp_dot.render('simple_mlp.gv', view=True)
  59.  
  60. #
  61.  
  62. import pickle
  63. import logging
  64.  
  65. with open('data.pkl', 'rb') as f:
  66.     samples, labels = pickle.load(f)
  67.  
  68. logging.getLogger().setLevel(logging.DEBUG)
  69.  
  70. batch_size = len(labels)
  71. samples = np.array(samples)
  72. labels = np.array(labels)
  73.  
  74. train_iter = mx.io.NDArrayIter(samples, labels, batch_size)
  75.  
  76. model = mx.model.FeedForward.create(
  77.     symbol=mlp,
  78.     X=train_iter,
  79.     num_epoch=1000,
  80.     learning_rate=0.1,
  81.     momentum=0.99
  82. )
  83. '''
  84. model = mx.model.FeedForward(
  85.     symbol=mlp,
  86.     num_epoch=1000,
  87.     learning_rate=0.1
  88.     momentum=0.99
  89. )
  90. model.fit(X=train_iter)
  91. '''
  92. print(model.predict(mx.nd.array([[0.5, 0.5]])))
  93.  
  94. #
  95.  
  96. import matplotlib.pyplot as plt
  97. from mpl_toolkits.mplot3d import Axes3D
  98.  
  99. X = np.arange(0, 1.05, 0.05)
  100. Y = np.arange(0, 1.05, 0.05)
  101. X, Y = np.meshgrid(X, Y)
  102.  
  103. grids = mx.nd.array([[X[i][j], Y[i][j]] for i in range(X.shape[0]) for j in range(X.shape[1])])
  104.  
  105. grid_probs = model.predict(grids)[:, 1].reshape(X.shape)
  106.  
  107. fig = plt.figure('Sample Surface')
  108. ax = fig.gca(projection='3d')
  109.  
  110. ax.plot_surface(X, Y, grid_probs, alpha=0.15, color='k', rstride=2, cstride=2, lw=0.5)
  111.  
  112. samples0 = samples[labels==0]
  113. samples0_probs = model.predict(samples0)[:, 1]
  114. samples1 = samples[labels==1]
  115. samples1_probs = model.predict(samples1)[:, 1]
  116.  
  117. ax.scatter(samples0[:, 0], samples0[:, 1], samples0_probs, c='r', marker='o', s=50)
  118. ax.scatter(samples1[:, 0], samples1[:, 1], samples1_probs, c='b', marker='^', s=50)
  119.  
  120. plt.show()


Matplotlib RGB & OpenCV BGR

Matplotlib RGB & OpenCV BGR

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import cv2
  4.  
  5. img = np.array([
  6.     [[255, 0, 0], [0, 255, 0], [0, 0, 255]],
  7.     [[255, 255, 0], [255, 0, 255], [0, 255, 255]],
  8.     [[255, 255, 255], [128, 128, 128], [0, 0, 0]],
  9. ], dtype=np.uint8)
  10.  
  11. plt.imsave('img_pyplot.png', img)
  12. cv2.imwrite('img_cv2.jpg', img)


Matplotlib 3D Example 2 : Python

3D Example 2

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from mpl_toolkits.mplot3d import Axes3D
  4.  
  5. np.random.seed(42)
  6.  
  7. n_samples = 500
  8. dim = 3
  9.  
  10. samples = np.random.multivariate_normal(
  11.     np.zeros(dim),
  12.     np.eye(dim),
  13.     n_samples
  14. )
  15.  
  16. for i in range(samples.shape[0]) :
  17.     r = np.power(np.random.random(), 1.0 / 3.0)
  18.     samples[i] *= r / np.linalg.norm(samples[i])
  19.  
  20. upper_samples = []
  21. lower_samples = []
  22. for x, y, z in samples:
  23.     if z > 3 * x + 2 * y - 1:
  24.         upper_samples.append((x, y, z))
  25.     else:
  26.         lower_samples.append((x, y, z))
  27.  
  28. fig = plt.figure('3D scatter plot')
  29. ax = fig.add_subplot(111, projection='3d')
  30. uppers = np.array(upper_samples)
  31. lowers = np.array(lower_samples)
  32.  
  33. ax.scatter(uppers[:, 0], uppers[:, 1], uppers[:, 2], c='r', marker='o')
  34. ax.scatter(uppers[:, 0], uppers[:, 1], uppers[:, 2], c='g', marker='^')
  35.  
  36. plt.show()

Matplotlib 3D Example : Python

3D Example

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from mpl_toolkits.mplot3d import Axes3D
  4.  
  5. np.random.seed(42)
  6.  
  7. n_grids = 51
  8. c = n_grids / 2
  9. nf = 2
  10.  
  11. x = np.linspace(0, 1, n_grids)
  12. y = np.linspace(0, 1, n_grids)
  13. X, Y = np.meshgrid(x, y)
  14.  
  15. spectrum = np.zeros((n_grids, n_grids), dtype=np.complex)
  16. noise = [np.complex(x, y) for x, y in np.random.uniform(-1, 1, ((2 * nf + 1) ** 2 / 2, 2))]
  17. noisy_block = np.concatenate((noise, [0j], np.conjugate(noise[:: -1])))
  18. spectrum[c - nf: c + nf + 1, c - nf: c + nf + 1] = noisy_block.reshape((2 * nf + 1, 2 * nf + 1))
  19. Z = np.real(np.fft.ifft2(np.fft.ifftshift(spectrum)))
  20.  
  21. fig = plt.figure('3D surface & wire')
  22. ax = fig.add_subplot(1, 2, 1, projection='3d')
  23. ax.plot_surface(X, Y, Z, alpha=0.7, cmap='jet', rstride=1, cstride=1, lw=0)
  24.  
  25. ax = fig.add_subplot(1, 2, 2, projection='3d')
  26. ax.plot_wireframe(X, Y, Z, rstride=3, cstride=3, lw=0.5)
  27.  
  28. plt.show()

Matplotlib 2D Example : Python

2D Example

  1. import numpy as np
  2. import matplotlib as mpl
  3. import matplotlib.pyplot as plt
  4.  
  5. mpl.rcParams['xtick.labelsize'] = 24
  6. mpl.rcParams['ytick.labelsize'] = 24
  7. np.random.seed(42)
  8.  
  9. x = np.linspace(0, 5, 100)
  10. y = 2 * np.sin(x) + 0.3 * x ** 2
  11. y_data = y + np.random.normal(scale=0.3, size=100)
  12. plt.figure('data')
  13. plt.plot(x, y_data, '.')
  14.  
  15. plt.figure('model')
  16. plt.plot(x, y)
  17.  
  18. plt.figure('data & model')
  19. plt.plot(x, y, 'k', lw=3)
  20. plt.scatter(x, y_data)
  21.  
  22. plt.savefig('result.png')
  23.  
  24. plt.show()