《昇思25天学习打卡营第5天|数据变换》

数据变换 Transforms

通常情况下,直接加载的原始数据并不能直接送入神经网络进行训练,此时我们需要对其进行数据预处理。MindSpore提供不同种类的数据变换(Transforms),配合数据处理Pipeline来实现数据预处理。所有的Transforms均可通过map方法传入,实现对指定数据列的处理。

mindspore.dataset提供了面向图像、文本、音频等不同数据类型的Transforms,同时也支持使用Lambda函数。下面分别对其进行介绍。

%%capture captured_output
# 实验环境已经预装了mindspore==2.2.14,如需更换mindspore版本,可更改下面mindspore的版本号
!pip uninstall mindspore -y
!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.2.14
import numpy as np
from PIL import Image
from download import download
from mindspore.dataset import transforms, vision, text
from mindspore.dataset import GeneratorDataset, MnistDataset

Common Transforms

mindspore.dataset.transforms模块支持一系列通用Transforms。这里我们以Compose为例,介绍其使用方式。

Compose

Compose接收一个数据增强操作序列,然后将其组合成单个数据增强操作。我们仍基于Mnist数据集呈现Transforms的应用效果。

# Download data from open datasets

url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/" \
      "notebook/datasets/MNIST_Data.zip"
path = download(url, "./", kind="zip", replace=True)

train_dataset = MnistDataset('MNIST_Data/train')
Downloading data from https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip (10.3 MB)

file_sizes: 100%|███████████████████████████| 10.8M/10.8M [00:00<00:00, 126MB/s]
Extracting zip file...
Successfully downloaded / unzipped to ./
image, label = next(train_dataset.create_tuple_iterator())
print(image.shape)
(28, 28, 1)
composed = transforms.Compose(
    [
        vision.Rescale(1.0 / 255.0, 0),
        vision.Normalize(mean=(0.1307,), std=(0.3081,)),
        vision.HWC2CHW()
    ]
)
train_dataset = train_dataset.map(composed, 'image')
image, label = next(train_dataset.create_tuple_iterator())
print(image.shape)
(1, 28, 28)

更多通用Transforms详见mindspore.dataset.transforms

Vision Transforms

mindspore.dataset.vision模块提供一系列针对图像数据的Transforms。在Mnist数据处理过程中,使用了RescaleNormalizeHWC2CHW变换。下面对其进行详述。

Rescale

Rescale变换用于调整图像像素值的大小,包括两个参数:

  • rescale:缩放因子。
  • shift:平移因子。

图像的每个像素将根据这两个参数进行调整,输出的像素值为 o u t p u t i = i n p u t i ∗ r e s c a l e + s h i f t output_{i} = input_{i} * rescale + shift outputi=inputirescale+shift

这里我们先使用numpy随机生成一个像素值在[0, 255]的图像,将其像素值进行缩放。

random_np = np.random.randint(0, 255, (48, 48), np.uint8)
random_image = Image.fromarray(random_np)
print(random_np)
[[ 58   8 213 ...  46 144 100]
 [170  60 185 ... 130  25   8]
 [ 98   0 169 ... 139 174 215]
 ...
 [118  87 219 ... 102  24 155]
 [ 36 161  31 ...  77 251 115]
 [ 10 106 106 ... 191  42  78]]

为了更直观地呈现Transform前后的数据对比,我们使用Transforms的Eager模式进行演示。首先实例化Transform对象,然后调用对象进行数据处理。

rescale = vision.Rescale(1.0 / 255.0, 0)
rescaled_image = rescale(random_image)
print(rescaled_image)
[[0.227451   0.03137255 0.8352942  ... 0.18039216 0.5647059  0.3921569 ]
 [0.6666667  0.23529413 0.7254902  ... 0.50980395 0.09803922 0.03137255]
 [0.38431376 0.         0.6627451  ... 0.54509807 0.68235296 0.8431373 ]
 ...
 [0.46274513 0.34117648 0.8588236  ... 0.40000004 0.09411766 0.60784316]
 [0.14117648 0.6313726  0.12156864 ... 0.3019608  0.9843138  0.45098042]
 [0.03921569 0.4156863  0.4156863  ... 0.7490196  0.16470589 0.30588236]]

可以看到,使用Rescale后的每个像素值都进行了缩放。

Normalize

Normalize变换用于对输入图像的归一化,包括三个参数:

  • mean:图像每个通道的均值。
  • std:图像每个通道的标准差。
  • is_hwc:bool值,输入图像的格式。True为(height, width, channel),False为(channel, height, width)。

图像的每个通道将根据meanstd进行调整,计算公式为 o u t p u t c = i n p u t c − m e a n c s t d c output_{c} = \frac{input_{c} - mean_{c}}{std_{c}} outputc=stdcinputcmeanc,其中 c c c代表通道索引。

normalize = vision.Normalize(mean=(0.1307,), std=(0.3081,))
normalized_image = normalize(rescaled_image)
print(normalized_image)
[[ 0.31402466 -0.3223871   2.286901   ...  0.1612858   1.4086528
   0.8486106 ]
 [ 1.7395868   0.33948112  1.9305104  ...  1.2304575  -0.10600709
  -0.3223871 ]
 [ 0.8231541  -0.42421296  1.7268586  ...  1.3450117   1.7904998
   2.3123577 ]
 ...
 [ 1.0777187   0.6831434   2.3632705  ...  0.87406707 -0.11873532
   1.5486634 ]
 [ 0.03400347  1.6250328  -0.02963769 ...  0.55586106  2.7705739
   1.0395341 ]
 [-0.29693064  0.92498     0.92498    ...  2.0068798   0.11037287
   0.5685893 ]]

HWC2CHW

HWC2CHW变换用于转换图像格式。在不同的硬件设备中可能会对(height, width, channel)或(channel, height, width)两种不同格式有针对性优化。MindSpore设置HWC为默认图像格式,在有CHW格式需求时,可使用该变换进行处理。

这里我们先将前文中normalized_image处理为HWC格式,然后进行转换。可以看到转换前后的shape发生了变化。

hwc_image = np.expand_dims(normalized_image, -1)
hwc2chw = vision.HWC2CHW()
chw_image = hwc2chw(hwc_image)
print(hwc_image.shape, chw_image.shape)
(48, 48, 1) (1, 48, 48)

更多Vision Transforms详见mindspore.dataset.vision

Text Transforms

mindspore.dataset.text模块提供一系列针对文本数据的Transforms。与图像数据不同,文本数据需要有分词(Tokenize)、构建词表、Token转Index等操作。这里简单介绍其使用方法。

首先我们定义三段文本,作为待处理的数据,并使用GeneratorDataset进行加载。

texts = ['Welcome to Beijing']
test_dataset = GeneratorDataset(texts, 'text')

PythonTokenizer

分词(Tokenize)操作是文本数据的基础处理方法,MindSpore提供多种不同的Tokenizer。这里我们选择基础的PythonTokenizer举例,此Tokenizer允许用户自由实现分词策略。随后我们利用map操作将此分词器应用到输入的文本中,对其进行分词。

def my_tokenizer(content):
    return content.split()

test_dataset = test_dataset.map(text.PythonTokenizer(my_tokenizer))
print(next(test_dataset.create_tuple_iterator()))
[Tensor(shape=[3, 1], dtype=String, value=
[['Welcome'],
 ['to'],
 ['Beijing']])]

Lookup

Lookup为词表映射变换,用来将Token转换为Index。在使用Lookup前,需要构造词表,一般可以加载已有的词表,或使用Vocab生成词表。这里我们选择使用Vocab.from_dataset方法从数据集中生成词表。

vocab = text.Vocab.from_dataset(test_dataset)

获得词表后我们可以使用vocab方法查看词表。

print(vocab.vocab())
{'to': 2, 'Welcome': 1, 'Beijing': 0}

生成词表后,可以配合map方法进行词表映射变换,将Token转为Index。

test_dataset = test_dataset.map(text.Lookup(vocab))
print(next(test_dataset.create_tuple_iterator()))
[Tensor(shape=[3, 1], dtype=Int32, value=
[[1],
 [2],
 [0]])]

更多Text Transforms详见mindspore.dataset.text

Lambda Transforms

Lambda函数是一种不需要名字、由一个单独表达式组成的匿名函数,表达式会在调用时被求值。Lambda Transforms可以加载任意定义的Lambda函数,提供足够的灵活度。在这里,我们首先使用一个简单的Lambda函数,对输入数据乘2:

test_dataset = GeneratorDataset([1, 2, 3], 'data', shuffle=False)
test_dataset = test_dataset.map(lambda x: x * 2)
print(list(test_dataset.create_tuple_iterator()))
[[Tensor(shape=[], dtype=Int64, value= 2)], [Tensor(shape=[], dtype=Int64, value= 4)], [Tensor(shape=[], dtype=Int64, value= 6)]]

可以看到map传入Lambda函数后,迭代获得数据进行了乘2操作。

我们也可以定义较复杂的函数,配合Lambda函数实现复杂数据处理:

def func(x):
    return x * x + 2

test_dataset = test_dataset.map(lambda x: func(x))
print(list(test_dataset.create_tuple_iterator()))
[[Tensor(shape=[], dtype=Int64, value= 6)], [Tensor(shape=[], dtype=Int64, value= 18)], [Tensor(shape=[], dtype=Int64, value= 38)]]

在这里插入图片描述

心得

  1. 图像的不同格式
    类型上 ,除了PIL特殊,为 pytorch,opencv,skimage等读取的图片格式均为numpy.ndarray格式;
  2. 维度上,除了PIL其它都是H,W,C,PIL是W,H,C。pytorch是N,C,H,W,tensorflow是N,H,W,C
  3. 通道上,除了opencv(cv2)读进来的顺序是BGR,其他都是RGB。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值