resnet18,tensorflow1.x和tensorflow2.x 环境和完整训练、测试代码

环境(conda list在文末):

python                    3.8.18

tensorflow                2.3.0

keras                     2.4.3 

numpy                     1.19.1

代码:

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, Model

from keras.datasets import cifar10

def residual_block(x, filters, kernel_size=3, strides=(1, 1), activation='relu'):
    y = layers.Conv2D(filters, kernel_size, strides=strides, padding='same')(x)
    y = layers.BatchNormalization()(y)
    y = layers.Activation(activation)(y)

    y = layers.Conv2D(filters, kernel_size, padding='same')(y)
    y = layers.BatchNormalization()(y)

    if strides != (1, 1) or x.shape[-1] != filters:
        x = layers.Conv2D(filters, (1, 1), strides=strides, padding='same')(x)

    out = layers.add([x, y])
    out = layers.Activation('relu')(out)
    return out

def resnet_18(input_shape=(32, 32, 3), num_classes=10):
    input = layers.Input(shape=input_shape)
   
    x = layers.Conv2D(64, (7, 7), padding='same', strides=(2, 2))(input)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)
    x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)

    x = residual_block(x, 64, strides=(1, 1))
    x = residual_block(x, 64)
    x = residual_block(x, 128, strides=(2, 2))
    x = residual_block(x, 128)
    x = residual_block(x, 256, strides=(2, 2))
    x = residual_block(x, 256)
    x = residual_block(x, 512, strides=(2, 2))
    x = residual_block(x, 512)

    x = layers.GlobalAveragePooling2D()(x)
    output = layers.Dense(num_classes, activation='softmax')(x)

    model = Model(input, output)
    return model

# 加载CIFAR-10数据集并预处理
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

# 构建并训练模型
model = resnet_18()

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=64, epochs=5, validation_split=0.2)

# 在测试集上评估模型
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Accuracy: {:.2f}%".format(accuracy * 100))

-----------------------------------------------------------------------------------------------------------------------------------------------------------

环境:

python                    3.6.10

tensorflow                1.2.0

keras                     2.0.9

numpy                     1.19.2

代码:

# 导入所需的库
import numpy as np
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dense
from keras.layers import BatchNormalization, Activation, add
from keras.utils import to_categorical
from keras.datasets import cifar10

# 定义Residual Unit模块
def residual_unit(x, filters, strides=(1, 1), activation='relu'):
    res_path = x

    # 第一层
    x = Conv2D(filters, (3, 3), padding='same', strides=strides)(x)
    x = BatchNormalization()(x)
    x = Activation(activation)(x)

    # 第二层
    x = Conv2D(filters, (3, 3), padding='same')(x)
    x = BatchNormalization()(x)

    # 如果步长不为1或输入通道数与输出通道数不一致,使用卷积调整尺寸
    if strides != (1, 1) or res_path.shape[-1] != filters:
        res_path = Conv2D(filters, (1, 1), padding='valid', strides=strides)(res_path)

    # 合并残差路径
    x = add([x, res_path])
    x = Activation(activation)(x)
    return x

# 搭建ResNet-18模型结构
def build_resnet(input_shape=(32, 32, 3), num_classes=10):
    input = Input(shape=input_shape)
    x = Conv2D(64, (7, 7), padding='same', strides=(2, 2))(input)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)

    x = residual_unit(x, 64)
    x = residual_unit(x, 64)
    x = residual_unit(x, 128, strides=(2, 2))
    x = residual_unit(x, 128)
    x = residual_unit(x, 256, strides=(2, 2))
    x = residual_unit(x, 256)
    x = residual_unit(x, 512, strides=(2, 2))
    x = residual_unit(x, 512)

    x = GlobalAveragePooling2D()(x)
    output = Dense(num_classes, activation='softmax')(x)

    model = Model(input, output)
    return model

# 加载CIFAR-10数据集并预处理
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# 构建并训练模型
model = build_resnet()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test))

# 在测试集上评估模型
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Accuracy: {:.2f}%".format(accuracy * 100))

-----------------------------------------------------------------------------------------------------

tensorflow 2 对应的conda list:

# packages in environment at C:\Users\USER\anaconda3\envs\tf2:
#
# Name Version Build Channel
_tflow_select 2.3.0 eigen
abseil-cpp 20230802.0 h5da7b33_2
absl-py 1.4.0 py38haa95532_0
aiohttp 3.9.3 py38h2bbff1b_0
aiosignal 1.2.0 pyhd3eb1b0_0
astor 0.8.1 py38haa95532_0
astunparse 1.6.3 py_0
async-timeout 4.0.3 py38haa95532_0
attrs 23.1.0 py38haa95532_0
blas 1.0 mkl
blinker 1.6.2 py38haa95532_0
c-ares 1.19.1 h2bbff1b_0
ca-certificates 2023.12.12 haa95532_0
cachetools 4.2.2 pyhd3eb1b0_0
certifi 2024.2.2 py38haa95532_0
cffi 1.16.0 py38h2bbff1b_0
charset-normalizer 2.0.4 pyhd3eb1b0_0
click 8.1.7 py38haa95532_0
colorama 0.4.6 py38haa95532_0
console_shortcut 0.1.1 4
cryptography 42.0.2 py38h89fc84f_0
frozenlist 1.4.0 py38h2bbff1b_0
gast 0.4.0 pyhd3eb1b0_0
google-auth 2.6.0 pyhd3eb1b0_0
google-auth-oauthlib 0.4.4 pyhd3eb1b0_0
google-pasta 0.2.0 pyhd3eb1b0_0
grpc-cpp 1.48.2 h6772dbd_4
grpcio 1.48.2 py38h6772dbd_4
gtest 1.14.0 h59b6b97_0
h5py 2.10.0 py38h5e291fa_0
hdf5 1.10.4 h7ebc959_0
icc_rt 2022.1.0 h6049295_2
idna 3.4 py38haa95532_0
importlib-metadata 7.0.1 py38haa95532_0
intel-openmp 2023.1.0 h59b6b97_46320
keras 2.4.3 hd3eb1b0_0
keras-applications 1.0.8 py_1
keras-base 2.4.3 pyhd3eb1b0_0
keras-preprocessing 1.1.2 pyhd3eb1b0_0
libffi 3.4.4 hd77b12b_0
libprotobuf 3.20.3 h23ce68f_0
markdown 3.4.1 py38haa95532_0
markupsafe 2.1.3 py38h2bbff1b_0
mkl 2020.2 256
mkl-service 2.3.0 py38h196d8e1_0
mkl_fft 1.3.0 py38h46781fe_0
mkl_random 1.1.1 py38h47e9c7a_0
multidict 6.0.4 py38h2bbff1b_0
numpy 1.19.1 py38h5510c5b_0
numpy-base 1.19.1 py38ha3acd2a_0
oauthlib 3.2.2 py38haa95532_0
openssl 3.0.13 h2bbff1b_0
opt_einsum 3.3.0 pyhd3eb1b0_1
packaging 23.1 py38haa95532_0
pip 23.3.1 py38haa95532_0
platformdirs 3.10.0 py38haa95532_0
pooch 1.7.0 py38haa95532_0
protobuf 3.20.3 py38hd77b12b_0
pyasn1 0.4.8 pyhd3eb1b0_0
pyasn1-modules 0.2.8 py_0
pycparser 2.21 pyhd3eb1b0_0
pyjwt 2.4.0 py38haa95532_0
pyopenssl 24.0.0 py38haa95532_0
pyreadline 2.1 py38_1
python 3.8.18 h1aa4202_0
pyyaml 6.0.1 py38h2bbff1b_0
re2 2022.04.01 hd77b12b_0
requests 2.31.0 py38haa95532_1
requests-oauthlib 1.3.0 py_0
rsa 4.7.2 pyhd3eb1b0_1
scipy 1.6.2 py38h14eb087_0
setuptools 68.2.2 py38haa95532_0
six 1.16.0 pyhd3eb1b0_1
sqlite 3.41.2 h2bbff1b_0
tbb 2021.8.0 h59b6b97_0
tensorboard 2.10.0 py38haa95532_0
tensorboard-data-server 0.6.1 py38haa95532_0
tensorboard-plugin-wit 1.8.1 py38haa95532_0
tensorflow 2.3.0 mkl_py38h8c0d9a2_0
tensorflow-base 2.3.0 eigen_py38h75a453f_0
tensorflow-estimator 2.6.0 pyh7b7c402_0
termcolor 2.1.0 py38haa95532_0
urllib3 2.1.0 py38haa95532_0
vc 14.2 h21ff451_1
vs2015_runtime 14.27.29016 h5e58377_2
werkzeug 2.3.8 py38haa95532_0
wheel 0.41.2 py38haa95532_0
wrapt 1.14.1 py38h2bbff1b_0
yaml 0.2.5 he774522_0
yarl 1.9.3 py38h2bbff1b_0
zipp 3.17.0 py38haa95532_0
zlib 1.2.13 h8cc25b3_0

 

posted @ 2023-09-12 22:24  园友1683564  阅读(34)  评论(0编辑  收藏  举报