本文已在公众号
机器视觉与算法建模发布,转载请联系我。
使用TensorFlow的基本流程
本篇文章将介绍使用tensorflow的训练模型的基本流程,包括制作读取TFRecord,训练和保存模型,读取模型。
准备
- 语言:Python3
- 库:tensorflow、cv2、numpy、matplotlib
- 数据集:Chars74K dataset 的数字部分
- 网络:CNN
所有代码已经上传至github:https://github.com/wmpscc/TensorflowBaseDemo
TFRecord
TensorFlow提供了一种统一的格式来存储数据,这个格式就是TFRecord.
message Example {
Features features = 1;
};
message Features{
map<string,Feature> featrue = 1;
};
message Feature{
oneof kind{
BytesList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
从代码中我们可以看到, tf.train.Example 包含了一个字典,它的键是一个字符串,值为Feature,Feature可以取值为字符串(BytesList)、浮点数列表(FloatList)、整型数列表(Int64List)。
写入一个TFRecord一般分为三步:
- 读取需要转化的数据
- 将数据转化为Example Protocol Buffer,并写入这个数据结构
- 通过将数据转化为字符串后,通过TFRecordWriter写出
方法一
这次我们的数据是分别保存在多个文件夹下的,因此读取数据最直接的方法是遍历目录下所有文件,然后读入写出TFRecord文件。该方法对应文件MakeTFRecord.py,我们来看关键代码
filenameTrain = 'TFRecord/train.tfrecords'
filenameTest = 'TFRecord/test.tfrecords'
writerTrain = tf.python_io.TFRecordWriter(filenameTrain)
writerTest = tf.python_io.TFRecordWriter(filenameTest)
folders = os.listdir(HOME_PATH)
for subFoldersName in folders:
label = transform_label(subFoldersName)
path = os.path.join(HOME_PATH, subFoldersName) # 文件夹路径
subFoldersNameList = os.listdir(path)
i = 0
for imageName in subFoldersNameList:
imagePath = os.path.join(path, imageName)
images = cv2.imread(imagePath)
res = cv2.resize(images, (128, 128), interpolation=cv2.INTER_CUBIC)
image_raw_data = res.tostring()
example = tf.train.Example(features=tf.train.

本文详细介绍了使用TensorFlow训练模型的基本步骤,包括制作和读取TFRecord文件、训练和保存模型、在测试集上评估准确率。内容涵盖数据预处理、原尺寸及减半尺寸的CNN模型、模型保存与恢复,以及如何查看TFRecord图片。
最低0.47元/天 解锁文章
7154

被折叠的 条评论
为什么被折叠?



