import numpy as np
from tensorflow.keras.optimizers import Adam
import cv2
from tensorflow.keras.preprocessing.image import img_to_array
from sklearn.model_selection import train_test_split
from tensorflow.python.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.applications import DenseNet121
import os
import tensorflow as tf
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.models import Sequential
import albumentations
norm_size = 224
datapath = 'data/train'
EPOCHS = 20
INIT_LR = 1e-3
labelList = []
dicClass = {'cat': 0, 'dog': 1}
classnum = 2
batch_size = 4
np.random.seed(42)
def loadImageData():
imageList = []
listImage = os.listdir(datapath)
for img in listImage:
labelName = dicClass[img.split('.')[0]]
print(labelName)
labelList.append(labelName)
dataImgPath = os.path.join(datapath, img)
print(dataImgPath)
imageList.append(dataImgPath)
return imageList
print("开始加载数据")
imageArr = loadImageData()
labelList = np.array(labelList)
print("加载数据完成")
print(labelList)
trainX, valX, trainY, valY = train_test_split(imageArr, labelList, test_size=0.3, random_state=42)
train_transform = albumentations.Compose([
albumentations.OneOf([
albumentations.RandomGamma(gamma_limit=(60, 120), p=0.9),
albumentations.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9),
albumentations.CLAHE(clip_limit=4.0, tile_grid_size=(4, 4), p=0.9),
]),
albumentations.OneOf([
albumentations.Blur(blur_limit=4, p=1),
albumentations.MotionBlur(blur_limit=4, p=1),
], p=0.5),
albumentations.HorizontalFlip(p=0.5),
albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=20,
interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_CONSTANT, p=1),
albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)
])
def generator(file_pathList,labels,batch_size,train_action=False):
L = len(file_pathList)
while True:
input_labels = []
input_samples = []
for row in range(0, batch_size):
temp = np.random.randint(0, L)
X = file_pathList[temp]
Y = labels[temp]
image = cv2.imdecode(np.fromfile(X, dtype=np.uint8), -1)
if train_action:
image=train_transform(image=image)['image']
image = cv2.resize(image, (norm_size, norm_size), interpolation=cv2.INTER_LANCZOS4)
image = img_to_array(image)
input_samples.append(image)
input_labels.append(Y)
batch_x = np.asarray(input_samples)/255.0
batch_y = np.asarray(input_labels)
yield (batch_x, batch_y)
checkpointer = ModelCheckpoint(filepath='weights_best_Deset_model.hdf5',
monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
reduce = ReduceLROnPlateau(monitor='val_accuracy', patience=10,
verbose=1,
factor=0.5,
min_lr=1e-6)
#model = ResNet50(weights="imagenet",input_shape=(224,224,3),include_top=False, classes=classnum) #include_top=False 去掉最后的全连接层
model = Sequential()
model.add(DenseNet121(include_top=False, pooling='avg', weights='imagenet'))
model.add(Dense(classnum, activation='softmax'))
# 如果想指定classes,有两个条件:include_top:True, weights:None。否则无法指定classes
# model = ResNet50(weights=None,input_shape=(norm_size, norm_size, 3), classes=classnum)
optimizer = Adam(learning_rate=INIT_LR)
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(generator(trainX,trainY,batch_size,train_action=True),
steps_per_epoch=len(trainX) / batch_size,
validation_data=generator(valX,valY,batch_size,train_action=False),
epochs=EPOCHS,
validation_steps=len(valX) / batch_size,
callbacks=[checkpointer, reduce])
model.save('my_model_Desnet.h5')
print(history)
loss_trend_graph_path = r"WW_loss.jpg"
acc_trend_graph_path = r"WW_acc.jpg"
import matplotlib.pyplot as plt
print("Now,we start drawing the loss and acc trends graph...")
# summarize history for accuracy
fig = plt.figure(1)
plt.plot(history.history["accuracy"])
plt.plot(history.history["val_accuracy"])
plt.title("Model accuracy")
plt.ylabel("accuracy")
plt.xlabel("epoch")
plt.legend(["train", "test"], loc="upper left")
plt.savefig(acc_trend_graph_path)
plt.close(1)
# summarize history for loss
fig = plt.figure(2)
plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("Model loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(["train", "test"], loc="upper left")
plt.savefig(loss_trend_graph_path)
plt.close(2)
print("We are done, everything seems OK...")
# #windows系统设置10关机
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
本例提取了猫狗大战数据集中的部分数据做数据集,演示tensorflow2.0以上的版本如何使用Keras实现图像分类,分类的模型使用DenseNet121。本文实现的算法有一下几个特点: 1、自定义了图片加载方式,更加灵活高效,节省内存 2、加载模型的预训练权重,训练时间更短。 3、数据增强选用albumentations。 详见:https://wanghao.blog.csdn.net/article/details/122607363?spm=1001.2014.3001.5502
资源推荐
资源详情
资源评论
收起资源包目录
DenseNet实战:tensorflow2.X版本,DenseNet121图像分类任务(大数据集) (2000个子文件)
my_model_Desnet.h5 81.95MB
weights_best_Deset_model.hdf5 81.95MB
cat.835.jpg 91KB
dog.3085.jpg 85KB
dog.2274.jpg 79KB
dog.10708.jpg 79KB
dog.9452.jpg 77KB
dog.11685.jpg 76KB
dog.1870.jpg 75KB
dog.3785.jpg 74KB
dog.9869.jpg 74KB
dog.3076.jpg 73KB
dog.7931.jpg 72KB
dog.6259.jpg 72KB
dog.157.jpg 71KB
dog.8524.jpg 70KB
dog.1427.jpg 70KB
dog.4835.jpg 69KB
dog.10706.jpg 68KB
dog.11795.jpg 68KB
dog.1039.jpg 68KB
dog.9148.jpg 68KB
dog.10456.jpg 68KB
cat.5665.jpg 68KB
dog.9436.jpg 67KB
dog.11263.jpg 67KB
dog.6098.jpg 67KB
dog.1035.jpg 67KB
cat.1772.jpg 66KB
cat.6156.jpg 66KB
dog.5451.jpg 66KB
dog.3518.jpg 66KB
dog.11266.jpg 65KB
dog.1201.jpg 65KB
cat.787.jpg 65KB
dog.1132.jpg 65KB
dog.4769.jpg 65KB
dog.7179.jpg 65KB
dog.815.jpg 65KB
dog.8400.jpg 64KB
dog.7033.jpg 64KB
dog.11486.jpg 64KB
dog.6682.jpg 64KB
dog.1408.jpg 64KB
dog.5477.jpg 63KB
dog.11560.jpg 63KB
dog.4353.jpg 63KB
dog.4677.jpg 63KB
dog.10865.jpg 63KB
dog.9160.jpg 63KB
dog.6285.jpg 63KB
cat.9512.jpg 63KB
dog.7947.jpg 63KB
dog.7194.jpg 63KB
dog.11571.jpg 63KB
dog.10980.jpg 63KB
dog.7002.jpg 63KB
dog.4266.jpg 62KB
dog.3782.jpg 62KB
dog.4025.jpg 62KB
dog.9737.jpg 62KB
dog.4719.jpg 62KB
dog.4200.jpg 62KB
dog.1976.jpg 62KB
dog.11358.jpg 62KB
dog.1869.jpg 62KB
dog.55.jpg 62KB
dog.3292.jpg 62KB
dog.5226.jpg 62KB
dog.3551.jpg 61KB
dog.9343.jpg 61KB
dog.4894.jpg 61KB
dog.3071.jpg 61KB
dog.6113.jpg 61KB
dog.735.jpg 61KB
dog.10473.jpg 61KB
dog.6090.jpg 61KB
dog.10963.jpg 61KB
dog.355.jpg 61KB
dog.11655.jpg 61KB
dog.1817.jpg 61KB
dog.9588.jpg 60KB
dog.9127.jpg 60KB
dog.2649.jpg 60KB
dog.9564.jpg 60KB
dog.3027.jpg 60KB
dog.1560.jpg 60KB
dog.10514.jpg 60KB
dog.10431.jpg 60KB
dog.8659.jpg 60KB
dog.811.jpg 60KB
dog.9510.jpg 60KB
cat.5515.jpg 60KB
dog.10565.jpg 60KB
dog.1912.jpg 60KB
cat.3016.jpg 60KB
dog.9952.jpg 59KB
dog.7259.jpg 59KB
cat.1048.jpg 59KB
dog.8862.jpg 59KB
共 2000 条
- 1
- 2
- 3
- 4
- 5
- 6
- 20
AI浩
- 粉丝: 14w+
- 资源: 216
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
- 3
- 4
- 5
前往页