如何在 TensorFlow 2.0 中获取张量值?
How to get tensor value in Tensorflow 2.0?
我尝试在 Keras 中创建自定义图层。我从例子中得到的这段代码。如何得到这一层的计算结果?
class Linear(keras.layers.Layer):
def __init__(self, units=32):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.ones((2, 2))
# At instantiation, we don't know on what inputs this is going to get called
linear_layer = Linear(32)
# The layer's weights are created dynamically the first time the layer is called
y = linear_layer(x)
print(type(y))
print(y)
输出为:
<class 'tensorflow.python.framework.ops.Tensor'>
Tensor("linear_17/add:0", shape=(2, 32), dtype=float32)
我需要获取张量 y 的值。如何获得它们? tf.Session 不工作,因为我使用 Tensorflow 2.2.0。
linear是一层,你要放到模型结构里
class Linear(keras.layers.Layer):
def __init__(self, units=32):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.ones((2, 2))
inp = Input(2)
linear_layer = Linear(32)(inp)
model = Model(inp, linear_layer)
y = model.predict(x)
我尝试在 Keras 中创建自定义图层。我从例子中得到的这段代码。如何得到这一层的计算结果?
class Linear(keras.layers.Layer):
def __init__(self, units=32):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.ones((2, 2))
# At instantiation, we don't know on what inputs this is going to get called
linear_layer = Linear(32)
# The layer's weights are created dynamically the first time the layer is called
y = linear_layer(x)
print(type(y))
print(y)
输出为:
<class 'tensorflow.python.framework.ops.Tensor'>
Tensor("linear_17/add:0", shape=(2, 32), dtype=float32)
我需要获取张量 y 的值。如何获得它们? tf.Session 不工作,因为我使用 Tensorflow 2.2.0。
linear是一层,你要放到模型结构里
class Linear(keras.layers.Layer):
def __init__(self, units=32):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
x = tf.ones((2, 2))
inp = Input(2)
linear_layer = Linear(32)(inp)
model = Model(inp, linear_layer)
y = model.predict(x)