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

相关推荐
不写八个4 分钟前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
肖遥Janic6 分钟前
Stable Diffusion绘画 | 插件-Deforum:动态视频生成(上篇)
人工智能·ai·ai作画·stable diffusion
robinfang201913 分钟前
AI在医学领域:Arges框架在溃疡性结肠炎上的应用
人工智能
给自己一个 smile17 分钟前
如何高效使用Prompt与AI大模型对话
人工智能·ai·prompt
_.Switch21 分钟前
Python机器学习框架介绍和入门案例:Scikit-learn、TensorFlow与Keras、PyTorch
python·机器学习·架构·tensorflow·keras·scikit-learn
赵荏苒33 分钟前
Python小白之Pandas1
开发语言·python
魔力之心44 分钟前
人工智能与机器学习原理精解【30】
人工智能·机器学习
Hiweir ·1 小时前
NLP任务之文本分类(情感分析)
人工智能·自然语言处理·分类·huggingface
百里香酚兰1 小时前
【AI学习笔记】基于Unity+DeepSeek开发的一些BUG记录&解决方案
人工智能·学习·unity·大模型·deepseek
一眼万里*e1 小时前
fish-speech语音大模型本地部署
python·flask·大模型