最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python神經(jīng)網(wǎng)絡(luò)tfrecords文件的寫入讀取及內(nèi)容解析

 更新時間:2022年05月04日 10:17:25   作者:Bubbliiiing  
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)tfrecords文件的寫入讀取及內(nèi)容解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

學(xué)習(xí)前言

前一段時間對SSD預(yù)測與訓(xùn)練的整體框架有了一定的了解,但是對其中很多細(xì)節(jié)還是把握的不清楚。今天我決定好好了解以下tfrecords文件的構(gòu)造。

tfrecords格式是什么

tfrecords是一種二進制編碼的文件格式,tensorflow專用。能將任意數(shù)據(jù)轉(zhuǎn)換為tfrecords。更好的利用內(nèi)存,更方便復(fù)制和移動,并且不需要單獨的標(biāo)簽文件。

之所以使用到tfrecords格式是因為當(dāng)今數(shù)據(jù)爆炸的情況下,使用普通的數(shù)據(jù)格式不僅麻煩,而且速度慢,這種專門為tensorflow定制的數(shù)據(jù)格式可以大大增快數(shù)據(jù)的讀取,而且將所有內(nèi)容規(guī)整,在保證速度的情況下,使得數(shù)據(jù)更加簡單明晰。

tfrecords的寫入

這個例子將會講述如何將MNIST數(shù)據(jù)集寫入到tfrecords,本次用到的MNIST數(shù)據(jù)集會利用tensorflow原有的庫進行導(dǎo)入。

from tensorflow.examples.tutorials.mnist import input_data
# 讀取MNIST數(shù)據(jù)集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)

對于MNIST數(shù)據(jù)集而言,其中的訓(xùn)練集是mnist.train,而它的數(shù)據(jù)可以分為images和labels,可通過如下方式獲得。

# 獲得image,shape為(55000,784)
images = mnist.train.images
# 獲得label,shape為(55000,10)
labels = mnist.train.labels
# 獲得一共具有多少張圖片
num_examples = mnist.train.num_examples

接下來定義存儲TFRecord文件的地址,同時創(chuàng)建一個writer來寫TFRecord文件。

# 存儲TFRecord文件的地址
filename = 'record/output.tfrecords'
# 創(chuàng)建一個writer來寫TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)

此時便可以按照一定的格式寫入了,此時需要對每一張圖片進行循環(huán)并寫入,在tf.train.Features中利用features字典定義了數(shù)據(jù)保存的方式。以image_raw為例,其經(jīng)過函數(shù)_float_feature處理后,存儲到tfrecords文件的’image/encoded’位置上。

# 將每張圖片都轉(zhuǎn)為一個Example,并寫入
for i in range(num_examples):
    image_raw = images[i]  # 讀取每一幅圖像
    image_string = images[i].tostring()
    example = tf.train.Example(
        features=tf.train.Features(
            feature={
                'image/class/label': _int64_feature(np.argmax(labels[i])),
                'image/encoded': _float_feature(image_raw),
                'image/encoded_tostring': _bytes_feature(image_string)
            }
        )
    )
    print(i,"/",num_examples)
    writer.write(example.SerializeToString())  # 將Example寫入TFRecord文件

在最終存入前,數(shù)據(jù)還需要經(jīng)過處理,處理方式如下:

# 生成整數(shù)的屬性
def _int64_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮點數(shù)的屬性
def _float_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的屬性
def _bytes_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

tfrecords的讀取

tfrecords的讀取首先要創(chuàng)建一個reader來讀取TFRecord文件中的Example。

# 創(chuàng)建一個reader來讀取TFRecord文件中的Example
reader = tf.TFRecordReader()

再創(chuàng)建一個隊列來維護輸入文件列表。

# 創(chuàng)建一個隊列來維護輸入文件列表
filename_queue = tf.train.string_input_producer(['record/output.tfrecords'])

利用reader讀取輸入文件列表隊列,并用parse_single_example將讀入的Example解析成tensor

# 從文件中讀出一個Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example將讀入的Example解析成tensor
features = tf.parse_single_example(
    serialized_example,
    features={
        'image/class/label': tf.FixedLenFeature([], tf.int64),
        'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
        'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
    }
)

此時我們得到了一個features,實際上它是一個類似于字典的東西,我們額可以通過字典的方式讀取它內(nèi)部的內(nèi)容,而字典的索引就是我們再寫入tfrecord文件時所用的feature。

# 將字符串解析成圖像對應(yīng)的像素數(shù)組
labels = tf.cast(features['image/class/label'], tf.int32)
images = tf.cast(features['image/encoded'], tf.float32)
images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)

最后利用一個循環(huán)輸出:

# 每次運行讀取一個Example。當(dāng)所有樣例讀取完之后,在此樣例中程序會重頭讀取
for i in range(5):
    label, image = sess.run([labels, images])
    images_tostring = sess.run(images_tostrings)
    print(np.shape(image))
    print(np.shape(images_tostring))
    print(label)
    print("#########################")

測試代碼

1、tfrecords文件的寫入

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 生成整數(shù)的屬性
def _int64_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮點數(shù)的屬性
def _float_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的屬性
def _bytes_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
# 讀取MNIST數(shù)據(jù)集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)
# 獲得image,shape為(55000,784)
images = mnist.train.images
# 獲得label,shape為(55000,10)
labels = mnist.train.labels
# 獲得一共具有多少張圖片
num_examples = mnist.train.num_examples
# 存儲TFRecord文件的地址
filename = 'record/Mnist_Out.tfrecords'
# 創(chuàng)建一個writer來寫TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
# 將每張圖片都轉(zhuǎn)為一個Example,并寫入
for i in range(num_examples):
    image_raw = images[i]  # 讀取每一幅圖像
    image_string = images[i].tostring()
    example = tf.train.Example(
        features=tf.train.Features(
            feature={
                'image/class/label': _int64_feature(np.argmax(labels[i])),
                'image/encoded': _float_feature(image_raw),
                'image/encoded_tostring': _bytes_feature(image_string)
            }
        )
    )
    print(i,"/",num_examples)
    writer.write(example.SerializeToString())  # 將Example寫入TFRecord文件
print('data processing success')
writer.close()

運行結(jié)果為:

……
54993 / 55000
54994 / 55000
54995 / 55000
54996 / 55000
54997 / 55000
54998 / 55000
54999 / 55000
data processing success

2、tfrecords文件的讀取

import tensorflow as tf
import numpy as np
# 創(chuàng)建一個reader來讀取TFRecord文件中的Example
reader = tf.TFRecordReader()
# 創(chuàng)建一個隊列來維護輸入文件列表
filename_queue = tf.train.string_input_producer(['record/Mnist_Out.tfrecords'])
# 從文件中讀出一個Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example將讀入的Example解析成tensor
features = tf.parse_single_example(
    serialized_example,
    features={
        'image/class/label': tf.FixedLenFeature([], tf.int64),
        'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
        'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
    }
)
# 將字符串解析成圖像對應(yīng)的像素數(shù)組
labels = tf.cast(features['image/class/label'], tf.int32)
images = tf.cast(features['image/encoded'], tf.float32)
images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)
sess = tf.Session()
# 啟動多線程處理輸入數(shù)據(jù)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# 每次運行讀取一個Example。當(dāng)所有樣例讀取完之后,在此樣例中程序會重頭讀取
for i in range(5):
    label, image = sess.run([labels, images])
    images_tostring = sess.run(images_tostrings)
    print(np.shape(image))
    print(np.shape(images_tostring))
    print(label)
    print("#########################")

運行結(jié)果為:

#########################
(784,)
(784,)
7
#########################
#########################
(784,)
(784,)
4
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
9
#########################

以上就是python神經(jīng)網(wǎng)絡(luò)tfrecords文件的寫入讀取及內(nèi)容解析的詳細(xì)內(nèi)容,更多關(guān)于python神經(jīng)網(wǎng)絡(luò)tfrecords寫入讀取的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python利用dir函數(shù)查看類中所有成員函數(shù)示例代碼

    python利用dir函數(shù)查看類中所有成員函數(shù)示例代碼

    這篇文章主要給大家介紹了關(guān)于python如何利用dir函數(shù)查看類中所有成員函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)下吧。
    2017-09-09
  • Python使用OpenPyXL處理Excel表格

    Python使用OpenPyXL處理Excel表格

    這篇文章主要介紹了Python使用OpenPyXL處理Excel表格,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • django傳值給模板, 再用JS接收并進行操作的實例

    django傳值給模板, 再用JS接收并進行操作的實例

    今天小編就為大家分享一篇django傳值給模板, 再用JS接收并進行操作的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • Python 3中的yield from語法詳解

    Python 3中的yield from語法詳解

    在python 3.3里,generator新增了一個語法 yield from,這個yield from的作用是什么?語法是什么呢?下面通過這篇文章主要給大家詳細(xì)介紹了Python 3中yield from語法的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-01-01
  • 使用Python在Windows下獲取USB PID&VID的方法

    使用Python在Windows下獲取USB PID&VID的方法

    今天小編就為大家分享一篇使用Python在Windows下獲取USB PID&VID的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 基于numpy實現(xiàn)邏輯回歸

    基于numpy實現(xiàn)邏輯回歸

    這篇文章主要為大家詳細(xì)介紹了基于numpy實現(xiàn)邏輯回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • Python urllib3軟件包的使用說明

    Python urllib3軟件包的使用說明

    這篇文章主要介紹了Python urllib3軟件包的使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • python實現(xiàn)掃描局域網(wǎng)指定網(wǎng)段ip的方法

    python實現(xiàn)掃描局域網(wǎng)指定網(wǎng)段ip的方法

    這篇文章主要介紹了python實現(xiàn)掃描局域網(wǎng)指定網(wǎng)段ip的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-04-04
  • Numpy中arange()的用法及說明

    Numpy中arange()的用法及說明

    Numpy的arange()函數(shù)用于在指定間隔內(nèi)生成均勻間隔的數(shù)組,它接受開始值、停止值和步長來創(chuàng)建數(shù)組,返回的是ndarray類型,如果沒有提供dtype,則會根據(jù)其他參數(shù)推斷數(shù)據(jù)類型,對于浮點類型參數(shù),結(jié)果數(shù)組的長度計算方式為ceil((stop-start)/step)
    2024-10-10
  • python如何編寫類似nmap的掃描工具

    python如何編寫類似nmap的掃描工具

    這篇文章主要介紹了python如何編寫類似nmap的掃描工具,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11

最新評論

临汾市| 崇明县| 集贤县| 郓城县| 花莲市| 望奎县| 内江市| 京山县| 微山县| 宁晋县| 蒲江县| 工布江达县| 鄂托克前旗| 金川县| 华容县| 蒲江县| 彭山县| 潮安县| 慈溪市| 滦南县| 潍坊市| 宁陵县| 延长县| 平昌县| 宝丰县| 盐亭县| 兰溪市| 涟水县| 临颍县| 惠安县| 昌吉市| 皋兰县| 辰溪县| 崇州市| 阿坝| 凤翔县| 微山县| 永平县| 布拖县| 河北省| 丽江市|