Tensorflow之CNN实战

基本卷积操作
import tensorflow as tf
from tensorflow.keras import layers
# 4代表卷积核个数,也就是输出维度;5代表卷积核大小;strides=2则size减半
# padding=valid代表不padding,padding=same代表padding成size不变
layer = layers.Conv2D(4,kernel_size=5,strides=1,padding='valid')
					# x : [b,32,32,3]
out = layer(x)		# [b,28,28,4],此时权重w的size为[28,28,3,4],b:[4]
池化与采样
  • 池化
x   				# [1,14,14,4]
# pooling不会改变channel,对每个channel进行同样的操作
pool = layers.MaxPool2D(2,strides=2)		
out = pool(x)		# [1,7,7,4]
  • 上采样
x 					# [1,7,7,4]
layer = layers.Upsampling2D(size=3)
out = layer(x)		# [1,21,21,4],每一个pixel变为3*3大小的块,这个块内的pixel值相等
  • Relu函数
layers.ReLU()(x)
Batch Normalization

让每一层数据的分布都比较规范,易于学习,不易发生梯度离散或者梯度爆炸

  • batch normalization

    [N,C,H*W] => [C] : 表示每一个channel上一个Batch的均值

  • layer normalization

    [N,C,H*W] => [N] : 表示每一个实例的均值

  • instance normalization

    [N,C,H*W] => [N,C] : 表示每一个实例上每一个channel的均值

  • group normalization : 表示每一个实例上一部分channel的均值

  • net = layers.BatchNormalization() 其参数如下:axis代表在哪个维度进行BN,center=True代表均值,scale=True代表方差,trainable=True

x = tf.random.normal([2,4,4,3],mean=1,stddev=0.5)
net = layers.BatchNormalization(axis=3) 
out = net(x,training=True)
# net.variables : 可见逐渐均值为1,标准差为0.5
实战ResNet18
  • ResNet实现
import  tensorflow as tf
from    tensorflow import keras
from    tensorflow.keras import layers, Sequential

class BasicBlock(layers.Layer):	# 2层

    def __init__(self, filter_num, stride=1):
        super(BasicBlock, self).__init__()

        self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same')	# 通过stride取值看是否下采样
        self.bn1 = layers.BatchNormalization()
        self.relu = layers.Activation('relu')

        self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same')
        self.bn2 = layers.BatchNormalization()

        if stride != 1:		# 下采样
            self.downsample = Sequential()
            self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride))
            self.downsample.add(layers.BatchNormalization())
        else:				# 未下采样
            self.downsample = lambda x:x

    def call(self, inputs, training=None):
        # [b, h, w, c], pytorch是[b, c, h, w]
        out = self.conv1(inputs)
        out = self.bn1(out,training=training)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out,training=training)

        identity = self.downsample(inputs)

        output = layers.add([out, identity])
        output = tf.nn.relu(output)			# 不能用self.relu(),防止共享激活函数层

        return output

class ResNet(keras.Model):

    def __init__(self, layer_dims, num_classes=100): # [2, 2, 2, 2],每个resblock有几个basicblock
        super(ResNet, self).__init__()

        self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)),
                                layers.BatchNormalization(),
                                layers.Activation('relu'),
                                layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same')
                                ])

        self.layer1 = self.build_resblock(64,  layer_dims[0])
        self.layer2 = self.build_resblock(128, layer_dims[1], stride=2)
        self.layer3 = self.build_resblock(256, layer_dims[2], stride=2)
        self.layer4 = self.build_resblock(512, layer_dims[3], stride=2)

        # output: [b, 512, h, w],
        self.avgpool = layers.GlobalAveragePooling2D()
        self.fc = layers.Dense(num_classes)

    def call(self, inputs, training=None):

        x = self.stem(inputs,training=training)

        x = self.layer1(x,training=training)
        x = self.layer2(x,training=training)
        x = self.layer3(x,training=training)
        x = self.layer4(x,training=training)

        x = self.avgpool(x)
        # 输出为:[b, 100]
        x = self.fc(x)

        return x

    def build_resblock(self, filter_num, blocks, stride=1):
    	# 参数:basicblock数量以及channel数量
        res_blocks = Sequential()
        # 只有这一个basicblock可以进行下采样
        res_blocks.add(BasicBlock(filter_num, stride))

        for _ in range(1, blocks):
            res_blocks.add(BasicBlock(filter_num, stride=1))

        return res_blocks

def resnet18():
    return ResNet([2, 2, 2, 2])		# 有2*2*4+1+1=18层

def resnet34():
    return ResNet([3, 4, 6, 3])		# 有3*2+4*2+6*2+3*2+1+1=34层
  • 训练与测试
import  os
import  tensorflow as tf
from    tensorflow.keras import layers, optimizers, datasets, Sequential 
from    resnet import resnet18 
tf.random.set_seed(2345)

def preprocess(x, y):
    # 数据范围预处理成:[-1~1]
    x = tf.cast(x, dtype=tf.float32) / 255. - 0.5
    y = tf.cast(y, dtype=tf.int32)
    return x,y

(x,y), (x_test, y_test) = datasets.cifar100.load_data()
y = tf.squeeze(y, axis=1)
y_test = tf.squeeze(y_test, axis=1)

train_db = tf.data.Dataset.from_tensor_slices((x,y))
train_db = train_db.shuffle(1000).map(preprocess).batch(512)

test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test))
test_db = test_db.map(preprocess).batch(512)

def main():
    # [b, 32, 32, 3] => [b, 1, 1, 512]
    model = resnet18()
    model.build(input_shape=(None, 32, 32, 3))
    model.summary()
    optimizer = optimizers.Adam(lr=1e-3)

    for epoch in range(500):
        for step, (x,y) in enumerate(train_db):

            with tf.GradientTape() as tape:
                # [b, 32, 32, 3] => [b, 100]
                logits = model(x,training=True)
                # [b] => [b, 100]
                y_onehot = tf.one_hot(y, depth=100)
                # compute loss
                loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
                loss = tf.reduce_mean(loss)

            grads = tape.gradient(loss, model.trainable_variables)
            optimizer.apply_gradients(zip(grads, model.trainable_variables))

            if step % 50 == 0:
                print(epoch, step, 'loss:', float(loss))

        total_num = 0
        total_correct = 0
        for x,y in test_db:

            logits = model(x,training=False)
            prob = tf.nn.softmax(logits, axis=1)
            pred = tf.argmax(prob, axis=1)
            pred = tf.cast(pred, dtype=tf.int32)

            correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)
            correct = tf.reduce_sum(correct)

            total_num += x.shape[0]
            total_correct += int(correct)

        acc = total_correct / total_num
        print(epoch, 'acc:', acc)

if __name__ == '__main__':
    main()

你可能感兴趣的:(Tensorflow)