[譯] TensorFlow 教程 #09 – 視訊資料

thrillerist發表於2017-08-27

題圖來自: Pictures: S06E16 Bart vs. Australia
本文主要演示了如何使用自己的影像資料,建立分類器。

01 – 簡單線性模型 | 02 – 卷積神經網路 | 03 – PrettyTensor | 04 – 儲存&
恢復

05 – 整合學習 | 06 – CIFAR 10 | 07 – Inception 模型 | 08 – 遷移學習

by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube
中文翻譯 thrillerist / Github

如有轉載,請附上本文連結。


介紹

上一篇教程#08介紹瞭如何在CIFAR-10資料集上用預訓練的Inception模型來做遷移學習(Transfer Learning)。本文將會展示如何使用你自己的影像。

為了示範,我們使用新的資料集Knifey-Spoony,它包含了上千張不同背景下的餐刀、勺子和叉子的影像。訓練集有4170張影像,測試集有530張。類別為knifey、sppony和forky,這是對辛普森一家的引用。

knifey-spoony資料集中的影像是用一個簡單的Python指令碼從視訊檔案中獲取的,指令碼在Linux上執行(它需要avconv程式將視訊轉成影像)。這讓你可以很快地從幾分鐘的錄影視訊中建立包含上千張影像的資料集。

本文基於上一篇教程,你需要了解熟悉教程#08中的遷移學習,以及之前教程中關於如何在TensorFlow中建立和訓練神經網路的部分。

流程圖

下圖展示了用Inception模型做遷移學習時資料的流向。首先,我們在Inception模型中輸入並處理一張影像。在模型最終的分類層之前,將所謂的Transfer- Values儲存到快取檔案中。

這與在教程#08中做的相似,只是現在用Knifey-Spoony資料集代替CIFAR-10,這說明我們將jpeg影像送到Inception模型中,而不是使用包含影像資料的numpy陣列。

當新資料集裡的所有影像都用Inception處理過,並且生成的transfer-values都儲存到快取檔案之後,我們可以將這些transfer-values作為其它神經網路的輸入。接著用新資料集中的類別來訓練第二個神經網路,因此,網路基於Inception模型的transfer-values來學習如何分類影像。

這樣,Inception模型從影像中提取出有用的資訊,然後用另外的神經網路來做真正的分類工作。

from IPython.display import Image, displayImage('images/09_transfer_learning_flowchart.png')複製程式碼

匯入

%matplotlib inlineimport matplotlib.pyplot as pltimport tensorflow as tfimport numpy as npimport timefrom datetime import timedeltaimport os# Functions and classes for loading and using the Inception model.import inception# We use Pretty Tensor to define the new classifier.import prettytensor as pt複製程式碼

使用Python3.5.2(Anaconda)開發,TensorFlow版本是:

tf.__version__複製程式碼
'0.12.0-rc0'複製程式碼

PrettyTensor 版本:

pt.__version__複製程式碼

'
0.7.1'

載入資料

import knifey複製程式碼

knifey模組中已經定義好了資料維度,因此我們需要時只要匯入就行。

from knifey import num_classes複製程式碼

設定電腦上儲存資料集的路徑。

# knifey.data_dir = "data/knifey-spoony/"複製程式碼

設定本教程中儲存快取檔案的資料夾。

data_dir = knifey.data_dir複製程式碼

Knifey-Spoony資料集大概有22MB,如果給定路徑沒有找到檔案的話,將會自動下載。

knifey.maybe_download_and_extract()複製程式碼

Data has apparently already been downloaded and unpacked.

現在載入資料集。程式會遍歷子資料夾來獲取所有*.jpg格式的影像,然後將檔名放入訓練集和測試集的兩個列表中。實際上此時並未載入影像,在計算好transfer-values之後再執行載入。

檔名列表將會儲存到硬碟上,我們必須確保它們按之後過載資料集的順序排列。這個很重要,這樣我們就能知道哪些影像對應哪些transfer-values。

dataset = knifey.load()複製程式碼

Creating dataset from the files in: data/knifey-spoony/

  • Data loaded from cache-file: data/knifey-spoony/knifey-spoony.pkl

你的資料

你可以用自己的影像來代替knifey-spoony資料集。需要建立一個dataset.py模組中的DataSet物件。最好的方法是使用load_cache()封裝函式,它會自動將影像列表儲存到快取檔案中,因此你需要確保列表順序和後面生成的transfer-values順順序一致。

每個類別的影像需要組織在各自的資料夾裡。dataset.py模組中的文件有更多細節。

# This is the code you would run to load your own image-files.# It has been commented out so it won't run now.# from dataset import load_cached# dataset = load_cached(cache_path='my_dataset_cache.pkl', in_dir='my_images/')# num_classes = dataset.num_classes複製程式碼

訓練集和測試集

獲取類別名。

class_names = dataset.class_namesclass_names複製程式碼

['
forky'
, '
knifey'
, '
spoony'
]

獲取測試集。它返回影像的檔案路徑、整形類別號和One-Hot編碼的類別號陣列,稱為標籤。

image_paths_train, cls_train, labels_train = dataset.get_training_set()複製程式碼

列印第一個影像地址,看看是否正確。

image_paths_train[0]複製程式碼

'
/home/magnus/development/TensorFlow-Tutorials/data/knifey-spoony/forky/forky-05-0023.jpg'

獲取測試集。

image_paths_test, cls_test, labels_test = dataset.get_test_set()複製程式碼

列印第一個影像地址,看看是否正確。

image_paths_test[0]複製程式碼

'
/home/magnus/development/TensorFlow-Tutorials/data/knifey-spoony/forky/test/forky-test-01-0163.jpg'

現在已經載入了Knifey-Spoony資料集,它包含4700張影像以及相應的標籤(影像的分類)。資料集被手動地分為兩個子集,訓練集和測試集。

print("Size of:")print("- Training-set:\t\t{
}"
.format(len(image_paths_train)))print("- Test-set:\t\t{
}"
.format(len(image_paths_test)))複製程式碼

Size of:

  • Training-set: 4170
  • Test-set: 530

用來繪製影像的幫助函式

這個函式用來在3×3的柵格中畫9張影像,然後在每張影像下面寫出真實類別和預測類別。

def plot_images(images, cls_true, cls_pred=None, smooth=True):    assert len(images) == len(cls_true)    # Create figure with sub-plots.    fig, axes = plt.subplots(3, 3)    # Adjust vertical spacing.    if cls_pred is None:        hspace = 0.3    else:        hspace = 0.6    fig.subplots_adjust(hspace=hspace, wspace=0.3)    # Interpolation type.    if smooth:        interpolation = 'spline16'    else:        interpolation = 'nearest'    for i, ax in enumerate(axes.flat):        # There may be less than 9 images, ensure it doesn't crash.        if i <
len(images): # Plot image. ax.imshow(images[i], interpolation=interpolation) # Name of the true class. cls_true_name = class_names[cls_true[i]] # Show true and predicted classes. if cls_pred is None: xlabel = "True: {0
}"
.format(cls_true_name) else: # Name of the predicted class. cls_pred_name = class_names[cls_pred[i]] xlabel = "True: {0
}\nPred: {1
}"
.format(cls_true_name, cls_pred_name) # Show the classes as the label on the x-axis. ax.set_xlabel(xlabel) # Remove ticks from the plot. ax.set_xticks([]) ax.set_yticks([]) # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show()複製程式碼

載入影像的幫助函式

資料集並未載入實際影像,在訓練集和測試集中各有一個影像(地址)列表。下面的幫助函式載入了一些影像檔案。

from matplotlib.image import imreaddef load_images(image_paths):    # Load the images from disk.    images = [imread(path) for path in image_paths]    # Convert to a numpy array and return it.    return np.asarray(images)複製程式碼

繪製一些影像看看資料是否正確

# Load the first images from the test-set.images = load_images(image_paths=image_paths_test[0:9])# Get the true classes for those images.cls_true = cls_test[0:9]# Plot the images and labels using our helper-function above.plot_images(images=images, cls_true=cls_true, smooth=True)複製程式碼

下載Inception模型

從網上下載Inception模型。這是你儲存資料檔案的預設資料夾。如果資料夾不存在就自動建立。

# inception.data_dir = 'inception/'複製程式碼

如果資料夾中不存在Inception模型,就自動下載。 它有85MB。

更多詳情見教程#07。

inception.maybe_download()複製程式碼
Downloading Inception v3 Model ...Data has apparently already been downloaded and unpacked.複製程式碼

載入Inception模型

載入模型,為影像分類做準備。

注意warning資訊,以後可能會導致程式執行失敗。

model = inception.Inception()複製程式碼

計算 Transfer-Values

匯入用來從Inception模型中獲取transfer-values的幫助函式。

from inception import transfer_values_cache複製程式碼

設定訓練集和測試集快取檔案的目錄。

file_path_cache_train = os.path.join(data_dir, 'inception-knifey-train.pkl')file_path_cache_test = os.path.join(data_dir, 'inception-knifey-test.pkl')複製程式碼
print("Processing Inception transfer-values for training-images ...")# If transfer-values have already been calculated then reload them,# otherwise calculate them and save them to a cache-file.transfer_values_train = transfer_values_cache(cache_path=file_path_cache_train,                                              image_paths=image_paths_train,                                              model=model)複製程式碼
Processing Inception transfer-values for training-images ...- Data loaded from cache-file: data/knifey-spoony/inception-knifey-train.pkl複製程式碼
print("Processing Inception transfer-values for test-images ...")# If transfer-values have already been calculated then reload them,# otherwise calculate them and save them to a cache-file.transfer_values_test = transfer_values_cache(cache_path=file_path_cache_test,                                             image_paths=image_paths_test,                                             model=model)複製程式碼
Processing Inception transfer-values for test-images ...- Data loaded from cache-file: data/knifey-spoony/inception-knifey-test.pkl複製程式碼

檢查transfer-values的陣列大小。在訓練集中有4170張影像,每張影像有2048個transfer-values。

transfer_values_train.shape複製程式碼

(4170, 2048)

同樣,在測試集中有530張影像,每張影像有2048個transfer-values。

transfer_values_test.shape複製程式碼

(530, 2048)

繪製transfer-values的幫助函式

def plot_transfer_values(i):    print("Input image:")    # Plot the i'th image from the test-set.    image = imread(image_paths_test[i])    plt.imshow(image, interpolation='spline16')    plt.show()    print("Transfer-values for the image using Inception model:")    # Transform the transfer-values into an image.    img = transfer_values_test[i]    img = img.reshape((32, 64))    # Plot the image for the transfer-values.    plt.imshow(img, interpolation='nearest', cmap='Reds')    plt.show()複製程式碼
plot_transfer_values(i=100)複製程式碼

Input image:

Transfer-values for the image using Inception model:

plot_transfer_values(i=300)複製程式碼

Input image:

Transfer-values for the image using Inception model:

transfer-values的PCA分析結果

用scikit-learn裡的主成分分析(PCA),將transfer-values的陣列維度從2048維降到2維,方便繪製。

from sklearn.decomposition import PCA複製程式碼

建立一個新的PCA-object,將目標陣列維度設為2。

pca = PCA(n_components=2)複製程式碼

計算PCA需要一段時間。本文的資料集並不是很大,否則你需要挑選訓練集中的一小部分,來加速計算。

# transfer_values = transfer_values_train[0:3000]transfer_values = transfer_values_train複製程式碼

獲取你選取的樣本的類別號。

# cls = cls_train[0:3000]cls = cls_train複製程式碼

保陣列有4170份樣本,每個樣本有2048個transfer-values。

transfer_values.shape複製程式碼

(4170, 2048)

用PCA將transfer-value從2048維降低到2維。

transfer_values_reduced = pca.fit_transform(transfer_values)複製程式碼

陣列現在有4170個樣本,每個樣本兩個值。

transfer_values_reduced.shape複製程式碼

(4170, 2)

幫助函式用來繪製降維後的transfer-values。

def plot_scatter(values, cls):    # Create a color-map with a different color for each class.    import matplotlib.cm as cm    cmap = cm.rainbow(np.linspace(0.0, 1.0, num_classes))    # Create an index with a random permutation to make a better plot.    idx = np.random.permutation(len(values))    # Get the color for each sample.    colors = cmap[cls[idx]]    # Extract the x- and y-values.    x = values[idx, 0]    y = values[idx, 1]    # Plot it.    plt.scatter(x, y, color=colors, alpha=0.5)    plt.show()複製程式碼

畫出用PCA降維後的transfer-values。用3種不同的顏色來表示Knifey-Spoony資料集中不同的類別。顏色有很多重疊部分。這可能是因為PCA無法正確地分離transfer-values。

plot_scatter(transfer_values_reduced, cls=cls)複製程式碼

transfer-values的t-SNE分析結果

from sklearn.manifold import TSNE複製程式碼

另一種降維的方法是t-SNE。不幸的是,t-SNE很慢,因此我們先用PCA將維度從2048減少到50。

pca = PCA(n_components=50)transfer_values_50d = pca.fit_transform(transfer_values)複製程式碼

建立一個新的t-SNE物件,用來做最後的降維工作,將目標維度設為2維。

tsne = TSNE(n_components=2)複製程式碼

用t-SNE執行最終的降維。目前在scikit-learn中實現的t-SNE可能無法處理很多樣本的資料,所以如果你用整個訓練集的話,程式可能會崩潰。

transfer_values_reduced = tsne.fit_transform(transfer_values_50d)複製程式碼

確保陣列有4170份樣本,每個樣本有兩個transfer-values。

transfer_values_reduced.shape複製程式碼

(4170, 2)

畫出用t-SNE降低至二維的transfer-values,相比上面PCA的結果,它有更好的分離度。

這意味著由Inception模型得到的transfer-values似乎包含了足夠多的資訊,可以對Knifey-Sponny影像進行分類,然而還是有一些重疊部分,說明分離並不完美。

plot_scatter(transfer_values_reduced, cls=cls)複製程式碼

TensorFlow中的新分類器

在我們將會在TensorFlow中建立一個新的神經網路。這個網路會把Inception模型中的transfer-values作為輸入,然後輸出Knifey-Spoony影像的預測類別。

這裡假定你已經熟悉如何在TensorFlow中建立神經網路,否則請閱讀教程#03。

佔位符 (Placeholder)變數

首先需要找到transfer-values的陣列長度,它是儲存在Inception模型物件中的一個變數。

transfer_len = model.transfer_len複製程式碼

現在為輸入的transfer-values建立一個placeholder變數,輸入到我們新建的網路中。變數的形狀是[None, transfer_len]None表示它的輸入陣列包含任意數量的樣本,每個樣本元素個數為2048,即transfer_len

x = tf.placeholder(tf.float32, shape=[None, transfer_len], name='x')複製程式碼

為輸入影像的真實型別標籤定義另外一個placeholder變數。這是One-Hot編碼的陣列,包含10個元素,每個元素代表了資料集中的一種可能類別。

y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')複製程式碼

計算代表真實類別的整形數字。這也可能是一個placeholder變數。

y_true_cls = tf.argmax(y_true, dimension=1)複製程式碼

神經網路

建立在Knifey-Spoony資料集上做分類的神經網路。它將Inception模型得到的transfer-values作為輸入,儲存在placeholder變數x中。網路輸出預測的類別y_pred

教程#03中有更多使用Pretty Tensor構造神經網路的細節。

# Wrap the transfer-values as a Pretty Tensor object.x_pretty = pt.wrap(x)with pt.defaults_scope(activation_fn=tf.nn.relu):    y_pred, loss = x_pretty.\        fully_connected(size=1024, name='layer_fc1').\        softmax_classifier(num_classes=num_classes, labels=y_true)複製程式碼

優化方法

建立一個變數來記錄當前優化迭代的次數。

global_step = tf.Variable(initial_value=0,                          name='global_step', trainable=False)複製程式碼

優化新的神經網路的方法。

optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss, global_step)複製程式碼

分類準確率

網路的輸出y_pred是一個包含3個元素的陣列。類別號是陣列中最大元素的索引。

y_pred_cls = tf.argmax(y_pred, dimension=1)複製程式碼

建立一個布林向量,表示每張影像的真實類別是否與預測類別相同。

correct_prediction = tf.equal(y_pred_cls, y_true_cls)複製程式碼

將布林值向量型別轉換成浮點型向量,這樣子False就變成0,True變成1,然後計算這些值的平均數,以此來計算分類的準確度。

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))複製程式碼

執行TensorFlow

建立TensorFlow會話(session)

一旦建立了TensorFlow圖,我們需要建立一個TensorFlow會話,用來執行圖。

session = tf.Session()複製程式碼

初始化變數

我們需要在開始優化weights和biases變數之前對它們進行初始化。

session.run(tf.global_variables_initializer())複製程式碼

獲取隨機訓練batch的幫助函式

訓練集中有4170張影像(以及儲存transfer-values的陣列)。用這些影像(transfer-vlues)計算模型的梯度會花很多時間。因此,我們在優化器的每次迭代裡只用到了一小部分的影像(transfer-vlues)。

如果記憶體耗盡導致電腦當機或變得很慢,你應該試著減少這些數量,但同時可能還需要更優化的迭代。

train_batch_size = 64複製程式碼

函式用來從訓練集中選擇隨機batch的transfer-vlues。

def random_batch():    # Number of images (transfer-values) in the training-set.    num_images = len(transfer_values_train)    # Create a random index.    idx = np.random.choice(num_images,                           size=train_batch_size,                           replace=False)    # Use the random index to select random x and y-values.    # We use the transfer-values instead of images as x-values.    x_batch = transfer_values_train[idx]    y_batch = labels_train[idx]    return x_batch, y_batch複製程式碼

執行優化迭代的幫助函式

函式用來執行一定數量的優化迭代,以此來逐漸改善網路層的變數。在每次迭代中,會從訓練集中選擇新的一批資料,然後TensorFlow在這些訓練樣本上執行優化。每100次迭代會列印出進度。

def optimize(num_iterations):    # Start-time used for printing time-usage below.    start_time = time.time()    for i in range(num_iterations):        # Get a batch of training examples.        # x_batch now holds a batch of images (transfer-values) and        # y_true_batch are the true labels for those images.        x_batch, y_true_batch = random_batch()        # Put the batch into a dict with the proper names        # for placeholder variables in the TensorFlow graph.        feed_dict_train = {x: x_batch,                           y_true: y_true_batch
} # Run the optimizer using this batch of training data. # TensorFlow assigns the variables in feed_dict_train # to the placeholder variables and then runs the optimizer. # We also want to retrieve the global_step counter. i_global, _ = session.run([global_step, optimizer], feed_dict=feed_dict_train) # Print status to screen every 100 iterations (and last). if (i_global % 100 == 0) or (i == num_iterations - 1): # Calculate the accuracy on the training-batch. batch_acc = session.run(accuracy, feed_dict=feed_dict_train) # Print status. msg = "Global Step: {0:>
6
}, Training Batch Accuracy: {1:>
6.1%
}"
print(msg.format(i_global, batch_acc)) # Ending time. end_time = time.time() # Difference between start and end-times. time_dif = end_time - start_time # Print the time-usage. print("Time usage: " + str(timedelta(seconds=int(round(time_dif)))))複製程式碼

展示結果的幫助函式

繪製錯誤樣本的幫助函式

函式用來繪製測試集中被誤分類的樣本。

def plot_example_errors(cls_pred, correct):    # This function is called from print_test_accuracy() below.    # cls_pred is an array of the predicted class-number for    # all images in the test-set.    # correct is a boolean array whether the predicted class    # is equal to the true class for each image in the test-set.    # Negate the boolean array.    incorrect = (correct == False)    # Get the indices for the incorrectly classified images.    idx = np.flatnonzero(incorrect)    # Number of images to select, max 9.    n = min(len(idx), 9)    # Randomize and select n indices.    idx = np.random.choice(idx,                           size=n,                           replace=False)    # Get the predicted classes for those images.    cls_pred = cls_pred[idx]    # Get the true classes for those images.    cls_true = cls_test[idx]    # Load the corresponding images from the test-set.    # Note: We cannot do image_paths_test[idx] on lists of strings.    image_paths = [image_paths_test[i] for i in idx]    images = load_images(image_paths)    # Plot the images.    plot_images(images=images,                cls_true=cls_true,                cls_pred=cls_pred)複製程式碼

繪製混淆(confusion)矩陣的幫助函式

# Import a function from sklearn to calculate the confusion-matrix.from sklearn.metrics import confusion_matrixdef plot_confusion_matrix(cls_pred):    # This is called from print_test_accuracy() below.    # cls_pred is an array of the predicted class-number for    # all images in the test-set.    # Get the confusion matrix using sklearn.    cm = confusion_matrix(y_true=cls_test,  # True class for test-set.                          y_pred=cls_pred)  # Predicted class.    # Print the confusion matrix as text.    for i in range(num_classes):        # Append the class-name to each line.        class_name = "({
}) {
}"
.format(i, class_names[i]) print(cm[i, :], class_name) # Print the class-numbers for easy reference. class_numbers = [" ({0
})"
.format(i) for i in range(num_classes)] print("".join(class_numbers))複製程式碼

計算分類的幫助函式

這個函式用來計算影像的預測類別,同時返回一個代表每張影像分類是否正確的布林陣列。

由於計算可能會耗費太多記憶體,就分批處理。如果你的電腦當機了,試著降低batch-size。

# Split the data-set in batches of this size to limit RAM usage.batch_size = 256def predict_cls(transfer_values, labels, cls_true):    # Number of images.    num_images = len(transfer_values)    # Allocate an array for the predicted classes which    # will be calculated in batches and filled into this array.    cls_pred = np.zeros(shape=num_images, dtype=np.int)    # Now calculate the predicted classes for the batches.    # We will just iterate through all the batches.    # There might be a more clever and Pythonic way of doing this.    # The starting index for the next batch is denoted i.    i = 0    while i <
num_images: # The ending index for the next batch is denoted j. j = min(i + batch_size, num_images) # Create a feed-dict with the images and labels # between index i and j. feed_dict = {x: transfer_values[i:j], y_true: labels[i:j]
} # Calculate the predicted class using TensorFlow. cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict) # Set the start-index for the next batch to the # end-index of the current batch. i = j # Create a boolean array whether each image is correctly classified. correct = (cls_true == cls_pred) return correct, cls_pred複製程式碼

計算測試集上的預測類別。

def predict_cls_test():    return predict_cls(transfer_values = transfer_values_test,                       labels = labels_test,                       cls_true = cls_test)複製程式碼

計算分類準確率的幫助函式

這個函式計算了給定布林陣列的分類準確率,布林陣列表示每張影像是否被正確分類。比如, cls_accuracy([True, True, False, False, False]) = 2/5 = 0.4

def classification_accuracy(correct):    # When averaging a boolean array, False means 0 and True means 1.    # So we are calculating: number of True / len(correct) which is    # the same as the classification accuracy.    # Return the classification accuracy    # and the number of correct classifications.    return correct.mean(), correct.sum()複製程式碼

展示分類準確率的幫助函式

函式用來列印測試集上的分類準確率。

為測試集上的所有圖片計算分類會花費一段時間,因此我們直接從這個函式裡呼叫上面的函式,這樣就不用每個函式都重新計算分類。

def print_test_accuracy(show_example_errors=False,                        show_confusion_matrix=False):    # For all the images in the test-set,    # calculate the predicted classes and whether they are correct.    correct, cls_pred = predict_cls_test()    # Classification accuracy and the number of correct classifications.    acc, num_correct = classification_accuracy(correct)    # Number of images being classified.    num_images = len(correct)    # Print the accuracy.    msg = "Accuracy on Test-Set: {0:.1%
} ({1
} / {2
})"
print(msg.format(acc, num_correct, num_images)) # Plot some examples of mis-classifications, if desired. if show_example_errors: print("Example errors:") plot_example_errors(cls_pred=cls_pred, correct=correct) # Plot the confusion matrix, if desired. if show_confusion_matrix: print("Confusion Matrix:") plot_confusion_matrix(cls_pred=cls_pred)複製程式碼

結果

優化之前的效能

測試集上的準確度很低,這是由於模型只做了初始化,並沒做任何優化,所以它只是對影像做隨機分類。

print_test_accuracy(show_example_errors=False,                    show_confusion_matrix=True)複製程式碼

Accuracy on Test-Set: 30.0% (159 / 530)
Confusion Matrix:
[151 0 0] (0) forky
[122 3 12] (1) knifey
[237 0 5] (2) spoony
(0) (1) (2)

1000次優化迭代後的效能

在1000次優化迭代之後,測試集上的準確率大約為70%。

optimize(num_iterations=1000)複製程式碼

Global Step: 100, Training Batch Accuracy: 95.3%
Global Step: 200, Training Batch Accuracy: 96.9%
Global Step: 300, Training Batch Accuracy: 98.4%
Global Step: 400, Training Batch Accuracy: 100.0%
Global Step: 500, Training Batch Accuracy: 100.0%
Global Step: 600, Training Batch Accuracy: 100.0%
Global Step: 700, Training Batch Accuracy: 100.0%
Global Step: 800, Training Batch Accuracy: 100.0%
Global Step: 900, Training Batch Accuracy: 100.0%
Global Step: 1000, Training Batch Accuracy: 100.0%
Time usage: 0:00:02

print_test_accuracy(show_example_errors=True,                    show_confusion_matrix=True)複製程式碼

Accuracy on Test-Set: 71.3% (378 / 530)
Example errors:

Confusion Matrix:
[35 36 80] (0) forky
[ 6 101 30] (1) knifey
[ 0 0 242] (2) spoony
(0) (1) (2)

關閉TensorFlow會話

現在我們已經用TensorFlow完成了任務,關閉session,釋放資源。注意,我們需要關閉兩個TensorFlow-session,每個模型物件各有一個。

# This has been commented out in case you want to modify and experiment# with the Notebook without having to restart it.# model.close()# session.close()複製程式碼

總結

這篇教程向我們展示瞭如何在Inception模型上用自己的影像做遷移學習。教程中使用的幾千張影像是我們用一個Python指令碼從幾分鐘的錄影視訊中生成的。

然而,Knifey-Spoony資料集上的分類準確率不是很高,特別是叉子的影像。可能是因為Inception模型在ImageNet資料集上訓練,而其中只有16張叉子的影像,但它卻包括了1200多張勺子影像和1300多張餐刀影像。因此Inception模型很可能無法正確識別叉子。

因此我們需要另一種技巧來微調Inception模型,這樣它就能更好地識別叉子。

練習

下面使一些可能會讓你提升TensorFlow技能的一些建議練習。為了學習如何更合適地使用TensorFlow,實踐經驗是很重要的。

在你對這個Notebook進行修改之前,可能需要先備份一下。

  • 試著為新的分類器改變神經網路。如果你刪掉全連線層或新增更多的全連線層會發生什麼?
  • 如果你執行更多或更少的迭代會出現什麼情況?
  • 試著在訓練集中刪掉一些勺子的影像,這樣每種類別的圖象數量就差不多(先做個備份)。你還需要刪除所有檔名帶有*.pkl的快取檔案,然後重新執行Notebook。這樣會提高分類準確率嗎?比較改變前後的混淆矩陣。
  • convert.py 指令碼建立你自己的資料集。比如,錄下汽車和摩托車的視訊,然後建立一個分類系統。
  • 需要從你建立的訓練集中刪除一些不明確的影像嗎?如何你刪掉這些影像之後,分類準確率有什麼變化?
  • 改變Notebook,這樣你可以輸入單張影像而不是整個資料集。你不用從Inception模型中儲存transfer-values。
  • 你能建立一個比用Inception模型來做遷移學習更好的或更快的神經網路嗎?
  • 向朋友解釋程式如何工作。

來源:https://juejin.im/post/59a2c9565188252445327242

相關文章