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

基本介绍🤖 快速入门MindSpore AI:打造你的智能助手

基本介绍 || 快速入门 || 张量 Tensor || 数据集 Dataset || 数据变换 Transforms || 网络构建 || 函数式自动微分 || 模型训练 || 保存与加载 || 使用静态图加速

数据变换 Transforms

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

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

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, 147MB/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)转换HWC CHW 后展示使用image_np[0]
import matplotlib.pyplot as plt
image_np = image.asnumpy()  # Convert mindspore tensor to NumPy array

plt.imshow(image_np[0], cmap='gray')  # Display the first image in the batch
plt.axis('off')  # Turn off axis labels
plt.show()

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

Vision Transforms

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

Rescale

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

  • rescale:缩放因子。

  • shift:平移因子。

图像的每个像素将根据这两个参数进行调整,输出的像素值为𝑜𝑢𝑡𝑝𝑢𝑡𝑖=𝑖𝑛𝑝𝑢𝑡𝑖∗𝑟𝑒𝑠𝑐𝑎𝑙𝑒+𝑠ℎ𝑖𝑓𝑡。

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

random_np = np.random.randint(0, 255, (48, 48), np.uint8)
random_image = Image.fromarray(random_np)
print(random_np)
[[ 64  34  38 ...   5 138 242]
 [ 81  73 103 ... 183 156  50]
 [ 64 195 195 ... 193 169 178]
 ...
 [186 130  57 ... 246  75  97]
 [ 80 107  89 ...  14 204 152]
 [237  30 252 ...  85  87  21]]

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

rescale = vision.Rescale(1.0 / 255.0, 0)
rescaled_image = rescale(random_image)
print(rescaled_image)
[[0.2509804  0.13333334 0.14901961 ... 0.01960784 0.5411765  0.9490197 ]
 [0.31764707 0.28627452 0.4039216  ... 0.7176471  0.6117647  0.19607845]
 [0.2509804  0.76470596 0.76470596 ... 0.7568628  0.6627451  0.69803923]
 ...
 [0.7294118  0.50980395 0.22352943 ... 0.96470594 0.29411766 0.3803922 ]
 [0.3137255  0.41960788 0.34901962 ... 0.05490196 0.8000001  0.59607846]
 [0.9294118  0.11764707 0.98823535 ... 0.33333334 0.34117648 0.08235294]]

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

Normalize

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

  • mean:图像每个通道的均值。

  • std:图像每个通道的标准差。

  • is_hwc:bool值,输入图像的格式。True为(height, width, channel),False为(channel, height, width)。

图像的每个通道将根据meanstd进行调整,计算公式为𝑜𝑢𝑡𝑝𝑢𝑡𝑐=(𝑖𝑛𝑝𝑢𝑡𝑐−𝑚𝑒𝑎𝑛𝑐)/𝑠𝑡𝑑𝑐,其中 𝑐代表通道索引。

normalize = vision.Normalize(mean=(0.1307,), std=(0.3081,))
normalized_image = normalize(rescaled_image)
print(normalized_image)
[[ 0.39039403  0.00854701  0.05945994 ... -0.3605718   1.3322834
   2.65602   ]
 [ 0.60677403  0.50494814  0.8867953  ...  1.905054    1.5613916
   0.21219878]
 [ 0.39039403  2.057793    2.057793   ...  2.0323365   1.7268586
   1.8414128 ]
 ...
 [ 1.9432386   1.2304575   0.3012964  ...  2.7069328   0.5304046
   0.8104258 ]
 [ 0.59404576  0.9377082   0.70859987 ... -0.24601768  2.172347
   1.5104787 ]
 [ 2.5923786  -0.04236592  2.783302   ...  0.65768695  0.6831434
  -0.15692005]]

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')

分词(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], 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, 'Beijing': 0, 'Welcome': 1}

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

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

更多Text Transforms详见mindspore.dataset.text

Text Transforms,PythonTokenizer &  Lookup using Chinese

texts = ['使用中文北京欢迎你'] 
test_dataset = GeneratorDataset(texts, 'text')
def my_tokenizer(content):
    return list(content)

test_dataset = test_dataset.map(text.PythonTokenizer(my_tokenizer))
print(next(test_dataset.create_tuple_iterator()))
[Tensor(shape=[1, 9], dtype=String, value=
[['使', '用', '中', '文', '北', '京', '欢', '迎', '你']])]
vocab = text.Vocab.from_dataset(test_dataset)
print(vocab.vocab())
{'迎': 8, '用': 7, '欢': 6, '使': 3, '京': 1, '文': 5, '北': 4, '你': 2, '中': 0}
# Use the Lookup operation to map tokens to ids
lookup = text.Lookup(vocab)

# Apply the Lookup operation to your dataset
test_dataset = test_dataset.map(operations=[lookup])

# Print the result of the Lookup operation
print(next(test_dataset.create_tuple_iterator()))
[Tensor(shape=[9], dtype=Int32, value= [3, 7, 0, 5, 4, 1, 6, 8, 2])

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)]]
  • 30
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值