If you are extracting variable tensor and then to an array, then below are the example for different versions of tensorflow.
If you would like to extract the value in tensorflow version 1.14 OR other versions that support session, then below is an example -
#!pip install tensorflow==1.14
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import time
print("tensorflow version:",tf.__version__)
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(7,(3,3) , padding = "same" , input_shape = (28,28,1)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dense(50,activation = 'relu'))
model.add(tf.keras.layers.Dense(1))
return model
model_discriminator = make_discriminator_model()
output = model_discriminator(np.random.rand(1,28,28,1).astype("float32"))
#initialize the variable
init_op = tf.initialize_all_variables()
#run the graph
with tf.Session() as sess:
sess.run(init_op) #execute init_op
print("Output as a Tensor:",output)
out = np.array(sess.run(output))
print("Output as an Array:",out)
print("Type of the Array:",type(out))
Output will be -
tensorflow version: 1.14.0
Output as a Tensor: Tensor("sequential_7/dense_15/BiasAdd:0", shape=(1, 1), dtype=float32)
Output as an Array: [[-0.29746282]]
Type of the Array: <class 'numpy.ndarray'>
If you would like to extract the value in tensorflow version 2.1 OR other versions that supports tensor print, then below is an example -
#!pip install tensorflow==2.1
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
print("tensorflow version:",tf.__version__)
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(7,(3,3) , padding = "same" , input_shape = (28,28,1)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dense(50,activation = 'relu'))
model.add(tf.keras.layers.Dense(1))
return model
model_discriminator = make_discriminator_model()
output = model_discriminator(np.random.rand(1,28,28,1).astype("float32"))
print("Output as a Tensor:",output)
out = np.array(output)
print("Output as an Array:",out)
print("Type of the Array:",type(out))
Output will be -
tensorflow version: 2.1.0
Output as a Tensor: tf.Tensor([[0.32392436]], shape=(1, 1), dtype=float32)
Output as an Array: [[0.32392436]]
Type of the Array: <class 'numpy.ndarray'>
NOTE: There are symbolic and variable tensor, you can understand the difference between them here - Symbolic Tensor Vs Variable Tensor