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

Pytorch复习

一、Tensor属性

import torch

#整数类型
a = torch.tensor([1, 2, 3],dtype = int)
print(a)
#查看数据类型
print(a.dtype)

#浮点数类型
b = torch.tensor([4,5,6],dtype = float)
print(b)
print(b.dtype)

tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
#查看维度
print(tensor.ndim)
#查看形状
print(tensor.shape)
print(tensor.size())

二、数据生成

import torch
import numpy as np

a = torch.ones(2,3)
print(a)

b = torch.zeros(3,3)
print(b)

c = torch.rand(3,4)
print(c)

d = torch.randint(0,10,(2,3))
print(d)

#随机生成符合正态分布的随机数
e = torch.randn(3,4)
print(e)

#生成一个三行两列的数据
f = torch.tensor([[1,2],[3,4],[5,6]])
print(f)
#生成跟f相同的数据
g = torch.rand_like(a,dtype = float)
print(g)

#修改数据形状
h = g.view(6)
h = g.reshape(6)

#查看tensor里的值
print(h[1].item)
#tensor转换为nparray
i = np.array(h)
array = np.array([1,2,3])
#nparray转换为tensor
tensor = torch.tensor(array)
print(tensor)

三、基本运算操作

import torch
import numpy as np

a = torch.randint(1,5,(2,3))
b = torch.randint(1,5,(2,3))
#加法
print(a + b)
print(torch.add(a,b))
#注意:add_()是inplace操作,即直接修改a的值
a.add_(b)

#减法
print(a - b)
print(torch.sub(a,b))
#乘法
print(a * b)
print(torch.mul(a,b))
#除法
print(a / b)
print(torch.div(a,b))
#取余数
print(a % b)
print(torch.fmod(a,b))
#取整
print(a // b)
print(torch.floor_divide(a,b))
#矩阵乘法
tensor = torch.ones(3,5,dtype = int)
print(torch.matmul(a,tensor))
#矩阵的转置
print(a.T)
sample = torch.rand(2,3)
#求和
print(torch.sum(sample))
#求均值
print(torch.mean(sample))
#求最大值
print(torch.max(sample))
#求最大值所在的索引
print(torch.argmax(sample))
#求最小值
print(torch.min(sample))
#求最小值所在的索引
print(torch.argmin(sample))
#求方差
print(torch.var(sample))
#求标准差
print(torch.std(sample))
#求对数
print(torch.log(sample))

四、数据索引

import torch
import numpy as np

tensor = torch.arange(2,14)
print(tensor)
#取第三个数据
print(tensor[2])
#取第3到第5个数据
print(tensor[2:5])
#取第3个数据到倒数第二个数据
print(tensor[2:-1])

print(tensor[:5])
print(tensor[-3:])


index = [1,3,4,5,5]
print(tensor[index])

五、自动求导

import torch
#requires_grad表示可以计算它的梯度
x = torch.ones((2,2),requires_grad = True)

y = x + 2
z = y * y * 3
out = z.mean()
print(out)
#求导,计算梯度
out.backward()
print(x.grad)

http://www.kler.cn/news/365010.html

相关文章:

  • 机器人学习仿真框架
  • Flutter 状态管理框架Get
  • 人工智能的未来:重塑生活与工作的变革者
  • 文档透明加密系统怎么用?五款透明加密软件汇总!2024热门推荐,实测分享!
  • 基于Spring Boot的宿舍管理系统设计与实现(源码+定制+开发)宿舍信息管理平台、智能宿舍系统开发、学生宿舍管理平台设计、宿舍入住与信息管理
  • WISE:重新思考大语言模型的终身模型编辑与知识记忆机制
  • Python自动化测试+邮件推送+企业微信推送+Jenkins
  • 如何做出高质量的PPT报告
  • Python画笔案例-092 绘制 吃豆人图案
  • The First:Starknet如何让以太坊更快更安全?
  • 202409电子学会青少年机器人技术等级考试(一级)真题
  • 华为云数据治理中心:全面保护您的业务安全
  • spark统一内存模型 详解
  • 【重学 MySQL】七十七、掌握存储过程与存储函数的查看、修改与删除技巧
  • nginx的负载均衡配置和重定向
  • FFmpeg 库的简要说明
  • 1.ubuntu下安装noetic
  • vue2解决uniapp使用uview的u-popup弹出层,遮罩下主页面还可以滑动问题
  • 【AscendC算子开发】笔记2 算子高级开发和调试调优
  • C++STL面试题笔记 01 vector、list
  • 电脑无法开机,怎么解决?
  • 10分钟快速学会Git使用
  • Codeforces Round 660 (Div. 2) D. Captain Flint and Treasure(图论建模,拓扑排序)
  • 【树莓派 5B】anaconda换源 更换清华源
  • MapReduce 与 Spark 的shuffle对比
  • 活动预告丨CCF开源发展委员会“开源高校行”第二十九期—北京理工大学站