1.基本概念

标量:就是一个数,是0维的,只有大小,没有方向

向量:是1*n的一列数,是1维的,有大小,也有方向

张量:是n*n的一堆数,是2维的,n个向量合并而成

2.a.size(),a.shape(),a.numel(),a.dim()的区别

a.size():输出a的某一维度中元素的个数,若未指定维度,则计算所有元素的个数

a.shape():输出a数组各维度的长度信息,返回是元组类型。

a.numel():输出a占用内存的数量

a.dim():输出a的维数

3.tensor的基本函数:

import torch
import numpy as np if __name__ == '__main__':
# 随机正太分布
a=torch.randn(2,3)
print("a:",a)
print("a.size():",a.size())
print("a.size(0):",a.size(0))
print("a.size(1):",a.size(1))
print("a.shape[0]:",a.shape[0])
print("a.shape[1]:",a.shape[1])
print("a.shape:",a.shape)
# 将a.shape转换成list
print("list(a.shape):",list(a.shape))
# 输出a占用内存的数量=2*3
print("a.numel():",a.numel())
# 输出a的维数
print("a.dim():",a.dim())
print() # 0~1随机均匀分布
b=torch.rand(2,3,4)
print("b:",b)
print("b.size():",b.size())
print("b.size(0):",b.size(0))
print("b.size(1):",b.size(1))
print("b.shape[0]:",b.shape[0])
print("b.shape[1]:",b.shape[1])
print("b.shape:",b.shape)
print("list(b.shape):",list(b.shape))
# 输出b占用内存的数量=2*3*4
print("b.numel():",b.numel())
print("b.dim():",b.dim())
print()

运行结果:

a: tensor([[-0.2106, -2.1292, -0.8221],
[-1.5805, 0.2592, -1.1203]])
a.size(): torch.Size([2, 3])
a.size(0): 2
a.size(1): 3
a.shape[0]: 2
a.shape[1]: 3
a.shape: torch.Size([2, 3])
list(a.shape): [2, 3]
a.numel(): 6
a.dim(): 2 b: tensor([[[0.8126, 0.8908, 0.3507, 0.1554],
[0.8679, 0.5295, 0.5461, 0.5021],
[0.2570, 0.2250, 0.6310, 0.0662]], [[0.1139, 0.9552, 0.5847, 0.5421],
[0.3589, 0.0090, 0.0324, 0.6984],
[0.9562, 0.4533, 0.4296, 0.4052]]])
b.size(): torch.Size([2, 3, 4])
b.size(0): 2
b.size(1): 3
b.shape[0]: 2
b.shape[1]: 3
b.shape: torch.Size([2, 3, 4])
list(b.shape): [2, 3, 4]
b.numel(): 24
b.dim(): 3

tensor的创建:

# 将一个numpy的变量转变成torch类型的
# c是一个一行两列的,[2.2 , 3.3] 矩阵
c=np.array([2.2,3.3])
print(torch.from_numpy(c)) # d是一个三行四列的值为1的矩阵
d=np.ones([3,4])
# 导入后类型转变成了torch.float64()
print(torch.from_numpy(d))
print() # 小写的tensor()接受的是现有的数据,一行两列
print("torch.tensor([2,3]):\n",torch.tensor([2,3]))
print()
# 大写的FloatTensor()接受的是数据的维度,两行三列,(也可以接受现有的数据)
print("torch.FloatTensor(2,3):\n",torch.FloatTensor(2,3))
print() # 不推荐使用上边的方法,因为上边初始化,会生成非常大或者非常小的值
# 而是推荐使用随机生成指定数值区间的初始化
# rand(2,3):随机生成值在0~1区间的,两行三列的的张量
print("torch.rand(2,3):\n",torch.rand(2,3))
print() # rand_like() 参数是一个张量(tensor),相当于把e的shape读出来,之后再送给rand函数
e=torch.rand(3,4)
print("torch.rand_like(e): //e是一个三行四列的张量\n",torch.rand_like(e))
print() # randint() 参数依次是,randint(最小值,最大值,shape),取不到最大值
print("torch.randint(1,10,[3,4]):\n",torch.randint(1,10,[3,4]))

运行结果:

tensor([2.2000, 3.3000], dtype=torch.float64)
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]], dtype=torch.float64) torch.tensor([2,3]):
tensor([2, 3]) torch.FloatTensor(2,3):
tensor([[0., 0., 0.],
[0., 0., 0.]]) torch.rand(2,3):
tensor([[0.4876, 0.7776, 0.3553],
[0.3311, 0.9068, 0.0672]]) torch.rand_like(e): //e是一个三行四列的张量
tensor([[0.0792, 0.8138, 0.6931, 0.8604],
[0.2047, 0.9061, 0.8075, 0.1821],
[0.0216, 0.2109, 0.4703, 0.7405]]) torch.randint(1,10,[3,4]):
tensor([[8, 3, 2, 7],
[6, 3, 8, 6],
[1, 4, 1, 5]])

4.tensor的创建与切片

import torch

if __name__ == '__main__':

    # 生成一个两行三列的矩阵,并把所有值赋值为3.92
c=torch.full((2, 3), 3.92)
print('torch.full((2, 3), 3.92):\n',c,'\n') # 步长为2,按序生成0~10之间的数字
d=torch.arange(0,10,step=2)
print('d=torch.arange(0,10,step=2):\n',d,'\n') # 均匀生成某段数据
e=torch.linspace(0,10,steps=10)
print('torch.linspace(0,10,steps=10):\n',e,'\n')
e1=torch.linspace(0,10,steps=11)
print('e1=torch.linspace(0,10,steps=11):\n',e1,'\n') # 值全为1矩阵
f=torch.ones(3,3)
print('torch.ones(3,3):\n',f,'\n')
# 值全为零矩阵
f1=torch.zeros(3,3)
print('torch.zeros(3,3):\n',f1,'\n')
# 单位矩阵
f2=torch.eye(3,3)
print('torch.eye(3,3):\n',f2,'\n') g=torch.rand(4,3,28,28)
print('shape的基本使用:')
print(g[0].shape)
print(g[0,0].shape)
print(g[0,0,2,4]) print('\ntensor的切片使用:')
# 取前两张图片
print(g[:2].shape)
# 取第二张图片向后及第一个通道向后
print(g[2:,1:].shape)
# 行:隔七个采一个样,列:隔14个采一个样,(start:stop:step)
print(g[0,0,0:28:7,::14]) h=torch.randn(3,4)
print('\n',h)
# 矩阵中值大于0.5的 赋值为ture
mask=h.__ge__(0.5)
print(mask)
print(torch.masked_select(h,mask))

运行结果:

torch.full((2, 3), 3.92):
tensor([[3.9200, 3.9200, 3.9200],
[3.9200, 3.9200, 3.9200]]) d=torch.arange(0,10,step=2):
tensor([0, 2, 4, 6, 8]) torch.linspace(0,10,steps=10):
tensor([ 0.0000, 1.1111, 2.2222, 3.3333, 4.4444, 5.5556, 6.6667, 7.7778,
8.8889, 10.0000]) e1=torch.linspace(0,10,steps=11):
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]) torch.ones(3,3):
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]) torch.zeros(3,3):
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]) torch.eye(3,3):
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]) shape的基本使用:
torch.Size([3, 28, 28])
torch.Size([28, 28])
tensor(0.7568) tensor的切片使用:
torch.Size([2, 3, 28, 28])
torch.Size([2, 2, 28, 28])
tensor([[0.4571, 0.3198],
[0.6540, 0.3359],
[0.2601, 0.8069],
[0.9713, 0.6876]])
tensor([[-2.4096, 1.1243, -1.0314, -1.4685],
[-2.5054, 0.7131, -0.0376, -0.2110],
[ 1.8922, 1.8989, 0.0459, -1.6457]])
tensor([[False, True, False, False],
[False, True, False, False],
[ True, True, False, False]])
tensor([1.1243, 0.7131, 1.8922, 1.8989])

Pytorch-tensor的创建,索引,切片的更多相关文章

  1. pytorch张量数据索引切片与维度变换操作大全(非常全)

    (1-1)pytorch张量数据的索引与切片操作1.对于张量数据的索引操作主要有以下几种方式:a=torch.rand(4,3,28,28):DIM=4的张量数据a(1)a[:2]:取第一个维度的前2 ...

  2. Pytorch Tensor 常用操作

    https://pytorch.org/docs/stable/tensors.html dtype: tessor的数据类型,总共有8种数据类型,其中默认的类型是torch.FloatTensor, ...

  3. Python array,list,dataframe索引切片操作 2016年07月19日——智浪文档

    array,list,dataframe索引切片操作 2016年07月19日——智浪文档 list,一维,二维array,datafrme,loc.iloc.ix的简单探讨 Numpy数组的索引和切片 ...

  4. 列表的初识,列表的索引切片,列表的增删改查,列表的嵌套,元组的初识,range

    1 内容总览 列表的初识 列表的索引切片 列表的增删改查 列表的嵌套 元组的初识(了解) 元组的简单应用(了解) range 2 具体内容 列表的初识 why: str: 存储少量的数据.切片出来全都 ...

  5. SQL语句-创建索引

    语法:CREATE [索引类型] INDEX 索引名称ON 表名(列名)WITH FILLFACTOR = 填充因子值0~100 GO USE 库名GO IF EXISTS (SELECT * FRO ...

  6. *使用while循环遍历数组创建索引和自增索引值

    package com.chongrui.test;/* *使用while循环遍历数组 *  *  * */public class test {    public static void main ...

  7. 程序员眼中的 SQL Server-执行计划教会我如何创建索引?

    先说点废话 以前有 DBA 在身边的时候,从来不曾考虑过数据库性能的问题,但是,当一个应用程序从头到脚都由自己完成,而且数据库面对的是接近百万的数据,看着一个页面加载速度像乌龟一样,自己心里真是有种挫 ...

  8. SQL Server创建索引(转)

    什么是索引 拿汉语字典的目录页(索引)打比方:正如汉语字典中的汉字按页存放一样,SQL Server中的数据记录也是按页存放的,每页容量一般为4K .为了加快查找的速度,汉语字(词)典一般都有按拼音. ...

  9. hive创建索引

    索引是hive0.7之后才有的功能,创建索引需要评估其合理性,因为创建索引也是要磁盘空间,维护起来也是需要代价的 创建索引 hive> create index [index_studentid ...

  10. MongoDB性能篇之创建索引,组合索引,唯一索引,删除索引和explain执行计划

    这篇文章主要介绍了MongoDB性能篇之创建索引,组合索引,唯一索引,删除索引和explain执行计划的相关资料,需要的朋友可以参考下 一.索引 MongoDB 提供了多样性的索引支持,索引信息被保存 ...

随机推荐

  1. php的php-fpm

    FastCgi与PHP-fpm到底是个什么样的关系 昨晚有一位某知名在线教育的大佬问了我一个问题,你知道php-fpm和cgi之间的关系吗?作为了一个5年的phper了,这个还不是很简单的问题,然后我 ...

  2. 10、mysql的锁

    锁概述 锁是计算机协调多个进程或线程并发访问某一资源的机制(避免争抢). 在数据库中,除传统的计算资源(如 CPU.RAM.I/O 等)的争用以外,数据也是一种供许多用户共享的资源.如何保证数据并发访 ...

  3. ASP.NET Core 移除已注册的过滤器

    背景 ABP vNext 默认对异常响应进行了处理,现在某个项目需要自定义异常响应结果. 问题 在 ABP vNext 的 MVC 模块当中,可以看到是通过 AddService(typeof(Abp ...

  4. 使用PdfSharp从模板生成Pdf文件

    ​ 最近在做一个生成文档的需求.通过先制作一个包含各字段占位符的文档模板,导入这个模板并填写内容替换掉占位符,再输出成最终文件. 由于版式固定,安全性更好,业务上常用Pdf作为最终标准化的格式, 在. ...

  5. vue 可选链 功能 ?. 替代 res && res.status 可以变成 res?.status

    安装 cnpm install --save-dev @babel/plugin-proposal-optional-chaining .babelrc { "presets": ...

  6. Python爬虫实战系列3:今日BBNews编程新闻采集

    一.分析页面 打开今日BBNews网址 https://news.bicido.com ,下拉选择[编程]栏目 1.1.分析请求 F12打开开发者模式,然后点击Network后点击任意一个请求,Ctr ...

  7. js之实现页面内所有图片旋转

    javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=do ...

  8. 从API到Agent:万字长文洞悉LangChain工程化设计

    我想做一个尝试,看看能不能用尽量清晰的逻辑,给"AI外行人士"(当然,我也是--)引入一下LangChain,试着从工程角度去理解LangChain的设计和使用.同时大家也可以将此 ...

  9. Django_文件下载

    一.小文件下载 1.视图 views.py 三种方式实现,任选其一 (1)使用HttpResponse # 导入模块from django.shortcuts import HttpResponse ...

  10. offer收割机--js的隐式类型转换规则整理

    类型转换 文中的值类型等价于所说的基础类型,其范围是(boolean,string,number) 转换为基础类型 布尔值 undefined, null, false, NaN,'', 0 --&g ...