{ "cells": [ { "cell_type": "markdown", "source": [ "# 张量\n", "\n", "`Ascend` `GPU` `CPU` `入门`\n", "\n", "[![](https://gitee.com/mindspore/docs/raw/r1.5/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9taW5kc3BvcmUtd2Vic2l0ZS5vYnMuY24tbm9ydGgtNC5teWh1YXdlaWNsb3VkLmNvbS9ub3RlYm9vay9tYXN0ZXIvdHV0b3JpYWxzL3poX2NuL21pbmRzcG9yZV90ZW5zb3IuaXB5bmI=&imageid=65f636a0-56cf-49df-b941-7d2a07ba8c8c) [![](https://gitee.com/mindspore/docs/raw/r1.5/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/r1.5/tutorials/zh_cn/mindspore_tensor.ipynb) [![](https://gitee.com/mindspore/docs/raw/r1.5/resource/_static/logo_download_code.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/r1.5/tutorials/zh_cn/mindspore_tensor.py) [![](https://gitee.com/mindspore/docs/raw/r1.5/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/r1.5/tutorials/source_zh_cn/tensor.ipynb)\n", "\n", "张量([Tensor](https://www.mindspore.cn/docs/api/zh-CN/r1.5/api_python/mindspore/mindspore.Tensor.html))是MindSpore网络运算中的基本数据结构。\n", "\n", "首先导入本文档需要的模块和接口,如下所示:" ], "metadata": {} }, { "cell_type": "code", "execution_count": 1, "source": [ "import numpy as np\n", "from mindspore import Tensor, context\n", "from mindspore import dtype as mstype\n", "context.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")" ], "outputs": [], "metadata": {} }, { "cell_type": "markdown", "source": [ "## 初始化张量\n", "\n", "张量的初始化方式有多种,构造张量时,支持传入`Tensor`、`float`、`int`、`bool`、`tuple`、`list`和`NumPy.array`类型。\n", "\n", "- **根据数据直接生成**\n", "\n", "可以根据数据创建张量,数据类型可以设置或者自动推断。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 2, "source": [ "x = Tensor(0.1)" ], "outputs": [], "metadata": {} }, { "cell_type": "markdown", "source": [ "- **从NumPy数组生成**\n", "\n", "可以从NumPy数组创建张量。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 3, "source": [ "arr = np.array([1, 0, 1, 0])\n", "x_np = Tensor(arr)" ], "outputs": [], "metadata": {} }, { "cell_type": "markdown", "source": [ "初始值是`NumPy.array`,则生成的`Tensor`数据类型与之对应。" ], "metadata": {} }, { "cell_type": "markdown", "source": [ "- **使用init初始化器构造张量**\n", "\n", "当使用`init`初始化器对张量进行初始化时,支持传入的参数有`init`、`shape`、`dtype`。\n", "\n", "- `init`: 支持传入[initializer](https://www.mindspore.cn/docs/api/zh-CN/r1.5/api_python/mindspore.common.initializer.html)的子类。\n", "\n", "- `shape`: 支持传入 `list`、`tuple`、 `int`。\n", "\n", "- `dtype`: 支持传入[mindspore.dtype](https://www.mindspore.cn/docs/api/zh-CN/r1.5/api_python/mindspore.html#mindspore.dtype)。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 4, "source": [ "from mindspore import Tensor\n", "from mindspore import set_seed\n", "from mindspore import dtype as mstype\n", "from mindspore.common.initializer import One, Normal\n", "\n", "set_seed(1)\n", "\n", "tensor1 = Tensor(shape=(2, 2), dtype=mstype.float32, init=One())\n", "tensor2 = Tensor(shape=(2, 2), dtype=mstype.float32, init=Normal())\n", "print(tensor1)\n", "print(tensor2)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[1. 1.]\n", " [1. 1.]]\n", "[[-0.00128023 -0.01392901]\n", " [ 0.0130886 -0.00107818]]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "`init`是用在并行模式下用来进行延后初始化的,在正常情况下不建议使用init对参数进行初始化。\n", "\n", "- **继承另一个张量的属性,形成新的张量**" ], "metadata": {} }, { "cell_type": "code", "execution_count": 5, "source": [ "from mindspore import ops\n", "oneslike = ops.OnesLike()\n", "x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))\n", "output = oneslike(x)\n", "print(output)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[1 1]\n", " [1 1]]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "- **输出指定大小的恒定值张量**\n", "\n", "`shape`是张量的尺寸元组,确定输出的张量的维度。\n" ], "metadata": {} }, { "cell_type": "code", "execution_count": 6, "source": [ "import mindspore.ops as ops\n", "\n", "shape = (2, 2)\n", "ones = ops.Ones()\n", "output = ones(shape, mstype.float32)\n", "print(output)\n", "\n", "zeros = ops.Zeros()\n", "output = zeros(shape, mstype.float32)\n", "print(output)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[1. 1.]\n", " [1. 1.]]\n", "[[0. 0.]\n", " [0. 0.]]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "`Tensor`初始化时,可指定dtype,如`mstype.int32`、`mstype.float32`、`mstype.bool_`等。\n", "\n", "## 张量的属性\n", "\n", "张量的属性包括形状(shape)和数据类型(dtype)。\n", "\n", "- 形状:`Tensor`的shape,是一个tuple。\n", "- 数据类型:`Tensor`的dtype,是MindSpore的一个数据类型。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 7, "source": [ "t1 = Tensor(np.zeros([1, 2, 3]), mstype.float32)\n", "print(\"Datatype of tensor: {}\".format(t1.dtype))\n", "print(\"Shape of tensor: {}\".format(t1.shape))" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Datatype of tensor: Float32\n", "Shape of tensor: (1, 2, 3)\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "## 张量运算\n", "\n", "张量之间有很多运算,包括算术、线性代数、矩阵处理(转置、标引、切片)、采样等,下面介绍其中几种操作,张量运算和NumPy的使用方式类似。\n", "\n", "类似NumPy的索引和切片操作:\n" ], "metadata": {} }, { "cell_type": "code", "execution_count": 8, "source": [ "tensor = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n", "print(\"First row: {}\".format(tensor[0]))\n", "print(\"First column: {}\".format(tensor[:, 0]))\n", "print(\"Last column: {}\".format(tensor[..., -1]))" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "First row: [0. 1.]\n", "First column: [0. 2.]\n", "Last column: [1. 3.]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "`Concat`将给定维度上的一系列张量连接起来。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 9, "source": [ "data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n", "data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))\n", "op = ops.Concat()\n", "output = op((data1, data2))\n", "print(output)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[0. 1.]\n", " [2. 3.]\n", " [4. 5.]\n", " [6. 7.]]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "`Stack`则是从另一个维度上将两个张量合并起来。" ], "metadata": {} }, { "cell_type": "code", "execution_count": 10, "source": [ "data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n", "data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))\n", "op = ops.Stack()\n", "output = op([data1, data2])\n", "print(output)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[[0. 1.]\n", " [2. 3.]]\n", "\n", " [[4. 5.]\n", " [6. 7.]]]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "普通运算:" ], "metadata": {} }, { "cell_type": "code", "execution_count": 11, "source": [ "input_x = Tensor(np.array([1.0, 2.0, 3.0]), mstype.float32)\n", "input_y = Tensor(np.array([4.0, 5.0, 6.0]), mstype.float32)\n", "mul = ops.Mul()\n", "output = mul(input_x, input_y)\n", "print(output)" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[ 4. 10. 18.]\n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "## 与NumPy转换\n", "\n", "张量可以和NumPy进行互相转换。\n", "\n", "### 张量转换为NumPy" ], "metadata": {} }, { "cell_type": "code", "execution_count": 12, "source": [ "zeros = ops.Zeros()\n", "output = zeros((2, 2), mstype.float32)\n", "print(\"output: {}\".format(type(output)))\n", "n_output = output.asnumpy()\n", "print(\"n_output: {}\".format(type(n_output)))" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "output: \n", "n_output: \n" ] } ], "metadata": {} }, { "cell_type": "markdown", "source": [ "### NumPy转换为张量" ], "metadata": {} }, { "cell_type": "code", "execution_count": 13, "source": [ "output = np.array([1, 0, 1, 0])\n", "print(\"output: {}\".format(type(output)))\n", "t_output = Tensor(output)\n", "print(\"t_output: {}\".format(type(t_output)))" ], "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "output: \n", "t_output: \n" ] } ], "metadata": {} } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.5" } }, "nbformat": 4, "nbformat_minor": 4 }