python - 在 Tensorflow 中将函数按元素应用于具有不同参数的张量

标签 python machine-learning tensorflow

我有一个由常量和变量混合组成的列表,它们充当我试图优化的函数的输入。这是复杂的部分:我需要对列表中的每个元素应用一个函数,每个元素都有不同的参数。我相信这必须在计算图中完成才能有效。

我想做的是将参数放入逐个元素匹配的张量中,并将函数应用于三个张量,以便一起评估每行元素。这可能吗?

示例:

enter image description here

最终可能会得到类似的结果:

# The list of variables and constants to optimize
optimal = [[tf.constant(10.0), tf.constant(1.0), tf.Variable(0.0)]]

# Parameters
p1 = [[None, None, 2.0]]
p2 = [[None, None, 5.0]]

# Apply the function
# ----------------------- HOW TO DO THIS -----------------------
g = f(optimal, p1, p2)
# --------------------------------------------------------------

# Loss
loss = tf.abs(tf.sub(g, label))

# Optimize
trainstep = tf.train.ProximalGradientDescentOptimizer(.1).minimize(loss, var_list= [optimal[2]])

sess.run(trainstep)

提前非常感谢您。

最佳答案

使用tf.map_fn

g = tf.map_fn(f, tf.transpose(tf.concat(0, [optimal, p1, p2])))

首先沿着dim 0连接,然后转置它,使得行io_i, p1_i, p2_imap_fn 只是将 f 应用于每一行。

关于python - 在 Tensorflow 中将函数按元素应用于具有不同参数的张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851619/

相关文章:

python - 如何迭代一个列表的值,用函数更改它并将其添加到第二个列表?

c# - 为什么这个隐马尔可夫模型会做出这样的预测?

numpy - 具有负相似度的 TensorFlow Cookbook Skip-Gram 模型

python - 将 tf.keras.utils.image_dataset_from_directory 与标签列表一起使用

python - Django 模型 : user ID

python - ImageField 与 django-storages 导致 : "Error parsing the X-Amz-Credential parameter; the region ' us-east- 1' is wrong; expecting ' us-west- 1'"

python - 将可变长度列表数据(来自 csv)分配给 'indicator_column' 特征

r - 通过创建附加列将 R data.table 从 4 个 id 列转换为 1 个 id 列

python - 如何处理 pandas 中的插补和热一编码?

tensorflow - 如何在 GKE 上运行分布式 Tensorflow?