重学PyTorch,粗略笔记(一)

很久之前学PyTorch记的笔记,顺手整理一下

安装

Start Locally | PyTorch

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

tensors张量

标量是零维张量,向量是一维张量,矩阵是二维张量,一个RGB图像数组就是一个三维张量,第一维是图像高,第二维是图像的宽,第三维是图像颜色通道。

torch.Tensor是一个类, torch.tensor是一个函数,tensor是pytorch中最核心的数据结构,梯度的记录也是被其实现的

模型的输入输出,模型的参数都是张量

张量和numpy数组共享内存

import torch#直接创建tensor
import torch
import numpy as np
l = [[1.,-1.],[1.,-1.]]
tensor_from_list = torch.tensor(l)
print(tensor_from_list,tensor_from_list.dtype)
"""
tensor([[ 1., -1.],[ 1., -1.]]) torch.float32
"""
#从列表创建张量,自动判别类型
data = [[1, 2],[3, 4]]
print(type(data))
x_data = torch.tensor(data)
print(type(x_data))
print(x_data)#查看数据类型
x_data.dtype
"""
<class 'list'>
<class 'torch.Tensor'>
tensor([[1, 2],[3, 4]])torch.int64
"""
#从numpy创建张量import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
t_from_array = torch.tensor(arr)
# print(t_from_list, t_from_list.dtype)
print(t_from_array, t_from_array.dtype)
"""
tensor([[1, 2, 3],[4, 5, 6]], dtype=torch.int32) torch.int32
"""
#通过numpy的第二种方式:和numpy的原arrray共享内存
#当改变array里的数值,tensor中的数值也会被改变arr = np.array([[1,2,3],[4,5,6]])
print(arr)
tensor_from_numpy = torch.from_numpy(arr)
print(tensor_from_numpy)
arr[0,0] = 10
print(arr)
print(tensor_from_numpy)
"""
[[1 2 3][4 5 6]]
tensor([[1, 2, 3],[4, 5, 6]], dtype=torch.int32)
[[10  2  3][ 4  5  6]]
tensor([[10,  2,  3],[ 4,  5,  6]], dtype=torch.int32)
"""a = np.random.normal((2,3))
print(a)
a = torch.tensor(a)
a
"""
[2.03773753 0.70605461]tensor([2.0377, 0.7061], dtype=torch.float64)
"""
# 指定out:即为指定返回的tensor赋值给out
# torch.zeros()给定的size创建一个全0的tensor,默认数据类型为torch.float32(也称为torch.float)。
o_t = torch.tensor([1])
print(o_t)
t = torch.zeros((3, 3), out=o_t)
print(t, '\n', o_t)
print(id(t), id(o_t))
# 通过torch.zeros创建的张量不仅赋给了t,同时赋给了o_t,并且这两个张量是共享同一块内存,只是变量名不同。
"""
tensor([1])
tensor([[0, 0, 0],[0, 0, 0],[0, 0, 0]]) tensor([[0, 0, 0],[0, 0, 0],[0, 0, 0]])
2804923738192 2804923738192
"""
#从另一个张量初始化,保留形状,数据类型
#全为1的张量
print(torch.ones_like(a))
#rand_like,zeros_like#使用shape元组+随机值或常量值,也可以传入列表,也可以加,号
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
#依据给定的size创建
t1 = torch.tensor([[1., -1.], [1., -1.]])
t2 = torch.zeros_like(t1)
print(t2)
#类似创建全0,还有创建全1的:torch.ones(),torch.ones_like()
# torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)# 功能:依给定的size创建一个值全为fill_value的tensor。
print(torch.full((2, 3), 3.141592))
# 还有full_likeprint(torch.arange(1,6,2))#创建等差的1维张量,长度为 (end-start)/step,需要注意数值区间为[start, end)。
"""
tensor([[0., 0.],[0., 0.]])
tensor([[3.1416, 3.1416, 3.1416],[3.1416, 3.1416, 3.1416]])
tensor([1, 3, 5])
"""
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
"""
tensor([1., 1.], dtype=torch.float64)
Random Tensor: tensor([[0.4611, 0.4579, 0.1990],[0.7588, 0.5500, 0.7764]]) Ones Tensor: tensor([[1., 1., 1.],[1., 1., 1.]]) Zeros Tensor: tensor([[0., 0., 0.],[0., 0., 0.]])
"""
#属性
tensor = torch.rand(3,4)print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
"""
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
"""
#长度为steps 的均分一维张量
print(torch.linspace(3, 10, steps=5))
print(torch.linspace(1, 5, steps=3))
# 对数均分的1维张量,长度为steps, 底为base(默认10)
torch.logspace(start=0.1, end=1.0, steps=5)
torch.logspace(start=2, end=2, steps=1, base=2)
#单位对角矩阵
print(torch.eye(3))#如果列为空则创建方阵
print(torch.eye(3,4))#空张量,这里的“空”指的是不会进行初始化赋值操作,类似还有torch.empty_like()
print(torch.empty((2,3)))
#stride (tuple of python:ints) - 张量存储在内存中的步长,是设置在内存中的存储方式。
print(torch.empty_strided((2,5),(1,2)))
"""
tensor([ 3.0000,  4.7500,  6.5000,  8.2500, 10.0000])
tensor([1., 3., 5.])
tensor([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]])
tensor([[1., 0., 0., 0.],[0., 1., 0., 0.],[0., 0., 1., 0.]])
tensor([[0.0000, 1.8750, 0.0000],[1.8750, 0.0000, 1.8750]])
tensor([[0.0000e+00, 1.4013e-45, 0.0000e+00, 1.4013e-45, 0.0000e+00],[0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00]])
"""
mean = torch.arange(1,11.)
print(mean)
std = torch.arange(1,0,-0.1)
print(std)
torch.normal(mean = mean,std = std)
#1.3530是通过均值为1,标准差为1的高斯分布采样得来,# -1.3498是通过均值为2,标准差为0.9的高斯分布采样得来,以此类推
#在区间[0, 1)上,生成均匀分布。
print(torch.rand((2,3)))
#torch.rand_like之于torch.rand等同于torch.zeros_like之于torch.zeros
# 在区间[low, high)上,生成整数的均匀分布。
print(torch.randint(3,10,(3,3)))
#torch.randint_like# 生成形状为size的标准正态分布张量,torch.rafndn_like
print(torch.randn((2,3)))

torch.randperm(n, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False)

功能:生成从0到n-1的随机排列。perm == permutation

torch.bernoulli(input, *, generator=None, out=None)

功能:以input的值为概率,生成伯努力分布(0-1分布,两点分布)。

主要参数:

input (Tensor) - 分布的概率值,该张量中的每个值的值域为[0-1]

example:

p = torch.empty(3, 3).uniform_(0, 1)
b = torch.bernoulli(p)
print("probability: \n{}, \nbernoulli_tensor:\n{}".format(p, b))
"""
probability: 
tensor([[0.8256, 0.6711, 0.1326],[0.8749, 0.7119, 0.6666],[0.8028, 0.8902, 0.2548]]), 
bernoulli_tensor:
tensor([[0., 1., 0.],[1., 1., 1.],[0., 1., 1.]])
"""

张量操作

#转移到gpu
if torch.cuda.is_available():tensor = tensor.to("cuda")
print(torch.is_tensor(tensor))#Returns True if obj is a PyTorch tensor.
#判断复数,判断浮点型
#Returns True if the input is a single element tensor which is not equal to zero after type conversions.
test = torch.tensor(1.0)
print(torch.is_nonzero(test))
"""
True
True
"""
#切片+索引
tensor = torch.rand(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
"""
First row: tensor([0.5492, 0.0567, 0.2490, 0.5438])
First column: tensor([0.5492, 0.8558, 0.5434, 0.5295])
Last column: tensor([0.5438, 0.7757, 0.2420, 0.6499])
tensor([[0.5492, 0.0000, 0.2490, 0.5438],[0.8558, 0.0000, 0.8031, 0.7757],[0.5434, 0.0000, 0.0919, 0.2420],[0.5295, 0.0000, 0.7761, 0.6499]])
"""
#沿给定维度连接一系列张量,使用torch.cat((A,B),dim)时,除拼接维数dim数值可不同外其余维数数值需相同,方能对齐。
C = torch.cat( (A,B),0 )  #按维数0拼接(竖着拼)C = torch.cat( (A,B),1 )  #按维数1拼接(横着拼)t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
#torch.arange返回一维张量,range比arange长1
print(torch.arange(5))
print(torch.arange(1,5,3))
"""
tensor([0, 1, 2, 3, 4])
tensor([1, 4])
"""
#eye,对角线全为1
#填充
torch.full([2,2],5)#==torch.ones([2,2])*5
torch.ones([2,2])*5
"""
tensor([[5., 5.],[5., 5.]])
"""
#chunk尝试将张量拆分为指定数量的块。
b = torch.rand([3,2,])
print(b)
torch.chunk(b,chunks = 2)#各种堆叠,各种分割
"""
tensor([[0.2334, 0.3184],[0.6157, 0.6722],[0.3690, 0.3402]])(tensor([[0.2334, 0.3184],[0.6157, 0.6722]]),tensor([[0.3690, 0.3402]]))
"""
#gather
t = torch.tensor([[1,2],[3,4]])
torch.gather(t,1,torch.tensor([[0,0],[1,0]]))
"""
tensor([[1, 1],[4, 3]])
"""
# reshape,元素顺序不变
#scatter,inplace:原地操作,内存位置没有改变
# squeeze,对多余的维度压缩
# 将维度为1的维度移除
b = torch.rand([3,2])
print(b.shape)b = torch.reshape(b,[3,1,2])#只要保证列表元素个数相等就可以
print(b)b = torch.squeeze(b)
print(b)b = torch.reshape(b,[3,2,1,1,1])
print(b)
b = torch.squeeze(b,dim = 2)#从0开始
print(b.shape)
"""
torch.Size([3, 2])
tensor([[[0.5230, 0.6472]],[[0.1827, 0.7827]],[[0.3485, 0.8408]]])
tensor([[0.5230, 0.6472],[0.1827, 0.7827],[0.3485, 0.8408]])
tensor([[[[[0.5230]]],[[[0.6472]]]],[[[[0.1827]]],[[[0.7827]]]],[[[[0.3485]]],[[[0.8408]]]]])
torch.Size([3, 2, 1, 1])
"""
#stack,沿着新的维度拼接,tensor维度要一样
a = torch.rand([3,2])
b = torch.rand([3,2])
print(torch.stack([a,b],dim = 0).shape)
print(torch.stack([a,b],dim = 1).shape)
print(torch.stack([a,b],dim = 2).shape)
"""
torch.Size([2, 3, 2])
torch.Size([3, 2, 2])
torch.Size([3, 2, 2])
"""

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/871649.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【JavaEE】网络编程——TCP

&#x1f921;&#x1f921;&#x1f921;个人主页&#x1f921;&#x1f921;&#x1f921; &#x1f921;&#x1f921;&#x1f921;JavaEE专栏&#x1f921;&#x1f921;&#x1f921; 文章目录 前言1.网络编程套接字1.1流式套接字(TCP)1.1.1特点1.1.2编码1.1.2.1ServerSo…

华为USG6000V防火墙v1

目录 一、实验拓扑图 二、要求 三、IP地址规划 四、实验配置 1&#x1f923;防火墙FW1web服务配置 2.网络配置 要求1&#xff1a;DMZ区内的服务器&#xff0c;办公区仅能在办公时间内(9:00-18:00)可以访问&#xff0c;生产区的设备全天可以访问 要求2&#xff1a;生产区不…

电影《头脑特工队2》观后感

上周看了电影《头脑特工队2》&#xff0c;整体是非常不错的&#xff0c;一个大脑中&#xff0c;想象的世界。 &#xff08;1&#xff09;人格-多元政体理论 记得前几年是看过《头脑特工队1》的&#xff0c;当时电影是非常出名的&#xff0c;当时有很多研究理论&#xff0c;都…

【练习】分治--归并排序

&#x1f3a5; 个人主页&#xff1a;Dikz12&#x1f525;个人专栏&#xff1a;算法(Java)&#x1f4d5;格言&#xff1a;吾愚多不敏&#xff0c;而愿加学欢迎大家&#x1f44d;点赞✍评论⭐收藏 目录 归并排序 代码实现 交易逆序对的总数 题目描述 ​编辑 题解 代码实…

JAVA从入门到精通之入门初阶(二)

1. 自动类型转换 自动类型转换&#xff1a;类型范围小的变量可以赋值给类型范围大的变量 byte->int public class java_7_10 {public static void main(String[] args) {//自动类型转换//类型范围小的变量可以赋值给类型范围大的变量 byte->intbyte a 12;int b a;//自动…

C语言 ——— 输入两个正整数,求出最小公倍数

目录 何为最小公倍数 题目要求 代码实现 方法一&#xff1a;暴力求解法&#xff08;不推荐&#xff09; 方法二&#xff1a;递乘试摸法&#xff08;推荐&#xff09; 何为最小公倍数 最小公倍数是指两个或者多个正整数&#xff08;除了0以外&#xff09;的最小的公共倍数…

【LeetCode】205. 同构字符串

认真地分类讨论&#xff0c;评判复杂度&#xff0c;再决定是否要写代码执行。整套流程干净利落&#xff0c;不存在主观臆想&#xff0c;也不会有对事实结果计算的巨大偏差。 1. 题目 2. 分析 这里提供一版可以解题的思路。 定义两个词典&#xff0c;这两个词典分别记录s字符串…

DHC2-2多时段电子式时间继电器 带底座 约瑟JOSEF

DHC2多时段电子式时间继电器 DHC2-H多时段电子式时间继电器 DHC2-1多时段电子式时间继电器 DHC2-2多时段电子式时间继电器 DHC2-3多时段电子式时间继电器 一、特点 超小型面板尺寸DIN 36X36mm(DHC1)、DIN 48X48m(DHC2) 有延时吸合、延时释放、等周期循环三种规格 可替代…

kibana连接elasticsearch(版本8.11.3)

前言 elasticsearch在8版本之后就出现了很大变化&#xff0c;由于kibana版本需要需elasticsearch进行版本对象&#xff0c;kibana连接方式也出现了很大变化。我在这里记录下自己的踩坑记录。 服务部署 本文中的服务都是在docker环境中部署的。其中elasticsearch版本和kibana版…

5G-A通感融合赋能低空经济-RedCap芯片在无人机中的应用

1. 引言 随着低空经济的迅速崛起&#xff0c;无人机在物流、巡检、农业等多个领域的应用日益广泛。低空飞行器的高效、安全通信成为制约低空经济发展的关键技术瓶颈。5G-A通感一体化技术通过整合通信与感知功能&#xff0c;为低空网络提供了强大的技术支持。本文探讨了5G-A通感…

OpenCV 寻找棋盘格角点及绘制

目录 一、概念 二、代码 2.1实现步骤 2.2完整代码 三、实现效果 一、概念 寻找棋盘格角点&#xff08;Checkerboard Corners&#xff09;是计算机视觉中相机标定&#xff08;Camera Calibration&#xff09;过程的重要步骤。 OpenCV 提供了函数 cv2.findChessboardCorners…

什么? CSS 将支持 if() 函数了?

CSS Working Group 简称 CSSWG, 在近期的会议中决定将 if() 添加到 CSS Values Module Level 5 中。 详情可见&#xff1a;css-meeting-bot 、[css-values] if() function 当我看到这个消息的时候&#xff0c;心中直呼这很逆天了&#xff0c;我们知道像 less 这些 css 这些预…

用Speedtest-Tracker跟踪上网速度(续)

什么是 Speedtest Tracker ? Speedtest Tracker 是一款自托管互联网性能跟踪应用程序&#xff0c;可针对 Ookla 的 Speedtest 服务运行速度测试检查。 之前老苏介绍的另一个 https://github.com/henrywhitaker3/Speedtest-Tracker 已被放弃。现在这个是积极维护的替代品&#…

STM32编写代码之嵌入式常用位操作

在单片机编程的过程中&#xff0c;经常会遇到位操作进行赋值&#xff0c;例如 //程序1 int a 0,b 0x5b,c 0; //1 for (i 0; i < 8; i ) { //2a b & (0x80 >> i)); //3 c | (0x80 >> i); //4 } 这些位操作是什么意思呢&#xff1f…

GuLi商城-商品服务-API-品牌管理-JSR303自定义校验注解

自定义注解规则: 可以参考@NotNull注解 package com.nanjing.common.valid;import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target;i…

跨域解决方案

跨域 当发起请求的协议号、域名、端口号中有一个不一样时就会导致跨域 跨域解决方案 分为两个方面&#xff0c;是否可以修改服务器端。 可以修改服务器端&#xff1a;cors方案、jsonp方案 不可以修改服务器端&#xff1a; 使用代理&#xff1a; 因为跨域主要是针对浏览器…

T113-i系统启动速度优化方案

背景: 硬件:T113-i + emmc 软件:uboot2018 + linux5.4 + QT应用 分支:longan 问题: 全志T113-i的官方系统软件编译出的固件,开机启动时间10多秒,启动时间太长,远远超过行业内linux系统的开机速度,需要进一步优化。 T113-i 优化后启动速度实测数据 启动阶段启动时间(…

Fastgpt本地使用Docker Compose 快速部署

使用 Docker Compose 快速部署 FastGPT 部署架构图 MongoDB:用于存储除了向量外的各类数据 PostgreSQL/Milvus:存储向量数据 OneAPI: 聚合各类 AI API,支持多模型调用 (任何模型问题,先自行通过 OneAPI 测试校验) 推荐配置 PgVector版本 体验测试首选 环境最低配置(单…

MySql性能调优04-[MySql事务与锁机制原理]

MySql事务与锁机制原理 从undo与redo日志&#xff0c;理解事务底层ACID底层原理事务四大隔离级别事务底层锁机制和MVCC并发优化机制串行化底层实现机制读已提交和可重复读底层实现MVCC机制详解脏写问题(重要)读已提交&#xff1f;实现机制 BufferPool缓存与redo日志是如何提升事…

海康相机GrabImage

#include <stdio.h> #include <Windows.h> #include <process.h> #include <conio.h> #include "MvCameraControl.h"bool g_bExit false;// ch:等待按键输入 | en:Wait for key press void WaitForKeyPress(void) {while(!_kbhit()){Sleep(…