Resnet结构
详细结构
具体代码实现 准确率 42%左右
网络结构代码:
import tensorflow as tf
from tensorflow.keras import layers, Sequential
class BasicBlock(layers.Layer):
def __init__(self, filter_num, stride=1):
"""
:param filter_num: 卷积核的个数
:param stride: 步长
"""
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.down_sample = Sequential()
self.down_sample.add(layers.Conv2D(filter_num, (1, 1), strides=stride))
self.down_sample.add(layers.BatchNormalization())
else:
self.down_sample = lambda x: x
self.stride = stride
def call(self, inputs, training=None):
identity = self.down_sample(inputs)
out = self.conv1(inputs)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out_put = layers.add([out, identity])
out_put = tf.nn.relu(out_put)
return out_put
class ResNet(tf.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_res_block(64, layer_dims[0])
self.layer2 = self.build_res_block(128, layer_dims[1], stride=2)
self.layer3 = self.build_res_block(256, layer_dims[2], stride=2)
self.layer4 = self.build_res_block(512, layer_dims[3], stride=2)
self.avg_pool = 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.avg_pool(x)
x = self.fc(x)
return x
@staticmethod
def build_res_block(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数据集处理
使用 Resnet18、Resnet34 网络层
"""
import os
import tensorflow as tf
from tensorflow.keras import datasets, optimizers
from resnet import resnet18
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
tf.random.set_seed(2345)
gpu_lst = tf.config.experimental.list_physical_devices("GPU")
print("GPU:{}个".format(len(gpu_lst)))
for gpu in gpu_lst:
tf.config.experimental.set_memory_growth(gpu, True)
def pre_process(x_data, y_data):
x_data = 2 * tf.cast(x_data, dtype=tf.float32) / 255. - 1
y_data = tf.cast(y_data, dtype=tf.int32)
return x_data, y_data
(x, y), (x_test, y_test) = datasets.cifar100.load_data()
y = tf.squeeze(y, axis=1)
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(10000).map(pre_process).batch(128)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.map(pre_process).batch(64)
sample = next(iter(train_db))
print("sample:", sample[0].shape, sample[1].shape,
tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
def main():
model = resnet18()
model.build(input_shape=(None, 32, 32, 3))
optimizer = optimizers.Adam(lr=1e-4)
model.summary()
for epoch in range(50):
for step, (x, y) in enumerate(train_db):
with tf.GradientTape() as tape:
y_prd = model(x)
y_true = tf.one_hot(y, depth=100)
loss = tf.losses.categorical_crossentropy(y_true, y_prd, 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, "loss:", float(loss))
total_num = 0
total_correct = 0
for x, y in test_db:
y_prd = model(x)
prob = tf.nn.softmax(y_prd, 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()