【人工智能概论】 利用Dataset、DataLoader将excel、csv文件构建成数据集
本质上讲就是利用pandas模块中的read_excel,read_csv方法进行数据读取,利用Dataset,DataLoader构建数据集
- 废话少说直接上代码
import torch
import pandas
import numpy as np
from torch.utils.data import Dataset,DataLoader
class ExcelDataset(Dataset):
def __init__(self,filepath=r"./dataset/dataset_test01.xlsx",sheet_name = 0):
# sheet_name = 0 默认读第一个表单
print(f"reading {filepath},sheet={sheet_name}") # 打印日志
df = pandas.read_excel(
filepath,header=0,index_col=[3,5],
names=['pH','pH/mV','Turb/NTU',"ID",'let','id'],
sheet_name=sheet_name,
dtype={'pH':np.float32,'pH/mV':np.float32,'Tutb/NTU':np.float32,'let':np.int32})
# header = 0 # 表示第0行作为标题行,并非实际数据
# index_col = [3,5] # 表示第3列,第5列是id,也不是真实数据(不想要的列)
# name = []设置列名必须是list类型,且长度必须与列数一致,否则有逻辑问题
# 如果用sheet_name = none 得到的就是所有sheet的数据 但此时df也就是一个字典了,对应每个sheet
print(f'the shape of dataframe is {df.shape}')
feat = df.iloc[:,:2].values # 这里的列和行是排除掉header和index_col之后的
label = df.iloc[:,2:].values
# iloc就像python里面的切片操作,此处得到的是numpy数组
self.x = torch.from_numpy(feat)
self.y = torch.from_numpy(label)
def __len__(self):
return len(self.y)
def __getitem__(self,index):
return self.x[index],self.y[index]
excel_dataset = ExcelDataset()
excel_dataloder = DataLoader(excel_dataset,batch_size = 2 , shuffle = False)
for idx,(batch_x,batch_y) in enumerate(excel_dataloder):
print(f'batch_id:{idx},{batch_x.shape},{batch_y.shape}')
print(batch_x,batch_y)
class CsvDataset(Dataset):
def __init__(self,filepath=r"./dataset/dataset_test02.csv"):
# csv文件中没有sheet表单的说法
print(f"reading {filepath}") # 打印日志
df = pandas.read_csv(
filepath,header=0,index_col=[3,5],
encoding = 'utf-8',
names=['pH','pH/mV','Turb/NTU',"ID",'let','id'],
dtype={'pH':np.float32,'pH/mV':np.float32,'Tutb/NTU':np.float32,'let':np.int32},
skip_blank_lines = True)
# header = 0 # 表示第0行作为标题行,并非实际数据
# index_col = [3,5] # 表示第3列,第5列是id,也不是真实数据(不想要的列)
# name = []设置列名必须是list类型,且长度必须与列数一致
print(f'the shape of dataframe is {df.shape}')
feat = df.iloc[:,:2].values # 这里的列和行是排除掉header和index_col之后的
label = df.iloc[:,2:].values
# iloc就像python里面的切片操作,此处得到的是numpy数组
self.x = torch.from_numpy(feat)
self.y = torch.from_numpy(label)
def __len__(self):
return len(self.y)
def __getitem__(self,index):
return self.x[index],self.y[index]
csv_dataset = CsvDataset()
csv_dataloder = DataLoader(csv_dataset,batch_size = 2 , shuffle = False)
for idx,(batch_x,batch_y) in enumerate(csv_dataloder):
print(f'batch_id:{idx},{batch_x.shape},{batch_y.shape}')
print(batch_x,batch_y)