tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

人工智能42

1.什么是tfrecord

TFRecord 是Google官方推荐的一种数据格式,是Google专门为TensorFlow设计的一种数据格式。

TFRecord本质上是二进制文件,目的是更好的利用内存。用户可以将训练集/测试集打包成生成TFRecord文件,后续就可以配合TF中相关的API实现数据的加载,处理,训练等一系列工作,可以方便高效的训练与评估模型。

2.tfrecord原理

TFRecord 并非是TensorFlow唯一支持的数据格式,你也可以使用CSV或文本等格式,但是对于TensorFlow来说,TFRecord 是最友好也是最方便的。
tf.Example是TFRecord的基本结果,其实他就是一个Protobuffer定义的message,表示一组string到bytes value的映射。TFRecord文件里面存储的就是序列化的tf.Example。在github上tensorflow的源码就能看到其定义
message Example

message Example {
  Features features = 1;
};

里面只有一个变量features。如果我们继续查看Features

message Features {
  // Map from feature name to feature.

  map<string, feature> feature = 1;
};
</string,>

features里面就是一组string到Feature的映射。其中这个string表示feature name,后面的Feature又是一个message

继续查看Feature的定义

message Feature {
  // Each feature can be exactly one kind.

  oneof kind {
    BytesList bytes_list = 1;
    FloatList float_list = 2;
    Int64List int64_list = 3;
  }
};

到这里,我们就可以看到tfrecord里存储的真正数据类型有三种
bytes_list: 可以存储string 和byte两种数据类型。
float_list: 可以存储float(float32)与double(float64) 两种数据类型 。
int64_list: 可以存储:bool, enum, int32, uint32, int64, uint64 。

3.实操生成tfrecords文件

下面来手把手教大家如何生成tfrecords文件,并解析tfrecords文件。
我们以titanic数据为例

PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S
2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C
3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S
4,1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S
5,0,3,"Allen, Mr. William Henry",male,35,0,0,373450,8.05,,S
6,0,3,"Moran, Mr. James",male,,0,0,330877,8.4583,,Q
7,0,1,"McCarthy, Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S
8,0,3,"Palsson, Master. Gosta Leonard",male,2,3,1,349909,21.075,,S
9,1,3,"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)",female,27,0,2,347742,11.1333,,S

上面是titanic部分数据,第一行为各列字段名,后面几行为具体数据。如果想看完整的titanic数据,大家可以自行网上搜索并下载。

首先定义几个辅助方法

import tensorflow as tf
import csv

# Generate Integer Features.

def build_int64_feature(data):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[data]))

# Generate Float Features.

def build_float_feature(data):
    return tf.train.Feature(float_list=tf.train.FloatList(value=[data]))

# Generate String Features.

def build_string_feature(data):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(data).encode()]))

然后再定义生成Example的方法

# Generate a TF `Example`, parsing all features of the dataset.

def convert_to_tfexample(survived, pclass, name, sex, age, sibsp, parch, ticket, fare):
    return tf.train.Example(
        features=tf.train.Features(
            feature={
                'survived': build_int64_feature(survived),
                'pclass': build_int64_feature(pclass),
                'name': build_string_feature(name),
                'sex': build_string_feature(sex),
                'age': build_string_feature(age),
                'sibsp': build_int64_feature(sibsp),
                'parch': build_int64_feature(parch),
                'ticket': build_string_feature(ticket),
                'fare': build_float_feature(fare),
            })
    )

再将其写入文件

def write_tf_records():
    writer = tf.io.TFRecordWriter('output.tfrecords')
    with open('titanic.csv') as f:
        reader = csv.reader(f, skipinitialspace=True)
        for i, record in enumerate(reader):
            if i == 0:
                continue
            survived, pclass, name, sex, age, sibsp, parch, ticket, fare = record[1:10]
            print("age, fare is: ", age, fare)
            example = convert_to_tfexample(int(survived), int(pclass), name, sex, age, int(sibsp), int(parch), ticket, float(fare))

            writer.write(example.SerializeToString())

这样,就生成了名为output.tfrecords的文件。

4.解析tfrecords文件

接下来我们解析上面生成的文件

首先定义features字典:

features = {
        'survived': tf.io.FixedLenFeature([], tf.int64),
        'pclass': tf.io.FixedLenFeature([], tf.int64),
        'name': tf.io.FixedLenFeature([], tf.string),
        'sex': tf.io.FixedLenFeature([], tf.string),
        'age': tf.io.FixedLenFeature([], tf.string),
        'sibsp': tf.io.FixedLenFeature([], tf.int64),
        'parch': tf.io.FixedLenFeature([], tf.int64),
        'ticket': tf.io.FixedLenFeature([], tf.string),
        'fare': tf.io.FixedLenFeature([], tf.float32)
}

然后使用parse_single_example方法,解析单条数据

# Parse features, using the above template.

def parse_record(record):
    return tf.io.parse_single_example(record, features=features)

主方法:

def read_tf_records():
    filenames = ["output.tfrecords"]
    data = tf.data.TFRecordDataset(filenames)
    data = data.map(parse_record)
    data = data.repeat()
    # Shuffle data.

    data = data.shuffle(buffer_size=1000)
    # Batch data (aggregate records together).

    data = data.batch(batch_size=4)
    # Prefetch batch (pre-load batch for faster consumption).

    data = data.prefetch(buffer_size=1)

    # Dequeue data and display.

    for record in data.take(1):
        print("record is: ", record)
        print("record[survived is: ", record['survived'])
        print(type(record['survived']))
        print()
        print(record['survived'].numpy())
        print(record['name'].numpy())
        print(record['fare'].numpy())

主方法的输出为:

record is:  {'age': <tf.tensor: shape="(4,)," dtype="string," numpy="array([b''," b'9', b'20', b'32'],>, 'fare': <tf.tensor: shape="(4,)," dtype="float32," numpy="array([16.1" , 27.9 15.7417, 7.925 ],>, 'name': <tf.tensor: shape="(4,)," dtype="string," numpy="array([b'Davison," mrs. thomas henry (mary e finck)', b'skoog, miss. mabel', b'nakid, mr. sahid', b'jussila, eiriik'],>, 'parch': <tf.tensor: shape="(4,)," dtype="int64," numpy="array([0," 2, 1, 0])>, 'pclass': <tf.tensor: shape="(4,)," dtype="int64," numpy="array([3," 3, 3])>, 'sex': <tf.tensor: shape="(4,)," dtype="string," numpy="array([b'female'," b'female', b'male', b'male'],>, 'sibsp': <tf.tensor: shape="(4,)," dtype="int64," numpy="array([1," 3, 1, 0])>, 'survived': <tf.tensor: shape="(4,)," dtype="int64," numpy="array([1," 0, 1, 1])>, 'ticket': <tf.tensor: shape="(4,)," dtype="string," numpy="array([b'386525'," b'347088', b'2653', b'ston o 2. 3101286'],>}
record[survived is:  tf.Tensor([1 0 1 1], shape=(4,), dtype=int64)
<class 'tensorflow.python.framework.ops.eagertensor'>

[1 0 1 1]
[b'Davison, Mrs. Thomas Henry (Mary E Finck)' b'Skoog, Miss. Mabel'
 b'Nakid, Mr. Sahid' b'Jussila, Mr. Eiriik']
[16.1    27.9    15.7417  7.925 ]
</class></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:></tf.tensor:>

使用上面的方式,就解析出来原有的数据!

Original: https://blog.csdn.net/bitcarmanlee/article/details/123569419
Author: bitcarmanlee
Title: tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

Original: https://blog.csdn.net/bitcarmanlee/article/details/123569419
Author: bitcarmanlee
Title: tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件



相关阅读

Title: Tensorflow 2.9.1安装笔记

CPU:i7-4790k

显卡:GTX2060

Cuda 版本:11.3

Cunn版本: 11.6

Python版本:3.7.7

不想用anacoda,直接装 tensorflow

1.准备工作

  • 安装python3.7.7(之前安装好的)

可以根据需要安装相应的版本,不建议安装最新版,python版本之间的代码兼容度不好。3.6~3.8可能比较合适。

我安装的是11.3版本。

deviceQuery.exe 和 bandwithTest.exe测试通过。

  • 下载Tensorflow

我下载的是 tensorflow-2.9.1-cp37-cp37m-win_amd64.whl

  • 安装组件

安装Tensorflow之前,安装好以下支持模块

A.Numpy: pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

B.mkl: pip install mkl -i https://pypi.tuna.tsinghua.edu.cn/simple

C.protobuf pip install protobuf -i https://pypi.tuna.tsinghua.edu.cn/simple

2.安装Tensorflow

把 tensorflow-2.9.1-cp37-cp37m-win_amd64.whl 放到d盘根目录,打开命令行并转到D:\

pip install tensorflow-2.9.1-cp37-cp37m-win_amd64.whl -i https://pypi.tuna.tsinghua.edu.cn/simple

这样在安装过程中加载其他模块的时候,速度会非常快。

3.测试

import tensorflow as tf
print("Tensorflow version:")
print(tf.__version__)

print("CPU/GPU devices for Tensorflow:")
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus)
print(cpus)

运行结果:

Tensorflow version:
2.9.1
CPU/GPU devices for Tensorflow:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

至此安装完毕。

IDE可以使用Visual Studio Code(小规模测试)

或者Pycharm(程序较大很方便)

Original: https://blog.csdn.net/st01lsp/article/details/125294794
Author: st01lsp
Title: Tensorflow 2.9.1安装笔记



相关阅读

Title: pycharm安装torch和cuda(在anaconda创建的新环境下)

1.问题所在

pycharm中torch和tensorflow好像是有些冲突的,所以我创建了两个conda环境(一个名字叫pytorch,一个名字叫tensorflow),其中pytorch环境中没有tensorflow库,tensorflow环境同理。

现在问题在于每次在Terminal中用pip install torch 后总是cpu版本的

pip install torch
import torch
print(torch.__version__)
print(torch.cuda.is_available())

这段代码是看torch到底有没有用到cuda(或者我理解为是否用的是gpu版本),输出为False为cpu版本。

2.安装cuda

这个我觉得可能很多人电脑上已经安装了cuda

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

可以自己在电脑中看一下到底有没有,有了更好,没了接下来讲怎么下载NVIDIA cuda

(1)查看自己应该下载NVIDIA版本

右键"此电脑"——管理——设备管理器——显示适配器
这样就能查到自己的显卡型号了

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

NVIDIA显卡驱动的下载地址:官方高级驱动搜索 | NVIDIA
选择自己合适的型号,开始下载

(2)下载对应的cuda版本

CUDA的下载地址:https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64&target_version=10&target_type=exelocal
选择合适的型号,点击download即可
tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

检验安装是否安装正确:win+R→cmd→nvcc -V
如图即为安装正确

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

至此,cuda已经安装在你的电脑里了(如果在安装图中遇到其他问题,可以继续搜搜问题所在,但是这个安装流程一定是没问题的) 。接下来就是安装gpu版本的torch

3.安装torch(在pycharm中的Terminal中,因为我喜欢用这个方式,不喜欢用cmd或者anaconda)

直接打开这个网址https://pytorch.org/get-started/locally/

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

如何选择我想大家都应该能看懂,其中我用的Terminal所以Package中选的pip,第一个我看了其他博主都选的Stable,至于最后那个Compute Platform选项因为我的cuda版本就是11.7,所以选了这个(听说版本差不多接近就行 不至于那么严格)。

教大家如何选择最后的Compute Platform(即如何查看自己cuda版本)

桌面右键打开NAIDIA控制面板后,在帮助中找到系统信息,点击组件,蓝色这一条就可以看到CUDA 11.7.57(意思就是11.7版本的)

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

至此学会了查看cuda版本以及下载了对应于cuda的pytorch

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

这时候基本成了,吧最后一栏中Run this Command一栏内容直接复制到Terminal中就行。

4.发现用上述方法安装torch很慢很慢

很好解决,打开网址https://download.pytorch.org/whl/torch_stable.html

进去后找到自己需要的版本,比如我是cuda11.7+python3.7+windows,就选择了下面这个

tfrecord原理详解 手把手教生成tfrecord文件与解析tfrecord文件

cu代表cuda(即选用gpu版本而不是cpu版本,这里一定要看仔细),torch1.11.0版本,这个我觉得没有什么特别的要求,但我喜欢新版本,cp37代表python3.7,win代表windows系统,64代表64位。

下载后我是放在我自己创建的pytorch环境中LIB中site-package中,然后在Terminal中写入下面的代码

pip install D:\anaconda\Anaconda\envs\pytorch\Lib\site-packages\torch-1.11.0+cu113-cp37-cp37m-win_amd64.whl

代码说明:文件放在D:\anaconda\Anaconda\envs\pytorch\Lib\site-packages中,文件名字叫torch-1.11.0+cu113-cp37-cp37m-win_amd64.whl,直接回车就行。

至此问题全部解决,如何判定解决?

import torch
print(torch.__version__)
print(torch.cuda.is_available())

输出为

1.11.0+cu113
True

希望大家能够顺利解决此类问题

Original: https://blog.csdn.net/m0_51623233/article/details/125150882
Author: 无处不乐zhc
Title: pycharm安装torch和cuda(在anaconda创建的新环境下)

相关文章
聚类算法介绍(欧氏距离和余弦距离) 人工智能

聚类算法介绍(欧氏距离和余弦距离)

1.聚类就是将数据集划分为若干相似对象组成的多个组或簇的过程,使得同一个组或簇相似度最大化,不同簇间相似度最小化。(有时候聚类可以评价相似性) 2.聚类的本质是分组,属于无监督机器学习(只需要特征X,...
2022年,鉴历史,谋发展 人工智能

2022年,鉴历史,谋发展

我也不知道从什么时候开始比较关注历史,学习的过程中确实带给了我很多思考,这种思考没有对与错,而是多角度对事物发展的分析与认知。 最近,偶然机会对宋代历史又学习了一遍,主要讲的是王安石变法,历史上的变法...
神经网络那些事儿(一) 人工智能

神经网络那些事儿(一)

这次主要说说神经网络的一些主要思想,包括介绍两种人工神经元(perceptron neuron和sigmoid neuron)以及神经网络的标准学习算法,随机梯度下降法。神经网络可以认为是一种不同于使...