"""
Created on 2023/1/3 10:06.
@Author: haifei
"""
from __future__ import print_function # 必须放在第一行
import torch
import time
# 构造一个5x3矩阵,不初始化
x = torch.empty(5, 3)
print(x)
"""
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
"""
# 构造一个随机初始化的矩阵
x = torch.rand(5, 3)
print(x)
'''
tensor([[0.6776, 0.6315, 0.9299],
[0.8867, 0.6325, 0.2507],
[0.2035, 0.6077, 0.9731],
[0.6938, 0.7488, 0.1132],
[0.6091, 0.5762, 0.4716]])
'''
# 构造一个矩阵全为 0,而且数据类型是 long
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
'''
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
'''
# 直接使用数据构造一个张量
x = torch.tensor([5.5, 3])
print(x)
'''
tensor([5.5000, 3.0000])
'''
# 创建一个 tensor 基于已经存在的 tensor
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
'''
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
'''
x = torch.rand_like(x, dtype=torch.float)
print(x)
'''
tensor([[0.5983, 0.0666, 0.9064],
[0.4012, 0.6202, 0.8771],
[0.0147, 0.7532, 0.9623],
[0.5253, 0.5974, 0.5697],
[0.4968, 0.1105, 0.4458]])
'''
# 获取它的维度信息
print(x.size()) # 是一个元组,所以它支持左右的元组操作
'''
torch.Size([5, 3])
'''
y = torch.rand(5, 3)
# torch加法方式1
print(x + y)
'''
tensor([[1.1285, 0.5830, 0.0489],
[0.9867, 0.8027, 0.6900],
[1.0094, 0.9405, 0.9767],
[1.5128, 1.1366, 0.7828],
[1.3099, 1.0841, 0.7579]])
'''
# torch加法方式2
print(torch.add(x, y))
'''
tensor([[1.1285, 0.5830, 0.0489],
[0.9867, 0.8027, 0.6900],
[1.0094, 0.9405, 0.9767],
[1.5128, 1.1366, 0.7828],
[1.3099, 1.0841, 0.7579]])
'''
# torch加法方式3: 提供一个输出 tensor 作为参数
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
'''
tensor([[1.1285, 0.5830, 0.0489],
[0.9867, 0.8027, 0.6900],
[1.0094, 0.9405, 0.9767],
[1.5128, 1.1366, 0.7828],
[1.3099, 1.0841, 0.7579]])
'''
# torch加法方式4: in-place: adds x to y
y.add_(x)
print(y)
'''
tensor([[1.1285, 0.5830, 0.0489],
[0.9867, 0.8027, 0.6900],
[1.0094, 0.9405, 0.9767],
[1.5128, 1.1366, 0.7828],
[1.3099, 1.0841, 0.7579]])
'''
# 可以使用标准的 NumPy 类似的索引操作
print(x[:, 1])
'''
tensor([0.0025, 0.3533, 0.6957, 0.6749, 0.7565])
'''
# 改变一个 tensor 的大小或者形状
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)
print(x.size(), y.size(), z.size())
'''
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
'''
# 如果你有一个元素 tensor ,使用 .item() 来获得这个 value
x = torch.randn(1)
print(x) # tensor([0.4217])
print(x.item()) # 0.42166027426719666
if __name__ == '__main__':
start = time.time()
print('It takes', time.time() - start, "seconds.")
标签:__,0.6900,tensor,PyTorch1,torch,张量,time,print,Tensors From: https://www.cnblogs.com/yppah/p/17021329.html