问题驱动
在使用python语言基于tensorflow框架搭建网络模型的时候,对于数据内容和shape的确定难免会参杂着使用numpy和tensorflow的内置函数,但是我们都知道ndarray为numpy的主要存储数据的格式,而tensor又是tensorflow的特色,下面来总结一下两者的转换方法
知识小结
- 对于直接调用tf.*形式的,返回值一般均为Tensor,无论是tf.constant, 还是占位符
import tensorflow as tf
a = tf.constant([1,2])
print(a) # out:Tensor("Const:0", shape=(2,), dtype=int32)
b = tf.placeholder(shape=[2, 2], dtype=tf.int32)
print(c) # out:Tensor("Placeholder:0", shape=(2, 2), dtype=int32)
# 这里注意 定义tf.Variable(...)时,其属于tf.Variables类,而不是tf.Tensor类
c = tf.Variable([3,4]) # 定义一个3x4的二维系数矩阵
print(c) # out:<tf.Variable 'Variable:0' shape=(2,) dtype=float32_ref>
- 通过tf.*类的operation返回的也是Tensor
import numpy as np
import tensorflow as tf
a = [1,2,3,4] # 此时创建的是python中的列表(list)数据类型
print(a) # out:list
b = np.ndarray([1,2,3,4])
print(type(b)) # out:numpy.ndarray
# 这里如果直接输出 print(b) 的话,会打印出一系列的值,4-D数组
c = tf.reshape(b, [4, 6]) # 注意变换维度的时候,数组元素的个数总数,保持不变
print(c) # out:Tensor("Reshape_3:0", shape=(4, 6), dtype=float64)
- ndarray与tensor的相互转换
- ndarray ----> tensor
import numpy as np
import tensorflow as tf
# 函数法
# 先找出一个ndarray的数据,这里我直接定义一个
a = np.ndarray([3,4]) # 3x4形状的ndarray数据
b = tf.convert_to_tensor(a)
print(b) # out:Tensor("Const:0", shape=(3, 4), dtype=float64)
- tensor ------> ndarray
# 通过调用启动会话进行转换
op = tf.constant([1, 2, 3, 4])
print(op) # out:Tensor("Const_1:0", shape=(4,), dtype=int32)
sess = tf.InteractiveSession()
op_ndarray = op.eval() # 这里等效于op_ndarray = sess.run(op)
print(op_ndarray) # out:<class 'numpy.ndarray'>