python - 有没有办法在 TensorFlow session 中调用 Numpy 函数?

标签 python tensorflow tensorflow-probability

我正在尝试使用 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 秒。我猜发生这种情况是因为我在 session 中创建了不同的张量,这弄乱了内存或其他东西。

我对 TensorFlow 很陌生,很多人只使用 TensorFlow 进行深度学习和神经网络,所以我找不到解决方案。

然后我尝试仅使用 numpy 数组和 numpy 操作来实现前面的 for 循环以及在该循环内调用的函数。但这返回了以下错误:

You must feed a value for placeholder tensor 'Placeholder_4' with dtype double and 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})

有什么办法可以解决这个问题吗?谢谢。

最佳答案

为了回答您的标题问题“有没有办法在 TensorFlow session 中调用 Numpy 函数?”,我在下面放置了一些示例代码来执行“numpy 函数”(sklearn.mixture.txt)。 GaussianMixture)通过直接调用函数或通过 Tensorflow 的 py_function 给出缺失数据。我感觉这可能不是 100% 是您正在寻找的...如果您只是想实现 EM..? Tensorflow 中高斯混合模型的现有实现可能会有所帮助:

有关tf.contrib.factorization.gmm的文档: https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/gmm

实现: https://github.com/tensorflow/tensorflow/blob/r1.14/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L462-L506

直接在 Tensorflow 图中调用“numpy 函数”的示例代码:

import numpy as np
np.set_printoptions(2)
import tensorflow as tf
from sklearn.mixture import GaussianMixture as GMM

def myfunc(x,istf=True):
    #strip nans
    if istf:
        mask = ~tf.is_nan(x)
        x = tf.boolean_mask(x,mask)
    else:
        ind=np.where(~np.isnan(x))
        x = x[ind]
    x = np.expand_dims(x,axis=-1)
    gmm = GMM(n_components=2)
    gmm.fit(x)
    m0,m1 = gmm.means_[:,0]    
    return np.array([m0,m1])
# create data with nans
np.random.seed(42)
x = np.random.rand(5,28,1)
c = 5
x.ravel()[np.random.choice(x.size, c, replace=False)] = np.nan

# directly call "numpy function"
for ind in range(x.shape[0]):
    val = myfunc(x[ind,:],istf=False)
    print(val)
    [0.7  0.26]
    [0.15 0.72]
    [0.77 0.2 ]
    [0.65 0.23]
    [0.35 0.87]
# initialization
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

# create graph
X = tf.placeholder(tf.float32, [28,1])
Y = tf.py_function(myfunc,[X],[tf.float32],name='myfunc')

# call "numpy function" in tensorflow graph
for ind in range(x.shape[0]):
    val = sess.run(Y, feed_dict={X: x[ind,:],})
    print(val)
    [array([0.29, 0.76], dtype=float32)]
    [array([0.72, 0.15], dtype=float32)]
    [array([0.77, 0.2 ], dtype=float32)]
    [array([0.23, 0.65], dtype=float32)]
    [array([0.35, 0.87], dtype=float32)]

关于python - 有没有办法在 TensorFlow session 中调用 Numpy 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57236864/

相关文章:

php - 如何将 php number_format() 函数转换为 python

python - 在 cython 中编写未知维度的 numpy 代码

python-3.x - 如何训练 YOLO-Tensor flow 自己的数据集

python - 在 TensorFlow Probability 中,与贝叶斯层的损失属性相关的损失是什么?

python - ImageField() 不在 ModelForm 中保存图像 - Django/Python

python搜索技术: word similarity

python - PyTorch 的 `no_grad` 函数在 TensorFlow/Keras 中的等价物是什么?

python - 如何使用Keras TimeseriesGenerator为每n个训练样本获取一个验证样本?

tensorflow-probability - tensorflow 概率中外行术语中的双射是什么

python - 为什么 tf.executing_eagerly() 在 TensorFlow 2 中返回 False?