3、PyTorch张量的运算API(下)
文章目录
- 1. 数值转换
- 2. 相关API
1. 数值转换
12.34 = 16# 4145 7074
16# 4145 7074 = 12.34
import struct
class IEEE754Converter:
@staticmethod
def float_to_hex(f):
"""
将浮点数转换为IEEE 754格式的16进制表示
"""
binary_representation = struct.pack('>f', f)
hex_representation = ''.join(f'{byte:02X}' for byte in binary_representation)
return f"16#{hex_representation}"
@staticmethod
def hex_to_float(hex_str):
"""
将IEEE 754格式的16进制表示转换为浮点数
"""
if not hex_str.startswith("16#"):
raise ValueError("输入必须以 '16#' 开头")
hex_value = hex_str[3:] # 去掉 "16#"
if len(hex_value) != 8:
raise ValueError("无效的16进制格式(需要8位字符)")
binary_representation = bytes.fromhex(hex_value)
return struct.unpack('>f', binary_representation)[0]
# 测试
converter = IEEE754Converter()
# 浮点数转16进制
# input_float = 50.8
input_float = 12.34
hex_result = converter.float_to_hex(input_float)
print(f"输入: {input_float}, 转换为: {hex_result}")
# 16进制转浮点数
input_hex = hex_result
float_result = converter.hex_to_float(input_hex)
print(f"输入: {input_hex}, 转换为: {float_result}")
- 结果:
输入: 12.34, 转换为: 16#414570A4
输入: 16#414570A4, 转换为: 12.34000015258789
2. 相关API
- 重点:torch.take,torch.where,torch.randperm
- python
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :pytorch_learn3.py
# @Time :2024/11/17 16:08
# @Author :Jason Zhang
import torch
torch.manual_seed(12232)
if __name__ == "__main__":
run_code = 0
test_a = torch.randint(1, 20, (4, 5))
index_a = torch.randint(1, 10, (1, 10))
take_a = torch.take(input=test_a, index=index_a)
print(f"test_a=\n{test_a}")
print(f"index_a={index_a}")
print(f"take_a=\n{take_a}")
test_b = torch.arange(12).reshape(3, 4)
index_b = [2, 3]
tile_b = torch.tile(test_b, index_b)
print(f"test_b=\n{test_b}")
print(f"index_b=\n{index_b}")
print(f"tile_b=\n{tile_b}")
test_c = torch.arange(24).reshape(2, 3, 4)
transpose_01_c = torch.transpose(test_c, 0, 1)
transpose_02_c = torch.transpose(test_c, 0, 2)
transpose_12_c = torch.transpose(test_c, 1, 2)
print(f"shape={test_c.shape};test_c=\n{test_c}")
print(f"shape={transpose_01_c.shape};transpose_01_c=\n{transpose_01_c}")
print(f"transpose01 from {test_c.shape} -->{transpose_01_c.shape}")
print(f"transpose02 from {test_c.shape} -->{transpose_02_c.shape}")
print(f"transpose12 from {test_c.shape} -->{transpose_12_c.shape}")
test_d = torch.arange(12).reshape(3, 4)
unbind_d0 = torch.unbind(test_d)
unbind_d1 = torch.unbind(test_d, dim=1)
print(f"test_d=\n{test_d}")
print(f"unbind_d0=\n{unbind_d0}")
print(f"unbind_d1=\n{unbind_d1}")
test_e = torch.arange(12).reshape(3, 4)
un_squeeze_d = torch.unsqueeze(test_e, dim=0)
print(f"test_e=\n{test_e}")
print(f"un_squeeze_d=\n{un_squeeze_d}")
print(f"un_squeeze_0 from {test_e.shape} to --> {un_squeeze_d.shape}")
test_f = torch.randn(3, 4)
condition_f = torch.zeros_like(test_f)
where_f = torch.where(test_f > 0, test_f, condition_f)
print(f"test_f=\n{test_f}")
print(f"condition_f=\n{condition_f}")
print(f"where_f=\n{where_f}")
test_uniform = torch.empty(3, 3).uniform_(0, 1)
test_bernoulli = torch.bernoulli(test_uniform)
print(f"test_uniform=\n{test_uniform}")
print(f"test_bernoulli=\n{test_bernoulli}")
test_normal = torch.normal(mean=0, std=3, size=(1, 4))
print(f"test_normal=\n{test_normal}")
test_rand = torch.rand((3, 4))
print(f"test_rand=\n{test_rand}")
test_ones = torch.ones((4, 5))
test_rand_like = torch.rand_like(test_ones)
print(f"test_ones=\n{test_ones}")
print(f"test_rand_like=\n{test_rand_like}")
test_randint = torch.randint(1, 10, (3, 4))
print(f"test_randint=\n{test_randint}")
test_randn = torch.randn((3,4))
print(f"test_randn=\n{test_randn}")
test_randperm = torch.randperm(8)
print(f"test_randperm={test_randperm}")
- 结果:
test_a=
tensor([[10, 10, 13, 9, 13],
[18, 3, 18, 13, 14],
[12, 3, 2, 6, 15],
[17, 10, 8, 3, 19]])
index_a=tensor([[3, 8, 1, 3, 4, 7, 3, 4, 3, 9]])
take_a=
tensor([[ 9, 13, 10, 9, 13, 18, 9, 13, 9, 14]])
test_b=
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
index_b=
[2, 3]
tile_b=
tensor([[ 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3],
[ 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7],
[ 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11],
[ 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3],
[ 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7],
[ 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11]])
shape=torch.Size([2, 3, 4]);test_c=
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
shape=torch.Size([3, 2, 4]);transpose_01_c=
tensor([[[ 0, 1, 2, 3],
[12, 13, 14, 15]],
[[ 4, 5, 6, 7],
[16, 17, 18, 19]],
[[ 8, 9, 10, 11],
[20, 21, 22, 23]]])
transpose01 from torch.Size([2, 3, 4]) -->torch.Size([3, 2, 4])
transpose02 from torch.Size([2, 3, 4]) -->torch.Size([4, 3, 2])
transpose12 from torch.Size([2, 3, 4]) -->torch.Size([2, 4, 3])
test_d=
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
unbind_d0=
(tensor([0, 1, 2, 3]), tensor([4, 5, 6, 7]), tensor([ 8, 9, 10, 11]))
unbind_d1=
(tensor([0, 4, 8]), tensor([1, 5, 9]), tensor([ 2, 6, 10]), tensor([ 3, 7, 11]))
test_e=
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
un_squeeze_d=
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]])
un_squeeze_0 from torch.Size([3, 4]) to --> torch.Size([1, 3, 4])
test_f=
tensor([[-1.0091, -1.6478, 0.2227, -0.6253],
[-1.1560, -0.3321, 0.6481, -0.6534],
[-0.0812, 0.3430, -0.5654, 1.3285]])
condition_f=
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
where_f=
tensor([[0.0000, 0.0000, 0.2227, 0.0000],
[0.0000, 0.0000, 0.6481, 0.0000],
[0.0000, 0.3430, 0.0000, 1.3285]])
test_uniform=
tensor([[0.8787, 0.1452, 0.5137],
[0.3538, 0.1417, 0.2804],
[0.5722, 0.0614, 0.8160]])
test_bernoulli=
tensor([[1., 0., 1.],
[0., 0., 0.],
[0., 0., 1.]])
test_normal=
tensor([[ 1.4836, 3.7629, -0.9947, 3.2829]])
test_rand=
tensor([[0.8395, 0.9317, 0.4699, 0.1299],
[0.6146, 0.6594, 0.6898, 0.4271],
[0.1025, 0.0930, 0.0631, 0.8740]])
test_ones=
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
test_rand_like=
tensor([[0.2708, 0.1703, 0.9583, 0.3686, 0.9401],
[0.9255, 0.0381, 0.8322, 0.0164, 0.3185],
[0.9103, 0.2022, 0.8393, 0.8391, 0.3060],
[0.9032, 0.6207, 0.4548, 0.8162, 0.6557]])
test_randint=
tensor([[5, 2, 3, 2],
[7, 5, 4, 8],
[5, 6, 4, 3]])
test_randn=
tensor([[ 2.5142, -0.9164, 0.9966, -0.3689],
[ 1.4050, 1.1789, -0.0524, -0.4698],
[ 0.5387, -1.1596, 0.1878, -0.7700]])
test_randperm=tensor([3, 5, 1, 4, 6, 0, 2, 7])