常见的tenor操作

常见的tenor操作tensor 常见操作的总结 import torch import numpy as np 1 tensor 的初始化 1 1 直接从数据初始化 data 1 2 3 4 x data torch tensor data print f the x data is

大家好,我是讯享网,很高兴认识大家。
# tensor常见操作的总结 import torch import numpy as np # 1.tensor 的初始化 #1.1 直接从数据初始化 data = [[1,2],[3,4]] x_data = torch.tensor(data) print(f"the x_data is { 
     x_data}") #1.2 从numpy初始化 np_array = np.array(data) x_np = torch.from_numpy(np_array) print(f"the x_np is { 
     x_np}") # 1.3 从其他的tensor初始化 x_ones = torch.ones_like(x_data) print(f"the x_ones is { 
     x_ones}") x_rand = torch.rand_like(x_data, dtype = torch.float) print(f"the x_rand is { 
     x_rand}") # 1.4 生成随机的或者是固定的一个值的tensor,shape是一个元组 shape = (2,3,) rand_tensor = torch.rand(shape) ones_tensor = torch.ones(shape) zeros_tensor = torch.zeros(shape) print(f"the rand_tensor is { 
     rand_tensor}") print(f"the ones_tensor is { 
     ones_tensor}") print(f"the zeros_tensor is { 
     zeros_tensor}") #2. tensor 的属性: 形状,type(默认就是float32),device tensor = torch.rand(1,2,3) print(f" the shape of the tensor is { 
     tensor.shape}") print(f" the type of the tensor is { 
     tensor.dtype}") print(f" the device of the tensor is { 
     tensor.device}") #3. 常见的nummpy的寻址和切片操作 tensor = torch.ones(3,4) print(f" the first row is : { 
     tensor[0]}") print(f" the first column is : { 
     tensor[:,0]}") print(f" the last column is : { 
     tensor[...,-1]}") tensor[:,1] = 0 print(tensor) #4.常见的tensor的堆叠操作 #4.1 通过cat方式堆叠tensor,指定要堆叠的tenso以及堆叠的维度 t1 = torch.cat([tensor,tensor,tensor], dim =1) print(t1) t1 = torch.cat([tensor,tensor,tensor], dim =0) print(t1.shape) #4.2 通过torch.stack的方式堆叠tensor,指的是在一个新的维度上堆叠tensor t2 = torch.stack([tensor,tensor,tensor],dim =0) print(t2.shape) #5.常见的tensor的算数运算 #5.1 计算tensor的矩阵乘法 y1 = tensor @ tensor.T y2 = tensor.matmul(tensor.T) y3 = torch.rand_like(tensor) torch.matmul(tensor,tensor.T,out=y3) print(y1) print(y2) print(y3) #5.2 计算element-wise的乘法,z1,z2,z3拥有相同的数值 z1 = tensor*tensor z2 = tensor.mul(tensor) z3 = torch.rand_like(tensor) torch.mul(tensor, tensor, out=z3) print(z1) print(z2) #5.3 单元素tensor转化成一个值 agg= tensor.sum() print(agg) agg_value = agg.item() print(agg_value) #5.4 inplace operation 改变当前tensor的操作,用_表示 print(f"{ 
     tensor}") print(f"{ 
     tensor.add_(5)}") print(f"{ 
     tensor.t_()}") # 6.Numpy和tensor之间互相转化 # 6.1 tensor转成 numpy t = torch.ones(4,4) n = t.numpy() print(f" tensor is { 
     t}") print(f" nummpy is { 
     n}") t.add_(1) print(f" tensor is { 
     t}") print(f" nummpy is { 
     n}") # 一个特征就是改变了这个tensor的值会影响到numpy #7.numpy转成 tensor n = np.ones(5) t = torch.from_numpy(n) np.add(n,1,out=n) print(f" tensor is { 
     t}") print(f" nummpy is { 
     n}") 

讯享网
小讯
上一篇 2025-02-23 15:51
下一篇 2025-03-07 12:03

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/128341.html