Day02-02.张量和Numpy之间相互转换
一、张量转换为NumPy数组使用 Tensor.numpy 函数可以将张量转换为 ndarray 数组但是共享内存可以使用 copy 函数避免共享。# 1. 定义函数, 演示: 张量 - numpy def dm01(): # 1. 创建张量. t1 torch.tensor([1, 2, 3, 4, 5]) print(ft1: {t1}, type: {type(t1)}) # 2. 张量 - numpy. # n1 t1.numpy() # 共享内存. n1 t1.numpy().copy() # 不共享内存. print(fn1: {n1}, type: {type(n1)}) # 3. 演示上述方式 是否共享内存. n1[0] 100 print(fn1: {n1}) # [100, 2, 3, 4, 5] print(ft1: {t1}) # [?, 2, 3, 4, 5]二、NumPy数组转换为张量1、使用 from_numpy 可以将 ndarray 数组转换为 Tensor默认共享内存使用 copy 函数避免共享。2、使用 torch.tensor 可以将 ndarray 数组转换为 Tensor默认不共享内存。# 2. 定义函数, 演示: numpy - 张量 def dm02(): # 1. 创建numpy数组. n1 np.array([11, 22, 33]) print(fn1: {n1}, type: {type(n1)}) # 2. 把上述的numpy数组, 转换成张量. # t1 torch.from_numpy(n1).type(torch.float32) # 转换 转类型. t1 torch.from_numpy(n1) # 共享内存. print(ft1: {t1}, type: {type(t1)}) t2 torch.tensor(n1) # 不共享内存 print(ft2: {t2}, type: {type(t2)}) # 3. 演示上述方式 是否共享内存. n1[0] 100 print(fn1: {n1}) # 100, 22, 33 print(ft1: {t1}) # 100, 22, 33 print(ft2: {t2}) # 11, 22, 33三、标量张量和数字转换def dm03(): # 1. 创建张量. t1 torch.tensor(100) # 可以 # t1 torch.tensor([100, ]) # 可以 # t1 torch.tensor([100, 200]) # 不可以. print(ft1: {t1}, type: {type(t1)}) # 2. 从张量中提取内容. a t1.item() print(fvalue: {a}, type: {type(a)})