DATA_FORMAT = 'NCHW' 和DATA_FORMAT = 'CHWN'

本文详细解析了Theano与TensorFlow在表示彩色图片数据格式上的区别,包括NHWC(高度、宽度、通道)和NCHW(通道、高度、宽度)两种格式的转换方法,并提供了在Keras中指定数据格式的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自https://blog.youkuaiyun.com/qq_39622065/article/details/81228915

NHWC
[batch, in_height, in_width, in_channels]

NCHW
[batch, in_channels, in_height, in_width]

转换
NHWC –> NCHW:

import tensorflow as tf

x = tf.reshape(tf.range(24), [1, 3, 4, 2])
out = tf.transpose(x, [0, 3, 1, 2])

print x.shape
print out.shape

(1, 3, 4, 2)
(1, 2, 3, 4)
1
2

NCHW –> NHWC:

import tensorflow as tf

x = tf.reshape(tf.range(24), [1, 2, 3, 4])
out = tf.transpose(x, [0, 2, 3, 1])

print x.shape
print out.shape

(1, 2, 3, 4)
(1, 3, 4, 2)

这是一个无可奈何的问题,在如何表示一组彩色图片的问题上,Theano和TensorFlow发生了分歧, ‘日’模式,也即Theano模式会把100张RGB三通道的16×32(高为16宽为32)彩色图表示为下面这种形式(100,3,16,32),Caffe采取的也是这种方式。第0个维度是样本维,代表样本的数目,第1个维度是通道维,代表颜色通道数。后面两个就是高和宽了。这种theano风格的数据组织方法,称为“channels_first”,即通道维靠前。

而TensorFlow,的表达形式是(100,16,32,3),即把通道维放在了最后,这种数据组织方式称为“channels_last”。

tensorflow的格式如下:

[batch,in_height,in_with,in_channels]批量批次1000高度图片的长宽宽通道通道数

channels RGB则为3黑白为1

Keras默认的数据组织形式在〜/ .keras / keras.json中规定,查看柯林斯该文件的image_data_format一项查看,也可在代码中通过K.image_data_format()函数返回,请在网络的训练和测试中保持维度顺序一致。

唉,真是蛋疼,你们商量好不行吗?

keras中添加卷积层时,可以指定deat_format格式:


model.add(Convolution2D(
    batch_input_shape=(None, 1, 28, 28),   #多少数据  通道数  宽  高
    filters=32,     #滤波器数量
    kernel_size=5,   #滤波器大小5x5
    strides=1,       #步长1
    padding='same',     # Padding method
    data_format='channels_first',
))

1、代码中的DATA_FORMAT = ‘channels_first’,即通道维靠前。

[batch,in_channels,in_height,in_with]既批次:批次大小渠道:通道数高度:图片的长宽度:宽

2、当然也可以和tensorflow中的数据格式一样指定 channels_last = ‘channels_last’,keras默认为channels_last。

通用模板:



from keras import backend as K
w = 100   #图片宽度
h = 100   #图片高度
c = 3     #图片通道数
if K.image_dim_ordering() == 'th':
    X_train = X_train.reshape(-1, c, w, h)
    X_test = X_test.reshape(-1, c, w, h)
    input_shape = (1, w, h)
else:
    X_train = X_train.reshape(-1, w, h, c)
    X_test = X_test.reshape(-1, w, h, c)
    input_shape = (w, h, c)

X_train = X_train.reshape(-1, w, h, c)
X_test = X_test.reshape(-1, w, h, c)
input_shape = (w, h, c)

model.add(Convolution2D(
    batch_input_shape=(None,w,h,c),   #多少数据  通道数  宽  高
    filters=32,     #滤波器数量
    kernel_size=5,   #滤波器大小
    strides=1,       #步长
    padding='same'     # Padding method

))
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange class LayerNorm(nn.Module): def __init__(self, normalized_shape, eps=1e-6, data_format="channels_first"): super().__init__() # 可学习的权重参数,初始化为全 1 self.weight = nn.Parameter(torch.ones(normalized_shape)) # 可学习的偏置参数,初始化为全 0 self.bias = nn.Parameter(torch.zeros(normalized_shape)) # 用于数值稳定性的小常数 self.eps = eps # 数据格式,支持 "channels_last" "channels_first" self.data_format = data_format # 检查数据格式是否合法,若不合法则抛出异常 if self.data_format not in ["channels_last", "channels_first"]: raise NotImplementedError # 归一化的形状 self.normalized_shape = (normalized_shape,) def forward(self, x): # 如果数据格式为 "channels_last" if self.data_format == "channels_last": # 直接调用 PyTorch 的层归一化函数 return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) # 如果数据格式为 "channels_first" elif self.data_format == "channels_first": # 计算通道维度上的均值 u = x.mean(1, keepdim=True) # 计算通道维度上的方差 s = (x - u).pow(2).mean(1, keepdim=True) # 进行归一化操作 x = (x - u) / torch.sqrt(s + self.eps) # 应用可学习的权重偏置 x = self.weight[:, None, None] * x + self.bias[:, None, None] return x # Intensity Enhancement Layer,强度增强层 class IEL(nn.Module): def __init__(self, dim, ffn_expansion_factor=2.66, bias=False): # 调用父类的构造函数 super(IEL, self).__init__() # 计算隐藏层的特征维度 hidden_features = int(dim * ffn_expansion_factor) # 输入投影层,将输入特征维度映射到隐藏层特征维度的 2 倍 self.project_in = nn.Conv2d(dim, hidden_features * 2, kernel_size=1, bias=bias) # 深度可分离卷积层 1 self.dwconv = nn.Conv2d(hidden_features * 2, hidden_features * 2, kernel_size=3, stride=1, padding=1, groups=hidden_features
03-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值