点击查看代码
# -*- coding: utf-8 -*-
# @Author : 钱力
# @Time : 2024/7/26 10:36
import torch
a = torch.arange(5)
b = a[2:] # 截取a的部分值
print('a', a)
print('b', b)
# 打印存储地址
# 可以发现他们共用存储区
# b的索引比a偏移了2位
print(a.untyped_storage().data_ptr())
print(b.untyped_storage().data_ptr())
print('=======================')
# 修改b,a也会被修改
b[1] = 0
print('a', a)
print('b', b)
print(a.untyped_storage().data_ptr())
print(b.untyped_storage().data_ptr())
# 张量的stride
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([[1, 2], [3, 4], [5, 6]])
print('a:', a)
print('stride of a:', a.stride())
print('b:', b)
print('stride of b:', b.stride())
# 数值固定的向量
x = torch.zeros(2, 3)
print(x)
x = torch.ones(2, 3)
print(x)
y = torch.empty(3, 4) # 随机划一块内存,不给初始化
x = torch.zeros_like(y) # 全零尺寸和一样
print(y)
# 均值为1,方差为0的保准正态分布
x = torch.randn(3, 4) # 标准正态分布
print('x:', x)
# 均匀分布
x = torch.rand(3, 4)
print(x)
# 生成特殊数组
# tenser = torch.arange(0, 16).view(4, 4) # 0到15,把数据按4x4格式排列
# print(tenser)
#
# mask = torch.eye(4, dtype=torch.bool)#对角线矩阵
# print(mask)
#
# tensor = torch.masked_fill(mask,100)
# print(tensor)
# 一维的mask
x = torch.tensor([1, 0, -1])
mask = x.ge(0.5) # 对于数组(或类似数组的数据结构)x中的每一个元素,检查它是否大于等于0.5。生成布尔数组
print('mask:', mask)
y = torch.masked_select(x, mask)
print(y)
# 与人工智能相关的操作
x = torch.randn(3, 4)
print(x)
y = torch.sigmoid(x)
print('sigmoid', y)
y = torch.softmax(x, dim=-1)
print('softmax', y)
y = torch.relu(x)
print('relu', y)
y = torch.tanh(x)
print('tanh', y)
# 向量的计算
x = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float16)
y = torch.tensor([6, 7, 8, 9, 10], dtype=torch.float16)
print(x * y) # 对应元素相乘
# 求余弦相似度
print(torch.nn.CosineSimilarity(dim=-1)(x, y)) # 这是神经网络的一层,但是没有参数
print(torch.nn.functional.cosine_similarity(x, y, dim=-1)) # 纯函数
x = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32)
y = torch.tensor([6, 7, 8, 9, 10], dtype=torch.float32)
z = torch.dot(x, y) # 内积
print('内积:', z)
z = torch.outer(x, y) # 外积
print('外积:', z)
# 基本矩阵运算
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
y = torch.tensor([[3, 4], [5, 6]], dtype=torch.float32)
# 对应元素相乘
print(x * y)
# 矩阵乘法
print(torch.matmul(x, y))
# 矩阵计算
x = torch.tensor([[2, 1, 3],
[6, 5, 4]])
y = torch.sum(x) # 所有值相加
print('sum:', y)
y = torch.pow(x, 3) # 全部3次方
print('pow:', y)
y = torch.argmax(x) # 返回矩阵最大的元素
print('argmax,全量', y)
y = torch.argmax(x, dim=0) # 返回特定维度最大元素的索引
print('argmax dim=0', y)
y = torch.argmax(x, dim=1)
print('argmax dim=1', y)