问题描述
今天看见了两个函数,它们的结构很相似,输入输出也很相似,但是代码作者却实现了这个有相同功能的函数两次,我感到很疑惑。
代码如下:
def get_random_features(x, omega, bias, D):
nsample = x.shape[1]
return np.cos(np.dot(x, omega.T) + bias.T) * np.sqrt(2. / D)
def get_random_features_tf(x, omega, bias, D):
omega_tf = tf.constant(omega.T, dtype=tf.float32)
bias_tf = tf.constant(bias.T, dtype=tf.float32)
return tf.cos(tf.matmul(x, omega_tf) + bias_tf) * np.sqrt(2. / D)
后来想来,问题应该出在变量类型和返回值的类型上,用spyder试了一下果然如此。
实验结果
完整实验代码:
import numpy as np
import tensorflow.compat.v1 as tf
def get_random_features(x, omega, bias, D):
nsample = x.shape[1]
return np.cos(np.dot(x, omega.T) + bias.T) * np.sqrt(2. / D)
def get_random_features_tf(x, omega, bias, D):
omega_tf = tf.constant(omega.T, dtype=tf.float32)
bias_tf = tf.constant(bias.T, dtype=tf.float32)
return tf.cos(tf.matmul(x, omega_tf) + bias_tf) * np.sqrt(2. / D)
nbatch = 2
actdim = 50
pi = tf.random_normal([nbatch, actdim])
logstd = tf.get_variable(name="logstd", shape=[1, actdim], initializer=tf.zeros_initializer())
M = 10
noise = tf.random_normal([nbatch, M, actdim])
mu = tf.expand_dims(pi, axis=1)
std = tf.expand_dims(tf.exp(pi * 0.0 + logstd), axis=1)
a_reparameterized = mu + std * noise
x = a_reparameterized
D = 100
ac_space = 50
sigma = 0.1
omega = np.random.randn(D, ac_space) * 1.0 / sigma
bias = np.random.rand(D, 1) * 2 * np.pi
res1 = get_random_features(x, omega, bias, D)
res2 = get_random_features_tf(x, omega, bias, D)
spyder终端输出为:
可见确实在返回值的数据类型上存在区别。
后记
1. 不同的包对不同的函数有自己的实现方式,切不可盲目混用,遇到不明白的应该去查阅官方文档;
2. 要擅长通过小实验来观察程序的运行过程,不能看看就完了,亲自动手会有更深的理解。
numpy官方文档地址:
numpy.cos — NumPy v1.24 Manual
tensorflow官方文档地址: