当前位置: 首页 > news >正文

Python自学笔记

pytorch

花了好久时间终于装好了 pytorch,连上了 vscode

一些传送门:

pytorch 官网
pytorch 中文手册
深入浅出 pytorch

前置

引入 torch 库

import torch

查看是否有可用的 CUDA

torch.cuda.is_available()

tensor

张量

一些基本的操作:
创建一个 tensor

a = torch.tensor([1,2,3], dtype = int)

创建一个二维 tensor

a = torch.tensor([[1.1, 2, 8.1],[3.1, 6, 9.1]], dtype=float)

查看数据类型

a.dtype

查看数据维度(行数)

a.ndim

查看数据形状(几行几列)

a.shape  # method 1
a.size() # method 2

数据生成

生成全 \(1\) 矩阵

a = torch.ones(2, 3)

生成全 \(0\) 矩阵

a = torch.zeros(2, 3)

以上两例均默认生成 float,只填一个参数则默认一维

生成随机矩阵:
生成 $\left [ 0,1 \right ) $ 的随机 float 矩阵

a = torch.rand(3, 3)

生成在 low 与 high 之间(左闭右开,low 默认为 \(0\))的随机 int 矩阵

a = torch.randint(2, 18, (3, 4))

生成符合正态分布的随机矩阵

a = torch.randn(2, 4)

生成相似的随机矩阵

b = torch.rand_like(a, dtype=float)

改变矩阵形状(不改变大小)

# 此例中 a 原来大小为(3, 4)
a = a.view(2, 6)    # method 1
a = a.reshape(2, 6) # method 2

取出 tensor 中的值

a = torch.rand(3, 3)
b = a[2][1].item()

torch 的 tensor 与 numpy 的 array 之间互相转化

a = torch.randint(2, 7, (3, 4))
b = numpy.array(a)
c = torch.tensor(b)

生成固定整数列的矩阵

a = torch.arange(4, 12).reshape(2, 4)

基本运算操作

两个形状相同的矩阵对应位置相加

a + b                    # method 1
torch.add(a, b, out = c) # method 2 输出保存到 c
a.add_(b)				 # method 3 a = a + b

减法(-)、乘法(*)、除法(/)、取模(%)、整除(//)同理

a ** 2

矩阵乘法

torch.matmul(a, b) # a 的行数要和 b 的列数对上

开方

torch.sqrt(a)

转置

a.T

矩阵内统计

torch.sum(a)    #求和
torch.min(a)    #最小
torch.max(a)    #最大
torch.argmin(a) #最小值所在位置索引
torch.argmax(a) #最大值所在位置索引
torch.mean(a)   #平均数
torch.median(a) #中位数(偶数个取偏小的那个)

索引

跟 python 普通的列表的各种操作基本一样

取出一个子序列

index = [1, 3, 5, 5]
a = a[index]

自动求导

import torch
a = torch.ones((2, 2), requires_grad = True) #可获取梯度
b = a + 2
c = b * b * 3
out = c.mean()
out.backward()
print(a.grad) 
http://www.gsyq.cn/news/25231.html

相关文章:

  • sqlalchemy 密码@ 处理, 以及ssl连接处理
  • 2025 年破碎机厂家最新推荐榜,聚焦企业技术实力与市场口碑深度解析圆锥/辊式/对辊/煤矸石/砂石破碎机厂家推荐
  • 拆解3D Gaussian Splatting:原理框架、实战 demo 与自驾仿真落地探索!
  • Android脱壳
  • Gitee:本土化技术平台如何重塑中国开发者生态
  • 得帆AI aPaaS(AI低代码)1.0产品特性(5)-智能搭建(二)
  • 得帆AI aPaaS(AI低代码)1.0产品特性(4)-智能搭建(一)
  • 腾讯企业邮箱管理
  • element 表单校验失败定位到指定元素
  • 2025年湖北武汉实验室设计哪家口碑好/哪家信誉好/哪家售后好?
  • C# Avalonia 16- Animation- BombDropper
  • C# 使用NPOI生成Word文件
  • Python3 statistics 模块
  • 随机生成动态头像
  • 2025年AI搜索优化品牌推荐排行榜前十强深度解析
  • 2025年AI搜索优化品牌推荐排行榜:技术深度解析与选择指南
  • win10 开启大小核心调度--异类策略0~4介绍
  • Windows 已保护你的电脑:Microsoft Defender SmartScreen 阻止了无法识别的应用启动。运行此应用可能会导致你的电脑存在风险。
  • 恒生电子面经准备 - 详解
  • 想学习的数学
  • 详细介绍:Streamlit:CSS——从基础到实战美化应用
  • Win11设置默认打开全部右键菜单
  • 屏幕显示发白难题的硬件工程深度排查:架构兼容性边界分析
  • 详细介绍:【Linux】Linux管道与进程池深度解析:从原理到实战
  • windows2019的域控服务器更新时间.251020
  • 国内DOH解析速度测试(阿里 腾讯 360 Doh测速)
  • WatchAlert 轻量级AI日志告警 - Docker安装部署
  • java代码和c++代码相互调用的技术方案
  • 详细介绍:MyBatis动态sql
  • 对话智能体泛化研究在线挑战启动