版本为0.4.0以上才行
本节笔记对应视频
0.pytorch下张量的属性
1.通过numpy/list创建
"""张量的创建方法"""
import torch
import numpy as np
flag = True
if flag:
arr = np.ones((3,3))
print(arr)
print("*"*50)
print(arr.dtype)
t = torch.tensor(arr, device= "cuda") # 张量创建可以设置为GPU用于存储,GPU下由于数据需要从cpu迁移到GPU速度会变慢
t2 = torch.from_numpy(arr) # 和上面一样,但是这种写法共享了arr和t2变量的内存,其中一个改变都会改变
print(t)
print("*" * 50)
print(t2)
print("*" * 50)
arr[0][0] = 9
print(arr)
print("*" * 50)
print(t)
print("*" * 50)
print(t2)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
**************************************************
float64
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], device='cuda:0', dtype=torch.float64)
**************************************************
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
**************************************************
[[9. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
**************************************************
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], device='cuda:0', dtype=torch.float64)
**************************************************
tensor([[9., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
进程已结束,退出代码 0
2.依据数值创建
if flag == False:
out_t = torch.tensor([1])
print(out_t)
t = torch.zeros((3,3), out=out_t) #
print(t,"\n",out_t)
print(id(t)) # 内存地址
print(id(out_t))
print(id(t)==id(out_t))
tensor([1])
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
1750855205896
1750855205896
True
if flag2:
out_t = torch.tensor([9,15432,154])
out_t1 = torch.tensor([9])
print(out_t)
t = torch.zeros_like(out_t) # tensor([0, 0, 0])
print(t)
t2 = torch.ones(out_t1) # tensor([1., 1., 1., 1., 1., 1., 1., 1., 1.])
print(t2)
t3 = torch.ones_like(out_t) # tensor([1, 1, 1])
print(t3)
# 自定义维度和单一元素
t4 = torch.full((3,3),1)
print(t4)
#等差数列张量创建方式
t5 = torch.arange(2,10,2) # 一个偶数列,起始值为2结束为10(左闭右开),相差2 ----tensor([2, 4, 6, 8])
print(t5)
#均分数列
t6 = torch.linspace(2,10,6)
mean = torch.arange(1,5,dtype= torch.float)
std = torch.arange(1,5,dtype=torch.float)
t_normal = torch.normal(mean,std) #正态分布
print(mean)
print("*"*100)
print(std)
print("*"*500)
print(t_normal)
tensor([1., 2., 3., 4.])
****************************************************************************************************
tensor([1., 2., 3., 4.])
********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
tensor([0.6984, 2.3168, 2.8330, 3.2437])