CSV 文件处理
创建数据
import os
os.makedirs(os.path.join(".","data"),exist_ok=True)
data_file = os.path.join(".","data","house_tiny.csv")
with open(data_file,"w") as f:
f.write("NumRoos,Alley,Proces\n")
f.write("NA,Pave,12700\n")
f.write("2,NA,10789\n")
f.write("4,NA,187654\n")
f.write("NA,NA,140000\n")
读取数据:
import pandas as pd
data = pd.read_csv(data_file)
print(data)
输出:
NumRoos Alley Proces
0 NaN Pave 12700
1 2.0 NaN 10789
2 4.0 NaN 187654
3 NaN NaN 140000
为了处理缺失的数据,典型的方法包括插值法和删除法, 其中插值法用一个替代值弥补缺失值,而删除法则直接忽略缺失值。 在这里,我们将考虑插值法。
通过位置索引 iloc
,我们将 data
分成 inputs
和 outputs
, 其中前者为data的前两列,而后者为 data
的最后一列。
inputs,outputs = data.iloc[:,0:2],data.iloc[:,2]
inputs = inputs.fillna(inputs.mean())
print(inputs)
输出:
NumRoos Alley
0 3.0 Pave
1 2.0 NaN
2 4.0 NaN
3 3.0 NaN
缺少巷子类型的行会将“Alley_Pave”和“Alley_nan”分别设置为0和1:
inputs = pd.get_dummies(inputs,dummy_na = True)
print(inputs)
输出:
NumRoos Alley_Pave Alley_nan
0 3.0 1 0
1 2.0 0 1
2 4.0 0 1
3 3.0 0 1
转换为张量格式:
import torch
X,y = torch.tensor(inputs.values),torch.tensor(outputs.values)
X, y
输出:
(tensor([[3., 1., 0.],
[2., 0., 1.],
[4., 0., 1.],
[3., 0., 1.]], dtype=torch.float64),
tensor([ 12700, 10789, 187654, 140000]))
图片预处理
torchvision
torchvision 是一个计算机视觉工具包,主要包含:
torchvision.transforms
: 里面包括常用的图像预处理方法torchvision.datasets
: 里面包括常用数据集如 mnist、CIFAR-10、Image-Net 等torchvision.models
: 里面包括常用的预训练好的模型,如 AlexNet、VGG、ResNet、GoogleNet 等torchvision.utils
: 其他的一些有用的方法
Crop
常用剪裁方法:
- 中心裁剪:
transforms.CenterCrop
- 随机裁剪:
transforms.RandomCrop
- 随机长宽比裁剪:
transforms.RandomResizedCrop
- 上下左右中心裁剪:
transforms.FiveCrop
- 上下左右中心裁剪后翻转,
transforms.TenCrop
中心裁剪
torchvision.transforms.CenterCrop(size)
示例:
%matplotlib inline
from PIL import Image
from torchvision import transforms
import matplotlib
import matplotlib.pyplot as plt
image = Image.open("../ILSVRC2012_val_00000003.JPEG")
center_crop = transforms.CenterCrop(120)
plt.figure(1)
plt.subplot(1,2,1)
plt.imshow(image)
plt.subplot(1,2,2)
croped = center_crop(image)
plt.imshow(croped)
print(image.size) # (500, 375)
print(croped.size) # (120, 120)
如果裁剪的 size 比原图大,那么会填充值为 0 的像素:
center_crop = transforms.CenterCrop((600,600))
随机裁剪
从图片中随机裁剪出尺寸为 size 的图片,如果有 padding,那么先进行 padding,再随机裁剪 size 大小的图片:
torchvision.transforms.RandomCrop(size, padding=None, pad_if_needed=False, fill=0, padding_mode='constant')
- padding: 设置填充大小
- 当为 a 时,上下左右均填充 a 个像素
- 当为 (a, b) 时,左右填充 a 个像素,上下填充 b 个像素
- 当为 (a, b, c, d) 时,左上右下分别填充 a,b,c,d
- pad_if_need: 当图片小于设置的 size,是否填充
- padding_mode:
- constant: 像素值由 fill 设定
- edge: 像素值由图像边缘像素设定
- reflect: 镜像填充,最后一个像素不镜像。([1,2,3,4] -> [3,2,1,2,3,4,3,2])
- symmetric: 镜像填充,最后一个像素也镜像。([1,2,3,4] -> [2,1,1,2,3,4,4,4,3])
- fill: 当 padding_mode 为 constant 时,设置填充的像素