TensorFlow工具快速入门教程7 TensorFlow基础

在机器学习中,模型被提供称为特征向量的对象列表。特征向量可以是任何数据类型。特征向量通常是填充张量的主要输入。这些值将通过张量流入op节点,此操作/计算的结果将创建一个新的张量,该张量又将用于新的操作。所有这些操作都可以在图表中查看。

张量的表示

在TensorFlow中,张量是n维的特征向量(即阵列)的集合。例如,2x3矩阵,其值为1到6

图片.png

TensorFlow将此矩阵表示为:

[[1,2,3]
   [4,5,6]]

如果我们创建一个值为1到8的三维矩阵

图片.png

TensorFlow将此矩阵表示为:

[[[1,2]
       [[3,4]
       [[5,6]
       [[7,8]]

注意:张量可以用标量表示,也可以有三维以上的形状。可视化更高维度级别更加复杂。

张量的类型

张量具有三个属性的对象:name、shape、dtype

TensorFlow执行的每个操作都涉及张量的操作。您可以创建四个主要张量:tf.Variable,tf.constant,tf.placeholder,tf.SparseTensor

张量的维度

tf.constant的使用说明:

tf.constant(value, dtype, name = "")
arguments

- `value`: Value of n dimension to define the tensor. Optional
- `dtype`: Define the type of data:    
    - `tf.string`: String variable    
    - `tf.float32`: Flot variable    
    - `tf.int16`: Integer variable
- "name": Name of the tensor. Optional. By default, `Const_1:0`     

0维,即标量:

>>> r1 = tf.constant(1, tf.int16)
>>> r1
<tf.Tensor 'Const:0' shape=() dtype=int16>

图片.png

可以给标量取个名字:

>>> r2 = tf.constant(1, tf.int16, name = "my_scalar")
>>> r2
<tf.Tensor 'my_scalar:0' shape=() dtype=int16>
>>> r1_decimal = tf.constant(1.12345, tf.float32)
>>> r1_decimal
<tf.Tensor 'Const_1:0' shape=() dtype=float32>
>>> r1_string = tf.constant("https://china-testing.github.io", tf.string)
>>> r1_string
<tf.Tensor 'Const_2:0' shape=() dtype=string>

维度:

>>> r1_vector = tf.constant([1,3,5], tf.int16)
>>> r1_vector
<tf.Tensor 'Const_3:0' shape=(3,) dtype=int16>
>>> r2_boolean = tf.constant([True, True, False], tf.bool)
>>> r2_boolean
<tf.Tensor 'Const_4:0' shape=(3,) dtype=bool>
>>> r2_matrix = tf.constant([ [1, 2], [3, 4] ],tf.int16)
>>> r2_matrix
<tf.Tensor 'Const_5:0' shape=(2, 2) dtype=int16>
>>> r3_matrix = tf.constant([ [[1, 2], [3, 4], [5, 6]] ], tf.int16)
>>> r3_matrix
<tf.Tensor 'Const_6:0' shape=(1, 3, 2) dtype=int16>

张量的Shape

>>> m_shape = tf.constant([ [10, 11], [12, 13],   [14, 15] ] )
>>> m_shape.shape
TensorShape([Dimension(3), Dimension(2)])
>>> tf.zeros(10)
<tf.Tensor 'zeros:0' shape=(10,) dtype=float32>
>>> tf.ones([10, 10])
<tf.Tensor 'ones:0' shape=(10, 10) dtype=float32>
>>> tf.ones(m_shape.shape[0])
<tf.Tensor 'ones_2:0' shape=(3,) dtype=float32>
>>> tf.ones(m_shape.shape[1])
<tf.Tensor 'ones_4:0' shape=(2,) dtype=float32>
>>> tf.ones(m_shape.shape)
<tf.Tensor 'ones_5:0' shape=(3, 2) dtype=float32>

张量的数据类型

>>> m_shape.dtype
tf.int32
>>> type_float = tf.constant(3.123456789, tf.float32)
>>> type_int = tf.cast(type_float, dtype=tf.int32)
>>> type_float.dtype
tf.float32
>>> type_int.dtype
tf.int32

操作

  • tf.add(a, b)
  • tf.substract(a, b)
  • tf.multiply(a, b)
  • tf.div(a, b)
  • tf.pow(a, b)
  • tf.exp(a)
  • tf.sqrt(a)
>> tensor_a = tf.constant([[1,2]], dtype = tf.int32)
>>> tensor_b = tf.constant([[3, 4]], dtype = tf.int32)
>>> tensor_add = tf.add(tensor_a, tensor_b)
>>> tensor_add
<tf.Tensor 'Add:0' shape=(1, 2) dtype=int32>
>>> tensor_multiply = tf.multiply(tensor_a, tensor_b)
>>> tensor_multiply
<tf.Tensor 'Mul:0' shape=(1, 2) dtype=int32>

参考资料

变量

tf.get_variable(name = "", values, dtype, initializer)
argument
- `name = ""`: Name of the variable
- `values`: Dimension of the tensor
- `dtype`: Type of data. Optional
- `initializer`: How to initialize the tensor. Optional
If initializer is specified, there is no need to include the `values` as the shape of `initializer` is used.
>>> var = tf.get_variable("var", [1, 2])
>>> var.shape
TensorShape([Dimension(1), Dimension(2)])
>>> var_init_1 = tf.get_variable("var_init_1", [1, 2], dtype=tf.int32,  initializer=tf.zeros_initializer)
>>> var_init_1.shape
TensorShape([Dimension(1), Dimension(2)])
>>> tensor_const = tf.constant([[10, 20], [30, 40]])
>>> var_init_2 = tf.get_variable("var_init_2", dtype=tf.int32,  initializer=tensor_const)
>>> print(var_init_2.shape)
(2, 2)

图片.png

占位符

tf.placeholder(dtype,shape=None,name=None )
arguments:
- `dtype`: Type of data
- `shape`: dimension of the placeholder. Optional. By default, shape of the data
- `name`: Name of the placeholder. Optional         
>>> data_placeholder_a = tf.placeholder(tf.float32, name = "data_placeholder_a")
>>> print(data_placeholder_a)
Tensor("data_placeholder_a:0", dtype=float32)

Session

  • Graph TensorFlow的基础。 所有数学运算(ops)都在Graph中执行。 您可以将Graph想象为每个操作都已完成的项目。 节点代表这些操作,它们可以吸收或创建新的张量。

  • Tensor

张量表示在操作之间进行的数据。 您之前看到过如何初始化张量。 常量和变量之间的差异是变量的初始值将随时间变化。

  • Session

会话将从图中执行操作。 要使用张量值来提供图形,您需要打开会话。 在会话内,运行操作以创建输出。

>>> x = tf.constant([2])
>>> y = tf.constant([4])
>>> multiply = tf.multiply(x, y)
>>> sess = tf.Session()
2018-11-21 22:41:34.184786: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
>>> result_1 = sess.run(multiply)
>>> print(result_1)
[8]
>>> sess.close()
>>> with tf.Session() as sess:
...     result_2 = multiply.eval()
...     print(result_2)
...
[8]
>>> sess = tf.Session()
>>> print(sess.run(r1))
1
>>> print(sess.run(r2_matrix))
[[1 2]
 [3 4]]
>>> print(sess.run(r3_matrix))
[[[1 2]
  [3 4]
  [5 6]]]
>>> sess.run(tf.global_variables_initializer())
>>> print(sess.run(var))
[[ 0.5487809 -0.9846178]]
>>> print(sess.run(var_init_1))
[[0 0]]
>>> print(sess.run(var_init_2))
[[10 20]
 [30 40]]
>>> import numpy as np
>>> power_a = tf.pow(data_placeholder_a, 2)
>>> with tf.Session() as sess:
...     data = np.random.rand(1, 10)
...     print(sess.run(power_a, feed_dict={data_placeholder_a: data}))  # Will succeed.
...
[[0.00214566 0.22329086 0.03267581 0.97980934 0.10616333 0.08555447
  0.06780323 0.23336452 0.10076617 0.01539159]]

图片.png

图片.png

x = tf.get_variable("x", dtype=tf.int32,  initializer=tf.constant([5]))
z = tf.get_variable("z", dtype=tf.int32,  initializer=tf.constant([6]))
c = tf.constant([5], name = "constant")
square = tf.constant([2], name =    "square")
f = tf.multiply(x, z) + tf.pow(x, square) + z + c
init = tf.global_variables_initializer() # prepare to initialize all variables
with tf.Session() as sess:
    init.run() # Initialize x and y  
    function_result = f.eval()
    print(function_result)

执行结果: [66]

图片.png

参考资料

links