欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【python pytorch】Pytorch 基础知识

程序员文章站 2024-01-30 10:51:46
...

包含知识点:

  • 张量
  • 数学操作
  • 数理统计
  • 比较操作
#-*-coding:utf-8-*-

import numpy as np
np.set_printoptions(suppress=True)
import torch



# 构造一个4*5 的矩阵
z=torch.Tensor(4,5)
print(z)

# 两个矩阵进行加法操作
y=torch.rand(4,5)

print(z+y)
# 另一种表示
print(torch.add(z,y))


# 将tensor 转换为numpy
b=y.numpy()

print(b)


# 数学操作绝对值
kk=torch.abs(torch.FloatTensor([-4,6,90]))
print(kk)

# 均值(行操作)
print(torch.mean(kk,0))

# 比较操作

m1=torch.equal(torch.Tensor([1,2]),torch.Tensor([1,2]))

m2=torch.equal(torch.Tensor([1,2]),torch.Tensor([2,2]))

m3=torch.eq(torch.Tensor([1,2]),torch.Tensor([2,2]))
m4=torch.gt(torch.Tensor([1,2]),torch.Tensor([2,2]))

print(m1)

print(m2)

print(m3)

print(m4)

运行结果:

tensor([[ 0.0000,  0.0000,  0.0000,  0.0000, -3.7296],
        [ 0.0000, -8.2118,  0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000, -4.0750,  0.0000, -8.2119],
        [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000]])
tensor([[ 0.3490,  0.7795,  0.1428,  0.2517, -3.1552],
        [ 0.0427, -7.5753,  0.1780,  0.7305,  0.7264],
        [ 0.2967,  0.2977, -3.8018,  0.2856, -8.0059],
        [ 0.9123,  0.6403,  0.8935,  0.9008,  0.6926]])
tensor([[ 0.3490,  0.7795,  0.1428,  0.2517, -3.1552],
        [ 0.0427, -7.5753,  0.1780,  0.7305,  0.7264],
        [ 0.2967,  0.2977, -3.8018,  0.2856, -8.0059],
        [ 0.9123,  0.6403,  0.8935,  0.9008,  0.6926]])
[[0.34903067 0.7795371  0.14277744 0.25165677 0.57442063]
 [0.04269707 0.63649714 0.17801785 0.73047435 0.72639245]
 [0.29670775 0.29770297 0.27317053 0.28561223 0.20602047]
 [0.91231096 0.6403226  0.8934667  0.90082955 0.69256335]]
tensor([  4.,   6.,  90.])
tensor(33.3333)
True
False
tensor([ 0,  1], dtype=torch.uint8)
tensor([ 0,  0], dtype=torch.uint8)

Process finished with exit code 0

中文教程:
https://pytorch.apachecn.org/#/