【发布时间】:2019-07-27 23:41:30
【问题描述】:
我正在尝试使用 TensorFlow 和 TensorFlow Probability 实现期望最大化算法。在我尝试实现缺失数据(数据可以包含某些随机维度的 NaN 值)之前,它运行良好。
问题在于,由于缺少数据,我无法再将所有操作都作为向量操作进行,我必须使用索引和 for 循环,如下所示:
# Here we iterate through all the data samples
for i in range(n):
# x_i is the sample i
x_i = tf.expand_dims(x[:, i], 1)
gamma.append(estimate_gamma(x_i, pi, norm, ber))
est_x_n_i = []
est_xx_n_i = []
est_x_b_i = []
for j in range(k):
mu_k = norm.mean()[j, :]
sigma_k = norm.covariance()[j, :, :]
rho_k = ber.mean()[j, :]
est_x_n_i.append(estimate_x_norm(x_i[:d, :], mu_k, sigma_k))
est_xx_n_i.append(estimate_xx_norm(x_i[:d, :], mu_k, sigma_k))
est_x_b_i.append(estimate_x_ber(x_i[d:, :], rho_k))
est_x_n.append(tf.convert_to_tensor(est_x_n_i))
est_xx_n.append(tf.convert_to_tensor(est_xx_n_i))
est_x_b.append(tf.convert_to_tensor(est_x_b_i))
我发现这些操作效率不高。虽然第一个样本每个样本大约需要不到 1 秒,但在 50 个样本之后,每个样本大约需要 3 秒。我猜这是因为我在会话中创建了不同的张量,这会破坏内存或其他东西。
我是使用 TensorFlow 的新手,很多人只将 TensorFlow 用于深度学习和神经网络,所以我找不到解决方案。
然后我尝试仅使用 numpy 数组和 numpy 操作来实现前面的 for 循环和在该循环内调用的函数。但这返回了以下错误:
您必须为占位符张量“Placeholder_4”提供一个值 dtype double 和 shape [8,18]
发生此错误是因为当它尝试执行循环内的 numpy 函数时,尚未输入占位符。
pi_k, mu_k, sigma_k, rho_k, gamma_ik, exp_loglik = exp_max_iter(x, pi, dist_norm, dist_ber)
pi, mu, sigma, rho, responsability, NLL[i + 1] = sess.run([pi_k, mu_k, sigma_k, rho_k, gamma_ik, exp_loglik],{x: samples})
有没有办法解决这个问题?谢谢。
【问题讨论】:
-
还没有仔细看你的问题,但标题看起来你可能想看看
tf.py_func? -
@teng 好像有用,我试试。
-
@teng 我不认为工作正常......你能解释一下如何使用它吗?文档和示例不是很清楚....
-
tf 文档确实不是很清楚,如果您仍然决定使用
tf.py_func,这里有一个工作示例github.com/Johswald/Bayesian-FlowNet/blob/master/flownet.py。如果您决定将代码迁移到纯 tf,则 tf 中应该有一些方法可以帮助删除/忽略丢失的数据 - 如果您选择此路线,请在 SO 中搜索解决方案,如果您无法解决,您可以创建一个新问题。 -
另外,目前这个问题的范围有点太广了,所以没有得到太多的关注。如果您发布一些带有示例输入数据的最小(非)工作代码,这也会有所帮助,以便人们可以尝试使用代码。
标签: python tensorflow tensorflow-probability