我有一个 Pandas DataFrame,我正在将其部分加载到 tf.data 数据集中:
dataset = tf.data.Dataset.from_tensor_slices((
df.StringColumn.values,
df.IntColumn1.values,
df.IntColumn2.values,
))
现在我想做的是使用诸如 flat_map
之类的东西来生成一个派生数据集,该数据集获取每行中的数据,并为派生数据集中的每一行生成一堆行。原创。
但是 flat_map
似乎只是在 lambda
函数中向我传递占位符张量。
如果重要的话,我正在使用 TensorFlow 2.0 alpha 0。
编辑:
我想要的是能够写出这样的东西:
derived = dataset.flat_map(replicate)
def replicate(s, i1, i2):
return [[0, s, i1, i2],
[0.25, s, i1, i2],
[0.5, s, i1, i2],
[0.75, s, i1, i2]]
...然后将衍生
作为具有四列和四倍于数据集
行数的数据集。
但是当我尝试这个时,s
不是一个值,它是一个字符串占位符张量。
编辑2:
好吧,我的意思是 replicate
函数需要知道它正在复制的行的值:
slice_count = 16
def price(frac, total, size0, price0, size1, price1, size2, price2, size3, price3):
total_per_slice = total / slice_count
start = frac * total_per_slice
finish = start + total_per_slice
price = \
(price0 * (min(finish, size0) - max(start, 0) if 0 < finish and start < size0 else 0)) + \
(price1 * (min(finish, size1) - max(start, size0) if size0 < finish and start < size1 else 0)) + \
(price2 * (min(finish, size2) - max(start, size1) if size1 < finish and start < size2 else 0)) + \
(price3 * (min(finish, size3) - max(start, size2) if size2 < finish and start < size3 else 0))
def replicate(size0, price0, size1, price1, size2, price2, size3, price3):
total = size0 + size1 + size2 + size3
return [[
price(frac, total, size0, price0, size1, price1, size2, price2, size3, price3),
frac / slice_count] for frac in range(slice_count)]
derived = dataset.flat_map(replicate)
仅仅能够传递占位符是不够的。这是我可以做的事情吗?或者如果我能以某种方式将其转换为 TensorFlow 的计算图就可以实现,或者只是按照我尝试的方式不可行?
最佳答案
可能还有很长的路要走,但您也可以使用 .concatenate()
和 apply()
来实现“平面映射”
像这样:
def replicate(ds):
return (ds.map(lambda s,i1,i2: (s, i1, i2, tf.constant(0.0)))
.concatenate(ds.map(lambda s,i1,i2: (s, i1, i2, tf.constant(0.25))))
.concatenate(ds.map(lambda s,i1,i2: (s, i1, i2, tf.constant(0.5))))
.concatenate(ds.map(lambda s,i1,i2: (s, i1, i2, tf.constant(0.75)))))
derived = dataset.apply(replicate)
应该给你你期望的输出
关于python - 如何使用 TensorFlow tf.data.Dataset flat_map 生成派生数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266533/