<jupyter_start><jupyter_text>数据操作 首先，我们导入`mindspore`。此外，需要导入`mindspore`的`numpy`API来完成部分操作<jupyter_code>import mindspore
import mindspore.numpy as mnp<jupyter_output><empty_output><jupyter_text>张量表示由一个数值组成的数组，这个数组可能有多个维度<jupyter_code>x = mnp.arange(12)
x<jupyter_output><empty_output><jupyter_text>可以通过张量的`shape`属性来访问张量（沿每个轴的长度）的*形状*和张量中元素的总数<jupyter_code>x.shape
x.size<jupyter_output><empty_output><jupyter_text>要想改变一个张量的形状而不改变元素数量和元素值，可以调用`reshape`函数<jupyter_code>X = x.reshape(3, 4)
X<jupyter_output><empty_output><jupyter_text>使用全0、全1、其他常量，或者从特定分布中随机采样的数字<jupyter_code>mnp.zeros((2, 3, 4))
mnp.ones((2, 3, 4))<jupyter_output><empty_output><jupyter_text>由于MindSpore没有`randn`接口，需要随机实例化Tensor时，要配合numpy使用<jupyter_code>import numpy as np
mindspore.Tensor(np.random.randn(3, 4), dtype=mindspore.float32)
# 这里需要注意，要显式指定dtype为float32，否则默认为float64. (不知道咋想的)<jupyter_output><empty_output><jupyter_text>通过提供包含数值的Python列表（或嵌套列表），来为所需张量中的每个元素赋予确定值<jupyter_code>mindspore.Tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]], dtype=mindspore.float32)<jupyter_output><empty_output><jupyter_text>常见的标准算术运算符（`+`、`-`、`*`、`/`和`**`）都可以被升级为按元素运算<jupyter_code>x = mindspore.Tensor([1.0, 2, 4, 8], dtype=mindspore.float32)
y = mindspore.Tensor([2, 2, 2, 2], dtype=mindspore.float32)
x + y, x - y, x * y, x / y, x ** y<jupyter_output><empty_output><jupyter_text>“按元素”方式可以应用更多的计算<jupyter_code>mnp.exp(x)<jupyter_output><empty_output><jupyter_text>我们也可以把多个张量*连结*（concatenate）在一起<jupyter_code>X = mnp.arange(12, dtype=mindspore.float32).reshape((3,4))
Y = mindspore.Tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]], dtype=mindspore.float32)
# 这里mindspore需要使用mindspore.ops中的算子
import mindspore.ops as P
concat_dim0 = P.Concat(axis=0)
concat_dim1 = P.Concat(1)
concat_dim0((X, Y)), concat_dim1((X, Y))<jupyter_output><empty_output><jupyter_text>通过*逻辑运算符*构建二元张量<jupyter_code>X == Y<jupyter_output><empty_output><jupyter_text>对张量中的所有元素进行求和，会产生一个单元素张量<jupyter_code>X.sum()<jupyter_output><empty_output><jupyter_text>即使形状不同，我们仍然可以通过调用*广播机制*（broadcasting mechanism）来执行按元素操作<jupyter_code>a = mnp.arange(3).reshape((3, 1))
b = mnp.arange(2).reshape((1, 2))
a, b
a + b<jupyter_output><empty_output><jupyter_text>可以用`[-1]`选择最后一个元素，可以用`[1:3]`选择第二个和第三个元素<jupyter_code>X[-1], X[1:3]<jupyter_output><empty_output><jupyter_text>除读取外，我们还可以通过指定索引来将元素写入矩阵<jupyter_code>X[1, 2] = 9
X<jupyter_output>[WARNING] KERNEL(2917629,7f75134b4740,python):2021-10-28-15:52:24.645.372 [mindspore/ccsrc/backend/kernel_compiler/gpu/gpu_kernel_factory.cc:94] ReducePrecision] Kernel [TensorScatterUpdate] does not support int64, cast input 1 to int32.
[WARNING] PRE_ACT(2917629,7f75134b4740,python):2021-10-28-15:52:24.645.992 [mindspore/ccsrc/backend/optimizer/gpu/reduce_precision_fusion.cc:83] Run] Reduce precision for [TensorScatterUpdate] input 1<jupyter_text>为多个元素赋值相同的值，我们只需要索引所有元素，然后为它们赋值<jupyter_code>X[0:2, :] = 12
X<jupyter_output>[WARNING] KERNEL(2917629,7f75134b4740,python):2021-10-28-15:52:24.671.673 [mindspore/ccsrc/backend/kernel_compiler/gpu/gpu_kernel_factory.cc:94] ReducePrecision] Kernel [TensorScatterUpdate] does not support int64, cast input 1 to int32.
[WARNING] PRE_ACT(2917629,7f75134b4740,python):2021-10-28-15:52:24.672.094 [mindspore/ccsrc/backend/optimizer/gpu/reduce_precision_fusion.cc:83] Run] Reduce precision for [TensorScatterUpdate] input 1<jupyter_text>运行一些操作可能会导致为新结果分配内存 转换为NumPy张量（`ndarray`）<jupyter_code>A = X.asnumpy()
B = mindspore.Tensor(A)
type(A), type(B)<jupyter_output><empty_output><jupyter_text>将大小为1的张量转换为Python标量<jupyter_code>a = mindspore.Tensor([3.5])
# mindspore暂不支持直接进行scalar的转换, 需要先转换为numpy.ndarray再进行转换
a, a.asnumpy(), float(a.asnumpy()), int(a.asnumpy())<jupyter_output><empty_output><jupyter_text>而将Python标量转换为Tensor可以使用ScalarToTensor算子<jupyter_code>scalar_to_tensor = P.ScalarToTensor()
scalar_to_tensor(int(a.asnumpy()))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1562176165803109, 'fraction_numerical': 0.06839378238341969, 'mean_word_length': 12.222602739726028, 'pattern_counts': {'":': 0, '<': 75, '<?xml version=': 0, '>': 75, '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': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '594694', 'license': 'MIT', 'n_tokens_mistral': 2170, 'n_tokens_neox': 2091, 'n_words': 168, 'path': 'chapter_02_preliminaries/0_ndarray.ipynb', 'repo_name': 'lvyufeng/d2l-mindspore', 'size': '3860'}