tf.cos与np.cos的区别

6 篇文章 0 订阅
3 篇文章 0 订阅

问题描述

今天看见了两个函数,它们的结构很相似,输入输出也很相似,但是代码作者却实现了这个有相同功能的函数两次,我感到很疑惑。

代码如下:

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官方文档地址:

https://www.tensorflow.org/api_docs/python/tf/all_symbols

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码实现了一种常用的位置嵌入方法。它使用了正弦和余弦函数来对位置进行编码,生成一个位置嵌入矩阵。 输入参数为 `length` 和 `depth`,其中 `length` 表示序列的长度,`depth` 表示嵌入向量的维度。代码中,`depth` 被除以2,是因为后续会使用正弦和余弦函数分别生成两个维度的编码。 首先,通过 `np.arange(length)[:, np.newaxis]` 创建一个形状为 `(length, 1)` 的矩阵 `positions`,其中每个元素表示序列中的位置。 然后,通过 `np.arange(depth)[np.newaxis, :] / depth` 创建一个形状为 `(1, depth)` 的矩阵 `depths`,其中每个元素表示一个缩放因子。 接下来,通过计算 `1 / (10000 ** depths)` 得到一个形状为 `(1, depth)` 的矩阵 `angle_rates`,其中每个元素表示一个角度缩放因子。 最后,通过 `positions * angle_rates` 计算得到一个形状为 `(length, depth)` 的矩阵 `angle_rads`,其中每个元素表示一个角度值。 最后一步,通过将 `np.sin(angle_rads)` 和 `np.cos(angle_rads)` 沿着最后一个维度拼接起来,生成一个形状为 `(length, 2*depth)` 的位置嵌入矩阵 `pos_encoding`。 最后,通过 `tf.cast(pos_encoding, dtype=tf.float32)` 将位置嵌入矩阵转换为 `tf.float32` 类型,并返回结果。 请注意,代码中使用了 `tf.cast()` 函数来将位置嵌入矩阵转换为 `tf.float32` 类型。这可能是因为该代码片段是基于 TensorFlow 框架编写的,所以如果你想在其他框架中使用,可能需要进行相应的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值