pytorch基础

pytorch基础

基础

tensor基础

import torch
a = torch.tensor([1,2,3],dtype=int)
b = torch.tensor([4,5,6],dtype=float)
#a.dtype b.dtype 类型 int64 float64

tensor = torch.tensor([[1,2,3],
                       [4,5,6]])
# 数据的维度
tensor.ndim

# 数据的形状
tensor.shape
tensor.size()

tensor.dtype  #torch.int64

数据生成

torch.ones(2,3)
torch.zeros(3,3)
torch.rand(3,4) #随机浮点
torch.randint(0,10,(2,3)) #0到10 2行三列
torch.randn(3,4) #随机正负

#numpy转换
import numpy as np
array = np.array([1,2,3])
tensor = torch.tensor(array)

数据的索引

tensor = torch.arange(2,14)  #2到13
#2,3,4,5,6,7,8,9,10,11,12,13

print(tensor[2]) #4
print(tensor[1:4]) #3,4,5
print(tensor[2:-1]) #4,5,6,7,8,9,10,11,12
print(tensor[:5]) #2, 3, 4, 5, 6 #下表从0到5
print(tensor[-3:]) #11,12,13
for t in tensor:
    print(t)

facebook推出
是一个torch的端口 主要语言是python

tensor属性


tensor.ndim 纬度
.shape 形状
.size()
.dtype

对象的属性和方法

数据生成

torch.rand()随机
.randint()随机整形

rand_like() 形状一样数值不一样

修改形状 view 相当于reshape

d[1].item() 输出一个值

numpy as np
no.array(tensor)
转tensor
torch.tensor(array)

基本运算1


add
a.add_(b) a=a+b
%去余
//取整

矩阵
torch.matmul(a,tensor) 23 35 = 2*5
转置
a.T

基本运算2


sum
min max

argmin 最小值的索引位置

mean 平均
argmax 中位数

**2 平方

索引


arange()

[1:4] 1到4
[2:-1]
[:5] 从头开始
[-3]一直取到最后

自动求导


requires_grad=true
梯度 out.backward()
x.grad

MNIST数据集
图片 数字
一张图片是28*28 =784

pytroch

vllm

2025-6-28 17:21:18

职投一股票

人在情绪周期里面的心理状态

2025-7-29 19:15:10

搜索