使用TensorFlow训练模型的基本流程【转】

原文地址(https://github.com/wmpscc/TensorflowBaseDemo )

本篇文章将介绍使用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 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.Features(feature={
'label': _int64_feature(label),
'image_raw': _bytes_feature(image_raw_data)
}))
if i

上一篇:Java关键字——transient


下一篇:[转]Jmeter + Grafana + InfluxDB 性能测试监控