ResNet18和ResNet50的keras实现

ResNet18和ResNet50的keras实现fromtensorflowimportkerasfromtensorflow.kerasimportlayersINPUT_SIZE=224CLASS_NUM=1000#stage_name=2,3,4,5;block_name=a,b,c,d,e,fdefConvBlock(input_tensor,num_output,stride,stage_name,block_name):filter1,filter2,filter3=num_

大家好,又见面了,我是你们的朋友全栈君。

1.ResNet18

ResNet18

from tensorflow import keras
from tensorflow.keras import layers

INPUT_SIZE = 224
CLASS_NUM = 1000

# stage_name=2,3,4,5; block_name=a,b,c
def ConvBlock(input_tensor, num_output, stride, stage_name, block_name):
    filter1, filter2 = num_output

    x = layers.Conv2D(filter1, 3, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    shortcut = layers.Conv2D(filter2, 1, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch1')(input_tensor)
    shortcut = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch1')(shortcut)

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def IdentityBlock(input_tensor, num_output, stage_name, block_name):
    filter1, filter2 = num_output

    x = layers.Conv2D(filter1, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    shortcut = input_tensor

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def ResNet18(input_shape, class_num):
    input = keras.Input(shape=input_shape, name='input')

    # conv1
    x = layers.Conv2D(64, 7, strides=(2, 2), padding='same', name='conv1')(input)  # 7×7, 64, stride 2
    x = layers.BatchNormalization(name='bn_conv1')(x)
    x = layers.Activation('relu', name='conv1_relu')(x)
    x = layers.MaxPooling2D((3, 3), strides=2, padding='same', name='pool1')(x)   # 3×3 max pool, stride 2

    # conv2_x
    x = ConvBlock(input_tensor=x, num_output=(64, 64), stride=(1, 1), stage_name='2', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(64, 64), stage_name='2', block_name='b')

    # conv3_x
    x = ConvBlock(input_tensor=x, num_output=(128, 128), stride=(2, 2), stage_name='3', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(128, 128), stage_name='3', block_name='b')

    # conv4_x
    x = ConvBlock(input_tensor=x, num_output=(256, 256), stride=(2, 2), stage_name='4', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256), stage_name='4', block_name='b')

    # conv5_x
    x = ConvBlock(input_tensor=x, num_output=(512, 512), stride=(2, 2), stage_name='5', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(512, 512), stage_name='5', block_name='b')

    # average pool, 1000-d fc, softmax
    x = layers.AveragePooling2D((7, 7), strides=(1, 1), name='pool5')(x)
    x = layers.Flatten(name='flatten')(x)
    x = layers.Dense(class_num, activation='softmax', name='fc1000')(x)

    model = keras.Model(input, x, name='resnet18')
    model.summary()
    return model

if __name__ == '__main__':
    model = ResNet18((INPUT_SIZE, INPUT_SIZE, 3), CLASS_NUM)
    print('Done.')

train_resnet18.py

from tensorflow import keras
from tensorflow.keras import layers

INPUT_SIZE = 224
CLASS_NUM = 2

# stage_name=2,3,4,5; block_name=a,b,c
def ConvBlock(input_tensor, num_output, stride, stage_name, block_name):
    filter1, filter2 = num_output

    x = layers.Conv2D(filter1, 3, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    shortcut = layers.Conv2D(filter2, 1, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch1')(input_tensor)
    shortcut = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch1')(shortcut)

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def IdentityBlock(input_tensor, num_output, stage_name, block_name):
    filter1, filter2 = num_output

    x = layers.Conv2D(filter1, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    shortcut = input_tensor

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def ResNet18(input_shape, class_num):
    input = keras.Input(shape=input_shape, name='input')

    # conv1
    x = layers.Conv2D(64, 7, strides=(2, 2), padding='same', name='conv1')(input)  # 7×7, 64, stride 2
    x = layers.BatchNormalization(name='bn_conv1')(x)
    x = layers.Activation('relu', name='conv1_relu')(x)
    x = layers.MaxPooling2D((3, 3), strides=2, padding='same', name='pool1')(x)   # 3×3 max pool, stride 2

    # conv2_x
    x = ConvBlock(input_tensor=x, num_output=(64, 64), stride=(1, 1), stage_name='2', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(64, 64), stage_name='2', block_name='b')

    # conv3_x
    x = ConvBlock(input_tensor=x, num_output=(128, 128), stride=(2, 2), stage_name='3', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(128, 128), stage_name='3', block_name='b')

    # conv4_x
    x = ConvBlock(input_tensor=x, num_output=(256, 256), stride=(2, 2), stage_name='4', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256), stage_name='4', block_name='b')

    # conv5_x
    x = ConvBlock(input_tensor=x, num_output=(512, 512), stride=(2, 2), stage_name='5', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(512, 512), stage_name='5', block_name='b')

    # average pool, 1000-d fc, softmax
    x = layers.AveragePooling2D((7, 7), strides=(1, 1), name='pool5')(x)
    x = layers.Flatten(name='flatten')(x)
    x = layers.Dense(class_num, activation='softmax', name='fc1000')(x)

    model = keras.Model(input, x, name='resnet18')
    model.summary()
    return model

if __name__ == '__main__':
    model = ResNet18((INPUT_SIZE, INPUT_SIZE, 3), CLASS_NUM)
    print('Done.')

predict_resnet18.py

import matplotlib.pyplot as plt

from ResNet18 import ResNet18
import cv2
import numpy as np
from tensorflow.keras import backend as K   # K.set_image_dim_ordering('tf')
from tensorflow.keras.utils import to_categorical

INPUT_IMG_SIZE = 224
NUM_CLASSES = 2
label_dict = { 
   0:'CAT', 1:'DOG'}

def show_predict_probability(y_gts, predictions, x_imgs, predict_probabilitys, idx):
    for i in range(len(label_dict)):
        print(label_dict[i]+', Probability:%1.9f'%(predict_probabilitys[idx][i]))
    print('label: ', label_dict[int(y_gts[idx])], ', predict: ', label_dict[predictions[idx]])
    plt.figure(figsize=(2, 2))
    plt.imshow(np.reshape(x_imgs[idx], (INPUT_IMG_SIZE, INPUT_IMG_SIZE, 3)))
    plt.show()

def plot_images_labels_prediction(images, labels, prediction, idx, num):
    fig = plt.gcf()
    fig.set_size_inches(12, 14)
    if num>25: num=25
    for i in range(0, num):
        ax = plt.subplot(2, 5, 1+i)
        ax.imshow(images[idx], cmap='binary')
        title = 'labels='+str(labels[idx])
        if len(prediction) > 0:
            title += "prediction="+str(prediction[idx])
        ax.set_title(title, fontsize=10)
        idx += 1
    plt.show()

if __name__ == '__main__':
    log_path = r"D:\02.Work\00.LearnML\003.Net\ResNet\log\\"
    model = ResNet18((224, 224, 3), NUM_CLASSES)
    model.load_weights(log_path+"resnet18.h5")

    ### cat dog dataset
    lines = []
    root_path = r"D:\03.Data\01.CatDog"
    with open(root_path + "\\test.txt") as f:
       lines = f.readlines()

    x_images_normalize = []
    y_labels_onehot = []
    y_labels = []

    for i in range(len(lines)):
        img_path = lines[i].split(";")[0]
        img = cv2.imread(img_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = cv2.resize(img, (INPUT_IMG_SIZE, INPUT_IMG_SIZE))
        img = img / 255
        x_images_normalize.append(img)
        label = to_categorical(lines[i].split(";")[1], num_classes=NUM_CLASSES)
        y_labels_onehot.append(label)
        y_labels.append(lines[i].split(";")[1])
    x_images_normalize = np.array(x_images_normalize)
    # x_images_normalize = x_images_normalize.reshape(-1, INPUT_IMG_SIZE, INPUT_IMG_SIZE, 3)
    y_labels_onehot = np.array(y_labels_onehot)

    predict_probability = model.predict(x_images_normalize, verbose=1)
    predict = np.argmax(predict_probability, axis=1)

    plot_images_labels_prediction(x_images_normalize, y_labels, predict, 0, 10)
    show_predict_probability(y_labels, predict, x_images_normalize, predict_probability, 0)
    print('done')

2.ResNet50

ResNet50

from tensorflow import keras
from tensorflow.keras import layers

INPUT_SIZE = 224
CLASS_NUM = 1000

# stage_name=2,3,4,5; block_name=a,b,c
def ConvBlock(input_tensor, num_output, stride, stage_name, block_name):
    filter1, filter2, filter3 = num_output

    x = layers.Conv2D(filter1, 1, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    x = layers.Conv2D(filter3, 1, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2c')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2c')(x)

    shortcut = layers.Conv2D(filter3, 1, strides=stride, padding='same', name='res'+stage_name+block_name+'_branch1')(input_tensor)
    shortcut = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch1')(shortcut)

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def IdentityBlock(input_tensor, num_output, stage_name, block_name):
    filter1, filter2, filter3 = num_output

    x = layers.Conv2D(filter1, 1, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2a')(input_tensor)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2a')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2a_relu')(x)

    x = layers.Conv2D(filter2, 3, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2b')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2b')(x)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_branch2b_relu')(x)

    x = layers.Conv2D(filter3, 1, strides=(1, 1), padding='same', name='res'+stage_name+block_name+'_branch2c')(x)
    x = layers.BatchNormalization(name='bn'+stage_name+block_name+'_branch2c')(x)

    shortcut = input_tensor

    x = layers.add([x, shortcut], name='res'+stage_name+block_name)
    x = layers.Activation('relu', name='res'+stage_name+block_name+'_relu')(x)

    return x

def ResNet50(input_shape, class_num):
    input = keras.Input(shape=input_shape, name='input')

    # conv1
    x = layers.Conv2D(64, 7, strides=(2, 2), padding='same', name='conv1')(input)  # 7×7, 64, stride 2
    x = layers.BatchNormalization(name='bn_conv1')(x)
    x = layers.Activation('relu', name='conv1_relu')(x)
    x = layers.MaxPooling2D((3, 3), strides=2, padding='same', name='pool1')(x)   # 3×3 max pool, stride 2

    # conv2_x
    x = ConvBlock(input_tensor=x, num_output=(64, 64, 256), stride=(1, 1), stage_name='2', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(64, 64, 256), stage_name='2', block_name='b')
    x = IdentityBlock(input_tensor=x, num_output=(64, 64, 256), stage_name='2', block_name='c')

    # conv3_x
    x = ConvBlock(input_tensor=x, num_output=(128, 128, 512), stride=(2, 2), stage_name='3', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(128, 128, 512), stage_name='3', block_name='b')
    x = IdentityBlock(input_tensor=x, num_output=(128, 128, 512), stage_name='3', block_name='c')
    x = IdentityBlock(input_tensor=x, num_output=(128, 128, 512), stage_name='3', block_name='d')

    # conv4_x
    x = ConvBlock(input_tensor=x, num_output=(256, 256, 1024), stride=(2, 2), stage_name='4', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256, 1024), stage_name='4', block_name='b')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256, 1024), stage_name='4', block_name='c')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256, 1024), stage_name='4', block_name='d')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256, 1024), stage_name='4', block_name='e')
    x = IdentityBlock(input_tensor=x, num_output=(256, 256, 1024), stage_name='4', block_name='f')

    # conv5_x
    x = ConvBlock(input_tensor=x, num_output=(512, 512, 2048), stride=(2, 2), stage_name='5', block_name='a')
    x = IdentityBlock(input_tensor=x, num_output=(512, 512, 2048), stage_name='5', block_name='b')
    x = IdentityBlock(input_tensor=x, num_output=(512, 512, 2048), stage_name='5', block_name='c')

    # average pool, 1000-d fc, softmax
    x = layers.AveragePooling2D((7, 7), strides=(1, 1), name='pool5')(x)
    x = layers.Flatten(name='flatten')(x)
    x = layers.Dense(class_num, activation='softmax', name='fc1000')(x)

    model = keras.Model(input, x, name='resnet50')
    model.summary()
    return model

if __name__ == '__main__':
    model = ResNet50((INPUT_SIZE, INPUT_SIZE, 3), CLASS_NUM)
    print('Done.')
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/141343.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • JAVA贪吃蛇代码(带注释)

    JAVA贪吃蛇代码(带注释)贪吃蛇图片是代码里面的素材游戏数据类packagecom.tang.retor_snaker;importjavax.swing.*;importjava.net.URL;publicclassData{privatestaticURLbodyURL=Data.class.getResource(“/com/tang/retor_snaker/statics/body.png”);privatestaticImageIconbo

  • Python获取时间戳及常用的时间格式转换[通俗易懂]

    Python获取时间戳及常用的时间格式转换[通俗易懂]常用的时间格式转换:时间戳:10位13位16位ISO格式UTC时间代码如下:#!/usr/bin/envpython#coding=utf-8″””#:author:TerryLi#:url:https://blog.csdn.net/qq_42183962#:copyright:©2020-presentTerryLi#:motto:IbelievethattheGodrewardsthediligent.”””import

  • Redis Cluster集群收缩主从节点详细教程

    Redis Cluster集群收缩主从节点详细教程RedisCluster集群收缩主从节点文章目录RedisCluster集群收缩主从节点1.Cluster集群收缩概念2.将6390主节点从集群中收缩2.1.计算需要分给每一个节点的槽位数2.2.分配1365个槽位给192.168.81.210的6380节点2.3.分配1365个槽位给192.168.81.220的6380节点2.4.分配1365个槽位给192.168.81.230的6380节点2.5.查看当前集群槽位分配3.验证数据迁移过程是否导致数据异常4.将下线的主节点从集群中删除4.1.删除节

    2022年10月29日
  • Tomcat server missing

    Tomcat server missingTomcat server missing

  • 小米nfc模拟加密门禁卡详细图文教程(实测可用)—————– IC ID CUID卡区别

    小米nfc模拟加密门禁卡详细图文教程(实测可用)—————– IC ID CUID卡区别现在小区虽然都加装了智能门,可以通过手机NFC功能开启或者使用钥匙开启,但是有些用户并不知道原来手机是可以当钥匙使用的。今天我们来学习使用小米nfc模拟加密门禁卡,这样手机就可以变成一把钥匙了。以下是小米nfc模拟加密门禁卡步骤。1、非加密卡直接使用小米钱包的门卡模拟功能即可,如果能直接模拟的就不是加密卡。2、NFC手机支持的频段一般为13.56Mhz卡片,如果是其他门禁卡,手机贴上根本没反应的不可以模拟。3、只能模拟卡片的ID,不支持储值消费等功能。部分门禁等系统只认证卡片ID,所以有可能通过

  • 绕过问题也是一种能力–记一次接口的问题「建议收藏」

    绕过问题也是一种能力–记一次接口的问题

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号