日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

tensorflow教程 开始——Premade Estimators(预制评估器)

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 tensorflow教程 开始——Premade Estimators(预制评估器) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考文章:Premade Estimators

文章目錄

    • Premade Estimators
      • 前置要求
      • 獲取樣例代碼
        • 運行程序
      • 程序棧
      • 對 irises 分類:概覽
        • 數據集
        • 算法
        • 接口
      • 使用 Estimators 編程的概覽
      • 創建輸入函數
      • 定義特征列
      • 實例化一個 Estimator
      • 訓練,評估和預測
        • 訓練模型
        • 評估訓練好的模型
        • 通過訓練好的模型進行預測
    • 總結

Premade Estimators

該文檔將介紹 TensorFlow 的編程環境,并會向你展示如何使用 TensorFlow 解決 Iris 分類問題。

前置要求

你需要先做如下幾件事,才能夠使用本文檔的樣例代碼:

  • 安裝 TensorFlow
  • 如果你在 virtualenv 或者 Anaconda 上安裝了 TensorFlow,啟動你的 TensorFlow 環境。
  • 通過以下命令安裝或升級 pandas:
pip install pandas

獲取樣例代碼

通過以下幾步來獲得我們將要使用的樣例代碼:

  • 通過鍵入以下命令從 GitHub 下載 TensorFlow Models 倉庫:
  • git clone https://github.com/tensorflow/models
  • 進入含有樣例的文件夾:
  • cd models/samples/core/get_started/

    我們在本文檔中將使用的程序是
    premade_estimator.py.
    這個程序使用
    iris_data.py
    來獲取訓練數據。

    運行程序

    運行 TensorFlow 的程序和運行其他的 Python 程序方法一樣。例如

    python premade_estimator.py

    程序將會輸出一些訓練日志,還有一些對測試集的預測結果。例如,下列輸出的第一行顯示出,模型認為測試集中的第一個例子為 Setosa 的概率為 99.6%。由于測試集中確實為 Setosa,這表示此次預測表現不錯。

    ... Prediction is "Setosa" (99.6%), expected "Setosa"Prediction is "Versicolor" (99.8%), expected "Versicolor"Prediction is "Virginica" (97.9%), expected "Virginica" D:\Yolov3_Tensorflow\python\python.exe D:/20200123_華為筆記本_pycharm測試項目/202002010_創建定制化estimator/models/samples/core/get_started/premade_estimator.py INFO:tensorflow:Using default config. WARNING:tensorflow:Using temporary folder as model directory: C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_ INFO:tensorflow:Using config: {'_model_dir': 'C:\\Users\\HuaWei\\AppData\\Local\\Temp\\tmp9e1xbuw_', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true graph_options {rewrite_options {meta_optimizer_iterations: ONE} } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x000001F2C929B160>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Graph was finalized. 2020-02-10 22:48:31.934578: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 2020-02-10 22:48:32.649107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1411] Found device 0 with properties: name: GeForce MX250 major: 6 minor: 1 memoryClockRate(GHz): 1.582 pciBusID: 0000:01:00.0 totalMemory: 2.00GiB freeMemory: 1.62GiB 2020-02-10 22:48:32.649448: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1490] Adding visible gpu devices: 0 2020-02-10 22:48:33.621053: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] Device interconnect StreamExecutor with strength 1 edge matrix: 2020-02-10 22:48:33.621228: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] 0 2020-02-10 22:48:33.621328: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0: N 2020-02-10 22:48:33.621546: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1103] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1374 MB memory) -> physical GPU (device: 0, name: GeForce MX250, pci bus id: 0000:01:00.0, compute capability: 6.1) INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Saving checkpoints for 0 into C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_\model.ckpt. INFO:tensorflow:loss = 104.19969, step = 0 INFO:tensorflow:global_step/sec: 276.161 INFO:tensorflow:loss = 37.975826, step = 100 (0.364 sec) INFO:tensorflow:global_step/sec: 334.223 INFO:tensorflow:loss = 22.292067, step = 200 (0.298 sec) INFO:tensorflow:global_step/sec: 341.768 INFO:tensorflow:loss = 17.565737, step = 300 (0.292 sec) INFO:tensorflow:global_step/sec: 337.602 INFO:tensorflow:loss = 14.672792, step = 400 (0.297 sec) INFO:tensorflow:global_step/sec: 359.38 INFO:tensorflow:loss = 10.606393, step = 500 (0.278 sec) INFO:tensorflow:global_step/sec: 351.815 INFO:tensorflow:loss = 7.5208006, step = 600 (0.284 sec) INFO:tensorflow:global_step/sec: 346.946 INFO:tensorflow:loss = 9.5241785, step = 700 (0.288 sec) INFO:tensorflow:global_step/sec: 361.976 INFO:tensorflow:loss = 8.364717, step = 800 (0.276 sec) INFO:tensorflow:global_step/sec: 345.748 INFO:tensorflow:loss = 8.853266, step = 900 (0.289 sec) INFO:tensorflow:Saving checkpoints for 1000 into C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_\model.ckpt. INFO:tensorflow:Loss for final step: 10.949549. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2020-02-10-14:48:37 INFO:tensorflow:Graph was finalized. 2020-02-10 22:48:37.650667: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1490] Adding visible gpu devices: 0 2020-02-10 22:48:37.650864: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] Device interconnect StreamExecutor with strength 1 edge matrix: 2020-02-10 22:48:37.651021: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] 0 2020-02-10 22:48:37.651141: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0: N 2020-02-10 22:48:37.651427: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1103] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1374 MB memory) -> physical GPU (device: 0, name: GeForce MX250, pci bus id: 0000:01:00.0, compute capability: 6.1) INFO:tensorflow:Restoring parameters from C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_\model.ckpt-1000 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Finished evaluation at 2020-02-10-14:48:37 INFO:tensorflow:Saving dict for global step 1000: accuracy = 0.96666664, average_loss = 0.084238075, global_step = 1000, loss = 2.5271423Test set accuracy: 0.967INFO:tensorflow:Saving 'checkpoint_path' summary for global step 1000: C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_\model.ckpt-1000 INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Graph was finalized. 2020-02-10 22:48:38.023873: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1490] Adding visible gpu devices: 0 2020-02-10 22:48:38.024076: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] Device interconnect StreamExecutor with strength 1 edge matrix: 2020-02-10 22:48:38.024234: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] 0 2020-02-10 22:48:38.024332: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0: N 2020-02-10 22:48:38.024488: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1103] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1374 MB memory) -> physical GPU (device: 0, name: GeForce MX250, pci bus id: 0000:01:00.0, compute capability: 6.1) INFO:tensorflow:Restoring parameters from C:\Users\HuaWei\AppData\Local\Temp\tmp9e1xbuw_\model.ckpt-1000 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op.Prediction is "Setosa" (99.8%), expected "Setosa"Prediction is "Versicolor" (99.5%), expected "Versicolor"Prediction is "Virginica" (92.3%), expected "Virginica"Process finished with exit code 0

    如果程序出現報錯,那么請自查如下問題:

    • 你正確地安裝 TensorFlow 了嗎?
    • 你使用的是正確版本的 TensorFlow 嗎?
    • 你啟動安裝了 TensorFlow 的環境了嗎?(這條僅會出現在一些特定的安裝方法中)

    程序棧

    在深入程序細節之前,讓我們先了解一下程序的環境。如下所示,TensorFlow 提供了一個含有很多 API 層的程序棧:

    我們強烈建議使用如下 API 編寫 TensorFlow 程序:

    • 評估器
    • 數據集:快速了解

    對 irises 分類:概覽

    本文檔中的這個樣例程序搭建并測試了一個模型,根據花的萼片和花瓣將 Iris 花分成不同種類。

    從左至右為
    Iris setosa (by Radomil, CC BY-SA 3.0),
    Iris versicolor (by Dlanglois, CC BY-SA 3.0),
    and Iris virginica (by Frank Mayfield, CC BY-SA 2.0).

    數據集

    Iris 數據集包含四個特征和一個標簽。四個特征定義了 Iris 花的植物特征:

    • 花萼長度
    • 花萼寬度
    • 花瓣長度
    • 花瓣寬度

    我們的模型會用 float32 類型的數據來表示這些特征。

    標簽表明了 Iris 的種類,必須為以下一種:

    • Iris setosa (0)
    • Iris versicolor (1)
    • Iris virginica (2)

    我們的模型會用 int32 類型的數據來表示這些標簽。

    下面的表格顯示了數據集中的三個例子:

    花萼長度花萼寬度花瓣長度花瓣寬度類別(標簽)
    5.13.31.70.50 (Setosa)
    5.02.33.31.01 (versicolor)
    6.42.85.62.22 (virginica)

    算法

    程序訓練了一個深度神經網絡分類模型,有著如下的拓撲結構:

    • 2 個隱藏層。
    • 每個隱藏層擁有 10 個節點。

    下圖展示了神經網絡中的特征,隱藏層和預測結果(隱藏層中的節點沒有全部顯示出來):

    接口

    在未標記的樣例上運行一個訓練好的模型,會產生三個預測,分別是該花朵分別屬于三種 Iris 類別的概率。這三個預測值的和為 1.0。例如,對一個未標記的樣例的預測可能如下所示:

    • Iris Setosa 的可能性為 0.03
    • Iris Versicolor 的可能性為 0.95
    • Iris Virginica 的可能性為 0.02

    這個預測意味著所給的未標記樣例有 95% 的概率為 Iris Versicolor 品種。

    使用 Estimators 編程的概覽

    評估器

    tf.estimator.Estimator

    要寫出一個基于預制的 Estimator 的 TensorFlow 程序,你可以進行如下任務:

    • 創建一個或多個輸入函數。
    • 定義模型的特征列。
    • 實例化一個 Estimator,定義特征列和各類超參數。
    • 在 Estimator 對象上調用一個或多個方法,傳入合適的輸入函數來作為數據源。

    讓我們看看這些任務是如何實現 Iris 分類的。

    創建輸入函數

    你必須創建一個可以為訓練,評估和預測提供數據提供支持的輸入函數。

    tf.data.Dataset

    • features - 一個 Python 字典:
      每個鍵為特征的名字。 每個值為一個包含所有該特征的值的數組。
    • label - 一個數組包含著所有例子的標簽 。
      這里有一個輸入函數的實現,來展示它的格式:
    def input_evaluation_set():features = {'SepalLength': np.array([6.4, 5.0]),'SepalWidth': np.array([2.8, 2.3]),'PetalLength': np.array([5.6, 3.3]),'PetalWidth': np.array([2.2, 1.0])}labels = np.array([2, 1])return features, labels

    你的輸入函數可以通過任意的方法來生成 features 字典和 label 列表。不過,我們推薦使用 TensorFlow 的 Dataset API,它可以處理所有種類的數據。從高層次看,Dataset API 包含了如下的類:

    其中,單獨的成員為:

    • Dataset - 包含創建和傳輸數據集的基類。同時也允許你通過內存中的數據來初始化數據集,或從一個 Python 生成器。
    • TextLineDataset - 從文本文件逐行讀取
    • TFRecordDataset - 從 TFRecord 文件讀取記錄
    • FixedLengthRecordDataset - 從二進制文件讀取固定大小的記錄
    • Iterator - 提供了一種每次獲取數據集中的元素的方法

    Dataset API 可以為你處理很多常見的情況。例如,使用它可以簡單地從一系列巨大的文件中并行地讀取記錄并合成一個單個的流。

    為了讓這個例子簡單易見,我們將會使用 pandas 來加載數據,并根據這個在內存中的數據來建立我們的輸入管道。

    這個是此程序訓練中使用的輸入函數,可以在iris_data.py找到。

    def train_input_fn(features, labels, batch_size):"""訓練中使用的輸入函數"""# 將輸入變為一個 Datasetdataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))# 打亂,重復并將樣例分批次return dataset.shuffle(1000).repeat().batch(batch_size)

    定義特征列

    tf.feature_column

    對于 Iris 來說,4 個原始的特征為數值,所以我們將會建立一個特征列的列表來告訴 Estimator 模型,將四個特征分別表示為 32 位的浮點數值。因此,用于建立特征列的代碼為:

    # Feature columns describe how to use the input. my_feature_columns = [] for key in train_x.keys():my_feature_columns.append(tf.feature_column.numeric_column(key=key))

    特征列

    如今我們有了如何讓模型表示原始特征的定義,我們可以開始搭建 Estimator 了。

    實例化一個 Estimator

    Iris 問題是一個經典的分類問題。幸運的是,TensorFlow 提供了一些預制的 Estimator 分類器,包含:

    • tf.estimator.DNNClassifier
    • tf.estimator.DNNLinearCombinedClassifier
    • tf.estimator.LinearClassifier

    對于 Iris 問題,tf.estimator.DNNClassifier 看起來是最佳選擇。以下是我們如何實例化這個 Estimator:

    # 創建一個有兩個隱藏層和每層10個節點的 DNN classifier = tf.estimator.DNNClassifier(feature_columns=my_feature_columns,# 兩個隱藏層,每層 10 個節點。hidden_units=[10, 10],# 模型必須在 3 個類別中作出選擇n_classes=3)

    訓練,評估和預測

    現在我們有了一個 Estimator 對象,我們可以調用方法來做如下事情:

    • 訓練模型
    • 評估訓練好的模型
    • 使用訓練好的模型進行預測

    訓練模型

    像如下一樣調用 Estimator 的 train 方法來訓練模型:

    # 訓練模型 classifier.train(input_fn=lambda:iris_data.train_input_fn(train_x, train_y, args.batch_size),steps=args.train_steps)

    這里我們將 input_fn 的調用包含在一個 lambda 中來在提供一個無參數的輸入函數時獲取 Estimator 所需的參數。steps 參數告訴方法要在一定數量的訓練次數后停止訓練。

    評估訓練好的模型

    如今模型已被訓練好,我們可以獲得一些它的表現數據了。下面的代碼片段評估了該模型在測試集上的準確率:

    # 評估該模型 eval_result = classifier.evaluate(input_fn=lambda:iris_data.eval_input_fn(test_x, test_y, args.batch_size))print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    與我們調用 train 方法不同,我們并不能將 steps 參數傳給評估方法。我們的 eval_input_fn 僅產生了一次epoch(輪數) 的數據。

    運行這段代碼會產生如下的輸出(或者類似的東西):

    Test set accuracy: 0.967

    通過訓練好的模型進行預測

    我們如今有了一個訓練好的模型,而且能擁有不錯的評估結果。我們現在可以使用訓練好的模型,基于一些未標記的樣例來預測 Iris 花朵的類型了。與訓練和評估相同,我們進行預測時只需進行一次函數調用:

    # 通過模型進行預測 expected = ['Setosa', 'Versicolor', 'Virginica'] predict_x = {'SepalLength': [5.1, 5.9, 6.9],'SepalWidth': [3.3, 3.0, 3.1],'PetalLength': [1.7, 4.2, 5.4],'PetalWidth': [0.5, 1.5, 2.1], }predictions = classifier.predict(input_fn=lambda:iris_data.eval_input_fn(predict_x,batch_size=args.batch_size))

    predict 方法返回了一個 Python 的可迭代類型,是一個含有每個例子的預測結果的字典。如下的代碼打印出了一些預測和它們的可能性:

    template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')for pred_dict, expec in zip(predictions, expected):class_id = pred_dict['class_ids'][0]probability = pred_dict['probabilities'][class_id]print(template.format(iris_data.SPECIES[class_id],100 * probability, expec))

    運行以上的代碼會出現下面的結果:

    ... Prediction is "Setosa" (99.6%), expected "Setosa"Prediction is "Versicolor" (99.8%), expected "Versicolor"Prediction is "Virginica" (97.9%), expected "Virginica"

    總結

    預制的 Estimator 是一個很有效的快速創建標準模型的方法。

    現在如果你已經開始編寫 TensorFlow 程序了,那么注意關注如下的資料:

    • 檢查點
    • 數據集:快速了解
    • 創建定制化 Estimator

    總結

    以上是生活随笔為你收集整理的tensorflow教程 开始——Premade Estimators(预制评估器)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。