tf.placeholder inside a class in TF 2.0

tf.placeholder inside a class in TF 2.0

我正在尝试将我在 TF 1.0 中编写的代码更改为 TF 2.0,但我在替换 tf.placeholder 时遇到困难21=] 函数。我的代码如下

class User:
    x = tf.placeholder(tf.float32,shape=[None,784])
    y_true = tf.placeholder(tf.float32, [None, 10])

    W1 = tf.Variable(tf.random.truncated_normal([7840,1], stddev=0.1))
    lambda_W = tf.Variable(tf.zeros([7840,1]))    
    W = tf.reshape(W1,[784, 10])

    ylogits = W*x
    y = tf.nn.softmax(ylogits)
    def __init__(self):
        pass

有没有办法替换 class 中的 tf.placeholder 以在 TF 2.0 中生成代码 运行?

首先,我认为您打算为 class 的每个实例创建这些对象中的每一个,而不是像现在这样为整个 class 创建一个对象。我还认为您在 Wx 之间的乘积应该是矩阵乘积,而不是元素乘积,它不适用于给定的形状:

class User:
    def __init__(self):
        self.x = tf.placeholder(tf.float32,shape=[None,784])
        self.y_true = tf.placeholder(tf.float32, [None, 10])
        self.W1 = tf.Variable(tf.random.truncated_normal([7840,1], stddev=0.1))
        self.lambda_W = tf.Variable(tf.zeros([7840,1]))    
        self.W = tf.reshape(W1,[784, 10])
        self.ylogits = self.x @ self.W
        self.y = tf.nn.softmax(ylogits)

要在 TensorFlow 2.x 中使用它,您需要删除占位符并每次对每个新输入执行操作,例如使用新函数 call:

class User:
    def __init__(self):
        self.W1 = tf.Variable(tf.random.truncated_normal([7840,1], stddev=0.1))
        self.lambda_W = tf.Variable(tf.zeros([7840,1]))
        self.W = tf.reshape(W1,[784, 10])

    def call(self, x):
        ylogits = self.x @ self.W
        return tf.nn.softmax(ylogits)

您可以将其用作:

user1 = User()
x = ...  # Get some data
y = user1.call(x)

或者如果你更喜欢"idiomatic",你可以使用__call__:

class User:
    def __init__(self):
        self.W1 = tf.Variable(tf.random.truncated_normal([7840,1], stddev=0.1))
        self.lambda_W = tf.Variable(tf.zeros([7840,1]))
        self.W = tf.reshape(W1,[784, 10])

    def __call__(self, x):
        ylogits = x @ W
        return tf.nn.softmax(ylogits)

然后你会做:

user1 = User()
x = ...  # Get some data
y = user1(x)