import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
weight = tf.get_variable(name='weights',initializer=tf.random_normal([5,2], stddev=0.01))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('------------------打印出已经初始化之后的Variable的值------------------------------')
print(sess.run(weight))
print('----------weight的类型------------')
print(type(weight))
# Variable转换为Tensor
# Variable类型转换为tensor类型(无论是numpy转换为Tensor还是Variable转换为Tensor都可以使用tf.convert_to_tensor)
data_tensor = tf.convert_to_tensor(weight)
# 打印出Tensor的值(由Variable转化而来)
print('------------------Variable转化为Tensor,打印出Tensor的值--------------------------')
print(sess.run(data_tensor))
# tensor转化为numpy
print('-------------------tensor转换为numpy,打印出numpy的值-----------------')
data_numpy = data_tensor.eval()
print(data_numpy)
print('------------------numpy转换为Tensor---------------------------')
ten = tf.convert_to_tensor(data_numpy)
print(ten)
print(sess.run(ten))
# tensor转化为Variable(其实是Variable继承Tensor的结构,但是没有值
print('---------------------tensor转换为Variable(需要重新进行初始化)----------------------')
v = tf.Variable(data_tensor) # 此时Variable继承的是Tensor的结构,至于Variable的值,需要重新进行initialize
sess.run(tf.global_variables_initializer())
print(sess.run(weight)) # 此时输出的weight和v的结构是相同的,但是值是不同的。
print(sess.run(v))
# Variable转换为numpy(也是使用eval)
print('---------------Variable转换为numpy(也是使用eval)--------------------')
data_numpy2 = weight.eval()
print(data_numpy2)
输出