def epoch_guided(dataset_path): model_name = "cnn" image_size = (128, 128) threshold = 0.2 weights_path = './weights_HMB_2.hdf5' # Change to your model weights seed_inputs1 = os.path.join(dataset_path, "hmb3/") seed_labels1 = os.path.join(dataset_path, "hmb3/hmb3_steering.csv") seed_inputs2 = os.path.join(dataset_path, "Ch2_001/center/") seed_labels2 = os.path.join(dataset_path, "Ch2_001/CH2_final_evaluation.csv") new_inputs = "./new/" # Model build # --------------------------------------------------------------------------------- model_builders = { 'V3': (build_InceptionV3, preprocess_input_InceptionV3, exact_output), 'cnn': (build_cnn, normalize_input, exact_output) } if model_name not in model_builders: raise ValueError("unsupported model %s" % model_name) model_builder, input_processor, output_processor = model_builders[ model_name] model = model_builder(image_size, weights_path) print('model %s built...' % model_name) filelist1 = [] for file in sorted(os.listdir(seed_inputs1)): if file.endswith(".jpg"): filelist1.append(file) truth = {} with open(seed_labels1, 'rb') as csvfile1: label1 = list(csv.reader(csvfile1, delimiter=',', quotechar='|')) label1 = label1[1:] for i in label1: truth[i[0] + ".jpg"] = i[1] newlist = [] for file in sorted(os.listdir(new_inputs)): if file.endswith(".jpg"): newlist.append(file) flag = 0 #flag:0 start from beginning #flag:1 initialize from pickle files ''' Pickle files are used for continuing the search after rerunning the script. Delete all pkl files and generated images for starting from the beginnning. ''' if os.path.isfile("epoch_covdict2.pkl") and \ os.path.isfile("epoch_stack.pkl") and \ os.path.isfile("epoch_queue.pkl") and \ os.path.isfile("generated.pkl"): with open('epoch_covdict2.pkl', 'rb') as input: covdict = pickle.load(input) with open('epoch_stack.pkl', 'rb') as input: epoch_stack = pickle.load(input) with open('epoch_queue.pkl', 'rb') as input: epoch_queue = pickle.load(input) with open('generated.pkl', 'rb') as input: generated = pickle.load(input) flag = 1 nc = NCoverage(model, threshold) if flag == 0: filewrite = "wb" epoch_queue = deque() epoch_stack = [] generated = 0 else: nc.set_covdict(covdict) filewrite = "ab" print("initialize from files and continue from previous progress") C = 0 # covered neurons P = 0 # covered percentage T = 0 # total neurons transformations = [ image_translation, image_scale, image_shear, image_rotation, image_contrast, image_brightness2, image_blur ] params = [] params.append(list(xrange(-50, 50))) params.append(list(map(lambda x: x * 0.1, list(xrange(5, 20))))) params.append(list(map(lambda x: x * 0.1, list(xrange(-5, 5))))) params.append(list(xrange(-30, 30))) params.append(list(map(lambda x: x * 0.1, list(xrange(1, 20))))) params.append(list(xrange(-21, 21))) params.append(list(xrange(1, 11))) maxtrynumber = 10 maximages = 200 cache = deque() image_count = 0 #load nc, generation, population with open('result/epoch_rq3_100_2.csv', filewrite, 0) as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) if flag == 0: writer.writerow([ 'id', 'seed image(root)', 'parent image', 'new generated image', 'number of generated images', 'total_covered', 'total_neurons', 'coverage_percentage', 'transformations', 'yhat', 'baseline', 'label' ]) #initialize population and coverage print("compute coverage of original population") input_images = xrange(1, 101) for i in input_images: j = i * 50 epoch_queue.append(os.path.join(seed_inputs1, filelist1[j])) while len(epoch_queue) > 0: current_seed_image = epoch_queue[0] print(str(len(epoch_queue)) + " images are left.") if len(epoch_stack) == 0: epoch_stack.append(current_seed_image) image = cv2.imread(current_seed_image) test_x = read_transformed_image(image, image_size) test_x = input_processor(test_x.astype(np.float32)) nc.update_coverage(test_x) baseline_yhat = model.predict(test_x) #image_count = 0 while len(epoch_stack) > 0: try: image_file = epoch_stack[-1] print("current image in stack " + image_file) image = cv2.imread(image_file) new_generated = False for i in xrange(maxtrynumber): tid = random.sample([0, 1, 2, 3, 4, 5, 6], 2) if len(cache) > 0: tid[0] = cache.popleft() transinfo = "" new_image = image for j in xrange(2): transformation = transformations[tid[j]] #random choose parameter param = random.sample(params[tid[j]], 1) param = param[0] transinfo = transinfo + transformation.__name__ + ':' + str( param) + ';' print("transformation " + transformation.__name__ + " parameter " + str(param)) new_image = transformation(new_image, param) new_x = read_transformed_image(new_image, image_size) test_x = input_processor(new_x.astype(np.float32)) if nc.is_testcase_increase_coverage(test_x): print( "Generated image increases coverage and will be added to population." ) cache.append(tid[0]) cache.append(tid[1]) generated = generated + 1 #image_count = image_count + 1 name = os.path.basename( current_seed_image) + '_' + str( generated) + '.jpg' name = os.path.join(new_inputs, name) cv2.imwrite(name, new_image) epoch_stack.append(name) nc.update_coverage(test_x) yhat = model.predict(test_x) covered, total, p = nc.curr_neuron_cov() C = covered T = total P = p csvrecord = [] csvrecord.append(100 - len(epoch_queue)) csvrecord.append( os.path.basename(current_seed_image)) if len(epoch_stack) >= 2: parent = os.path.basename(epoch_stack[-2]) else: parent = os.path.basename(current_seed_image) child = os.path.basename( current_seed_image) + '_' + str( generated) + '.jpg' csvrecord.append(parent) csvrecord.append(child) csvrecord.append(generated) csvrecord.append(C) csvrecord.append(T) csvrecord.append(P) csvrecord.append(transinfo) csvrecord.append(yhat[0][0]) csvrecord.append(baseline_yhat[0][0]) csvrecord.append( truth[os.path.basename(current_seed_image)]) print(csvrecord) writer.writerow(csvrecord) new_generated = True break else: print( "Generated image does not increase coverage.") if not new_generated: epoch_stack.pop() save_object(epoch_stack, 'epoch_stack.pkl') save_object(epoch_queue, 'epoch_queue.pkl') save_object(nc.cov_dict, 'epoch_covdict2.pkl') save_object(generated, 'generated.pkl') except ValueError: print("value error") epoch_stack.pop() save_object(epoch_stack, 'epoch_stack.pkl') save_object(epoch_queue, 'epoch_queue.pkl') epoch_queue.popleft()
class ChauffeurModel(object): ''' Chauffeur model with integrated neuron coverage ''' def __init__(self, cnn_json_path, cnn_weights_path, lstm_json_path, lstm_weights_path, only_layer=""): self.cnn = self.load_from_json(cnn_json_path, cnn_weights_path) self.encoder = self.load_encoder(cnn_json_path, cnn_weights_path) self.lstm = self.load_from_json(lstm_json_path, lstm_weights_path) # hardcoded from final submission model self.scale = 16. self.timesteps = 100 self.threshold_cnn = 0.1 self.threshold_lstm = 0.4 self.timestepped_x = np.empty((1, self.timesteps, 8960)) self.nc_lstm = NCoverage(self.lstm, self.threshold_lstm) self.nc_encoder = NCoverage(self.encoder, self.threshold_cnn, exclude_layer=['pool', 'fc', 'flatten'], only_layer=only_layer) self.steps = deque() #print(self.lstm.summary()) #self.nc = NCoverage(self.lstm,self.threshold) def load_encoder(self, cnn_json_path, cnn_weights_path): model = self.load_from_json(cnn_json_path, cnn_weights_path) model.load_weights(cnn_weights_path) model.layers.pop() model.outputs = [model.layers[-1].output] model.layers[-1].outbound_nodes = [] return model def load_from_json(self, json_path, weights_path): model = model_from_json(open(json_path, 'r').read()) model.load_weights(weights_path) return model def make_cnn_only_predictor(self): def predict_fn(img): img = cv2.resize(img, (320, 240)) img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) img = img[120:240, :, :] img[:, :, 0] = cv2.equalizeHist(img[:, :, 0]) img = ((img-(255.0/2))/255.0) return self.cnn.predict_on_batch(img.reshape((1, 120, 320, 3)))[0, 0] / self.scale return predict_fn #def make_stateful_predictor(self): #steps = deque() def predict_fn(self, img, test=0): # test == 0: update the coverage only # test == 1: test if the input image will increase the current coverage steps = self.steps img = cv2.resize(img, (320, 240)) img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) img = img[120:240, :, :] img[:, :, 0] = cv2.equalizeHist(img[:, :, 0]) img = ((img-(255.0/2))/255.0) img1 = img if test == 1: return self.nc_encoder.is_testcase_increase_coverage(img1.reshape((1, 120, 320, 3))) else: cnn_ndict = self.nc_encoder.update_coverage(img1.reshape((1, 120, 320, 3))) cnn_covered_neurons, cnn_total_neurons, cnn_p = self.nc_encoder.curr_neuron_cov() return cnn_covered_neurons, cnn_total_neurons, cnn_p