这篇薄荷主要是讲了如何用tensorflow去训练好一个模型,然后生成相应的pb文件。最后会将如何重新加载这个pb文件。
首先先放出PO主的github:
https://github.com/ppplinday/tensorflow-vgg16-train-and-test
其中的pitcute文件是狗和猫的图片分别15张一共30(别吐槽,只是为了练手学习的233333), train那个就是训练的文件,test这个就是测试的文件。
接着PO主会慢慢讲解相应的步骤。
!!!ps:由于PO主也是新手,所以难免会出现一点(很多)小错误,希望大婶看了能够提出来让PO主好好学习233333。
- train
首先说一下train。一开始当然是读图片啦。
def read_img(path):
cate = [path + x for x in os.listdir(path) if os.path.isdir(path + x)]
imgs = []
labels = []
for idx, folder in enumerate(cate):
for im in glob.glob(folder + '/*.jpg'):
print('reading the image: %s' % (im))
img = io.imread(im)
img = transform.resize(img, (w, h, c))
imgs.append(img)
labels.append(idx)
return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)
data, label = read_img(path)
用io.imread来读取每一张图片,然后resize成vgg的输入的大小(224,224,3),最后分别放入了data和label中。
num_example = data.shape[0]
arr = np.arange(num_example)
np.random.shuffle(arr)
data = data[arr]
label = label[arr]
这里是把图片的顺序打乱,先生成一个等差数列,然后打乱,最后赋值回原来的data和label
ratio = 0.8
s = np.int(num_example * ratio)
x_train = data[:s]
y_train = label[:s]
x_val = data[s:]
y_val = label[s:]
全部的数据中百分之80的用来train,剩下20的用来test(虽然一共才30张图片。。。。。)
def build_network(height, width, channel):
x = tf.placeholder(tf.float32, shape=[None, height, width, channel], name='input')
y = tf.placeholder(tf.int64, shape=[None, 2], name='labels_placeholder')
开始build相应的vgg model,这一步不难,但是每一层最好都给上相应的name。上面的x和y是相应的输入和相应的标签。
finaloutput = tf.nn.softmax(output_fc8, name="softmax")
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=finaloutput, labels=y))
optimize = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)
prediction_labels = tf.argmax(finaloutput, axis=1, name="output")
read_labels = y
correct_prediction = tf.equal(prediction_labels, read_labels)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
correct_times_in_batch = tf.reduce_sum(tf.cast(correct_prediction, tf.int32))
return dict(
x=x,
y=y,
optimize=optimize,
correct_prediction=correct_prediction,
correct_times_in_batch=correct_times_in_batch,
cost=cost,
)
在build的最后,是需要进行误差计算。finaloutput是最后的输出,cost是计算误差,optimize是定义训练时候安什么方式,也注意一下最后的return。
接着是训练过程。
def train_network(graph, batch_size, num_epochs, pb_file_path):
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
epoch_delta = 2
for epoch_index in range(num_epochs):
for i in range(12):
sess.run([graph['optimize']], feed_dict={
graph['x']: np.reshape(x_train[i], (1, 224, 224, 3)),
graph['y']: ([[1, 0]] if y_train[i] == 0 else [[0, 1]])
})
其实训练的代码就这些,定好了batchsize和numepoch进行训练。下面的代码主要是为了看每几次相应的正确率。