当前位置:网站首页>[PaddleSeg 源码阅读] PaddleSeg Transform 的 Normalize操作
[PaddleSeg 源码阅读] PaddleSeg Transform 的 Normalize操作
2022-07-04 03:32:00 【氵文大师】
接上一篇,PaddleSeg 自定义数据类 https://blog.csdn.net/HaoZiHuang/article/details/125566058 这里再说一下 Normalize 操作
咱们自己写 Transform 时,总会担心一些细节,比如:
- np.uint8 转了没,要不要转为 np.float32
- 归一化做了没(
/255做了没) - 用不用减去0.5,然后除以0.5,将其移至 -1 到 1
- 送入数据之前,有没有 transpose 之类的
- 何时将 numpy.ndarray 初始化为 paddle.Tensor
上一篇PaddleSeg说到,在Compose结尾,会做输入通道数的转换(Transpose),而看源代码:
batch_sampler = paddle.io.DistributedBatchSampler(
eval_dataset, batch_size=1, shuffle=False, drop_last=False)
loader = paddle.io.DataLoader(
eval_dataset,
batch_sampler=batch_sampler,
num_workers=num_workers,
return_list=True, )
这个是实例化,Dataset 和 DataLoader 的部分,尽管 eval_dataset 返回的每个数据都是 np.ndarray,但是 paddle.io.DataLoader 这个类,会直接返回 Paddle.Tensor 类的数据,也就是无需再做 paddle.to_tensor操作
OK, 接下里的这三项:
- np.uint8 转了没,要不要转为 np.float32
- 归一化做了没
- 用不用减去0.5,然后除以0.5,将其移至 -1 到 1
就是 Normalize 部分的操作了,来看看它实现的源码
paddleseg\transforms\transforms.py 中 Normalize 类
@manager.TRANSFORMS.add_component
class Normalize:
""" Normalize an image. Args: mean (list, optional): The mean value of a data set. Default: [0.5, 0.5, 0.5]. std (list, optional): The standard deviation of a data set. Default: [0.5, 0.5, 0.5]. Raises: ValueError: When mean/std is not list or any value in std is 0. """
def __init__(self, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
self.mean = mean
self.std = std
if not (isinstance(self.mean,
(list, tuple)) and isinstance(self.std,
(list, tuple))):
raise ValueError(
"{}: input type is invalid. It should be list or tuple".format(
self))
from functools import reduce
if reduce(lambda x, y: x * y, self.std) == 0:
raise ValueError('{}: std is invalid!'.format(self))
def __call__(self, im, label=None):
""" Args: im (np.ndarray): The Image data. label (np.ndarray, optional): The label data. Default: None. Returns: (tuple). When label is None, it returns (im, ), otherwise it returns (im, label). """
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
im = functional.normalize(im, mean, std)
if label is None:
return (im, )
else:
return (im, label)
paddleseg\transforms\functional.py 中 normalize 函数
def normalize(im, mean, std):
im = im.astype(np.float32, copy=False) / 255.0
im -= mean
im /= std
return im
可以看到 在 normalize 函数中,做了转 np.float32, 归一化
然后 -0.5 之后 /0.5
如果你对这两行感兴趣:
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std )[np.newaxis, np.newaxis, :]
自己打印看看吧,就是个原来的array维度前面加了两个1
shape 从 (3,) 变成了 (1, 1, 3)
而 np.newaxis 其实就是 None
(np.newaxis == None) == True
如果对 Normalize __init__函数中的 reduce 感兴趣:
可以看看这个:
functools下的reduce函数
边栏推荐
- [Wu Enda deep learning] beginner learning record 3 (regularization / error reduction)
- @Scheduled scheduled tasks
- POSTECH | option compatible reward reverse reinforcement learning
- Li Chuang EDA learning notes IX: layers
- Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
- Problems and solutions of several concurrent scenarios of redis
- Zblog collection plug-in does not need authorization to stay away from the cracked version of zblog
- Unity controls the selection of the previous and next characters
- Backpropagation formula derivation [Li Hongyi deep learning version]
- The property of judging odd or even numbers about XOR.
猜你喜欢

Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress

PHP database connection succeeded, but data cannot be inserted
![[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love](/img/ab/066923f1aa1e8dd8dcc572cb60a25d.jpg)
[Valentine's Day confession code] - Valentine's Day is approaching, and more than 10 romantic love effects are given to the one you love

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?

Why is it recommended that technologists write blogs?

1day vulnerability pushback skills practice (3)

Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?

false sharing

Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex

Unspeakable Prometheus monitoring practice
随机推荐
Dare to climb here, you're not far from prison, reptile reverse actual combat case
Summary of Chinese remainder theorem
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
Love and self-discipline and strive to live a core life
Unspeakable Prometheus monitoring practice
Explain AI accelerator in detail: why is this the golden age of AI accelerator?
PHP database connection succeeded, but data cannot be inserted
Site favorites
(practice C language every day) pointer sorting problem
Recursive structure
Which product is better if you want to go abroad to insure Xinguan?
MySQL backup notes
[development team follows] API specification
1day vulnerability pushback skills practice (3)
Nbear introduction and use diagram
MySQL data query optimization -- data structure of index
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
1day vulnerability pushback skills practice (3)
I stepped on a foundation pit today
Leetcode51.n queen