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

TensorFlow1.14下如何获取类中方法内的Xproj、Yproj并打印形状

获取TensorFlow 1.14模型类中张量并打印形状的解决方法

我用Python类构建TensorFlow 1.14模型时,在类的build方法内定义了Yproj和Xproj两个张量,想要获取这两个张量并打印它们的形状,尝试通过return返回但操作可能有误,相关代码及修改思路如下:

原始代码

class test:
    def __init__(self):
        self.__build_flag = -1
        self.__train_flag = -1

    def build(self, dim, ddim, hdim, num_layers=3, 
              activation=tf.nn.tanh, init_lr=1e-5):
        """ Build tensorflow model """

        # Parameters
        self.__random_state = random_state  
            
        # Loss function definition

        Sx, Ux , Vx =tf.linalg.svd(self.__psiNNx, full_matrices=False, compute_uv=True)

        # # Project X and Y onto  Principal components
        Yproj=tf.matmul(tf.transpose(Ux), self.__psiNNy)
        Xproj=tf.matmul(tf.transpose(Ux), self.__psiNNx)

        # Build complete
        print("Built tensorflow graph.")
        self.__build_flag = 0

我的修改思路

class test:
    def __init__(self):

    def build(self, dim, ddim, hdim, num_layers=3, 
              activation=tf.nn.tanh, init_lr=1e-5):
        """ Build tensorflow model """

        bla bla bla 

        return Xproj, Yproj

正确修改方案

方案一:通过return返回张量

保留类初始化逻辑,在build方法末尾返回两个张量,调用时接收即可:

import tensorflow as tf

class TestModel:
    def __init__(self):
        self.__build_flag = -1
        self.__train_flag = -1
        # 示例:初始化输入张量(实际根据你的需求定义)
        self.__psiNNx = tf.placeholder(tf.float32, shape=[None, 10])
        self.__psiNNy = tf.placeholder(tf.float32, shape=[None, 10])

    def build(self, dim, ddim, hdim, num_layers=3, 
              activation=tf.nn.tanh, init_lr=1e-5):
        """ Build tensorflow model """

        # 补充random_state的定义(示例值)
        self.__random_state = 42  
            
        Sx, Ux , Vx = tf.linalg.svd(self.__psiNNx, full_matrices=False, compute_uv=True)

        Yproj = tf.matmul(tf.transpose(Ux), self.__psiNNy)
        Xproj = tf.matmul(tf.transpose(Ux), self.__psiNNx)

        print("Built tensorflow graph.")
        self.__build_flag = 0
        
        return Xproj, Yproj

调用示例

# 创建模型实例
model = TestModel()
# 调用build方法获取张量
x_proj, y_proj = model.build(dim=10, ddim=5, hdim=8)

# 打印静态形状(适用于维度固定的情况)
print("Xproj静态形状:", x_proj.shape)
print("Yproj静态形状:", y_proj.shape)

# 若存在动态维度(如None),需在会话中获取运行时形状
with tf.Session() as sess:
    # 生成测试数据
    test_x = tf.random_normal([10, 10]).eval()
    test_y = tf.random_normal([10, 10]).eval()
    # 运行获取动态形状
    x_shape, y_shape = sess.run(
        [tf.shape(x_proj), tf.shape(y_proj)], 
        feed_dict={model._TestModel__psiNNx: test_x, model._TestModel__psiNNy: test_y}
    )
    print("Xproj动态形状:", x_shape)
    print("Yproj动态形状:", y_shape)

方案二:将张量设为实例属性(推荐)

把Yproj和Xproj设为类的实例属性,后续直接通过实例访问,无需每次调用build都接收返回值:

import tensorflow as tf

class TestModel:
    def __init__(self):
        self.__build_flag = -1
        self.__train_flag = -1
        self.__psiNNx = tf.placeholder(tf.float32, shape=[None, 10])
        self.__psiNNy = tf.placeholder(tf.float32, shape=[None, 10])
        # 初始化投影张量属性
        self.Xproj = None
        self.Yproj = None

    def build(self, dim, ddim, hdim, num_layers=3, 
              activation=tf.nn.tanh, init_lr=1e-5):
        """ Build tensorflow model """

        self.__random_state = 42  
            
        Sx, Ux , Vx = tf.linalg.svd(self.__psiNNx, full_matrices=False, compute_uv=True)

        # 将投影张量赋值给实例属性
        self.Yproj = tf.matmul(tf.transpose(Ux), self.__psiNNy)
        self.Xproj = tf.matmul(tf.transpose(Ux), self.__psiNNx)

        print("Built tensorflow graph.")
        self.__build_flag = 0

调用示例

model = TestModel()
model.build(dim=10, ddim=5, hdim=8)

# 直接访问实例属性获取张量
print("Xproj静态形状:", model.Xproj.shape)
print("Yproj静态形状:", model.Yproj.shape)

with tf.Session() as sess:
    test_x = tf.random_normal([10, 10]).eval()
    test_y = tf.random_normal([10, 10]).eval()
    x_shape, y_shape = sess.run(
        [tf.shape(model.Xproj), tf.shape(model.Yproj)], 
        feed_dict={model._TestModel__psiNNx: test_x, model._TestModel__psiNNy: test_y}
    )
    print("Xproj动态形状:", x_shape)
    print("Yproj动态形状:", y_shape)

注意事项

  • 原代码中random_state未定义,需补充初始化逻辑或作为参数传入
  • TensorFlow 1.x中,静态形状通过.shape获取,动态维度需在会话中运行tf.shape()得到实际形状
  • 若使用私有变量(__开头),外部访问需用_类名__变量名的格式,也可改为受保护(_开头)或公开属性简化访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:39:22