Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
别团等shy哥发育
Tensorflow Deep Learning
提交
f63321af
T
Tensorflow Deep Learning
项目概览
别团等shy哥发育
/
Tensorflow Deep Learning
9 个月 前同步成功
通知
1
Star
1
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
T
Tensorflow Deep Learning
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
提交
f63321af
编写于
9月 15, 2022
作者:
别团等shy哥发育
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
ResNet50(迁移学习)花朵识别
上级
1be928da
变更
3
隐藏空白更改
内联
并排
Showing
3 changed file
with
210 addition
and
2 deletion
+210
-2
图像识别/花朵识别/DenseNet-test.py
图像识别/花朵识别/DenseNet-test.py
+3
-2
图像识别/花朵识别/ResNet-test.py
图像识别/花朵识别/ResNet-test.py
+77
-0
图像识别/花朵识别/ResNet50(迁移学习).py
图像识别/花朵识别/ResNet50(迁移学习).py
+130
-0
未找到文件。
图像识别/花朵识别/DenseNet-test.py
浏览文件 @
f63321af
...
...
@@ -56,8 +56,9 @@ def predict_directory(file_path):
# 传入文件路径进行预测
preds
,
prob
=
predict_single_image
(
file_dir
)
# 取出图片的真实标签(_前面的部分为标签值)
label_true
=
file
.
split
(
'_'
)[
0
].
title
()
# 取出图片的真实标签(这里直接将文件夹名称作为真实标签值了)
# label_true=file.split('_')[0].title()
label_true
=
file_dir
.
split
(
'
\\
'
)[
0
].
split
(
'/'
)[
-
1
]
# 保存真实值和预测值结果
classes_true
.
append
(
label_true
)
classes_pred
.
append
(
preds
)
...
...
图像识别/花朵识别/ResNet-test.py
0 → 100644
浏览文件 @
f63321af
import
tensorflow
as
tf
import
numpy
as
np
import
os
import
matplotlib.pyplot
as
plt
from
tensorflow.keras
import
layers
from
tensorflow.keras.models
import
load_model
# from PIL import Image
model
=
load_model
(
'model/ResNet50(迁移学习)-花朵分类(17).h5'
)
model
.
summary
()
# 类别总数
dataset_dir
=
'data/train'
classes
=
[]
for
filename
in
os
.
listdir
(
dataset_dir
):
classes
.
append
(
filename
)
# print('classes:',classes)
# 预测单张图片
def
predict_single_image
(
img_path
):
img
=
tf
.
io
.
read_file
(
img_path
)
# 将jpg格式转换为tensor
img
=
tf
.
image
.
decode_jpeg
(
img
,
channels
=
3
)
# 数据归一化
img
=
tf
.
image
.
convert_image_dtype
(
img
,
dtype
=
tf
.
float32
)
# resize
img
=
tf
.
image
.
resize
(
img
,
size
=
[
224
,
224
])
# 扩充一个维度
img
=
np
.
expand_dims
(
img
,
axis
=
0
)
# 预测:结果是二维的
test_result
=
model
.
predict
(
img
)
# print('test_result:', test_result)
# 转化为一维
result
=
np
.
squeeze
(
test_result
)
# print('转化后result:', result)
# 找到概率值最大的索引
predict_class
=
np
.
argmax
(
result
)
# print('概率值最大的索引:', predict_class)
# 返回类别和所属类别的概率
return
classes
[
int
(
predict_class
)],
result
[
predict_class
]
# 对整个文件夹的图片进行预测
def
predict_directory
(
file_path
):
classes_pred
=
[]
classes_true
=
[]
probs
=
[]
for
file
in
os
.
listdir
(
file_path
):
# 测试图片完整路径
file_dir
=
os
.
path
.
join
(
file_path
,
file
)
# 打印文件路径
print
(
file_dir
)
# 传入文件路径进行预测
preds
,
prob
=
predict_single_image
(
file_dir
)
# 取出图片的真实标签(_前面的部分为标签值)
# label_true=file.split('_')[0].title()
label_true
=
file_dir
.
split
(
'
\\
'
)[
0
].
split
(
'/'
)[
-
1
]
# 保存真实值和预测值结果
classes_true
.
append
(
label_true
)
classes_pred
.
append
(
preds
)
probs
.
append
(
prob
)
return
classes_pred
,
classes_true
,
probs
# img_path = 'Gemstones/train/Almandine/almandine_0.jpg'
# classes, prob = predict_single_image(img_path)
# print(classes, prob)
file_path
=
'data/test/flower0'
classes_pred
,
classes_true
,
probs
=
predict_directory
(
file_path
)
print
(
classes_pred
)
print
(
classes_true
)
print
(
probs
)
\ No newline at end of file
图像识别/花朵识别/ResNet50(迁移学习).py
0 → 100644
浏览文件 @
f63321af
import
tensorflow
as
tf
import
numpy
as
np
import
matplotlib.pyplot
as
plt
from
tensorflow.keras.preprocessing.image
import
ImageDataGenerator
from
tensorflow.keras
import
layers
from
tensorflow.keras.models
import
Model
from
tensorflow.keras.applications
import
ResNet50
from
tensorflow.keras.callbacks
import
LearningRateScheduler
model
=
ResNet50
(
include_top
=
False
,
input_shape
=
(
224
,
224
,
3
))
model
.
summary
()
# 类别数
num_classes
=
17
# 批次大小
batch_size
=
32
# 周期数
epochs
=
100
# 图片大小
image_size
=
224
model
=
tf
.
keras
.
Sequential
([
model
,
layers
.
GlobalAveragePooling2D
(),
layers
.
Dense
(
num_classes
,
activation
=
'softmax'
)
])
model
.
summary
()
# 训练集数据进行数据增强
train_datagen
=
ImageDataGenerator
(
rotation_range
=
20
,
# 随机旋转度数
width_shift_range
=
0.1
,
# 随机水平平移
height_shift_range
=
0.1
,
# 随机竖直平移
rescale
=
1
/
255
,
# 数据归一化
shear_range
=
10
,
# 随机错切变换
zoom_range
=
0.1
,
# 随机放大
horizontal_flip
=
True
,
# 水平翻转
brightness_range
=
(
0.7
,
1.3
),
# 亮度变化
fill_mode
=
'nearest'
,
# 填充方式
)
# 测试集数据只需要归一化就可以
test_datagen
=
ImageDataGenerator
(
rescale
=
1
/
255
,
# 数据归一化
)
# 训练集数据生成器,可以在训练时自动产生数据进行训练
# 从'data/train'获得训练集数据
# 获得数据后会把图片resize为image_size×image_size的大小
# generator每次会产生batch_size个数据
train_generator
=
train_datagen
.
flow_from_directory
(
'data/花朵分类(17)/train'
,
target_size
=
(
image_size
,
image_size
),
# 调整图像尺寸
batch_size
=
batch_size
,
)
# 测试集数据生成器
test_generator
=
test_datagen
.
flow_from_directory
(
'data/花朵分类(17)/test'
,
target_size
=
(
image_size
,
image_size
),
batch_size
=
batch_size
,
)
# 字典的键为17个文件夹的名字,值为对应的分类编号
print
(
train_generator
.
class_indices
)
# 学习率调节函数,逐渐减小学习率
def
adjust_learning_rate
(
epoch
):
# 前40周期
if
epoch
<=
40
:
lr
=
1e-4
# 前40到80周期
elif
40
<
epoch
<=
80
:
lr
=
1e-5
# 80到100周期
else
:
lr
=
1e-6
return
lr
# 定义优化器
adam
=
Adam
(
lr
=
1e-4
)
# 读取模型
checkpoint_save_path
=
"./checkpoint/ResNet50-花朵分类(17).ckpt"
if
os
.
path
.
exists
(
checkpoint_save_path
+
'.index'
):
print
(
'-------------load the model-----------------'
)
model
.
load_weights
(
checkpoint_save_path
)
# 保存模型
cp_callback
=
tf
.
keras
.
callbacks
.
ModelCheckpoint
(
filepath
=
checkpoint_save_path
,
save_weights_only
=
True
,
save_best_only
=
True
)
# 定义学习率衰减策略
callbacks
=
[]
callbacks
.
append
(
LearningRateScheduler
(
adjust_learning_rate
))
callbacks
.
append
(
cp_callback
)
# 定义优化器,loss function,训练过程中计算准确率
model
.
compile
(
optimizer
=
adam
,
loss
=
'categorical_crossentropy'
,
metrics
=
[
'accuracy'
])
# 训练
history
=
model
.
fit
(
x
=
train_generator
,
epochs
=
epochs
,
validation_data
=
test_generator
,
callbacks
=
callbacks
)
# 保存模型
# model.save('model/ResNet50(迁移学习)-花朵分类(17).h5')
# 画出训练集准确率曲线图
plt
.
plot
(
np
.
arange
(
epochs
),
history
.
history
[
'accuracy'
],
c
=
'b'
,
label
=
'train_accuracy'
)
# 画出验证集准确率曲线图
plt
.
plot
(
np
.
arange
(
epochs
),
history
.
history
[
'val_accuracy'
],
c
=
'y'
,
label
=
'val_accuracy'
)
# 图例
plt
.
legend
()
# x坐标描述
plt
.
xlabel
(
'epochs'
)
# y坐标描述
plt
.
ylabel
(
'accuracy'
)
# 显示图像
plt
.
show
()
# 画出训练集loss曲线图
plt
.
plot
(
np
.
arange
(
epochs
),
history
.
history
[
'loss'
],
c
=
'b'
,
label
=
'train_loss'
)
# 画出验证集loss曲线图
plt
.
plot
(
np
.
arange
(
epochs
),
history
.
history
[
'val_loss'
],
c
=
'y'
,
label
=
'val_loss'
)
# 图例
plt
.
legend
()
# x坐标描述
plt
.
xlabel
(
'epochs'
)
# y坐标描述
plt
.
ylabel
(
'loss'
)
# 显示图像
plt
.
show
()
\ No newline at end of file
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录