1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| import paddle import paddle.fluid as fluid import numpy import sys import os from multiprocessing import cpu_count import time import matplotlib.pyplot as plt
def train_mapper(sample): """ 根据传入的样本数据(一行文本)读取图片数据并返回 :param sample: 元组,格式为(图片路径,类别) :return:返回图像数据、类别 """ img, label = sample if not os.path.exists(img): print(img, "图片不存在")
img = paddle.dataset.image.load_image(img) img = paddle.dataset.image.simple_transform(im=img, resize_size=128, crop_size=128, is_color=True, is_train=True) img = img.astype("float32") / 255.0 return img, label
def train_r(train_list, buffered_size=1024): def reader(): with open(train_list, "r") as f: lines = [line.strip() for line in f] for line in lines: img_path, lab = line.replace("\n","").split("\t") yield img_path, int(lab) return paddle.reader.xmap_readers(train_mapper, reader, cpu_count(), buffered_size)
def convolution_neural_network(image, type_size): """ 创建CNN :param image: 图像数据 :param type_size: 输出类别数量 :return: 分类概率 """ conv_pool_1 = fluid.nets.simple_img_conv_pool(input=image, filter_size=3, num_filters=32, pool_size=2, pool_stride=2, act="relu") drop = fluid.layers.dropout(x=conv_pool_1, dropout_prob=0.5)
conv_pool_2 = fluid.nets.simple_img_conv_pool(input=drop, filter_size=3, num_filters=64, pool_size=2, pool_stride=2, act="relu") drop = fluid.layers.dropout(x=conv_pool_2, dropout_prob=0.5)
conv_pool_3 = fluid.nets.simple_img_conv_pool(input=drop, filter_size=3, num_filters=64, pool_size=2, pool_stride=2, act="relu") drop = fluid.layers.dropout(x=conv_pool_3, dropout_prob=0.5)
fc = fluid.layers.fc(input=drop, size=512, act="relu") drop = fluid.layers.dropout(x=fc, dropout_prob=0.5) predict = fluid.layers.fc(input=drop, size=type_size, act="softmax") return predict
BATCH_SIZE = 32 trainer_reader = train_r(train_list=train_file_path) random_train_reader = paddle.reader.shuffle(reader=trainer_reader, buf_size=1300) batch_train_reader = paddle.batch(random_train_reader, batch_size=BATCH_SIZE)
image = fluid.layers.data(name="image", shape=[3, 128, 128], dtype="float32") label = fluid.layers.data(name="label", shape=[1], dtype="int64")
predict = convolution_neural_network(image=image, type_size=5)
cost = fluid.layers.cross_entropy(input=predict, label=label) avg_cost = fluid.layers.mean(cost)
accuracy = fluid.layers.accuracy(input=predict, label=label)
optimizer = fluid.optimizer.Adam(learning_rate=0.001) optimizer.minimize(avg_cost)
place = fluid.CUDAPlace(0) exe = fluid.Executor(place) exe.run(fluid.default_startup_program())
feeder = fluid.DataFeeder(feed_list=[image, label], place=place)
model_save_dir = "model/fruits/" costs = [] accs = [] times = 0 batches = []
for pass_id in range(40): train_cost = 0 for batch_id, data in enumerate(batch_train_reader()): times += 1 train_cost, train_acc = exe.run(program=fluid.default_main_program(), feed=feeder.feed(data), fetch_list=[avg_cost, accuracy]) if batch_id % 20 == 0: print("pass_id:%d, step:%d, cost:%f, acc:%f" % (pass_id, batch_id, train_cost[0], train_acc[0])) accs.append(train_acc[0]) costs.append(train_cost[0]) batches.append(times)
if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) fluid.io.save_inference_model(dirname=model_save_dir, feeded_var_names=["image"], target_vars=[predict], executor=exe) print("训练保存模型完成!")
plt.title("training", fontsize=24) plt.xlabel("iter", fontsize=20) plt.ylabel("cost/acc", fontsize=20) plt.plot(batches, costs, color='red', label="Training Cost") plt.plot(batches, accs, color='green', label="Training Acc") plt.legend() plt.grid() plt.savefig("train.png") plt.show()
|