【问题标题】:Tensorflow - how to create a Dataset which is an array of tuplesTensorflow - 如何创建一个元组数组的数据集
【发布时间】:2020-12-10 08:07:46
【问题描述】:

问题

数据集可以是不同类型的元组的集合。我可以从元组创建数据集。

tf.data.Dataset.from_tensors(
    ([1, 2, 3], 'A')
)
-----
<TensorDataset shapes: ((3,), ()), types: (tf.int32, tf.string)>

如何从元组数组创建数据集?

tf.data.Dataset.from_tensors(
    [
        ([1, 2, 3], 'A'), 
        ([4, 5, 6], 'B')
    ]
)
----
ValueError: Can't convert non-rectangular Python sequence to Tensor.

Tensorflow Dataset IMDB review dataset是一个不同类型元组数组的例子,所以应该有办法。

import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds

imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True)
train_data, test_data = imdb['train'], imdb['test']

print(train_data.take(2))
for text, label in train_data.take(2).as_numpy_iterator():
  print("{}, {}".format(text[0:64], label))
----
<TakeDataset shapes: ((), ()), types: (tf.string, tf.int64)>
b'Being a fan of silent films, I looked forward to seeing this pic', 0
b"I haven't seen this film in years so my knowledge is a little ru", 1

【问题讨论】:

  • 我想你在找from_tensor_slices

标签: python tensorflow machine-learning keras tensorflow-datasets


【解决方案1】:

它适用于 IMDB 数据集,因为它们是独立的特征。如果特征是分开的,即作为多输入,您的示例也可以工作。

import numpy as np
import tensorflow as tf

input_1 = np.array(([1, 2, 3], [4, 5, 6]))
input_2 = np.array((['A'], ['B']))

tf.data.Dataset.from_tensor_slices((input_1, input_2))
<TensorSliceDataset shapes: ((3,), (1,)), types: (tf.int32, tf.string)>

例如:

ds = tf.data.Dataset.from_tensor_slices((input_1, input_2))

next(iter(ds))
(<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3])>,
 <tf.Tensor: shape=(1,), dtype=string, numpy=array([b'A'], dtype=object)>)

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2018-07-02
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多