如何使用tensorflow编写这个函数?

2024-10-01 02:31:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用tensorflow编写以下函数。由于张量不能iterable,我不知道如何处理张量流中的这条线。你知道吗

kernel_matrix = np.squeeze(np.array([[rq_convariance(1.5, x1, x2)     for x1 in plot_xs] for x2 in plot_xs]))

我想用'地图'但是我的函数有两个变量不能使用'地图'. 整个编码如下。你知道吗

import numpy as np
from scipy import interpolate
from numpy.linalg import inv
import tensorflow as tf
import tensorflow.contrib.distributions as tcd

def rq_convariance(theta, x1, x2):
    kernel = np.exp(-(x1 - x2)**2 / 2 * theta**2)
    return kernel

def expectation(x):
    plot_xs = np.reshape(np.linspace(-5, 5, 300), (300, 1))
    kernel_matrix = np.squeeze(np.array([[rq_convariance(1.5, x1, x2)     for x1 in plot_xs] for x2 in plot_xs]))
    inverse_kernel_matrix = inv(kernel_matrix)

    def reference_point():
        # calculate the convariance
        convariance = np.squeeze(kernel_matrix)
        sampled_funcs = np.random.multivariate_normal(np.ones(len(plot_xs)), convariance, size=1)
        return sampled_funcs

    ref_point = np.transpose(reference_point())
    kernel_vector = np.transpose(np.array([rq_convariance(1.5, x1, x) for x1 in plot_xs]))
    mu = kernel_vector.dot(inverse_kernel_matrix).dot(ref_point)
    return mu

Tags: inimportforplottensorflownpkernelmatrix
1条回答
网友
1楼 · 发布于 2024-10-01 02:31:03

来自Numpy:

def rq_convariance(theta, x1, x2):
   kernel = np.exp(-(x1 - x2)**2 / 2 * theta**2)
   return kernel

#Setting a smaller size
plot_xs = np.reshape(np.linspace(-5, 5, 5), (5, 1))
kernel_matrix = np.squeeze(np.array([[rq_convariance(1.5, x1, x2)     for x1 in plot_xs] for x2 in plot_xs]))

#Kernel_matrix output
   [[1.0000000, 0.0008838, 0.0000000, 0.0000000, 0.0000000],
   [0.0008838, 1.0000000, 0.0008838, 0.0000000, 0.0000000],
   [0.0000000, 0.0008838, 1.0000000, 0.0008838, 0.0000000],
   [0.0000000, 0.0000000, 0.0008838, 1.0000000, 0.0008838],
   [0.0000000, 0.0000000, 0.0000000, 0.0008838, 1.0000000]])

到Tensorflow:

t_plot_xs = tf.reshape(tf.linspace(-5., 5., 5, name="linspace"), (5,1))

#Let broadcasting do the trick
t_kernel = tf.exp(-0.5*theta**2*(t_plot_xs - tf.transpose(t_plot_xs))**2)

with tf.Session() as sess:
   print(sess.run(t_kernel))

#Output
   [[1.0000000 0.0008838 0.0000000 0.0000000 0.0000000]
   [0.0008838 1.0000000 0.0008838 0.0000000 0.0000000]
   [0.0000000 0.0008838 1.0000000 0.0008838 0.0000000]
   [0.0000000 0.0000000 0.0008838 1.0000000 0.0008838]
   [0.0000000 0.0000000 0.0000000 0.0008838 1.0000000]]

相关问题 更多 >