04 Pytorch tensor

一:老版本的 variable

二:新版 tensor

曾经:求导相关

如今:数据相关

--dtype: 张量的数据类型,三大类,共9种。torch.FloatTensor, torch.cuda.FloatTensor

--shape: 张量的形状。如:(64,3,224,224)

--decive: 所在设备

三:tensor创建方法

Tensor创建一:直接创建 (共享内存:out)

1)

复制代码
torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)

2) 从numpy创建tensor : torch.from_numpy(ndarray)

注意:共享内容

python 复制代码
import torch
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)

t[0, 0] = -1
print(arr)
print(t)
Tensor创建二:依据数值创建(等差,均分,单位矩阵)

4.2 依据数值创建

1)torch.zeros():按照size创建全0张量

复制代码
torch.zeros(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  1. 21torch.zeros_like()

    torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False)

  2. torch.ones()

  3. torch.ones_like()

  4. torch.full()

  5. torch.full_like()

  6. torch.arange(),创建等差数列,区间:[start, end,数值) 等差创建

6.torch.linspace(),创建均分数列,区间:start, end

注意:step是步长;steps是长度

t = torch.linspace(start=0, end=100, steps=5, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

Tensor创建三:依据概率创建(正太,标准正太,伯努利分布)

第二章:Tensor 操作与线性回归

2.1:张量的操作:拼接、切分、索引和变换
2.1.1拼接:
  • torch.cat(): 将张量按维度dim进行拼接
python 复制代码
t_0 = torch.cat([t, t], dim=0)
t_1 = torch.cat([t, t], dim=1)

torch.Size(4, 3)

torch.Size(2, 6)

  • torch.stack():在新建的维度dim上进行拼接
python 复制代码
t = torch.ones((2, 3))

t_0 = torch.cat([t, t], dim=0)
t_1 = torch.stack([t, t], dim=0)

print(t_0)
print(t_0.shape)
print(t_1)
print(t_1.shape)
2.1.2 切分

按维度dim进行平均切分: torch.chunk(input, chunks, dim)

python 复制代码
t = torch.ones((2, 7))
print(t)

list_of_tensor = torch.chunk(t, dim=1, chunks=3)
print(list_of_tensor)

指定切分:torch.split() 2,2,3切分三个,每个都有特定的te'zheng'sh

python 复制代码
t = torch.ones((2, 7))
print(t)
list_of_tensor_2 = torch.split(t, 3, dim=1)
print(list_of_tensor_2)

list_of_tensor_3 = torch.split(t, [2, 2, 3], dim=1)
print(list_of_tensor_3)
2.1.3 reshape

torch.reshape: 变换张量形状

notice: 注意事项:当张量在内存中是连续时,新张 量与input共享数据内存

python 复制代码
# torch.reshape
t = torch.randperm(8)
print(t)
t_reshape = torch.reshape(t, (2, 4))  # -1代表不关心
print(t_reshape)
2.2张量的数学运算

2.3线性回归

用wx+b 去拟合谁?

逻辑回归:

Deepshare-Pytorch/作业/第二周作业1/第二周作业1.md at master · 799609164/Deepshare-Pytorch · GitHub

相关推荐
A hao6 小时前
HDR LED显示屏工作原理:高动态范围显示技术解析
大数据·图像处理·人工智能
IT_陈寒6 小时前
SpringBoot自动配置的坑,我的Bean怎么不生效?
前端·人工智能·后端
nopSled6 小时前
AlphaAvatar v0.6.4 架构升级:统一实时感知、RTC 解耦与在线 ENV Memory
人工智能·架构·实时音视频·agent·多模态
Rubin智造社6 小时前
从“+AI”到“AI原生”:一场底层逻辑的思维革命
人工智能·ai-native
CoderYanger6 小时前
视频切割脚本(Python版)
linux·开发语言·windows·后端·python·程序人生·职场和发展
迷途呀6 小时前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
波动几何6 小时前
个人信息脱敏的本人角色模板技能personal-self
人工智能
领麦微红外6 小时前
MLX90614的国产替代方案——了解FW-D1红外测温传感器
人工智能·智能家居
回眸&啤酒鸭6 小时前
【回眸】搞钱灵感——AI 数字人口播博主自动化运营
大数据·人工智能·自动化
想会飞的蒲公英6 小时前
逻辑回归为什么叫回归,却用来做分类
人工智能·python·分类·回归·逻辑回归