天天看點

HaaS AI之手寫數字識别快速實踐,在VSCode中搭建TensorFlow 2.0簡單神經網絡1、Conda環境安裝2、建立TensorFlow Python虛拟環境3、TensorFlow之初體驗4. 訓練并驗證模型:4、FQA

1、Conda環境安裝

參考HaaS AI之VSCode中搭建Python虛拟環境

2、建立TensorFlow Python虛拟環境

conda維護到TensorFlow2.0版本,基于Python3.7版本,是以線建立一個TensorFlow的Python虛拟環境,命名為tf2。

conda create --name tf2 python=3.7

2.1、激活環境

(tf2)$conda activate tf2

2.2、安裝TensorFlow2.0

(tf2)$conda install tensorflow

2.3、安裝Matplotlib

matplotlib,風格類似 Matlab 的基于 Python 的圖表繪圖系統。

matplotlib 是 Python最著名的繪圖庫,它提供了一整套和 matlab 相似的命 API,十分适合互動式地進行制圖。而且也可以友善地将它作為繪圖控件,嵌入 GUI 應用程式中,在模型訓練中常常用來繪制圖形。

(tf2)$conda install matplotlib

3、TensorFlow之初體驗

TensorFlow是Google開源的深度學習架構,是一個端到端平台,無論您是專家還是初學者,它都可以讓您輕松地建構和部署機器學習模型。

HaaS AI之手寫數字識别快速實踐,在VSCode中搭建TensorFlow 2.0簡單神經網絡1、Conda環境安裝2、建立TensorFlow Python虛拟環境3、TensorFlow之初體驗4. 訓練并驗證模型:4、FQA

3.1、簡單手寫數字識别網絡

在VSCode中訓練一個簡單的手寫數字識别網絡模型:

1. 加載TensorFlow

In [1]:

#Mac OS KMP設定

import os

os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

# 安裝 TensorFlow

import tensorflow as tf

2. 載入并準備好 MNIST 資料集。将樣本從整數轉換為浮點數:

In [2]:

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train, x_test = x_train / 255.0, x_test / 255.0

3. 将模型的各層堆疊起來,以搭建 tf.keras.Sequential 模型。為訓練選擇優化器和損失函數:

In [3]:

model = tf.keras.models.Sequential([

 tf.keras.layers.Flatten(input_shape=(28, 28)),

 tf.keras.layers.Dense(128, activation='relu'),

 tf.keras.layers.Dropout(0.2),

 tf.keras.layers.Dense(10, activation='softmax')

])

model.compile(optimizer='adam',

             loss='sparse_categorical_crossentropy',

             metrics=['accuracy'])

4. 訓練并驗證模型:

In [4]:

model.fit(x_train, y_train, epochs=5)

model.evaluate(x_test,  y_test, verbose=2)

# 輸出結果

Out[4]:

Train on 60000 samples

Epoch 1/5

60000/60000 [==============================] - 9s 154us/sample - loss: 0.3008 - accuracy: 0.9120

Epoch 2/5

60000/60000 [==============================] - 9s 147us/sample - loss: 0.1444 - accuracy: 0.9579

Epoch 3/5

60000/60000 [==============================] - 10s 170us/sample - loss: 0.1073 - accuracy: 0.9676

Epoch 4/5

60000/60000 [==============================] - 10s 174us/sample - loss: 0.0890 - accuracy: 0.9726

Epoch 5/5

60000/60000 [==============================] - 11s 180us/sample - loss: 0.0765 - accuracy: 0.9764

10000/1 - 1s - loss: 0.0379 - accuracy: 0.9777

[0.0705649911917746, 0.9777]

3.2、模型儲存

model.save('tf_mnist_simple_net.h5')

3.3、模型預測

3.3.1、顯示待測圖檔

從測試集中選擇索引号為image_index的圖檔進行測試。

5. 模型預測

# 定義plot_image函數,檢視指定個數資料圖像

import matplotlib.pyplot as plt #導入matplotlib.pyplot

def plot_image(image):                  #輸入參數為image

   pic=plt.gcf()                       #擷取目前圖像

   pic.set_size_inches(2,2)            ##設定圖檔大

   plt.imshow(image, cmap='binary')    #使用plt.imshow顯示圖檔

   plt.show()                          #設定圖檔大

# 測試集中圖檔索引 0~10000

image_index=23

# 顯示待預測值

plot_image(x_test[image_index])

HaaS AI之手寫數字識别快速實踐,在VSCode中搭建TensorFlow 2.0簡單神經網絡1、Conda環境安裝2、建立TensorFlow Python虛拟環境3、TensorFlow之初體驗4. 訓練并驗證模型:4、FQA

3.3.2、列印測試結果

pred = model.predict_classes(x_test)

#列印預測結果

print(pred)

print("測試數字結果:")

print(pred[image_index])

Out [1]:

[7 2 1 ... 4 5 6]

測試數字結果:

5

為了節省訓練時間,把eporch疊代次數改為1,建立一個Jupyter notebook執行1次疊代訓練上述模型:

https://v.youku.com/v_show/id_XNTA5Mzk2NzU2NA==.html

注意:

在建立*.ipynb和*.py檔案的名稱不能是tensorflow.ipynb/tensorflow.py,否則會出現各種庫找不到的情形。

3.3.3、測試代碼

将以上代碼合在同一個檔案中(去掉輸出結果部分)就可以進行測試了。

4、FQA

Q1: Mac OS上在執行模型訓練時出現錯誤

OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.

OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see

http://www.intel.com/software/products/support/.

Abort trap: 6

A1:

大概意思就是初始化libiomp5.dylib時發現已經初始化過了。

經過Google發現這似乎是一個Mac OS 才存在的特殊問題,在代碼頭部加入: