CV视频代码练习
1. 机器学习代码大体流程(以自动驾驶部分代码为例)
包括:
- 定义网络模型Model
- 图像预处理image_transformation
- 产生批处理数据batch_generator
- 加载数据,分割为Train和Val
- 想要保留中间过程:Callback
- 训练模型(过程:epoch、batch_size、per_epoch:将数据整体全部训练epoch遍,其中每一遍内有per_epoch次,每次训练batch_size数据)
- 使用Tensorboard查看训练过程
- 保存模型
# -*- coding: utf-8 -*-
import numpy as np
from keras.optimizers import SGD, Adam
from keras.layers.core import Dense, Dropout, Activation
from keras.layers import Conv2D, MaxPooling2D, Flatten, PReLU
from keras.models import Sequential, Model
from keras import backend as K
from keras.regularizers import l2
import os.path
import csv
import cv2
import glob
import pickle
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import json
from keras import callbacks
import math
from matplotlib import pyplot
SEED = 13
def get_model(shape):
'''
预测方向盘角度: 以图像为输入, 预测方向盘的转动角度
shape: 输入图像的尺寸, 例如(128, 128, 3)
'''
model = Sequential()
model.add(Conv2D(8, (5, 5), strides=(1, 1), padding="valid", activation='relu', input_shape=shape))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='linear'))
sgd = SGD(lr=0.01)
model.compile(optimizer=sgd, loss='mean_squared_error')
return model
def image_transformation(img_address, degree, data_dir):
img = cv2.imread(data_dir + img_address)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return (img, degree)
def batch_generator(x, y, batch_size, shape, training=True, data_dir='data/', monitor=True, yieldXY=True, discard_rate=0.95):
"""
产生批处理的数据的generator
x: 文件路径list
y: 方向盘的角度
training: 值为True时产生训练数据
值为True时产生validation数据
batch_size: 批处理大小
shape: 输入图像的尺寸(高, 宽, 通道)
data_dir: 数据目录, 包含一个IMG文件夹
monitor: 保存一个batch的样本为 'X_batch_sample.npy‘ 和'y_bag.npy’
yieldXY: 为True时, 返回(X, Y)
为False时, 只返回 X only
discard_rate: 随机丢弃角度为零的训练数据的概率
"""
if training:
y_bag = []
x, y = shuffle(x, y)
new_x = x
new_y = y
else:
new_x = x
new_y = y
offset = 0
while True:
X = np.empty((batch_size, *shape))
Y = np.empty((batch_size, 1))
for example in range(batch_size):
img_address, img_steering = new_x[example + offset

本文介绍了自动驾驶代码流程,涉及模型定义、图像预处理、批处理数据生成和训练,同时展示了鸢尾花分类的完整步骤,包括数据加载、One-hot编码、模型构建、K折交叉验证及模型保存和预测。
最低0.47元/天 解锁文章
3722

被折叠的 条评论
为什么被折叠?



