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

相关推荐
丝斯201114 分钟前
AI学习笔记整理(63)——大模型对齐与强化学习
人工智能·笔记·学习
延凡科技4 小时前
无人机低空智能巡飞巡检平台:全域感知与智能决策的低空作业中枢
大数据·人工智能·科技·安全·无人机·能源
2501_941329724 小时前
YOLOv8-SEAMHead改进实战:书籍检测与识别系统优化方案
人工智能·yolo·目标跟踪
晓翔仔5 小时前
【深度实战】Agentic AI 安全攻防指南:基于 CSA 红队测试手册的 12 类风险完整解析
人工智能·安全·ai·ai安全
百家方案5 小时前
2026年数据治理整体解决方案 - 全1066页下载
大数据·人工智能·数据治理
北京耐用通信6 小时前
工业自动化中耐达讯自动化Profibus光纤链路模块连接RFID读写器的应用
人工智能·科技·物联网·自动化·信息与通信
Hgfdsaqwr6 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
开发者小天6 小时前
python中For Loop的用法
java·服务器·python
老百姓懂点AI7 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
小韩博7 小时前
一篇文章讲清AI核心概念之(LLM、Agent、MCP、Skills) -- 从解决问题的角度来说明
人工智能