PyTorch基础

这是有关PyTorch的简单的笔记。
由于缺少必要的解释,所以不适合自学
自学还是建议好好看下书或者PyTorch的官网教学

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import torch
import numpy as np

# 利用torch创建的矩阵叫做Tensor张量
# 创建5*3的0矩阵
x = torch.empty(5 * 3)
print(x)
# 创建5*3的随机矩阵
x = torch.randn(5, 3)
print(x)
# 创建5*3的0矩阵并指定类型
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
# 创建矩阵并指定数据
x = torch.tensor([5.5, 3])
print(x)
# 从已有的张量创建张量
x = torch.ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float)
print(x)
# 获取大小,返回的是个元组
print(x.size())

# 运算操作
y = torch.rand(5, 3)  # randn是从标准正态分布中返回值,rand是从[0,1)中返回值
print(x + y)
print(torch.add(x, y))
y.add_(x)
print(y)
# 将运算结果赋给变量
result = torch.add(x, y)
print(result)
# 也可以通过指定的方式赋给变量
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)

# 重造结构
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)
print(x.size(), y.size(), z.size())

# 获取值
x = torch.randn(4, 4)
print(x)
print(x[0][0])
x = torch.randn(1)  # 当只有一个元素的时候可以直接item访问
print(x)
print(x.item())

# Numpy Array和Torch Tensor的转换
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
a.add_(1)  # 这种方式是浅赋值,即a变化了b也会变
# tensor中对自己的操作都有一个_
print(a)
print(b)

a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

# 利用GUP来运算
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!

# input = input("Press <enter>")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值