PyTorch学习笔记--张量的创建

张量是什么?

张量是一个多维数组,它是标量、向量、矩阵的高维拓展。

Tensor 与 Variable

variable 是 torch.autograd 中的数据类型,主要用于封装 Tensor ,进行自动求导

  • data:被包装的 Tensor

  • grad:data 的梯度

  • grad_fn:创建 Tensor 的 Function,是自动求导的关键

  • requires_grad:指示是否需要梯度

  • is_leaf:指示是否是叶子节点(张量)

Tensor

PyTorch 0.4.0 版开始,variabe 并入 Tensor

  • dtype:张量的数据类型,如 torch.FloatTensor,torch.cuda.FloatTensor(表示数据放在 GPU)

  • shape:张量的形状,如(64,3,224,224) 四维

  • device:张量所在设备,GPU/CPU,是加速的关键

张量的创建

一、直接创建

torch.tensor()

功能:从 data 创建 tensor

  • data:数据,可以是 list,numppy

  • dtype:数据类型,默认与 data 保持一致

  • device:所在设备,cuda/cpu

  • requires_grade:是否需要梯度

  • pin_memory:是否存于锁业内存

使用示例:

torch.tensor(
			data,
			dtype=None,
			device=None,
			requires_grad=False,
			pin_memory=False)

代码演示:

 张量的创建
import torch
import numpy as np

arr = np.ones((3, 3)) #生成全为1的 3 * 3 张量
print("ndarray 的数据类型:", arr.dtype)

t = torch.tensor(arr, device='cuda')
print(t)

output:
"""
ndarray 的数据类型: float64
tensor([[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]], device='cuda:0', dtype=torch.float64)
"""

torch.from_numpy(ndarray)

功能:从 numpy 创建 tensor

注意事项:从 torch.from_numpy 创建的 tensor 与原来的 ndarray 共享内存,当修改其中一个数据,另一个也会改变

代码演示:

arr = np.array([[1,2,3],[4,5,6]])
t = torch.from_numpy(arr)
print(t)
t[0,0]=-1
print(arr)
print(t)

'''
output:
tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)
[[-1  2  3]
 [ 4  5  6]]
tensor([[-1,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)
'''


二、依据数值创建

1. torch.zeros()

功能:依 size 创建全 0 的张量

  • size:张量的形状、如(3,3)、(3,224,224)

  • out:输出的张量

  • layout:内存中布局形式,有 strided,sparse_coo 等

  • device:所在设备,GPU/CPU

  • requires_grad:是否需要梯度

使用示例:

torch.zeros(*size,
			out=None,
			dtype=None,
			layout=torch.strided,
			device=None,
			requires_grad=False)
out_t = torch.tensor([1])
t = torch.zeros((3,3),out=out_t)
print(t, "\n", out_t)
print(id(t), id(out_t), id(t)==id(out_t)) #判断内存地址

'''
output:
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
1687300636744 1687300636744 True  #结果显示,t 与 out_t 地址相同
'''

2. torch.zeros_like()

功能:依据 input 形状创建全 0 张量

  • input:创建与 input 同形状的张量

  • dtype:数据类型

  • layout:内存中布局形状

使用示例:

torch.zeros_like(input,
				dtype=None,
				layout=None,
				device=None,
				requires_grad=False)

3. torch.ones()

功能:创建全为 1 的张量

4. torch.ones_like()

功能:依 input 形状创建全为 1 的张量

  • size:张量的形状,如(3,3)、(3,224,224)

  • dtype:数据类型

  • layout:内存中的布局形状

  • device:所在设备,gpu/cpu

  • requires_grad:是否需要梯度

5. torch.full()

使用示例:

torch.full(size,
		fill_value,
		dtype=None,
		layout=torch.strided,
		device=None,
		requires_grad=False)
t = torch.full((3,3),1)
print(t,t.dtype)

'''
output:
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]) torch.float32
'''

6. torch.full_like()

功能:依 input 形状创建全 0 的张量

  • size:张量的形状,如(3,4)

  • fill_value:张量的值

7. torch.arange()

功能:创建等差的 1 维张量

注意事项:数值区间为 [start, end]

  • start:数列起始值

  • end:数列 “结束值”

  • step:数列公差,默认为 1

使用示例:

torch.arange(start=0,
			end,
			step=1,
			out=None,
			dtype=None,
			layot=torch.strided,
			device=None,
			requires_grad=False)
t = torch.arange(3, 20, 4)
print(t)

'''
output:
tensor([ 3,  7, 11, 15, 19])
'''

8. torch.linspace()

功能:创建均分的 1 维张量

注意事项:数值区间为[start, end]

  • start:数列起始值

  • end:数列结束值

  • steps:数列长度

使用示例:

torch.linspace(start,
				end,
				steps=100,
				out=None,
				dtype=None,
				layout=torch.strided,
				device=None,
				requires_grad=False)
t = torch.linspace(2,10,5)  # 步长:(end-start)/(steps-1)
print(t)

'''
output:
tensor([ 2.,  4.,  6.,  8., 10.])
'''

9. torch.logspace()

功能:创建对数均分的 1 维张量

注意事项:长度为 steps,底为 base

  • start:数列起始值

  • end:数列结束值

  • steps:数列长度

  • base:对数函数的底,默认为 10

torch.logspace(start,
				end,
				steps=100,
				base=10,
				out=None,
				dtype=None,
				layout=torch.strided,
				device=None,
				requires_grad=False)

10. torch.eye()

功能:创建单位对角矩阵(2 维张量)

注意事项:默认为方阵

  • n:矩阵行数

  • m:矩阵列数

torch.eye(n,
		m=None,
		out=None,
		dtype=None,
		layout=torch.strided,
		device=None,
		requires_grad=False)

三、依概率分布创建张量

1. torch.normal()

功能:生成正态分布(高斯分布)

  • mean:均值

  • std:标准差

使用示例:

torch.normal(mean,
			std,
			out=None)

使用的四种模式:

  1. mean 是标量,std 是标量

  2. mean 是张量,std 是标量

  3. mean 是标量,std 是张量

  4. mean 是张量,std 是张量

# 1.mean 是标量,std 是标量
t_normal = torch.normal(1, 5, size=(4,)) #mean,std 均为标量时,需要加 size
print(t_normal)

'''
output:
tensor([ 9.4515,  1.7080, -6.6720,  2.1244])
'''


# 2. mean 是张量,std 是标量
mean = torch.arange(1, 5, dtype=torch.float)
std = 1
t_normal = torch.normal(mean, std)
print(t_normal)

'''
output:
tensor([0.3063, 1.3824, 2.9597, 3.7992])
'''


# 3.mean 是标量,std 是张量
std = torch.arange(1, 5, dtype=torch.float)
mean = 1
t_normal = torch.normal(mean, std)
print("mean: {}\nstd:{}".format(mean, std) )
print(t_normal)

'''
output:
mean: 1
std:tensor([1., 2., 3., 4.])
tensor([ 2.1923,  1.7292,  0.6646, -1.3194])
'''


# 4.mean 是张量,std 是张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std) #依mean为均值,std 为方差
print("mean: {}\nstd:{}".format(mean, std) )
print(t_normal)

'''
output:
mean: tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([ 1.5662,  0.2100,  8.4844, 11.9603]) #生成的分别为 1 为均值 1为方差,2为均值,2为方差,3为均值,3为方差。。。
'''

2. torch.randn()

3. torch.randn_like()

功能:生成标准正态分布

  • size:张量的形状

使用示例:

torch.randn(*size,
			out=None,
			dtype=None,
			layout=torch.strided,
			device=None,
			requires_grad=False)

4. torch.rand()

5. torch.rand_like()

功能:在区间 [0, 1) 上,生成均匀分布

6. torch.randint()

7. torch.randint_like()

功能:区间 [low,high) 生成整数均匀分布

  • size:张量的形状

使用示例:

torch.rand(*size,
			out=None,
			dtype=None,
			layout=torch.strided,
			device=None,
			requires_grad=False)
			
torch.randint(low=0,
			high,
			size,
			out=None,
			dtype=None,
			layout=torch.strided,
			device=None,
			requires_grad=False)			

8. torch.randperm()

功能:生成从 0 到 n-1 的随机排列

  • n:张量的长度

torch.randperm(n,
			out=None,
			dtype=torch.int64,
			layout=torch.strided,
			device=None,
			requires_grad=False)

9. torch.bernoulli()

功能:以 input 为概率,生成伯努利分布(0-1分布,两点分布)

  • input :概率值

torch.bernoulli(input,
                *,
                generatot=None,
                out=None)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值