tf.newaxis和np.newaxis

# -*- coding: utf-8 -*-
"""
tf.newaxis 和 numpy newaxis
"""
import numpy as np
import tensorflow as tf


if __name__ == '__main__':
    feature = np.array([[1,2,3],
                        [2,4,6]])
    center = np.array([[1,1,1],
                       [0,0,0]])
    
    print("原始数组大小:")
    print(feature.shape)
    print(center.shape)
    
    
    np_feature = feature[:, np.newaxis]  
    np_center = center[np.newaxis, :]
    
    print("添加 np.newaxis 后数组大小:")
    print(np_feature.shape)
    print(np_center.shape)
    
    np_diff = np_feature - np_center
    
    print("矩阵相减,np_diff:")
    print(np_diff)
      
    print('\n*********************\n')
    
    tf_feature = tf.constant(feature)[:,tf.newaxis]
    tf_center = tf.constant(center)[tf.newaxis,:]
    
    print("添加 tf.newaxis 后数组大小:")
    print(tf_feature.shape)
    print(tf_center.shape)
   
    tf_diff = tf_feature - tf_center       
    mask = 1 - tf.eye(2, 2, dtype=tf_diff.dtype)
    diffs = tf_diff * mask[:, :, tf.newaxis]
    
    sess = tf.Session()
    print("矩阵相减,tf_diff:")
    print(sess.run(tf_diff))
    
    print("对角线元素置为0:")
    print(sess.run(diffs))

结果:

原始数组大小:
(2, 3)
(2, 3)
添加 np.newaxis 后数组大小:
(2, 1, 3)
(1, 2, 3)
矩阵相减,np_diff:
[[[0 1 2]
  [1 2 3]]

 [[1 3 5]
  [2 4 6]]]

*********************

添加 tf.newaxis 后数组大小:
(2, 1, 3)
(1, 2, 3)
矩阵相减,tf_diff:
[[[0 1 2]
  [1 2 3]]

 [[1 3 5]
  [2 4 6]]]
对角线元素置为0:
[[[0 0 0]
  [1 2 3]]

 [[1 3 5]
  [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
发出的红包

打赏作者

Peanut_范

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值