tensors学习

import torch
import numpy as np
data = [[1, 2],[3, 4]]
# Directly from data
x_data = torch.tensor(data)
# print(type(x_data))       # <class 'torch.Tensor'>
# From a NumPy array
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# print(type(np_array))     # <class 'numpy.ndarray'>
# print(type(np))           # <class 'module'>
# From another tensor:
x_ones = torch.ones_like(x_data)  # retains the properties of x_data
# print(f"Ones Tensor: \n {x_ones} \n")
# Ones Tensor: tensor([[1, 1],[1, 1]])
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
# print(f"Random Tensor: \n {x_rand} \n")
# Random Tensor: tensor([[0.3573, 0.3780],[0.8495, 0.2994]])
shape = (2, 3, ) # 设置矩阵形状 2行 3列
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

# print(f"Random Tensor:\n {rand_tensor}\n")
# print(f"Ones Tensor:\n {ones_tensor}\n")
# print(f"Zeros Tensor:\n {zeros_tensor}")

tensor = torch.rand(3,4)
# print(f"Shape of tensor:{tensor.shape}")
# print(f"Datatype of tensor:{tensor.dtype}")
# print(f"Device tensor is stored on:{tensor.device}")

# Operations on Tensors
# We move our tensor to the current accelerator if available
if torch.accelerator.is_available():
    tensor = tensor.to(torch.accelerator.current_accelerator())

# print(f"Device tensor is stored on:{tensor.device}")

tensor = torch.ones(4, 4)
# print(f"First row: {tensor[0]}")  # tensor[0] 选取张量的第一行(索引从 0 开始)。
# print(f"First column: {tensor[:, 0]}")  # : 表示选取所有行。0 表示选取第一列。整体效果是选取张量的第一列。
# ... 是 Ellipsis 对象的简写,用于表示在多维张量中选择 "所有其他维度"。
# 这里它等价于写多个冒号(如 :),具体取决于张量的维度。-1 表示选取最后一列。
# print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0 # 是一个张量赋值操作,其作用是将张量的特定列全部设为 0。具体来说:
# : 表示所有行 1表示选择第二列(索引从0开始)整体效果将张量的第二列全部元素赋值为0
# print(tensor)
# 加入张量你可以用torch.cat沿着给定的维数连接一系列张量。请参见火炬.栈,另一个张量连接运算符,与torch.cat
t1 = torch.cat([tensor, tensor, tensor], dim=1)
# print(t1)

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
# 计算两个张量之间的矩阵乘法。y1,y2,y3将具有相同的值# ``tensor.T ``返回张量的转置
print(tensor)
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
print(y1)
print(y2)
print(y3)
torch.matmul(tensor, tensor.T, out=y3)

tensor = torch.ones(4, 4)

posted @ 2025-06-03 21:24  长恨水长东  阅读(10)  评论(0)    收藏  举报