猫耳山在天边 2019-06-25
本AI(ScooterV2)使用AlexNet进行图像分类(前进、左转、右转)。
Alexnet是一个经典的卷积神经网络,有5个卷积层,其后为3个全连接层,最后的输出激活函数为分类函数softmax。其性能超群,在2012年ImageNet图像识别比赛上展露头角,是当时的冠军Model,由SuperVision团队开发,领头人物为AI教父Jeff Hinton。
网络结构如图1所示:
图1 AlexNet示意图
#导入依赖库(tflearn backended) import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression from tflearn.layers.normalization import local_response_normalization from collections import Counter from numpy.random import shuffle import numpy as np import numpy as np import pandas as pd #定义AlexNet模型 def alexnet(width, height, lr): network = input_data(shape=[None, width, height, 1], name='input') network = conv_2d(network, 96, 11, strides=4, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = conv_2d(network, 256, 5, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = conv_2d(network, 384, 3, activation='relu') network = conv_2d(network, 384, 3, activation='relu') network = conv_2d(network, 256, 3, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = fully_connected(network, 4096, activation='tanh') network = dropout(network, 0.5) network = fully_connected(network, 4096, activation='tanh') network = dropout(network, 0.5) network = fully_connected(network, 3, activation='softmax') network = regression(network, optimizer='momentum', loss='categorical_crossentropy', learning_rate=lr, name='targets') model = tflearn.DNN(network, checkpoint_path='model_alexnet', max_checkpoints=1, tensorboard_verbose=2, tensorboard_dir='log') return model
图2 Local_Response_Normolization示意图
WIDTH = 160 HEIGHT = 90 LR = 1e-3 EPOCHS = 10 MODEL_NAME = 'scooterv2.model' model = alexnet(WIDTH, HEIGHT, LR) train_data = np.load('training_data_after_shuffle.npy') train = train_data[:-1000] test = train_data[-1000:] X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1) Y = [i[1] for i in train] test_x = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1) test_y = [i[1] for i in test] for index in range(1,200): model.fit({'input': X}, {'targets': Y}, n_epoch=EPOCHS, validation_set=({'input': test_x}, {'targets': test_y}), snapshot_step=500, show_metric=True, run_id=MODEL_NAME) model.save(MODEL_NAME)
学习率为0.001,for循环中每一次迭代训练的epoch数量为10,mini_batch的样本数量使用默认值64;数据集的后1000个作为validation set,剩余的都作为测试集使用。
跑一次一共训练了200*10=2000次,但实际上参数更新了20万次,每一次mini_batch都更新一次参数。