tensorflow基本语法

 
 

tensorflow基本语法

内容主要来自tensorflow英文官网

1:tensor--张量

3 # a rank 0 tensor; a scalar with shape []
[1., 2., 3.] # a rank 1 tensor; a vector with shape [3]
[[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]
熟悉numpy的这一部分应该不会陌生,其实就和numpy的ndarray一致,就是多维数组。

2:可计算图(computational graph)

一般的神经网络就如上图,上面说是最简单的单个计算节点的神经网络。 tensorflow需要使用两个步骤来完成神经网络的训练。首先,构建图。然后,运行图。 正如上面的神经网络的图,存在x和1等节点,也存在橙色圆圈代表的节点,代表运算h(x)=f(W^t*x+b)。这些节点都必须通过tensorflow首先构建。比如说
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
output:Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32)
可以看到这里输出的是一些参数信息,因为这里没有运行图。前面说过,tensorflow分为独立的两步,只有运行之后才会出结果
sess = tf.Session()
print(sess.run([node1, node2]))
结果才是[3.0,4.0]。 tensorflow里面所有的运算也是节点,也需要构建点然后运行才能得到结果。比如说
from __future__ import print_function
node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess.run(node3))
node3: Tensor("Add:0", shape=(), dtype=float32)
sess.run(node3): 7.0
上面的结点都是常量节点以及基于常量节点的运算,根据神经网络的结构图就可以知道,还存在一些其他节点。比如说x,在构建的时候不知道x的值是多少,需要后来进行填充。
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b  # + provides a shortcut for tf.add(a, b)
print(sess.run(adder_node, {a: 3, b: 4.5}))
print(sess.run(adder_node, {a: [1, 3], b: [2, 4]}))
7.5
[ 3.  7.]
 
还可以进一步的操作,比如说
add_and_triple = adder_node * 3.
print(sess.run(add_and_triple, {a: 3, b: 4.5}))
输出就是22.5,可以看到,这里的输入参数依旧是a和b,其实这里的参数可以是adder_node 因为整个拓扑图是确定的,虽然定义的adder_node是一个计算节点,但是本身在节点直接流动的本来就是数据,计算a+b的结果赋值给adder_node和给他赋值效果是一样的。 因此,计算图里面运行节点的时候可以从任意节点当做参数赋值,而不用一定是输入节点。 除了上面讲到的节点之外,还有Variable节点。 Variables allow us to add trainable parameters to a graph. They are constructed with a type and initial value。Variable节点可以更新值,主要用于模型里面的一些参数,这些参数需要不断的更新来训练模型。placehoder其实可不是固定不变的,但是placeholder多用于一些实际的点,什么输入输出之类的,而Variable用于一些参数,另外,placeholder可以在run的时候输入值,而Variable不可以。Constant只要初始化,那么久不能进行改变。
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W*x + b
Constant在使用tf.Constant的时候就进行初始化,而Variable不是,Variable需要使用
init = tf.global_variables_initializer()
sess.run(init)
才能初始化,一般Variable提供类型以及初始值来进行构造。It is important to realize  init is a handle to the TensorFlow sub-graph that initializes all the global variables. Until we call  sess.run, the variables are uninitialized. 只有run了init之后才初始化。
print(sess.run(linear_model, {x: [1, 2, 3, 4]}))
[ 0.          0.30000001  0.60000002  0.90000004]
在得到线性模型之后,需要进行优化,一般的优化方法把汗梯度下降,梯度上升,牛顿法等等
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
其中,reduce_sum就是把所有的元素相加,得到一个标量,但是这仅仅是不加其余参数的情况下,加了axis参数的话就可以在指定维度上面进行相加。详情可以查看https://www.tensorflow.org/api_docs/python/tf/reduce_sum 如果要改变变量的值的话,需要使用assign方法。
fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}))
A complete discussion of machine learning is out of the scope of this tutorial. However, TensorFlow provides optimizers that slowly change each variable in order to minimize the loss function. The simplest optimizer is gradient descent. It modifies each variable according to the magnitude of the derivative of loss with respect to that variable. In general, computing symbolic derivatives manually is tedious and error-prone. Consequently, TensorFlow can automatically produce derivatives given only a description of the model using the function tf.gradients. For simplicity, optimizers typically do this for you. 上面这段讲的非常的细致,就照搬下来了。因为机器学习算法很多都需要进行优化,因此就涉及很多优化方法,比如上面提到的梯度方法和牛顿方法,梯度方法包含很多,比如说批梯度,随机梯度等等。因为人为的计算有可能出错而且很繁琐,所以tensorflow把这些优化方法给实现了。
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init) # reset values to incorrect defaults.
for i in range(1000):
  sess.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})

print(sess.run([W, b]))
下面是最简单的线性回归的代码:
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
上面的代码非常的简单,把tensorflow的流程讲的非常的好。 输出是
W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11
存在一个tf.estimator,它可以说是一个构件,它里面实现了一些诸如线性回归,线性分类等机器学习方法,可以直接使用。具体查看https://www.tensorflow.org/get_started/get_started

查看原文: http://www.hahaszj.top/%e6%b7%b1%e5%ba%a6%e5%ad%a6%e4%b9%a0/tensorflow%e5%9f%ba%e6%9c%ac%e8%af%ad%e6%b3%95/189

猜你喜欢

转载自blog.csdn.net/Flyingzhan/article/details/78632296
今日推荐