TensorFlow環(huán)境搭建
mac os環(huán)境:
macOS 10.12.6(Sierra)或更高版本(不支持GPU)
需要 Xcode 8.3 或更高版本
-
使用Python的pip軟件包管理器安裝TensorFlow
//首次安裝
pip install tensorflow
//升級
pip install --user --upgrade tensorflow
//驗證是否安裝成功
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
如果出現(xiàn)像我一樣的報錯
err
更新庫:
pip install --upgrade numpy
-
docker 容器運行tensorflow
首先在mac os安裝docker,使用docker 命令在終端運行容器
推薦使用這種方式,部署簡單隨心所欲
//在容器中run tensorflow 映射本地端口
docker run --name=tensorflow -it --rm -v $(realpath ~/notebooks):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:latest-py3-jupyter
docker 容器運行后會看到token
tensorflow容器運行成功
保持容器后臺運行并推出 : control + p
, control +q
使用Jupyter notebook server進行操作,使用瀏覽器打開
http://localhost:8888
copy token值點擊login,寫下造物主語句hello wold
//測試代碼
import tensorflow as tf
from tensorflow.keras import layers
print(tf.VERSION)
print(tf.keras.__version__)
tf.enable_eager_execution();
print(tf.reduce_sum(tf.random_normal([1000, 1000])));
tensorflow容器運行成功
TensorFlow Keras指南
TensorFlow是一個用于研究和生產(chǎn)的開源機器學習庫。TensorFlow為初學者和專家提供API,以便為桌面,移動,Web和云開發(fā)
高級Keras API提供構(gòu)建塊來創(chuàng)建和訓練深度學習模型
-
訓練第一個神經(jīng)網(wǎng)絡(luò)-基礎(chǔ)分類
使用的是 tf.keras,它是一種用于在 TensorFlow 中構(gòu)建和訓練模型的高階 API
copy一下code至juputer 運行,可以自己調(diào)試
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
# Fashion MNIST 數(shù)據(jù)集導入
# 將使用 60000 張圖像訓練網(wǎng)絡(luò),并使用 10000 張圖像評估經(jīng)過學習的網(wǎng)絡(luò)分類圖像的準確率
# 加載數(shù)據(jù)集會返回 4 個 NumPy 數(shù)組
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# 標簽是整數(shù)數(shù)組,介于 0 到 9 之間。這些標簽對應(yīng)于圖像代表的服飾所屬的類別
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 檢查數(shù)據(jù)格式
# 60000 張圖像,每張圖像都表示為 28x28 像素
# 輸出為(60000, 28, 28)
train_images.shape
# 數(shù)據(jù)長度
len(train_labels)
print("數(shù)據(jù)長度:",len(train_labels))
train_labels
print("標簽:",train_labels)
# 測試集1000張 28*28像素的圖片
test_images.shape
print("數(shù)據(jù)預(yù)處理,檢查第一張圖 應(yīng)該 0 到 255 之間")
#訓練的時候注釋掉,但必須運行一次
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
# 將這些值縮小到 0 到 1 之間,然后將其饋送到神經(jīng)網(wǎng)絡(luò)模型,將圖像組件的數(shù)據(jù)類型從整數(shù)轉(zhuǎn)換為浮點數(shù),然后除以 255
train_images = train_images / 255.0
test_images = test_images / 255.0
#訓練的時候注釋掉,但必須運行一次
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]])
print("構(gòu)建神經(jīng)網(wǎng)絡(luò)需要先配置模型的層,然后再編譯模型")
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
# 編譯模型
print("start 編譯模型")
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 訓練模型 epochs值自己修改
print("start 訓練模型")
model.fit(train_images, train_labels, epochs=5)
print ("評估準確率:比較一下模型在測試數(shù)據(jù)集上的表現(xiàn)")
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('測試數(shù)據(jù)的準確率:', test_acc)
print ("做出預(yù)測")
predictions = model.predict(test_images)
#看看第一個預(yù)測 ,數(shù)組的10個數(shù)字代表了每個標簽的可信度預(yù)測
predictions[0]
print("獲取可信度最大值:",np.argmax(predictions[0]))
# 檢查測試標簽以查看該預(yù)測是否正確
test_labels[0]
# 將該預(yù)測繪制成圖來查看全部 10 個通道
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], 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[i], true_label[i]
plt.grid(False)
plt.xticks([])
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')
print("看看第 0 張圖像、預(yù)測和預(yù)測數(shù)組")
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
# 看看第 12 張圖像、預(yù)測和預(yù)測數(shù)組
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
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, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
# 最后,使用經(jīng)過訓練的模型對單個圖像進行預(yù)測
print("最后,使用經(jīng)過訓練的模型對單個圖像進行預(yù)測")
img = test_images[0]
print(img.shape)
#tf.keras 模型已經(jīng)過優(yōu)化,可以一次性對樣本批次或樣本集進行預(yù)測
img = (np.expand_dims(img,0))
print(img.shape)
# 預(yù)測這張圖像
predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
np.argmax(predictions_single[0])
可以看到訓練的次數(shù)增加,模型準確度也變高,是不是越多越好呢?當然不是
模型訓練
識別結(jié)果:mode對測試集進行識別
mode對測試集進行識別