<jupyter_start><jupyter_text>使用 NDArray 进行数据交互 导入 `np` (numpy类似) 模块和 `npx` (numpy 扩展) 模块。<jupyter_code>from mxnet import np, npx
# 启用 MXNet 的 numpy 兼容模式。
npx.set_np()<jupyter_output><empty_output><jupyter_text>创建一个向量并访问属性。<jupyter_code>x = np.arange(12)
x
x.shape
x.size<jupyter_output><empty_output><jupyter_text>更多创建的方式。<jupyter_code>np.zeros((3, 4))
np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
np.random.normal(0, 1, size=(3, 4))<jupyter_output><empty_output><jupyter_text>按元素的操作。<jupyter_code>x = np.array([1, 2, 4, 8])
y = np.ones_like(x) * 2
print('x =', x)
print('x + y', x + y)
print('x - y', x - y)
print('x * y', x * y)
print('x ** y', x ** y)
print('x / y', x / y)<jupyter_output>x = [1. 2. 4. 8.]
x + y [ 3.  4.  6. 10.]
x - y [-1.  0.  2.  6.]
x * y [ 2.  4.  8. 16.]
x ** y [ 1.  4. 16. 64.]
x / y [0.5 1.  2.  4. ]<jupyter_text>矩阵乘法。<jupyter_code>x = np.arange(12).reshape((3,4))
y = np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
np.dot(x, y.T)<jupyter_output><empty_output><jupyter_text>沿着某个坐标的合并。<jupyter_code>np.concatenate([x, y], axis=0), np.concatenate([x, y], axis=1)<jupyter_output><empty_output><jupyter_text>广播机制。<jupyter_code>a = np.arange(3).reshape((3, 1))
b = np.arange(2).reshape((1, 2))
print('a:\n', a)
print('b:\n', b)
a + b<jupyter_output>a:
 [[0.]
 [1.]
 [2.]]
b:
 [[0. 1.]]<jupyter_text>访问元素。<jupyter_code>print('x[-1] =\n', x[-1])
print('x[1:3] =\n', x[1:3])
print('x[1:3, 2:4] =\n', x[1:3, 2:4])
print('x[1,2] =', x[1,2])<jupyter_output>x[-1] =
 [ 8.  9. 10. 11.]
x[1:3] =
 [[ 4.  5.  6.  7.]
 [ 8.  9. 10. 11.]]
x[1:3, 2:4] =
 [[ 6.  7.]
 [10. 11.]]
x[1,2] = 6.0<jupyter_text>`mxnet.numpy.ndarray` 和 `numpy.ndarray` 互换。<jupyter_code>a = x.asnumpy()
print(type(a))
b = np.array(a)
print(type(b))<jupyter_output><class 'numpy.ndarray'>
<class 'mxnet.numpy.ndarray'>
{'fraction_non_alphanumeric': 0.2645764576457646, 'fraction_numerical': 0.0737073707370737, 'mean_word_length': 4.287790697674419, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, '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': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '563600', 'license': 'Apache-2.0', 'n_tokens_mistral': 1090, 'n_tokens_neox': 1046, 'n_words': 188, 'path': 'notebooks-1/1-ndarray.ipynb', 'repo_name': 'jhlholly/d2l-1day-notebooks-zh', 'size': '1818'}