[譯]基于Tensorflow的交通標(biāo)志識(shí)別

原文出處:https://github.com/waleedka/traffic-signs-tensorflow/blob/master/notebook1.ipynb

這是用深度學(xué)習(xí)構(gòu)建交通標(biāo)志識(shí)別模型例子的第一部分。目標(biāo)是構(gòu)建一個(gè)模型,它能夠檢測和分類交通標(biāo)志。

第一步: 交通標(biāo)志分類

我將以一個(gè)小目標(biāo):分類作為開始。給一個(gè)交通標(biāo)志的圖片,我們的模型應(yīng)該能夠告訴我們它的類型(比如是“停止”標(biāo)志,“限速”標(biāo)志,“讓行”標(biāo)志等)。

在這個(gè)工程中,我用的python版本是3.5,Tensorflow是0.11,還用了Numpy,Scikit Image和Matplotlib庫,這些都是機(jī)器學(xué)習(xí)中的標(biāo)準(zhǔn)庫。為了方便,我創(chuàng)建了一個(gè)包含了許多深度學(xué)習(xí)工具庫的docker:https://hub.docker.com/r/waleedka/modern-deep-learning/ 。你可以用以下的命令來運(yùn)行它:

docker run -it -p 8888:8888 -p 6006:6006 -v ~/traffic:/traffic waleedka/modern-deep-learning

需要注意的是我的工程目錄是在~/traffic下,我在我的Docker中將其映射到了/traffic目錄下,如果你用了不同的目錄,請修改它。

第一步,讓我們導(dǎo)入我們所需要的庫。

import os
import random
import skimage.data
import skimage.transform
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# 運(yùn)行圖形嵌入到notebook中
%matplotlib inline

訓(xùn)練數(shù)據(jù)集

我們將用比利時(shí)的交通標(biāo)志數(shù)據(jù)集。進(jìn)入http://btsd.ethz.ch/shareddata/ 網(wǎng)站,下載相關(guān)的訓(xùn)練集和測試集數(shù)據(jù)。在那個(gè)網(wǎng)頁上有很多數(shù)據(jù)集,你只需要下載在BelgiumTS for Classification (cropped images)目錄下的兩個(gè)文件就行了:

  • BelgiumTSC_Training (171.3MBytes)
  • BelgiumTSC_Testing (76.5MBytes)

在下載完成后解壓文件,你的工程文件路徑應(yīng)該看起來像下面這樣:

/traffic/datasets/BelgiumTS/Training/
/traffic/datasets/BelgiumTS/Testing/

兩個(gè)目錄中都包含了62個(gè)子目錄,目錄名字是從00000到00061的編號。這些目錄名表示的是一個(gè)標(biāo)簽,而目錄下的圖片就是該標(biāo)簽的樣本。

加載訓(xùn)練數(shù)據(jù)

Training目錄下包含了名字從00000到00061連續(xù)編號的子目錄。這些名字代表了標(biāo)簽是從0到61編號,每個(gè)目錄下的交通標(biāo)志圖片就是屬于該標(biāo)簽的樣本。這些圖片是用一種古老的格式.ppm來存儲(chǔ)的,幸運(yùn)的是,Scikit Image庫支持這個(gè)格式。

def load_data(data_dir):
    """Loads a data set and returns two lists:
    
    images: a list of Numpy arrays, each representing an image.
    labels: a list of numbers that represent the images labels.
    """
    # Get all subdirectories of data_dir. Each represents a label.
    directories = [d for d in os.listdir(data_dir) 
                   if os.path.isdir(os.path.join(data_dir, d))]
    # Loop through the label directories and collect the data in
    # two lists, labels and images.
    labels = []
    images = []
    for d in directories:
        label_dir = os.path.join(data_dir, d)
        file_names = [os.path.join(label_dir, f) 
                      for f in os.listdir(label_dir) if f.endswith(".ppm")]
        # For each label, load it's images and add them to the images list.
        # And add the label number (i.e. directory name) to the labels list.
        for f in file_names:
            images.append(skimage.data.imread(f))
            labels.append(int(d))
    return images, labels


# Load training and testing datasets.
ROOT_PATH = "/traffic"
train_data_dir = os.path.join(ROOT_PATH, "datasets/BelgiumTS/Training")
test_data_dir = os.path.join(ROOT_PATH, "datasets/BelgiumTS/Testing")

images, labels = load_data(train_data_dir)

這里我們加載了兩個(gè)list列表:

  • images列表包含了一組圖像,每個(gè)圖像都轉(zhuǎn)換為numpy數(shù)組。
  • labels列表是標(biāo)簽,值為0到61的整數(shù)。

我們將所有的數(shù)據(jù)集都加載進(jìn)內(nèi)存中通常并不是一個(gè)好主意,不過這個(gè)數(shù)據(jù)集并不大而且我們又試著保持代碼的簡潔性,這樣做也未嘗不可。我們在下一個(gè)部分再來改進(jìn)它。對于更大的數(shù)據(jù)集,我們就應(yīng)該考慮批量載入數(shù)據(jù),用一個(gè)單獨(dú)的線程來加載數(shù)據(jù)塊,然后喂給訓(xùn)練線程。

探索數(shù)據(jù)集

先看看我們總共有多少圖像和標(biāo)簽?

print("Unique Labels: {0}\nTotal Images: {1}".format(len(set(labels)), len(images)))

顯示每組標(biāo)簽的第一幅圖像。

def display_images_and_labels(images, labels):
    """Display the first image of each label."""
    unique_labels = set(labels)
    plt.figure(figsize=(15, 15))
    i = 1
    for label in unique_labels:
        # Pick the first image for each label.
        image = images[labels.index(label)]
        plt.subplot(8, 8, i)  # A grid of 8 rows x 8 columns
        plt.axis('off')
        plt.title("Label {0} ({1})".format(label, labels.count(label)))
        i += 1
        _ = plt.imshow(image)
    plt.show()

display_images_and_labels(images, labels)

這些數(shù)據(jù)集看起來還不錯(cuò)?。∵@些交通標(biāo)志在每個(gè)圖像中占了很大部分的面積,這將讓我們的工作變得容易些:我們不需要在每幅圖像中再單獨(dú)識(shí)別到標(biāo)志上,只用做好我們的物體分類就可以了。而且圖像包含了大量角度和情況,有助于我們模型的推廣。

然后還有個(gè)問題,雖然這些圖像都是正方形的,但它們并不都是一樣的大小,它們有著不同的縮放比例。我們的簡單神經(jīng)網(wǎng)絡(luò)的輸入需要是固定大小的輸入,因此,我們需要對數(shù)據(jù)進(jìn)行預(yù)處理。我們接下來將進(jìn)行數(shù)據(jù)預(yù)處理,但首先,我們先挑選一個(gè)標(biāo)簽,看看它里面包含的圖像。來看看標(biāo)簽32:

def display_label_images(images, label):
    """Display images of a specific label."""
    limit = 24  # show a max of 24 images
    plt.figure(figsize=(15, 5))
    i = 1

    start = labels.index(label)
    end = start + labels.count(label)
    for image in images[start:end][:limit]:
        plt.subplot(3, 8, i)  # 3 rows, 8 per row
        plt.axis('off')
        i += 1
        plt.imshow(image)
    plt.show()

display_label_images(images, 32)

有意思吧,我們的數(shù)據(jù)看起來將所有的限速標(biāo)志都?xì)w為了同一個(gè)類,不管標(biāo)志上面的數(shù)字是多少。在剛開始的時(shí)候充分理解數(shù)據(jù)集是必要的,它可以在我們對輸出預(yù)測的時(shí)候減少很多不必要的麻煩。

我們繼續(xù)來看看其他的標(biāo)簽,看看標(biāo)簽26和27,他們都是在一個(gè)紅圈里有數(shù)字,因此我們的模型必須能很好地對這3類數(shù)據(jù)進(jìn)行區(qū)分才行。

處理不同大小的圖片?

許多神經(jīng)網(wǎng)絡(luò)都希望有一個(gè)固定大小的輸入,我們的神經(jīng)網(wǎng)絡(luò)也是如此。但是正如上面看到的一樣,我們數(shù)據(jù)集中的圖像并不都是一個(gè)大小的啊,那怎么辦呢?一個(gè)常用的做法是選一個(gè)高寬比,然后將每個(gè)圖片都拉伸到那個(gè)比例,但在這個(gè)過程中,我們必須確保我們沒有裁剪到這些交通標(biāo)志的一部分。這看起來需要我們手工進(jìn)行!我們用一個(gè)簡單點(diǎn)的解決辦法:我們調(diào)整圖像到固定的一個(gè)大小,不用管那些圖像是不是被水平或垂直拉伸了。一個(gè)人能輕而易舉的識(shí)別出被拉伸了的圖片,我們希望我們的模型也能識(shí)別。

我們的輸入數(shù)據(jù)越大的話,得到的模型也就越大,這樣訓(xùn)練它的時(shí)間就會(huì)花的越久,因此我們再把圖片的尺寸變小一些。在開發(fā)的早期階段,我們希望能快速的訓(xùn)練模型,而不是當(dāng)我們調(diào)整代碼后每次都在迭代的時(shí)候等待很長時(shí)間。

那么,我們的圖像大小是多少呢?

for image in images[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

打印信息:

shape: (141, 142, 3), min: 0, max: 255
shape: (120, 123, 3), min: 0, max: 255
shape: (105, 107, 3), min: 0, max: 255
shape: (94, 105, 3), min: 7, max: 255
shape: (128, 139, 3), min: 0, max: 255

這些尺寸大小看起來都在128x128左右。如果我們將尺寸調(diào)整為32x32,尺寸會(huì)是原來的1/16,減少了模型數(shù)據(jù)量。而且32x32對于識(shí)別這些標(biāo)志來說基本上已經(jīng)足夠大了,因此,我們就這樣干。

我也認(rèn)為經(jīng)常打印min()和max()函數(shù)的值是一個(gè)好的習(xí)慣。這樣做能讓我們很容易的發(fā)現(xiàn)我們數(shù)據(jù)的邊界范圍并有助于及早的發(fā)現(xiàn)bug。

# 調(diào)整圖像
images32 = [skimage.transform.resize(image, (32, 32)) for image in images]
display_images_and_labels(images32, labels)

可以看到,32x32的圖像雖然不是那么清晰,但仍然能夠辨認(rèn)。注意上面顯示圖像的尺寸要比實(shí)際尺寸大一些,因?yàn)閙atplotlib庫讓它們自動(dòng)適應(yīng)網(wǎng)格的大小。我們來打印一些圖像的尺寸看看是否符合我們的要求:

for image in images32[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

打印信息:

shape: (32, 32, 3), min: 0.007391237745099785, max: 1.0
shape: (32, 32, 3), min: 0.003576899509803602, max: 1.0
shape: (32, 32, 3), min: 0.0015567555147030507, max: 1.0
shape: (32, 32, 3), min: 0.0567746629901964, max: 0.9692670036764696
shape: (32, 32, 3), min: 0.026654411764708015, max: 0.98952205882353

可以看到打印出來的大小是符合我們所要求的。但是打印出來的最小值和最大值現(xiàn)在卻是在0到1.0之間,并不是像我們上面看到的0-255。那是因?yàn)閞esize函數(shù)自動(dòng)為我們進(jìn)行了歸一化。將數(shù)據(jù)歸一化到0.0-1.0范圍很常見,因此我們保持這樣既可。但要記住,如果之后想要把圖像轉(zhuǎn)換到0-255的正常范圍,記得乘上255這個(gè)值。

最小可行模型

labels_a = np.array(labels)
images_a = np.array(images32)
print("labels: ", labels_a.shape, "\nimages: ", images_a.shape)

打印信息:

labels: (4575,)
images: (4575, 32, 32, 3)

# Create a graph to hold the model.
graph = tf.Graph()

# Create model in the graph.
with graph.as_default():
    # Placeholders for inputs and labels.
    images_ph = tf.placeholder(tf.float32, [None, 32, 32, 3])
    labels_ph = tf.placeholder(tf.int32, [None])

    # Flatten input from: [None, height, width, channels]
    # To: [None, height * width * channels] == [None, 3072]
    images_flat = tf.contrib.layers.flatten(images_ph)

    # Fully connected layer. 
    # Generates logits of size [None, 62]
    logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)

    # Convert logits to label indexes (int).
    # Shape [None], which is a 1D vector of length == batch_size.
    predicted_labels = tf.argmax(logits, 1)

    # Define the loss function. 
    # Cross-entropy is a good choice for classification.
    loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels_ph))

    # Create training op.
    train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

    # And, finally, an initialization op to execute before training.
    # TODO: rename to tf.global_variables_initializer() on TF 0.12.
    init = tf.initialize_all_variables()

print("images_flat: ", images_flat)
print("logits: ", logits)
print("loss: ", loss)
print("predicted_labels: ", predicted_labels)

打印信息:

images_flat: Tensor("Flatten/Reshape:0", shape=(?, 3072), dtype=float32)
logits: Tensor("fully_connected/Relu:0", shape=(?, 62), dtype=float32)
loss: Tensor("Mean:0", shape=(), dtype=float32)
predicted_labels: Tensor("ArgMax:0", shape=(?,), dtype=int64)

開始訓(xùn)練

# Create a session to run the graph we created.
session = tf.Session(graph=graph)

# First step is always to initialize all variables. 
# We don't care about the return value, though. It's None.
_ = session.run([init])


for i in range(201):
    _, loss_value = session.run([train, loss], 
                                feed_dict={images_ph: images_a, labels_ph: labels_a})
    if i % 10 == 0:
        print("Loss: ", loss_value)

打印信息:

Loss: 4.2588
Loss: 2.88972
Loss: 2.42234
Loss: 2.20074
Loss: 2.06985
Loss: 1.98126
Loss: 1.91674
...

使用模型

session對象包含了我們模型中所有變量的值(即權(quán)重)。

# Pick 10 random images
sample_indexes = random.sample(range(len(images32)), 10)
sample_images = [images32[i] for i in sample_indexes]
sample_labels = [labels[i] for i in sample_indexes]

# Run the "predicted_labels" op.
predicted = session.run([predicted_labels], 
                        feed_dict={images_ph: sample_images})[0]
print(sample_labels)
print(predicted)

[7, 7, 19, 32, 39, 16, 18, 3, 38, 41]
[56 61 19 32 39 61 18 40 38 40]

# Display the predictions and the ground truth visually.
fig = plt.figure(figsize=(10, 10))
for i in range(len(sample_images)):
    truth = sample_labels[i]
    prediction = predicted[i]
    plt.subplot(5, 2,1+i)
    plt.axis('off')
    color='green' if truth == prediction else 'red'
    plt.text(40, 10, "Truth:        {0}\nPrediction: {1}".format(truth, prediction), 
             fontsize=12, color=color)
    plt.imshow(sample_images[i])

評估

可視化的結(jié)果很有趣,但我們需要一個(gè)更加精確的方法來衡量我們模型的準(zhǔn)確性。另外,重要的是要用那些它還沒有見過的圖片來進(jìn)行測試。BelgiumTS提供的驗(yàn)證數(shù)據(jù)集Testing就是用來干這個(gè)事的。

# Load the test dataset.
test_images, test_labels = load_data(test_data_dir)

# Transform the images, just like we did with the training set.
test_images32 = [skimage.transform.resize(image, (32, 32))
                 for image in test_images]
display_images_and_labels(test_images32, test_labels)
# Run predictions against the full test set.
predicted = session.run([predicted_labels], 
                        feed_dict={images_ph: test_images32})[0]
# Calculate how many matches we got.
match_count = sum([int(y == y_) for y, y_ in zip(test_labels, predicted)])
accuracy = match_count / len(test_labels)
print("Accuracy: {:.3f}".format(accuracy))

打印信息(準(zhǔn)確率):

Accuracy: 0.634

最后關(guān)閉Session:

# Close the session. This will destroy the trained model.
session.close()

PS:以上只是自己為了看而翻譯的簡譯版,譯完后發(fā)現(xiàn)網(wǎng)上有一篇翻譯了,o(╯□╰)o。不過我是直接翻譯的jupyter notebook上的,網(wǎng)上的文章中講的要詳細(xì)些:
一次神經(jīng)網(wǎng)絡(luò)的探索之旅-基于Tensorflow的路標(biāo)識(shí)別

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容