PyTorch框架学习-Day1-Tensor

1. Tensor

  • Tensor 相当于 NumPyndarrays
  • Tensor 可以使用 GPU 进行计算;

1. 不初始化,构建5x3矩阵

from __future__ import print_function
import torch

def not_init_array(row, column):
    x = torch.empty([row, column], dtype=float)
    return x

if __name__ == "__main__":
    print(not_init_array([5, 3]))
    
结果:
	tensor([[4.9407e-324,  0.0000e+00,  0.0000e+00],
        	[ 0.0000e+00,  0.0000e+00, 1.1032e-311],
        	[1.1032e-311, 9.8813e-324, 9.8813e-324],
        	[1.4822e-323,  0.0000e+00,  0.0000e+00],
        	[ 0.0000e+00, 1.4822e-323, 4.9407e-324]], dtype=torch.float64)

[注]:在不指定 dtype 类型时,默认值为float32

2. 构造一个随机初始化矩阵

import torch

def rand_array():
    x = torch.rand([5, 3], dtype=torch.float, requires_grad=False)
    return x

if __name__ == "__main__":
    print(rand_array())
    
结果:
	tensor([[0.4543, 0.7095, 0.5544],
        	[0.3758, 0.7982, 0.6718],
        	[0.2281, 0.5241, 0.0279],
        	[0.0862, 0.5257, 0.9148],
        	[0.0312, 0.8112, 0.6917]], dtype=torch.float64)

[注]:requires_grad为梯度计算,一般开关默认为False,需要进行梯度计算时,将其设置为True

3. 构建全0矩阵,数据类型为long

import torch

def zeros_array(row, colum):
    x = torch.zeros([row, colum], dtype=torch.long)
    return x

if __name__ == "__main__":
    print(zeros_array(4, 4))
    print(zeros_array().dtype)
    
结果:
	tensor([[0, 0, 0, 0],
        	[0, 0, 0, 0],
        	[0, 0, 0, 0],
        	[0, 0, 0, 0]])
	torch.int64

4. 构建一个张量,直接使用数据

import torch

def tensor():
    x = torch.tensor([8, 255, 255])
    return x

if __name__ == "__main__":
    print(tensor())
    
结果:
	tensor([  8, 255, 255])

5. 创建一个tensor基于已经存在的tensor

import torch

def new_basic_tensor(row, column):
    x = torch.ones([row, column], dtype=torch.double)  # x是一个tensor类型数据
    y = torch.randn_like(x, dtype=torch.float)
    
    return x, y

if __name__ == "__main__":
    res1, res2 = new_basic_tensor(3, 3)
    print(res1)
    print(res2)
    print(res2.size())  # 获取维度信息
    
结果:
	tensor([[1., 1., 1.],
        	[1., 1., 1.],
        	[1., 1., 1.]], dtype=torch.float64)
	tensor([[ 0.0287,  1.3357,  1.1125],
        	[-2.9300,  0.7372, -0.4044],
        	[ 0.1549, -1.3047, -1.4294]])
	torch.Size([3, 3])

[注]:torch.Size 是一个元组,支持左右元组操作


2. Tensor加法运算

1. 直接相加 tensor1 + tensor2

import torch

def t1_add_t2(row, column):
    x = torch.ones([row, column], dtype=torch.float)
    print(f"tensor x = {x}")
    
    y = torch.rand([row, column], dtype=torch.float)
    print(f"tensor y = {y}")
    
    return x + y

if __name__ == "__main__":
    print(f"tensor x+y = {t1_add_t2(3, 3)}")
    
    
结果:
	tensor x = tensor([[1., 1., 1.],
        	[1., 1., 1.],
        	[1., 1., 1.]]), dtype = torch.float32
	tensor y = tensor([[0.9242, 0.8121, 0.2289],
        	[0.0412, 0.1470, 0.9535],
        	[0.7616, 0.2433, 0.5139]]), dtype = torch.float32
	tensor x+y = tensor([[1.9242, 1.8121, 1.2289],
        	[1.0412, 1.1470, 1.9535],
        	[1.7616, 1.2433, 1.5139]])

2. 使用torch.add()函数

import torch

def add():
    x = torch.ones([3, 3])
    y = torch.ones([3, 3])
    
    return torch.add(x, y)

if __name__ == "__main__":
    print(add())
    
结果:
	tensor([[2., 2., 2.],
        	[2., 2., 2.],
        	[2., 2., 2.]])

3. 在add()函数上提供一个输出tensor作为参数

import torch

def add():
    x = torch.rand(3, 3)
    print(f"tensor x = {x}")
    y = torch.ones(3, 3)
    print(f"tensor y = {y}")
    
    result = torch.empty(3, 3)
    
    return torch.add(x, y, out=result)

if __name__ == "__main__":
    print(add())
    
结果:
	tensor x = tensor([[0.8031, 0.1675, 0.4783],
        	[0.4975, 0.5951, 0.7130],
        	[0.0187, 0.2694, 0.1196]])
	tensor y = tensor([[1., 1., 1.],
        	[1., 1., 1.],
        	[1., 1., 1.]])
	tensor([[1.8031, 1.1675, 1.4783],
        	[1.4975, 1.5951, 1.7130],
        	[1.0187, 1.2694, 1.1196]])

4. 加法:in-place方法

import torch

def in_place():
    x = torch.ones(5, 3)
    y = torch.ones_like(x)
    
    return y.add_(x)  # 这里使用的是 in_place加法,y.add_(x) 等价 torch.add(x, y)

if __name__ == "__main__":
    print(in_place())
    
结果:
	tensor([[2., 2., 2.],
        	[2., 2., 2.],
        	[2., 2., 2.],
        	[2., 2., 2.],
        	[2., 2., 2.]])

**[注]:任何使 张量(Tensor) 发生变化的操作都有一个前缀。eg:x.copy(y)、x.t_(),将会改变前缀 x. **


3. Tensor的其他操作方式

1. 使用索引操作

  • Tensor 可以使用标准的 NumPy 类似的 索引 操作;
import torch

def index_array():
    x = torch.rand(5, 3)
    print(f"tensor x = {x}")
    
    return x

if __name__ == "__main__":
    # 打印该矩阵列下标=1的所有数
    print(index_array()[:, 1])
    
结果:
	tensor x = tensor([[0.2170, 0.0599, 0.4345],
        	[0.4617, 0.3926, 0.6175],
        	[0.6764, 0.9664, 0.7748],
        	[0.0180, 0.3388, 0.9173],
        	[0.4653, 0.5886, 0.1087]])
    
	tensor([0.0599, 0.3926, 0.9664, 0.3388, 0.5886])

2. 改变Tensor大小形状

  • 使用 torch.view 方法实现改变 Tensor 大小形状;
import torch

def resize_array():
    x = torch.randn(4, 4)
    print(x)
    
    y = torch.view(16)  # 将(4, 4)矩阵改为(1, 16)矩阵,也就是一维矩阵
    print(y)
    
    z = torch.view(-1, 8)  # 将(4, 4)矩阵通过-1自动计算确定行数,列数为8
    print(z)
    
    return x.size(), y.size(), z.size()

if __name__ == "__main__":
    print(resize_array())
    
结果:
	tensor([[ 0.2900,  0.8518, -3.5446, -0.3621],
        	[-0.4792, -1.0429,  1.0261, -0.0310],
            [ 0.4935,  0.7629, -0.5164,  0.1652],
        	[-0.8043,  0.2716, -0.1145,  0.2164]])
    
	tensor([ 0.2900,  0.8518, -3.5446, -0.3621, -0.4792, -1.0429,  1.0261, -0.0310,
         	0.4935,  0.7629, -0.5164,  0.1652, -0.8043,  0.2716, -0.1145,  0.2164])
    
	tensor([[ 0.2900,  0.8518, -3.5446, -0.3621, -0.4792, -1.0429,  1.0261, -0.0310],
        	[ 0.4935,  0.7629, -0.5164,  0.1652, -0.8043,  0.2716, -0.1145,  0.2164]])
    
	(torch.Size([4, 4]), torch.Size([16]), torch.Size([2, 8]))

3. 获取一个元素tensor的value值

  • 若有一个元素 tensor,使用 .item() 来获取 value
import torch

def get_value():
    x = torch.rand(1)
    print(x)
    return x

if __name__ == "__main__":
    print(get_value.item())
    
结果:
	tensor([0.8983])
    
	0.8982625007629395
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch是一个用于深度学习的开源框架,它提供了一组工具和接口,使得我们可以轻松地进行模型训练、预测和部署。在PyTorch中,数据处理是深度学习应用的重要部分之一。 PyTorch中的数据处理主要涉及以下几个方面: 1.数据预处理:包括数据清洗、数据归一化、数据增强等操作,以提高模型的鲁棒性和泛化能力。 2.数据加载:PyTorch提供了多种数据加载方式,包括内置的数据集、自定义的数据集和数据加载器等,以便我们更好地管理和使用数据。 3.数据可视化:为了更好地理解数据和模型,PyTorch提供了多种数据可视化工具,如Matplotlib、TensorBoard等。 下面是一个简单的数据预处理示例,展示如何将图像进行归一化和数据增强: ```python import torch import torchvision.transforms as transforms from torchvision.datasets import CIFAR10 # 定义一个数据预处理管道 transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.2010]) ]) # 加载CIFAR10数据集,进行预处理 trainset = CIFAR10(root='./data', train=True, download=True, transform=transform_train) trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2) ``` 在上面的例子中,我们首先定义了一个数据预处理管道,其中包括了对图像进行随机裁剪、水平翻转、归一化等操作。然后,我们使用PyTorch内置的CIFAR10数据集,并将其预处理后,使用DataLoader进行批量加载。这个过程可以帮助我们更好地管理和使用数据,同时提高模型的训练效率和泛化能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值