深度学习——Tensor

一、理解

1.常数:scaler:0阶张量------标量

2.向量:vector:1阶张量

3.矩阵:matrix:2阶张量

4.三阶张量

二、创建张量的方法

1.使用列表创建Tensor

2.使用numpy数组创建Tensor

3.通过torch的API创建Tensor

python 复制代码
# 1.使用列表创建Tensor
t1 = torch.Tensor([1, 2, 3])
print(t1)
"""
tensor([1., 2., 3.])
"""

# 2.使用numpy数组创建Tensor
array1 = np.arange(12).reshape(3, 4)

t2 = torch.Tensor(array1)
print(t2)

# 3.通过torch的API创建Tensor
"""
torch.empty(3,4):创建3行四列的空的tensor,会用无用的数据进行填充
torch.ones([3,4]):三行四列全为1的tensor
torch.zeros([3,4]):三行四列全为0的tensor
torch.rand([3,4]):三行四列随机值在[0,1]之间的值
torch.randint(low = 0, high = 10, size = [3, 4]) 创建3*4的随机整数的Tensor,值区间:[low, high]
torch.randn([3,4]) 均值为0,方差为1,3*4的tensor
"""
print(torch.empty(3,4))
print(torch.ones([3,4]))
print(torch.zeros([3,4]))
print(torch.rand([3,4]))

三、张量的方法和属性

1.tensor.item(),当tensor中只有一个元素可以用的时候

2.Tensor转为ndarray

3.形状修改,tensor.view((3, 4)), 类似numpy中的reshape,是一种浅拷贝

4.获取维数、转置、轴滚动。

5.在方法后加_,会原地修改,相当于Tensorflow里的inplace

python 复制代码
# 1.tensor.item(),当tensor中只有一个元素可以用的时候
a =torch.tensor(np.arange(1))
print(a)
print(a.item()) #只有一个元素的时候可以用,返回一个python的标量,不可以用于多个元素的tensor
print('-'*50)
print(torch.Tensor([[[1]]]).item()) #获取一个tensor中的元素值
print('-'*50)

#%%
# 2.Tensor转为ndarray
t2 = torch.Tensor([[3,4]])
print(t2.numpy()) #tensor转为ndarray
print('-'*50)
print(t2.shape) #获取形状
print(t2.size()) #获取形状
print(t2.size(1))  #获取某个维度的数据,维度后的张量切片
#%%
t2
#%%
#写一个ndarray
array1 = np.array([[1,2,3],[4,5,6]])
print(id(array1))
array2=array1.reshape(3,2)
print(id(array2))
#%%
array2[0,0]=100
print(array1)
print(array2)
#%%
array1.ndim #获取维数
#%%
# 3.3.形状修改,tensor.view((3, 4)), 类似numpy中的reshape,是一种浅拷贝,仅仅形状发生改变,返回一个新的结果
t2 = torch.Tensor([[[3,4]]])
print(t2.size())
print(t2.view([1,2])) #[1,2]表示1行2列
print(t2.view([2])) # 一维tensor
#%%
b=t2.view([2, -1]) # -1表示自动计算
print(b)
print('-'*50)
print(t2) #t2的形状并没有发生改变
# https://pytorch.org/docs/stable/tensor_view.html
t2.untyped_storage().untyped().data_ptr() == b.untyped_storage().untyped().data_ptr() #判断两个tensor是否共享内存
#%%
b[0,0]=100
print(b)
print(t2) #t2的形状并没有发生改变
#%%
#3. 获取维数
print(t2.dim())

#4.获取最大值
print(t2.max())

#5.转置
t3 = torch.tensor([[1,3,4], [2,4,6]])
print(t3)
print(t3.t()) #转置


#%%
# 交换轴,这里的permute和rollaxis功能类型
t4 = torch.tensor(np.arange(24).reshape(2,3,4))
print(t4.shape)
print("-"*50)
print(t4.transpose(0,1).shape)#交换0轴和1轴
print("-"*50)
print(t4.permute(1, 0, 2).shape)#交换0轴和1轴,功能同上
print("-"*50)
print(t4.permute(1, 2, 0).shape)#变为了3*4*2
print("-"*50)
print(t4.permute(2, 1, 0).shape)#变为了4*3*2
#%%
t4.dtype
#%%
# 在方法后加_,会原地修改
x = torch.tensor(np.arange(12).reshape(3,4),dtype = torch.int8)
print(x)
y= torch.ones([3,4], dtype = torch.int64)
print(y)

print('-'*50)
x.sub_(y) # add_就地修改,不加下划线的会创建一个新的tensor来存储
print(x)
#%%
#tensor取值,和np完全相同
t5 = torch.tensor(np.arange(12).reshape(3,4))
print(t5)
print(t5[1,2]) #取值
print(t5[1]) #取一行
print(t5[:,1]) #取一列
print(t5[1:3,1:3]) #取一部分
print(t5[1:3,:]) #取一部分


#%%
#两个16行,1列的张量相减,求均值
t6 = torch.tensor(np.arange(16).reshape(16,1),dtype=torch.float32)
t7 = torch.tensor(np.arange(16,32).reshape(16,1),dtype=torch.float32)
print(t6)
print(t7)
((t6-t7)**2).mean()
#%%
#初始化两个张量,一个3,4,一个3,1,运算与ndarray相同
t8 = torch.tensor(np.arange(12).reshape(3,4),dtype=torch.float32)
t9 = torch.tensor(np.arange(3).reshape(3,1),dtype=torch.float32)
print(t8)
print(t9)
t8-t9
相关推荐
IT猿手34 分钟前
2025最新群智能优化算法:山羊优化算法(Goat Optimization Algorithm, GOA)求解23个经典函数测试集,MATLAB
人工智能·python·算法·数学建模·matlab·智能优化算法
Jet45052 小时前
玩转ChatGPT:GPT 深入研究功能
人工智能·gpt·chatgpt·deep research·深入研究
毕加锁2 小时前
chatgpt完成python提取PDF简历指定内容的案例
人工智能·chatgpt
Wis4e3 小时前
基于PyTorch的深度学习3——基于autograd的反向传播
人工智能·pytorch·深度学习
西猫雷婶4 小时前
神经网络|(十四)|霍普菲尔德神经网络-Hebbian训练
人工智能·深度学习·神经网络
梦丶晓羽5 小时前
自然语言处理:文本分类
人工智能·python·自然语言处理·文本分类·朴素贝叶斯·逻辑斯谛回归
SuperCreators5 小时前
DeepSeek与浏览器自动化AI Agent构建指南
人工智能·自动化
美狐美颜sdk5 小时前
什么是美颜SDK?从几何变换到深度学习驱动的美颜算法详解
人工智能·深度学习·算法·美颜sdk·第三方美颜sdk·视频美颜sdk·美颜api
訾博ZiBo5 小时前
AI日报 - 2025年3月10日
人工智能
waicsdn_haha5 小时前
Postman v11 安装与API测试入门教程(Windows平台)
人工智能·windows·测试工具·mysql·postman·dbeaver·rest