pytorch张量创建:
- 将numpy转化为tensor的方法: torch.Tensor(),torch.from_numpy()
- 创建指定数字大小或者指定shape的张量:torch.zeros(input=shape形状),torch.zeros_like(张量)
- 根据概率创建张量。
import torch
import numpy as np
# 1.首先通过np.ones((x,x)) 创建一个 x*x大小的矩阵
# 2.然后通过torch.tensor(data) 将一个numpy数据类型转化为一个 tensor数据类型
# 如果需要将该数据放入到gpu中需要将设备设置为cuda
def tensor_create1():
arr = np.ones((3, 3))
print("ndarray的数据类型:", arr.dtype)
print(type(arr))
t = torch.tensor(arr, device="cuda")
# print(arr)
print(t)
# 2. torch.from_numpy
def tensor_create2():
# 1.通过from_numpy 将tensor和numpy数据绑定到一起
arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)
print(arr)
print(t)
flag = False
# ----------------------------
# 2. 判断修改numpy是否对 tensor有影响
if flag:
arr[0][0] = -1
print(arr)
print(t)
# 3. 判断修改tensor是否对 numpy有影响
else:
t[0, 0] = -2
print(arr)
print(t)
# 3.依据数值创建张量
def tensor_create3():
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))
# 4. torch.ones()
# 5. torch.ones_like()
# 6. torch.full()
# 7. torch.full_like()
def tensor_create4():
out_t = torch.tensor([1])
t = torch.zeros_like(out_t)
print(t)
def tensor_create6():
# 以下解释是 torch.full_like()函数的解释,大概意思是 该函数的返回值大小和输入的张量大小一样。
# 它与torch.full()函数的差别是 full()函数input的是张量的shape而full_like()函数用户不用管输入张量的shape其会自己算并生成和输入张量
# 大小一样的张量并返回。
# 同理 ones_like()和zeros_like()也与其实现基本一样。
# Returns a tensor with the same size as input filled with fill_value. torch.full_like(input, fill_value) is
# equivalent to torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device).
out_t = torch.full((3, 3), 1)
print(out_t)
out_t2 = torch.full_like(out_t, 2)
print(out_t2)
# 8. 通过torch.arange()创建张量 需要输入start和end和step参数去控制起始值,结束值,步长。可以参考 python range的函数和其商城的一样。
# 9. 通过torch.linspace()创建张量 该函数也需要 start,end,steps三个参数 这个函数的意思是将 start到end的数等分steps份。
# 例如 start = 2 end = 10,steps =4 那么会成 2.,4.,6.,8.,10.
# torch.arrange() 和 torch.linspace 都是等分类函数 arrange()仅仅告诉你每一步间隔是多少能等分多少份与start-end的长度有关。
# torch.linspace()提前在函数中定义等分的份数不管其start和end的范围,我都等分这么多份。
# 其实 与 zeros 和zeros_like()是有一定相似性的。
def tensor_create9():
out_t = torch.linspace(2,10,5)
print(out_t)
# 10. torch.logspace() 是创建对数均分的1维张量。
# 11. torch.eye() 是创建 单位对角矩阵二维张量 默认方阵。n 和m一个行一个列m不输入就是方阵。
# 12. torch.normal() 根据概率分布生成张量
# 13. torch.randn() torch.randn_like()是根据标准正态分布生成张量
# 14. torch.rand() torch.rand_like() 在区间[0-1)生成均匀分布
# 15. torch.randint() torch.randint_like() 在[low,hight)生成整数均匀分布
# 16. torch.randperm() 生成0-n-1的随机排列。
# 17. torch.bernoulli() 生成伯努利分布 0-1分布 函数的输入是个张量.每个张量的数据对这个函数来说是为0-1的概率如果=1的话那么就一直是1如果
# 等于0的话就一直是0 小于和大于1的情况
# RuntimeError: Expected p_in >= 0 && p_in <= 1 to be true, but got false. (Could this error message be improved?
# If so, please report an enhancement request to PyTorch.)
def tensor_create17():
a = torch.full((6,6),1,dtype=float)
probability = torch.bernoulli(a)
print(probability)
if __name__ == '__main__':
# tensor_create1()
# tensor_create2()
tensor_create17()