TensorFlow入門(一)

TensorFlow環(huán)境搭建

mac os環(huán)境:

macOS 10.12.6(Sierra)或更高版本(不支持GPU)
需要 Xcode 8.3 或更高版本

  • 使用Python的pip軟件包管理器安裝TensorFlow

//首次安裝
pip install tensorflow

//升級(jí)
pip install --user --upgrade tensorflow


//驗(yàn)證是否安裝成功
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"

如果出現(xiàn)像我一樣的報(bào)錯(cuò)


err

更新庫(kù):

pip install --upgrade numpy
  • docker 容器運(yùn)行tensorflow

首先在mac os安裝docker,使用docker 命令在終端運(yùn)行容器

推薦使用這種方式,部署簡(jiǎn)單隨心所欲


//在容器中run tensorflow 映射本地端口 
docker run  --name=tensorflow  -it --rm -v $(realpath ~/notebooks):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:latest-py3-jupyter

docker 容器運(yùn)行后會(huì)看到token


tensorflow容器運(yùn)行成功

保持容器后臺(tái)運(yùn)行并推出 : control + p , control +q

使用Jupyter notebook server進(jìn)行操作,使用瀏覽器打開
http://localhost:8888

copy token值點(diǎn)擊login,寫下造物主語句hello wold


//測(cè)試代碼

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容器運(yùn)行成功

TensorFlow Keras指南

TensorFlow是一個(gè)用于研究和生產(chǎn)的開源機(jī)器學(xué)習(xí)庫(kù)。TensorFlow為初學(xué)者和專家提供API,以便為桌面,移動(dòng),Web和云開發(fā)

高級(jí)Keras API提供構(gòu)建塊來創(chuàng)建和訓(xùn)練深度學(xué)習(xí)模型

  • 訓(xùn)練第一個(gè)神經(jīng)網(wǎng)絡(luò)-基礎(chǔ)分類

案例是Google出的學(xué)習(xí)Demo

使用的是 tf.keras,它是一種用于在 TensorFlow 中構(gòu)建和訓(xùn)練模型的高階 API

copy一下code至juputer 運(yùn)行,可以自己調(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ù)集導(dǎo)入
# 將使用 60000 張圖像訓(xùn)練網(wǎng)絡(luò),并使用 10000 張圖像評(píng)估經(jīng)過學(xué)習(xí)的網(wǎng)絡(luò)分類圖像的準(zhǔn)確率
# 加載數(shù)據(jù)集會(huì)返回 4 個(gè) NumPy 數(shù)組
fashion_mnist = keras.datasets.fashion_mnist

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


# 標(biāo)簽是整數(shù)數(shù)組,介于 0 到 9 之間。這些標(biāo)簽對(duì)應(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ù)長(zhǎng)度
len(train_labels)
print("數(shù)據(jù)長(zhǎng)度:",len(train_labels))

train_labels
print("標(biāo)簽:",train_labels)

# 測(cè)試集1000張 28*28像素的圖片
test_images.shape

print("數(shù)據(jù)預(yù)處理,檢查第一張圖 應(yīng)該 0 到 255 之間")

#訓(xùn)練的時(shí)候注釋掉,但必須運(yùn)行一次
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)

# 將這些值縮小到 0 到 1 之間,然后將其饋送到神經(jīng)網(wǎng)絡(luò)模型,將圖像組件的數(shù)據(jù)類型從整數(shù)轉(zhuǎn)換為浮點(diǎn)數(shù),然后除以 255
train_images = train_images / 255.0

test_images = test_images / 255.0

#訓(xùn)練的時(shí)候注釋掉,但必須運(yùn)行一次
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'])

# 訓(xùn)練模型 epochs值自己修改
print("start 訓(xùn)練模型")

model.fit(train_images, train_labels, epochs=5)


print ("評(píng)估準(zhǔn)確率:比較一下模型在測(cè)試數(shù)據(jù)集上的表現(xiàn)")
test_loss, test_acc = model.evaluate(test_images, test_labels)

print('測(cè)試數(shù)據(jù)的準(zhǔn)確率:', test_acc)


print ("做出預(yù)測(cè)")
predictions = model.predict(test_images)

#看看第一個(gè)預(yù)測(cè)  ,數(shù)組的10個(gè)數(shù)字代表了每個(gè)標(biāo)簽的可信度預(yù)測(cè)
predictions[0]

print("獲取可信度最大值:",np.argmax(predictions[0]))

# 檢查測(cè)試標(biāo)簽以查看該預(yù)測(cè)是否正確
test_labels[0]

# 將該預(yù)測(cè)繪制成圖來查看全部 10 個(gè)通道
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ù)測(cè)和預(yù)測(cè)數(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ù)測(cè)和預(yù)測(cè)數(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)過訓(xùn)練的模型對(duì)單個(gè)圖像進(jìn)行預(yù)測(cè)
print("最后,使用經(jīng)過訓(xùn)練的模型對(duì)單個(gè)圖像進(jìn)行預(yù)測(cè)")

img = test_images[0]

print(img.shape)


#tf.keras 模型已經(jīng)過優(yōu)化,可以一次性對(duì)樣本批次或樣本集進(jìn)行預(yù)測(cè)

img = (np.expand_dims(img,0))

print(img.shape)


# 預(yù)測(cè)這張圖像
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])
    
    



可以看到訓(xùn)練的次數(shù)增加,模型準(zhǔn)確度也變高,是不是越多越好呢?當(dāng)然不是

模型訓(xùn)練

識(shí)別結(jié)果:mode對(duì)測(cè)試集進(jìn)行識(shí)別


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

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

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