从代码角度学习理解Pytorch学习框架01: Tensor的了解
# coding=utf-8
import numpy as np
import torch
"""Pytorch中tensor了解"""
def just_try():
# Tensor可以认为是一个高维数组,和numpy相似,但tensor可以用GPU加速
x = torch.FloatTensor(5, 3) # [torch.FloatTensor of size 5x3],预先分配空间
print('x: {}'.format(x))
print('x.size(): {}'.format(x.size())) # torch.Size([5, 3], torch.Size是tuple对象的子类,支持tuple的所有操作
y_tensor_gpu = x.cuda() # 转化为在GPU上的tensor
print('y_tensor_gpu: {}'.format(y_tensor_gpu))
def multiple_add():
x = torch.FloatTensor(3, 2)
y = torch.FloatTensor(3, 2)
# 第一种加法
result_1 = x + y
# 第二种加法
result_2 = torch.add(x, y)
# 第三种加法
result_3 = torch.FloatTensor(3, 2)
torch.add(x, y, out=result_3)
print('result_1: {}'.format(result_1))
print('result_2: {}'.format(result_2))
print('result_3: {}'.format(result_3))
def inplace_operation():
x = torch.FloatTensor(3, 2)
y = torch.FloatTensor(3, 2)
print('original y: {}'.format(y))
# 普通加法,不改变原始的y值
result_common = y.__add__(x)
print('common add, result_common: {}'.format(result_common))
print('common add, y: {}'.format(y))
# inplace 加法,改变y值
y.__iadd__(x)
print('inplace add, y: {}'.format(y))
def tensor_vs_numpy():
"""
tensor 和 numpy 之间的联系
:return:
"""
y = torch.FloatTensor(3, 2)
print('y: {}'.format(y))
# tensor的slice操作与numpy类似
print('y slice: {}'.format(y[:, 1]))
# 技巧: tensor与numpy之间的转换,互操作比较容易且快速,
# Tensor不支持的操作,可以先转换为numpy数组处理,之后再转回tensor
aa_tensor = torch.ones(3, 2)
print('orignal aa_tensor: {}'.format(aa_tensor))
# tensor ---> numpy
bb_numpy = aa_tensor.numpy() # Note: tensor和numpy之间共享内存,所以他们之间的转换很快,同时也意味着如果其中一个变了,
# 另外一个也会随之改变
print('bb_numpy: {}'.format(bb_numpy))
# numpy ---> tensor
cc_tensor = torch.from_numpy(bb_numpy)
print('cc_tensor: {}'.format(cc_tensor))
bb_numpy += 1
print('after adding one, bb_numpy: {}'.format(bb_numpy))
print('after adding one, aa_tensor: {}'.format(aa_tensor))
print('after adding one, cc_tensor: {}'.format(cc_tensor))
if __name__ == '__main__':
just_try()
# multiple_add()
# inplace_operation()
# tensor_vs_numpy()