You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查看Keras中张量对象的输出?含Embedding层向量查看方法

如何查看Keras Embedding层的密集向量输出及张量对象

嘿,这问题我熟!我来一步步教你怎么查看Embedding层的输出,以及Keras里Tensor对象的通用查看方法。


一、查看Embedding层的密集向量输出

Embedding层把整数索引转成密集向量后,有几种简单的方式能看到具体数值:

1. 直接调用Embedding层获取输出

不用搭建完整模型,单独实例化Embedding层后直接喂入输入数据就行:

from tensorflow.keras.layers import Embedding
import numpy as np

# 初始化Embedding层:词汇表大小1000,输出向量维度2,输入序列长度1
embedding_layer = Embedding(input_dim=1000, output_dim=2, input_length=1)

# 准备测试输入(比如你给的[[4], [20]])
test_input = np.array([[4], [20]])

# 获取输出Tensor,转成NumPy数组查看
output_vector = embedding_layer(test_input).numpy()
print(output_vector)

运行后你就能看到类似[[[0.25, 0.1]], [[0.6, -0.2]]]的输出(具体数值会随机初始化,除非你设置了embeddings_initializer)。

2. 从完整模型中提取输出

如果Embedding是模型的一部分,你可以通过model.predict()或者直接调用对应层来获取输出:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding
import numpy as np

# 搭建包含Embedding层的简单模型
model = Sequential()
model.add(Embedding(input_dim=1000, output_dim=2, input_length=1))

# 测试输入
test_input = np.array([[4], [20]])

# 方法1:用predict获取输出
predict_result = model.predict(test_input)
print("predict输出:\n", predict_result)

# 方法2:直接调用对应层(这里是第一层)
layer_output = model.layers[0](test_input).numpy()
print("层直接输出:\n", layer_output)

3. 查看整个词汇表的词向量

如果你想一次性看所有索引对应的词向量,可以直接取Embedding层的权重矩阵:

# 获取全部词向量(形状是(词汇表大小, 输出维度))
all_embeddings = embedding_layer.weights[0].numpy()
print("全部词向量形状:", all_embeddings.shape)

# 单独查看索引4和20的词向量
print("索引4的词向量:", all_embeddings[4])
print("索引20的词向量:", all_embeddings[20])

二、Keras张量对象的通用查看方法

Keras里的Tensor对象(其实就是TensorFlow的Tensor),常用的查看方式有这几种:

  • 转成NumPy数组:这是最常用的方式,在Eager Execution模式(TensorFlow默认开启)下,直接调用.numpy()就能把Tensor转成可查看的数组:

    import tensorflow as tf
    
    tensor = tf.constant([[0.25, 0.1], [0.6, -0.2]])
    print(tensor.numpy())
    
  • 直接打印Tensor:如果不需要单独提取数值,直接print(tensor)会显示Tensor的形状、数据类型,以及小张量的具体数值:

    print(tensor)
    # 输出类似:<tf.Tensor: shape=(2, 2), dtype=float32, numpy=array([[0.25, 0.1], [0.6, -0.2]], dtype=float32)>
    
  • Graph模式下用tf.print():如果是在tf.function装饰的函数(Graph模式)里,.numpy()可能无法使用,这时候用tf.print()可以直接输出Tensor内容:

    @tf.function
    def print_tensor(t):
        tf.print("Graph模式下的Tensor:", t)
    
    print_tensor(tensor)
    

内容的提问来源于stack exchange,提问作者Harsh2093

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:19:36