无人驾驶的实现,在算法上有大致两种:
1. 端到端的深度学习,也就是从摄像头或者其他的直接的输入原始数据,训练出一个转向、油门、刹车的结果。
2. 每一步都用确定的规则来实现,从感知、定位到控制都有明确的规则。
而这里要介绍的是前者,端到端的深度学习无人驾驶技术
以下内容来自 Udacity 的 Self-Driving Car 的 Behavior Cloning 的相关资料
import csv import numpy as np import cv2 lines = [] with open('driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: lines.append(line) images = [] measurements = [] for line in lines: source_path = line[0] # switch from absolute path to relative path # filename = source_path.split('/')[-1] filename = os.path.basename(source_path) current_path = os.path.join('../data/IMG/', filename) image = cv2.imread(current_path) images.append(image) measurement = float(line[3]) measurements.append(measurement) X_train = np.array(images) Y_train = np.array(measurements)
from keras.models import Sequential from keras.layers import Flatten, Dense model = Sequential() model.add(Flatten(input_shape = (160, 320, 3))) model.add(Dense(1)) model.compile(loss = 'mse', optimizer = 'adam') model.fit(X_train, Y_train, validation_split)这个 model 当然是非常简单的,估计效果也不会很好。不过可以从这么一个简单的模型开始,进一步改进。
from keras.layers import Cropping2D model = Sequential() model.add(Cropping2D(cropping=((50,20), (0,0)), input_shape=(3,160,320)))
from keras.models import Model import matplotlib.pyplot as plt history_object = model.fit_generator(train_generator, samples_per_epoch = len(train_samples), validation_data = validation_generator, nb_val_samples = len(validation_samples), nb_epoch=5, verbose=1) ### print the keys contained in the history object print(history_object.history.keys()) ### plot the training and validation loss for each epoch plt.plot(history_object.history['loss']) plt.plot(history_object.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'], loc='upper right') plt.show()
def generator(samples, batch_size=32): num_samples = len(samples) while 1: # Loop forever so the generator never terminates shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset+batch_size] images = [] angles = [] for batch_sample in batch_samples: name = './IMG/'+batch_sample[0].split('/')[-1] center_image = cv2.imread(name) center_angle = float(batch_sample[3]) images.append(center_image) angles.append(center_angle) # trim image to only see section with road X_train = np.array(images) y_train = np.array(angles) yield sklearn.utils.shuffle(X_train, y_train) train_generator = generator(train_samples, batch_size=32) validation_generator = generator(validation_samples, batch_size=32)