标签: tensorflow-datasets

有没有办法在 Tensorflow 中的另一个数据集中使用 tf.data.Dataset ?

我正在做分段。每个训练样本都有多个带有分割掩模的图像。我正在尝试编写input_fn将每个训练样本的所有掩模图像合并为一个的图像。我计划使用两个Datasets,一个迭代样本文件夹,另一个将所有掩模作为一个大批次读取,然后将它们合并为一个张量。

调用嵌套时出现错误make_one_shot_iterator。我知道这种方法有点牵强,而且很可能数据集不是为这种用途而设计的。但是我应该如何解决这个问题以避免使用 tf.py_func?

这是数据集的简化版本:

def read_sample(sample_path):
    masks_ds = (tf.data.Dataset.
        list_files(sample_path+"/masks/*.png")
        .map(tf.read_file)
        .map(lambda x: tf.image.decode_image(x, channels=1))
        .batch(1024)) # maximum number of objects
    masks = masks_ds.make_one_shot_iterator().get_next()

    return tf.reduce_max(masks, axis=0)

ds = tf.data.Dataset.from_tensor_slices(tf.glob("../input/stage1_train/*"))
ds.map(read_sample)
# ...
sample = ds.make_one_shot_iterator().get_next()
# ...
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-datasets

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

从张量流数据集迭代器获取输入(文件名)

我正在使用张量流数据集来训练模型。数据集获取文件名列表以在会话期间读取它们,我想将文件名与图像一起获取。更详细地说,我有这样的事情:

filenames = tf.constant(["/var/data/image1.jpg", "/var/data/image2.jpg", ...])
labels = tf.constant([0, 37, ...])
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset.shuffle()

def _parse_function(filename, label):
  image_string = tf.read_file(filename)
  image_decoded = tf.image.decode_jpeg(image_string)
  image_resized = tf.image.resize_images(image_decoded, [28, 28])
  return image_resized, label

dataset = dataset.map(_parse_function)
iterator = dataset.make_one_shot_iterator()
X, Y = iterator.get_next()

sess = tf.Session()
sess.run(iterator.initializer)
while True:
  sess.run(X) #Here I want the element from filenames being used for X
Run Code Online (Sandbox Code Playgroud)

我以为这个信息可以包含在 中iterator,但我找不到它。

python iterator tensorflow tensorflow-datasets

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

在 tensorflow 2.0 beta 中从 tf.data.Dataset 中检索下一个元素

在 tensorflow 2.0-beta 之前,为了从 tf.data.Dataset 中检索第一个元素,我们可以使用如下所示的迭代器:

#!/usr/bin/python

import tensorflow as tf

train_dataset = tf.data.Dataset.from_tensor_slices([1.0, 2.0, 3.0, 4.0])
iterator = train_dataset.make_one_shot_iterator()
with tf.Session() as sess:
    # 1.0 will be printed.
    print (sess.run(iterator.get_next()))
Run Code Online (Sandbox Code Playgroud)

在 tensorflow 2.0-beta 中,上面的一次性迭代器似乎已被弃用。要打印出整个元素,我们可以使用下面方法。

#!/usr/bin/python

import tensorflow as tf

train_dataset = tf.data.Dataset.from_tensor_slices([1.0, 2.0, 3.0, 4.0])

for data in train_dataset:
    # 1.0, 2.0, 3.0, and 4.0 will be printed.
    print (data.numpy())
Run Code Online (Sandbox Code Playgroud)

但是,如果我们只想从 tf.data.Dataset 中准确检索一个元素,那么我们如何使用 tensorflow 2.0 beta 呢?好像next(train_dataset)不支持。如上所示,使用旧的一次性迭代器可以轻松完成,但使用基于for的新方法不是很明显。

欢迎任何建议。

python iterator tensorflow tensorflow-datasets tensorflow2.0

4
推荐指数
2
解决办法
4129
查看次数

TensorFlow 中的实验是什么意思?

TensorFlow 2.0 API中,有一个模块tf.experimental。这样的名字也出现在其他地方,比如tf.data.experimental。我只是想知道设计这些模块的动机是什么。

tensorflow tensorflow-datasets tensorflow2.0

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

数据增强映射函数中的 Tensorflow 随机数

我想使用crop_central具有 0.50-1.00 之间的随机浮点数的函数来进行数据增强。然而,在使用numpy.random.uniform(0.50, 1.00)和绘制图像时,裁剪是恒定的。我通过使用 4 个图像并绘制 8 行进行了调试,图像是相同的。

一般来说,问题可以表述如下:如何在数据集映射函数中使用随机数?

def data_augment(image, label=None, seed=2020):
    # I want a random number here for every individual image
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00)) # random crop central
    image = tf.image.resize(image, INPUT_SHAPE) # the original image size

    return image

train_dataset = (
    tf.data.Dataset
        .from_tensor_slices((train_paths, train_labels))
        .map(decode_image, num_parallel_calls=AUTO)
        .map(data_augment, num_parallel_calls=AUTO)
        .repeat()
        .batch(4)
        .prefetch(AUTO)
    )

# Code to view the images
for idx, (imgs, _) in enumerate(train_dataset):
    show_imgs(imgs, 'image', imgs_per_row=4)
    if idx is …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-datasets data-augmentation

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

带有字符串输入的 Tensorflow 数据集不保留数据类型

下面所有可重现的代码都在 Google Colab 上使用 TF 2.2.0-rc2 运行。

改编文档中的简单示例以从简单的 Python 列表创建数据集:

import numpy as np
import tensorflow as tf
tf.__version__
# '2.2.0-rc2'
np.version.version
# '1.18.2'

dataset1 = tf.data.Dataset.from_tensor_slices([1, 2, 3]) 
for element in dataset1: 
  print(element) 
  print(type(element.numpy()))
Run Code Online (Sandbox Code Playgroud)

我们得到结果

tf.Tensor(1, shape=(), dtype=int32)
<class 'numpy.int32'>
tf.Tensor(2, shape=(), dtype=int32)
<class 'numpy.int32'>
tf.Tensor(3, shape=(), dtype=int32)
<class 'numpy.int32'>
Run Code Online (Sandbox Code Playgroud)

int32正如预期的那样,所有数据类型都是。

但是改变这个简单的例子来提供一个字符串列表而不是整数:

dataset2 = tf.data.Dataset.from_tensor_slices(['1', '2', '3']) 
for element in dataset2: 
  print(element) 
  print(type(element.numpy()))
Run Code Online (Sandbox Code Playgroud)

给出结果

tf.Tensor(b'1', shape=(), dtype=string)
<class 'bytes'>
tf.Tensor(b'2', shape=(), dtype=string)
<class 'bytes'> …
Run Code Online (Sandbox Code Playgroud)

numpy tensorflow tensorflow-datasets tensorflow2.0

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

将形状不等的数组列表转换为 Tensorflow 2 数据集:ValueError:无法将非矩形 Python 序列转换为 Tensor

我以不等形状数组列表的形式标记数据:

array([array([1179,    6,  208,    2, 1625,   92,    9, 3870,    3, 2136,  435,
          5, 2453, 2180,   44,    1,  226,  166,    3, 4409,   49, 6728,
         ...
         10,   17, 1396,  106, 8002, 7968,  111,   33, 1130,   60,  181,
       7988, 7974, 7970])], dtype=object)
Run Code Online (Sandbox Code Playgroud)

以及各自的目标:

Out[74]: array([0, 0, 0, ..., 0, 0, 1], dtype=object)
Run Code Online (Sandbox Code Playgroud)

我正在尝试将它们转换为 padded tf.data.Dataset(),但它不允许我将不相等的形状转换为张量。我会得到这个错误:

ValueError: Can't convert non-rectangular Python sequence to Tensor.
Run Code Online (Sandbox Code Playgroud)

完整的代码在这里。假设我的起点是在之后y = ...

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow_datasets as tfds …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tensorflow-datasets tensorflow2.0

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

如何创建 Cifar-10 子集?

我想使用更少的训练数据样本来训练深度神经网络,以减少测试代码的时间。我想知道如何使用 Keras TensorFlow 对 Cifar-10 数据集进行子集化。我有以下代码,用于训练 Cifar-10 完整数据集。

#load and prepare data
if WhichDataSet == 'CIFAR10':
    (x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.cifar10.load_data()
else:
    (x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.cifar100.load_data()
num_classes = np.unique(y_train).shape[0]
K_train = x_train.shape[0]
input_shape = x_train.shape[1:]
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)
Run Code Online (Sandbox Code Playgroud)

python deep-learning keras tensorflow tensorflow-datasets

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

将 PNG 文件加载到 TensorFlow 中

我正在尝试加载我生成的定制 png 文件来训练我的模型。按照此处TensorFlow 指南的说明,我使用了以下代码:

import tensorflow as tf
import numpy as np
from pathlib import Path, WindowPath

train_df = pd.DataFrame(
    {'file_name': {0: WindowsPath('hypothesis/temp/81882f4e-0a94-4446-b4ac-7869cf198534.png'), 1: WindowsPath('hypothesis/temp/531162e2-2b4c-4e64-8b3f-1f285b0e1040.png')}, 'label': {0: -0.019687398020669655, 1: 0.0002379227226001479}}
)

file_path_list = [i.read_bytes() for i in train_df['file_name']]

dataset = tf.data.TFRecordDataset(filenames=file_path_list)

raw_example = next(iter(dataset))
parsed = tf.train.Example.FromString(raw_example.numpy())


Run Code Online (Sandbox Code Playgroud)

运行该raw_example...行会返回以下错误消息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 43: invalid start byte
Run Code Online (Sandbox Code Playgroud)

我使用 matplotlib 生成了 PNG 文件。

python tensorflow tensorflow-datasets tensorflow2.0

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

是否可以只加载 TensorFlow 数据集的一部分?

我在 Google Colab 中有一个笔记本,其中包含以下代码:

batch_size = 64
dataset_name = 'coco/2017_panoptic'

tfds_dataset, tfds_info = tfds.load(
    dataset_name, 
    split='train', 
    with_info=True)
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以使用该tfds_load函数仅下载部分数据集(例如:5% 或 X 个图像)。据我在文档中看到,没有任何理由可以这样做。当然,下载后可以对数据集进行切片,但这个特定数据集 ( coco/2017_panoptic) 为 19.57 GiB,这显然需要相当长的时间来下载。

python tensorflow tensorflow-datasets

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