Pytorch实现上采用upsample和下采用downsample 简单调用函数即可实现,超简单的代码块调用


# 上采用函数,输入数据格式示例:tensor维度[3,300,300],即3通道RGB,大小300×300,当然4通道图像也能做
def upsample(image_tensor, width, height, mode):
    # mode可用:最近邻插值"nearest",双线性插值"bilinear",双三次插值"bicubic",如mode="nearest"
    image_upsample_tensor = torch.nn.functional.interpolate(image_tensor.unsqueeze_(0), size=[width, height], mode=mode)
    image_upsample_tensor.squeeze_(0)
    # 将数据归一到正常范围,尺寸改变过程可能数值范围溢出,此处浮点数据位[0,1],整数数据为[0,255]
    image_upsample_tensor = image_upsample_tensor.clamp(0, 1)  
    return image_upsample_tensor


# 下采用函数,输入数据格式示例:tensor维度[3,300,300],即3通道RGB,大小300×300,当然4通道图像也能做
def downsample(image_tensor, width, height):
    image_upsample_tensor = torch.nn.functional.interpolate(image_tensor.unsqueeze_(0), size=[width, height])
    image_upsample_tensor.squeeze_(0)
    # 将数据归一到正常范围,尺寸改变过程可能数值范围溢出,此处浮点数据位[0,1],整数数据为[0,255]
    image_upsample_tensor = image_upsample_tensor.clamp(0, 1)
    return image_upsample_tensor


分享创造快乐,欢迎复制使用!

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
CutMix是一种数据增强技术,可以在训练神经网络时,将两个不同的图像混合在一起,生成一个新的图像。这种技术可以增加模型的鲁棒性和泛化能力。 以下是使用PyTorch实现CutMix数据增强的代码: ```python import torch import numpy as np import random def cutmix_data(x, y, alpha=1.0): lam = np.random.beta(alpha, alpha) batch_size = x.size()[0] index = torch.randperm(batch_size) y_a, y_b = y, y[index] bbx1, bby1, bbx2, bby2 = rand_bbox(x.size(), lam) x[:, :, bbx1:bbx2, bby1:bby2] = x[index, :, bbx1:bbx2, bby1:bby2] lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (x.size()[-1] * x.size()[-2])) return x, y_a, y_b, lam def rand_bbox(size, lam): W = size[2] H = size[3] cut_rat = np.sqrt(1. - lam) cut_w = np.int(W * cut_rat) cut_h = np.int(H * cut_rat) # uniform cx = np.random.randint(W) cy = np.random.randint(H) bbx1 = np.clip(cx - cut_w // 2, 0, W) bby1 = np.clip(cy - cut_h // 2, 0, H) bbx2 = np.clip(cx + cut_w // 2, 0, W) bby2 = np.clip(cy + cut_h // 2, 0, H) return bbx1, bby1, bbx2, bby2 ``` 正则交叉熵损失函数是一种可以减少标签噪声对模型训练的影响的损失函数。以下是使用PyTorch实现正则交叉熵损失函数的代码: ```python import torch.nn.functional as F def reg_cross_entropy_loss(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', reg_lambda=0.1): logp = F.log_softmax(input, dim=1) loss = F.nll_loss(logp, target, weight, size_average, ignore_index, reduce, reduction) reg_loss = torch.mean(torch.sum(torch.square(torch.exp(logp)), dim=1)) return loss + reg_lambda * reg_loss ``` 在调用此函数时,您可以指定reg_lambda参数来控制正则化的程度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦星辰.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值