标签: tfrecord

TensorFlow - 立即从TFRecords中读取所有示例?

您如何一次性阅读TFRecords中的所有示例?

我一直在使用tf.parse_single_example类似于fully_connected_reader示例中的方法read_and_decode中给出的代码来读出单个示例.但是,我想立即针对我的整个验证数据集运行网络,因此希望完全加载它们.

我不完全确定,但文档似乎建议我可以使用tf.parse_example而不是tf.parse_single_example一次加载整个TFRecords文件.我似乎无法让这个工作.我猜它与我如何指定功能有关,但我不确定在功能规范中如何说明有多个例子.

换句话说,我尝试使用类似的东西:

reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_example(serialized_example, features={
    'image_raw': tf.FixedLenFeature([], tf.string),
    'label': tf.FixedLenFeature([], tf.int64),
})
Run Code Online (Sandbox Code Playgroud)

不起作用,我认为这是因为这些功能不会同时出现多个例子(但同样,我不确定).[导致错误ValueError: Shape () must have rank 1]

这是一次读取所有记录的正确方法吗?如果是这样,我需要更改什么来实际读取记录?非常感谢!

python tensorflow tfrecord

31
推荐指数
4
解决办法
3万
查看次数

如何检查Tensorflow .tfrecord文件?

我有一个,.tfrecord但我不知道它的结构.如何检查模式以了解.tfrecord文件包含的内容?

所有Stackoverflow答案或文档似乎都假设我知道文件的结构.

reader = tf.TFRecordReader()
file = tf.train.string_input_producer("record.tfrecord")
_, serialized_record = reader.read(file)

...HOW TO INSPECT serialized_record...
Run Code Online (Sandbox Code Playgroud)

tensorflow tfrecord

31
推荐指数
5
解决办法
2万
查看次数

从Tensorflow中的.tfrecords文件中获取记录总数

是否有可能从.tfrecords文件中获取记录总数?与此相关,人们如何通常跟踪训练模型时已经过的时期数?虽然我们可以指定batch_sizenum_of_epochs,但我不确定是否可以直接获得诸如current epoch每个时期的批次数等值- 这样我就可以更好地控制培训的进展情况.目前,我只是使用一个肮脏的黑客来计算这个,因为我事先知道我的.tfrecords文件中有多少记录和我的miniatches的大小.感谢任何帮助..

tensorflow tfrecord

24
推荐指数
4
解决办法
1万
查看次数

TensorFlow字符串:它们是什么以及如何使用它们

当我读取文件时,tf.read_file我得到了类型的东西tf.string.文档只说它是"可变长度字节数组.Tensor的每个元素都是一个字节数组." (https://www.tensorflow.org/versions/r0.10/resources/dims_types.html).我不知道如何解释这个.

我对这种类型无能为力.在通常的python中你可以通过索引获取元素my_string[:4],但是当我运行以下代码时,我得到一个错误.

import tensorflow as tf
import numpy as np

x = tf.constant("This is string")
y = x[:4]


init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
result = sess.run(y)
print result
Run Code Online (Sandbox Code Playgroud)

它说

  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 621, in assert_has_rank
    raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape () must have rank 1

我也无法将我的字符串转换为tf.float32张量.它是.flo文件,它有魔术标题"PIEH".这个numpy代码成功地将这样的头转换为数字(参见这里的例子/sf/answers/1961152861/)但我不能用tensorflow做到这一点.我试过tf.string_to_number(string, out_type=tf.float32)但它说

tensorflow.python.framework.errors.InvalidArgumentError: StringToNumberOp could not correctly convert string: …

python string numpy tensorflow tfrecord

15
推荐指数
1
解决办法
2万
查看次数

如何将numpy数组存储为tfrecord?

我正在尝试从numpy数组创建tfrecord格式的数据集.我想存储2d和3d坐标.

2d坐标是float64类型的numpy数组(2,10)3d坐标是float64类型的numpy数组(3,10)

这是我的代码:

def _floats_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))


train_filename = 'train.tfrecords'  # address to save the TFRecords file
writer = tf.python_io.TFRecordWriter(train_filename)


for c in range(0,1000):

    #get 2d and 3d coordinates and save in c2d and c3d

    feature = {'train/coord2d': _floats_feature(c2d),
                   'train/coord3d': _floats_feature(c3d)}
    sample = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(sample.SerializeToString())

writer.close()
Run Code Online (Sandbox Code Playgroud)

当我运行这个我得到错误:

  feature = {'train/coord2d': _floats_feature(c2d),
  File "genData.py", line 19, in _floats_feature
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\python_message.py", line 510, in init
copy.extend(field_value)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in extend
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  File …
Run Code Online (Sandbox Code Playgroud)

python numpy tensorflow tfrecord

12
推荐指数
3
解决办法
5615
查看次数

如何可视化TFRecord?

有人在另一个论坛上问我这个问题,但我想将它发布给任何在TFRecords上遇到麻烦的人。

如果TFRecord文件中的标签与labels.pbtxt文件中的标签不对齐,TensorFlow的对象检测API可能会产生奇怪的行为。它会运行,损失可能会减少,但网络将无法产生良好的检测结果。

另外,我总是会在XY,行列空间之间感到困惑,因此我总是想仔细检查以确保我的注释实际上在注释图像的正确部分。

我发现最好的方法是解码TFRecord并用TF工具绘制它。下面是一些代码:

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from object_detection.utils import visualization_utils as vu
from object_detection.protos import string_int_label_map_pb2 as pb
from object_detection.data_decoders.tf_example_decoder import TfExampleDecoder as TfDecoder
from google.protobuf import text_format
def main(tfrecords_filename, label_map=None):
    if label_map is not None:
        label_map_proto = pb.StringIntLabelMap()
        with tf.gfile.GFile(label_map,'r') as f:
            text_format.Merge(f.read(), label_map_proto)
            class_dict = {}
            for entry in label_map_proto.item:
                class_dict[entry.id] = {'name':entry.display_name}
    sess = tf.Session()
    decoder = TfDecoder(label_map_proto_file=label_map, use_display_name=False)
    sess.run(tf.tables_initializer())
    for record in tf.python_io.tf_record_iterator(tfrecords_filename):
        example = decoder.decode(record) …
Run Code Online (Sandbox Code Playgroud)

python object-detection tensorflow tfrecord

12
推荐指数
2
解决办法
980
查看次数

如何在tfrecord中使用python API从Google Earth引擎下载哨兵图像

尝试下载特定位置的哨兵图像时,默认情况下会在驱动器中生成tif文件,但openCV或PIL.Image()无法读取该tif文件。以下是该代码。如果我使用文件格式作为tfrecord。驱动器中没有下载图像。

starting_time = '2018-12-15' 
delta = 15  
L = -96.98  
B = 28.78  
R = -97.02  
T = 28.74

cordinates = [L,B,R,T] 
my_scale = 30 
fname = 'sinton_texas_30'


llx = cordinates[0] 
lly = cordinates[1] 
urx = cordinates[2] 
ury = cordinates[3]

geometry = [[llx,lly], [llx,ury], [urx,ury], [urx,lly]]

tstart = datetime.datetime.strptime(starting_time, '%Y-%m-%d') tend =
tstart+datetime.timedelta(days=delta)
collSent = ee.ImageCollection('COPERNICUS/S2').filterDate(str(tstart).split('')[0], str(tend).split(' ')[0]).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)).map(mask2clouds)


medianSent = ee.Image(collSent.reduce(ee.Reducer.median())) cropLand = ee.ImageCollection('USDA/NASS/CDL').filterDate('2017-01-01','2017-12-31').first() 
task_config = {
 'scale': my_scale,
 'region': geometry,
 'fileFormat':'TFRecord'
   }

f1 = medianSent.select(['B1_median','B2_median','B3_median'])


taskSent = ee.batch.Export.image(f1,fname+"_Sent",task_config) …
Run Code Online (Sandbox Code Playgroud)

tiff python-3.x google-earth-engine tfrecord sentinel2

10
推荐指数
1
解决办法
721
查看次数

Numpy to TFrecords:有没有更简单的方法来处理来自tfrecords的批量输入?

我的问题是如何从多个(或分片)tfrecords获得批量输入.我已经阅读了示例https://github.com/tensorflow/models/blob/master/inception/inception/image_processing.py#L410.基本的管道,把培训作为集为例,(1)首先产生一系列tfrecords(例如,train-000-of-005,train-001-of-005,...),(2)从这些文件名,生成一个列表并将其塞进了tf.train.string_input_producer获得队列,(3)同时生成一个tf.RandomShuffleQueue做其他的东西,(4)tf.train.batch_join用来生成批量输入.

我认为这很复杂,我不确定这个程序的逻辑.在我的情况下,我有一个.npy文件列表,我想生成分片的tfrecords(多个分离的tfrecords,而不只是一个单个大文件).这些.npy文件中的每一个都包含不同数量的正样本和负样本(2个类).一种基本方法是生成一个单个大型tfrecord文件.但文件太大(~20Gb).所以我采用分片的tfrecords.有没有更简单的方法来做到这一点?谢谢.

python tensorflow tfrecord tensorflow-datasets

9
推荐指数
1
解决办法
6411
查看次数

Tensorflow get_single_element 不适用于 tf.data.TFRecordDataset.batch()

我正在尝试对 Tensorflow 数据集执行 ZCA 白化。为了做到这一点,我尝试从数据集中提取数据作为张量,执行白化,然后创建另一个数据集。

我按照此处的示例从 TFRecordDataset 获取数据集作为 numpy 数组,不包括评估张量的点。

get_single_element 抛出此错误:

Traceback (most recent call last):
  File "/Users/takeoffs/Code/takeoffs_ai/test_pipeline_local.py", line 239, in <module>
    validation_steps=val_steps, callbacks=callbacks)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 780, in fit
    steps_name='steps_per_epoch')
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 198, in model_iteration
    val_iterator = _get_iterator(val_inputs, model._distribution_strategy)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 517, in _get_iterator
    return training_utils.get_iterator(inputs)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 1315, in get_iterator
    initialize_iterator(iterator)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 1322, in initialize_iterator
    K.get_session((init_op,)).run(init_op)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 950, in run
    run_metadata_ptr)
  File "/Users/takeoffs/Code/takeoffs_ai/venv/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 1173, in _run
    feed_dict_tensor, …
Run Code Online (Sandbox Code Playgroud)

python-3.x tensorflow tfrecord tensorflow-datasets

9
推荐指数
0
解决办法
1090
查看次数

Tensorflow:加载大数据的现代方法

我想使用 numpy 数组作为输入数据训练卷积神经网络(使用 Tensorflow 1.13 版中的 tf.keras)。训练数据(我目前存储在一个 > 30GB 的“.npz”文件中)不能一次全部放入 RAM。将大型数据集保存和加载到神经网络中进行训练的最佳方法是什么?由于我没有设法找到这个(肯定无处不在?)问题的好答案,我希望在这里听到一个。非常感谢您提供任何帮助!

来源

类似的问题似乎已经被问过很多次了(例如training-classifier-from-tfrecords-in-tensorflowtensorflow-synchronize-readings-from-tfrecordhow-to-load-data-parallelly-in-tensorflow)但有几个岁,通常不包含决定性的答案。

我目前的理解是使用 TFRecord 文件是解决这个问题的好方法。到目前为止,我发现的最有前途的教程解释了如何在 keras 中使用 TFRecord 文件是medium.com。其他有用的来源是machinelearninguru.commedium.com_source2和来源therin。

官方 tensorflow 文档和教程(关于tf.data.Dataset导入数据tf_records等)对我没有帮助。特别是,即使没有修改,那里给出的几个例子对我也不起作用。

我尝试使用 TFRecord 文件

我假设 TFRecords 是解决我的问题的好方法,但我很难使用它们。这是我根据教程medium.com制作的示例。我尽可能地精简了代码。

# python 3.6, tensorflow 1.13.
# Adapted from https://medium.com/@moritzkrger/speeding-up-keras-with-tfrecord-datasets-5464f9836c36
import tensorflow as tf
import numpy as np
from tensorflow.python import keras as keras


# Helper functions (see also https://www.tensorflow.org/tutorials/load_data/tf_records) …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tfrecord tf.keras

8
推荐指数
1
解决办法
4810
查看次数