機器學習(基本圖像分類)

1.安裝Anaconda3

下載地址:https://www.anaconda.com/distribution/#windows

一路下一步即可……

詳細:https://blog.csdn.net/ychgyyn/article/details/82119201

2.安裝TensorFlow

python -m pip install --upgrade pip
pip install --ignore-installed --upgrade tensorflow # cpu版本
pip install --ignore-installed --upgrade tensorflow-gpu # gpu版本
# https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-2.0.0-cp37-cp37m-win_amd64.whl

如果同時安裝了兩個版本,默認下運行gpu版,如想運行cpu版,可代碼中設置如下:

with tf.Session() as ses:
    with tf.device("/cpu:0"):
        matrix1=tf.constant([[3.,3.]])
        matrix2=tf.constant([[2.],[2.]])
        product=tf.matmul(matrix1,matrix2)
字符 對應的操作
"/cpu:0" The CPU of your machine
"/gpu:0" The GPU of yout machine ,if you have one

GPU版本需要安裝CUDA

參考: https://www.cnblogs.com/wanyu416/p/9536853.html

鏈接: https://pan.baidu.com/s/1vz_f_OQG9Cah2cGydzSvag 提取碼: hqiq 

cudnn安裝,其實就是解壓,解壓到當前文件夾,然後拷貝到對應的文件夾下:

cudnn64_7.dll 拷貝到:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin

cudnn.h 拷貝到:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\include

cudnn.lib 拷貝到:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib\x64

設置Pycharm環境:

基本圖像分類

from __future__ import absolute_import, division, print_function, unicode_literals

# 助手庫
import matplotlib.pyplot as plt
import numpy as np
# TensorFlow和tf.keras
import tensorflow as tf
from tensorflow import keras

print(tf.__version__)


def plot_image(i, predictions_array, true_label, img):
    predictions_array, true_label, img = predictions_array, true_label[i], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(img, cmap=plt.cm.binary)

    predicted_label = np.argmax(predictions_array)
    if predicted_label == true_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                         100 * np.max(predictions_array),
                                         class_names[true_label]),
               color=color)


def plot_value_array(i, predictions_array, true_label):
    predictions_array, true_label = predictions_array, true_label[i]
    plt.grid(False)
    plt.xticks(range(10))
    plt.yticks([])
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)

    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('blue')


# 加載數據
"""
加載數據集返回四個NumPy數組:
train_images和train_label數組是訓練集——模型用來學習的數據
模型將根據測試集test_images和test_label數組進行測試
"""
fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

"""
每個圖像都映射到單個標籤。由於類名沒有包含在數據集中,所以將它們存儲在這裏,以便以後繪製圖像時使用:
"""
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# 訓練集
print(train_images.shape)
print(len(train_labels))
print(train_labels)
# 測試集
print(test_images.shape)
print(len(test_images))
# 在訓練網絡之前,必須對數據進行預處理
# 如果你檢查訓練集中的第一個圖像,你會看到像素值落在0到255的範圍內:
plt.figure()
a = train_images[0]
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

"""
將這些值縮放到0到1的範圍
爲此,將這些值除以255。重要的是,訓練集和測試集以相同的方式預處理
"""
train_images = train_images / 255.0

test_images = test_images / 255.0
"""
爲了驗證數據的格式是否正確
以及您是否準備好構建和訓練網絡
讓我們顯示來自訓練集的前25個圖像
並在每個圖像下面顯示類名
"""
plt.figure(figsize=(10, 10))
for i in range(25):
    plt.subplot(5, 5, i + 1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

# 建模
# 設置圖層
"""
神經網絡的基本構件是層
層從輸入的數據中提取表示
大多數深度學習是由簡單的層次鏈接在一起構成的
比如tf.keras.layers
"""
"""
這個網絡的第一層,tf.keras.layers。Flatten
將圖像的格式從一個二維數組(28×28像素)轉換爲一個一維數組(28 * 28 = 784像素)
可以把這個層看作是將圖像中的像素行分解並排列起來
這一層沒有需要學習的參數;它只重新格式化數據
當像素被壓平後,網絡由兩個tf.keras.layers.Dense組成的序列組成層
這些神經層緊密相連第一Dense層有128個節點(或神經元)
第二層(也是最後一層)是一個10節點的softmax層,它返回一個10個概率值的數組,這些概率值的和爲1
每個節點包含一個分數,表示當前圖像屬於10個類之一的概率
"""
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

# 編譯模型
"""
在模型準備好進行培訓之前它需要更多的設置
這些是在模型的編譯步驟中添加的:
"""
"""
Optimizer     ——這是根據它看到的數據和它的損失函數更新模型的方法
loss function ——測量訓練過程中模型的準確性,您想要最小化這個函數來“引導”模型朝正確的方向前進
metrics       ——用於監視培訓和測試步驟,下面的例子使用精度,即正確分類的圖像的分數
"""
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 訓練模型
"""
訓練神經網絡模型需要以下步驟:
"""
"""
1.將訓練數據輸入模型,在本例中,訓練數據位於train_images和train_tags數組中
2.這個模型學會了把圖像和標籤聯繫起來
3.您要求模型對一個測試集做出預測—在這個例子中:test_images數組,驗證預測是否與test_labels數組中的標籤匹配
"""
# 要開始訓練,使用model.fit 方法——之所以這麼叫,是因爲它將模型“適合”於訓練數據:
# 當模型訓練時,顯示損失和精度指標。該模型對訓練數據的準確率約爲0.9099(或90%)
model.fit(train_images, train_labels, epochs=10)

# 評估準確性
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
# 結果表明,測試數據集的準確性略低於訓練數據集的準確性
# 這種訓練精度和測試精度之間的差距表示過度擬合
# 過度擬合是指機器學習模型在新的、以前未見過的輸入上的表現不如在訓練數據上的表現
print('\nTest accuracy:', test_acc)

# 作出預測
# 通過訓練模型,您可以使用它對一些圖像進行預測
predictions = model.predict(test_images)
# 模型已經預測了測試集中每張圖片的標籤
# 讓我們看一下第一個預測
print(predictions[0])
print(class_names[int(np.argmax(predictions[0]))])

# 繪製這張圖來查看完整的10個類預測
"""
讓我們看看第0張圖片、預測和預測數組
正確的預測標籤是藍色的,錯誤的預測標籤是紅色的
這個數字給出了預測標籤的百分比(滿分100)
"""
for i in range(3):
    plt.figure(figsize=(6, 3))
    plt.subplot(1, 2, 1)
    plot_image(i, predictions[i], test_labels, test_images)
    plt.subplot(1, 2, 2)
    plot_value_array(i, predictions[i], test_labels)
    plt.show()

# 繪製錯誤情況
num_rows = 5
num_cols = 3
num_images = num_rows * num_cols
plt.figure(figsize=(2 * 2 * num_cols, 2 * num_rows))
for i in range(num_images):
    plt.subplot(num_rows, 2 * num_cols, 2 * i + 1)
    plot_image(i, predictions[i], test_labels, test_images)
    plt.subplot(num_rows, 2 * num_cols, 2 * i + 2)
    plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

# 最後
# 利用訓練後的模型對單個圖像進行預測
img = test_images[1]
print(img.shape)
"""
tf.keras模型經過優化
可以一次對一批或一組示例進行預測
因此,即使你使用的是一張圖片,你也需要將它添加到一個列表中:
"""
# 將圖像添加到批處理中,其中它是唯一的成員。
img = (np.expand_dims(img, 0))
print(img.shape)
# 現在預測這個圖像的正確標籤:
predictions_single = model.predict(img)

print(predictions_single)
plt.figure(figsize=(6, 3))
plt.subplot(1, 2, 1)
# 繪圖
plot_image(1, predictions_single[0], test_labels, test_images)
plt.subplot(1, 2, 2)
# 繪製列表
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=90)
plt.show()
"""
model.predict 返回一個列表列表-爲批處理數據中的每個圖像一個列表。抓住預測我們的(唯一的)圖像批:
"""
print(class_names[int(np.argmax(predictions_single[0]))])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章