基础学习——关于list、numpy、torch在float和int等数据类型转换方面的总结

系列文章目录

Numpy学习——创建数组及常规操作(数组创建、切片、维度变换、索引、筛选、判断、广播)
Tensor学习——创建张量及常规操作(创建、切片、索引、转换、维度变换、拼接)
基础学习——numpy与tensor张量的转换
基础学习——关于list、numpy、torch在float和int等数据类型转换方面的总结



前言

因为自己最近总是遇到一些list、numpy、torch的数据类型转换错误,特别是不同类型间的float转int或int转float,总是遇到错误,所以在这里总结一下。


1、数据类型介绍

Python中基本数据类型主要可分为以下几种:
1.数字(Number);
2.字符串(String);
3.列表(List);
4.字典(Dictionary);
5.元组(Tuple);

在Python3中,支持的数字类型有:
1.int–整型
2.float–浮点型
3.bool–布尔型
4.fractions–分数
5.complex–复数

2、numpy与torch的一些数组函数的区别

导入包

import torch
import torch.nn as nn
import numpy as np 
import math

1、empty()

空数组:返回给定形状和类型的新数组,而不初始化条目

a = np.empty([3,3]) 
b = torch.empty([3,3])
print(a)
print(b)

结果:

[[6.23042070e-307 4.67296746e-307 1.69121096e-306]
 [3.22647253e-307 2.67018777e-306 1.42413555e-306]
 [1.78019082e-306 1.37959740e-306 2.29178686e-312]]
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

2、randint()

随机生成整数

a= np.random.randint(40, 100, (3, 4))
b = torch.randint(40, 100, (3, 4))
print(a)
print(b)

结果:

[[46 47 55 88]
 [73 96 44 98]
 [96 41 64 45]]
tensor([[98, 65, 57, 97],
        [90, 74, 45, 64],
        [67, 54, 79, 45]])

3、normal()

创建符合正态分布的4行5列数据

a = np.random.normal(0, 1, (4, 5))
b = torch.normal(0, 1, size = (4, 5))   
print(a)
print(b)

结果;

[[-0.97259852  1.51207726  0.54528577  1.1024245   0.47090239]
 [ 0.03231742  0.51741803  0.25911092 -1.14377841 -0.02595822]
 [-0.42955202 -0.25546385  0.74112698 -1.57833126  0.69611583]
 [ 0.08953791  0.32776525  0.74939352 -0.43138969  0.26458097]]
tensor([[ 0.6898,  0.4377,  1.8008, -1.3965, -1.7741],
        [-0.0722,  0.6072,  0.1556,  0.2961, -0.6501],
        [-1.6929, -1.0789,  2.0120,  1.0724,  1.6193],
        [ 1.1412, -0.9807,  0.5462, -0.3795, -1.2053]])

4、transpose()

维度转换函数np和torch的区别

import torch
import numpy as np 
a= np.random.randint(40, 100, (3, 4,5))
b = np.transpose(a,(2,1,0))
print(a.shape)
print(b.shape)

# torch.transpose只能由两个维度交换
c = torch.randn(2,3,4)
d = torch.transpose(c,0,1)
print(c.shape)
print(d.shape)

结果:

(3, 4, 5)
(5, 4, 3)
torch.Size([2, 3, 4])
torch.Size([3, 2, 4])

3、int和float的转换

导入包

import torch
import torch.nn as nn
import numpy as np 
import math

1、一个数的转换

a = float(1.0)
b = int(a)
print(a)
print(b)

结果:

1.0
1

2、list类型转换

列表类型转换

a = [0.0567, 9.2345, 8.1986, 4.3333]
c = [1,2,3,4]

b = [int(a) for a in a] # 或者用下面这个
# b = list(map(int, a))
# b = [math.ceil(a) for a in a]

print(a)
print(b)
d = list(map(float, c))
print(c)
print(d)

结果:

[0.0567, 9.2345, 8.1986, 4.3333]
[0, 9, 8, 4]
[1, 2, 3, 4]
[1.0, 2.0, 3.0, 4.0]

3、numpy类型转换

numpy float 转 int
其他类型转换也是一样的

a = np.array([1, 2], dtype = 'float32')        # dtype参数
print(a.dtype,a)
b = a.astype(np.int8)  
print(b.dtype,b)

结果:

float32 [1. 2.]
int8 [1 2]

astype里的类型还可以填这些:
在这里插入图片描述

4、torch数据类型转换

在Tensor后加.long(), .int(), .float(), .double()

a = torch.tensor([1, 2], dtype =torch.int8)        # dtype参数
print(a.dtype,a)
b = a.float()
print(b.dtype,b)

结果:

torch.int8 tensor([1, 2], dtype=torch.int8)
torch.float32 tensor([1., 2.])

用.to()函数进行转换

a = torch.tensor([1, 2], dtype =torch.uint8)        # dtype参数
print(a.dtype,a)
b = a.to(dtype =torch.float32)
print(b.dtype,b)

结果:

torch.uint8 tensor([1, 2], dtype=torch.uint8)
torch.float32 tensor([1., 2.])

其他类型转换也是一样的。
下面是一些类型的名称。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个DeepFashion数据集的PyTorch数据处理示例,包括数据清洗、数据预处理、数据增强、数据划分、标注处理和数据存储: ```python import os import numpy as np import cv2 import json from sklearn.model_selection import train_test_split import torch from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler # 定义DeepFashion数据集路径和预处理参数 data_dir = '/path/to/deepfashion/dataset' img_size = (256, 256) train_val_ratio = 0.9 val_test_ratio = 0.5 max_rotation_angle = 10 # 自定义数据集类 class DeepFashionDataset(Dataset): def __init__(self, data_dir, lines): self.data_dir = data_dir self.lines = lines def __len__(self): return len(self.lines) def __getitem__(self, idx): line = self.lines[idx] img_path = os.path.join(self.data_dir, 'Img', 'train', line[0]) bbox = line[1:] img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, img_size) rotation_angle = np.random.uniform(-max_rotation_angle, max_rotation_angle) M = cv2.getRotationMatrix2D((img_size[0] / 2, img_size[1] / 2), rotation_angle, 1.0) img = cv2.warpAffine(img, M, img_size) img = np.transpose(img, (2, 0, 1)).astype(np.float32) / 255.0 bbox = np.array(bbox, dtype=np.float32) return img, bbox # 读取标注文件,并进行数据清洗和划分 with open(os.path.join(data_dir, 'Anno/list_bbox.txt'), 'r') as f: lines = f.readlines()[2:] # 跳过前两行 lines = [line.strip().split() for line in lines] lines = [[line[0], *map(int, line[1:])] for line in lines] lines = [line for line in lines if line[3] > 0 and line[4] > 0] # 去掉宽度或高度为0的标注 train_lines, val_test_lines = train_test_split(lines, train_size=train_val_ratio, random_state=42) val_lines, test_lines = train_test_split(val_test_lines, train_size=val_test_ratio, random_state=42) # 创建数据集和数据加载器 train_dataset = DeepFashionDataset(data_dir, train_lines) val_dataset = DeepFashionDataset(data_dir, val_lines) test_dataset = DeepFashionDataset(data_dir, test_lines) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=32) test_loader = DataLoader(test_dataset, batch_size=32) # 将训练集、验证集和测试集数据保存到本地文件中 torch.save(train_loader, os.path.join(data_dir, 'train_loader.pth')) torch.save(val_loader, os.path.join(data_dir, 'val_loader.pth')) torch.save(test_loader, os.path.join(data_dir, 'test_loader.pth')) ``` 以上是一个简单的DeepFashion数据集的PyTorch数据处理示例,其中使用了自定义数据集类和数据加载器来加载数据,并将数据集和数据加载器保存到本地文件中。具体实现可以根据实际需求和数据集特点进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chaoy6565

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值