{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 3.1 线性回归" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.4.1\n" ] } ], "source": [ "import torch\n", "from time import time\n", "\n", "print(torch.__version__)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = torch.ones(1000)\n", "b = torch.ones(1000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "将这两个向量按元素逐一做标量加法:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.020173072814941406\n" ] } ], "source": [ "start = time()\n", "c = torch.zeros(1000)\n", "for i in range(1000):\n", " c[i] = a[i] + b[i]\n", "print(time() - start)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "将这两个向量直接做矢量加法:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.20159912109375e-05\n" ] } ], "source": [ "start = time()\n", "d = a + b\n", "print(time() - start)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**结果很明显,后者比前者更省时。因此,我们应该尽可能采用矢量计算,以提升计算效率。**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "广播机制例子🌰:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([11., 11., 11.])\n" ] } ], "source": [ "a = torch.ones(3)\n", "b = 10\n", "print(a + b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [default]", "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.6.3" } }, "nbformat": 4, "nbformat_minor": 2 }