Resnet训练CIFAR100数据集

resnet.py,用来构造一个18或34层的残差神经网络:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Sequential

class BasicBlock(layers.Layer):

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

		self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same')
		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))
		else :
			self.downsample = lambda x:x

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

		out = self.conv1(inputs)
		out = self.bn1(out)
		out = self.relu(out)

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

		identity = self.downsample(inputs)

		output = layers.add([out, identity])
		output = tf.nn.relu(output)

		return output

class ResNet(keras.Model):

	def __init__(self, layer_dims, num_classes=100):
		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)

		self.avgpool = layers.GlobalAveragePooling2D()
		self.fc = layers.Dense(num_classes)

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

		x = self.stem(inputs)
		x = self.layer1(x)
		x = self.layer2(x)
		x = self.layer3(x)
		x = self.layer4(x)
		x = self.avgpool(x)
		x = self.fc(x)
		return x

	def build_resblock(self, filter_num, blocks, stride=1):

		res_blocks = Sequential()
		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])		

def resnet34():
	return  ResNet([3,4,6,3])		

cifar100_res.py,利用resnet.py中的18层残差神经网络来训练CIFAR100数据集:

import tensorflow as tf
from tensorflow.keras import layers, optimizers, datasets, Sequential
from resnet import resnet18, resnet34

tf.random.set_seed(1234)

(x, y), (x_test, y_test) = datasets.cifar100.load_data()

x = 2 * tf.cast(x, dtype=tf.float32)/255. - 1
y = tf.cast(y, dtype=tf.int32)
y = tf.squeeze(y, axis=1)

x_test = 2 * tf.cast(x_test, dtype=tf.float32)/255. - 1
y_test = tf.cast(y_test, dtype=tf.int32)
y_test = tf.squeeze(y_test, axis=1)

print(x.shape, y.shape, x_test.shape, y_test.shape)

train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(1000).batch(64)

test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.batch(64)

def main():

	model = resnet18()
	model.build(input_shape = (None, 32, 32, 3))
	optimizer = optimizers.Adam(lr=1e-3)

	for epoch in range(50):
	
		for step, (x,y) in enumerate(train_db):
		
			with tf.GradientTape() as tape:
				logits = model(x)
				y_onehot = tf.one_hot(y, depth=100)
				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 % 100 == 0:
				print(epoch, step, 'losses:', float(loss))

		total_num = 0
		total_correct = 0
		
		for x,y in test_db:
			
			logits = model(x)
			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()



上一篇:自定义层or网络


下一篇:pytoch 模型初始化