2017年7月11日星期二

tensorflow初学习

(参考tensotflow官方文档,只做个人学习所用,原文来自于:https://www.tensorflow.org/get_started/get_started)
1.导入tensorflow (tensorflow的所有资源)
   import tensorflow as tf

2.tensorflow流程

   2.1 Building the computational graph
   2.2 Running the computational graph

3.开始,创建一个tf的常量,如果定义为常量,则初始化过后,他们的值就不能再被改变
  node1 = tf.constant(3.0,dtype=tf.float32)
  node2 = tf.constant(4.0) #also tf.float32
  print(node1,node2)

 它只会输出节点信息,而不会输出结点中的值,如果我们想要他输出实际结点中的值,必须在session中运行计算图。会话封装了tensorflow运行时的控制和状态。
下面创建一个session,并调用他的run方法
  sess = tf.Session()
  print(sess.run([node1,node2]))

>>[3.0,4.0]

4.创建更复杂的图
  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

5.问题来了,如果你想输入输出的时候肿么办呢?用placeholders
  a = tf.placeholder(tf.float32)
  b = tf.placeholder(tf.float32)
  adder_node = a + b   # + is equal to 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]



 6.让图变得更复杂
add_and_tripe = add_node * 3
print(sess.run(add_and_triple),{a:3,b:4.5})


 7.在机器学习中,我们通常会想要一个可以接受任意输入的模型,比如上面的一个。 为了使模型可训练,我们需要能够修改图形以获得具有相同输入的新输出。 变量允许我们向图表添加可训练的参数。 它们的构造类型和初始值:
  W = tf.Variable([.3],dtype=tf.float32)
   b = tf.Variable([-.3],dtype=tf.float32)
   x = tf.placeholder(tf.float32)
   linear_model = W*x + b 

当定义tf.constant的时候,常量直接被初始化并且值不会再发生变化;但是当变量被声明时,调用tf.Variable,这时候变量没有被赋值,为了给变量赋值,必须调用下面指定操作

  init = tf.global_variables_initializer()
  sess.run(init)

在我们运行sess.run(init)之前,变量都是未被赋值的(就是值已经定义好了,但是却没有给定赋值),运行过后因为x 是一个placeholder,我们可以评估linear_model
  print(sess.run(linear_model,{x:[1,2,3,4]}))

 >>[ 0.          0.30000001  0.60000002  0.90000004]

损失函数测量当前模型与提供的数据之间的距离。 我们将使用线性回归的标准损耗模型,它将当前模型和提供的数据之间的三角形的平方相加。 linear_model - y创建一个向量,其中每个元素都是对应的示例的错误增量。 我们称tf.square为该错误。 然后,我们求和所有平方误差,创建一个单一的标量,使用tf.reduce_sum抽象出所有示例的错误:

 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]}))

>>(0-0)^2+(0.3--1)^2+(0.6--2)^2+(0.9--3)^2=23.66

最后,输出会变成0.我们猜测他是在运行过程中为W和b找到了最好的值,使其与之比配。

8.tf.train API(optimizer的使用)
TensorFlow提供了optimizer,他缓慢地更改每个变量,以便最小化损失函数。 最简单的optimizer是梯度下降。 它根据相对于该变量的损失导数的大小修改每个变量。TensorFlow可以使用函数tf.gradients自动生成仅给出模型描述的导数。 为了简单起见,optimizer通常为您做这个。 例如,
  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]))

>>[array([-0.9999969], dtype=float32), array([ 0.99999082],dtype=float32)]


 8.1 .完整的程序
import numpy as np
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)) 

>>W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11

可以看出,loss是一个接近于0非常小的值,重复的运行也许会得到不同的loss,因为每次的随机初始化是不同的值
(Ques:为什么是随机初始化的?不是直接初始化为w为0.3和b为-0.3吗)

9 tf.contrib.learn
  tf.contib.learn是一个tensorflow高层学习库,它被用来简化机器学习 ,包括下面几部分:
     9.1 running training loops
     9.2 running evaluation loops
     9.3 managing data sets
     9.4 managing feeding
tf.contrib.learn定义了许多公共的模型

基础使用:(暂时没看)
import tensorflow as tf
# NumPy is often used to load, manipulate and preprocess data.
import numpy as np

# Declare list of features. We only have one real-valued feature. There are many
# other types of columns that are more complicated and useful.
features = [tf.contrib.layers.real_valued_column("x", dimension=1)]

# An estimator is the front end to invoke training (fitting) and evaluation
# (inference). There are many predefined types like linear regression,
# logistic regression, linear classification, logistic classification, and
# many neural network classifiers and regressors. The following code
# provides an estimator that does linear regression.
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)

# TensorFlow provides many helper methods to read and set up data sets.
# Here we use two data sets: one for training and one for evaluation
# We have to tell the function how many batches
# of data (num_epochs) we want and how big each batch should be.
x_train = np.array([1., 2., 3., 4.])
y_train = np.array([0., -1., -2., -3.])
x_eval = np.array([2., 5., 8., 1.])
y_eval = np.array([-1.01, -4.1, -7, 0.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x_train}, y_train,
                                              batch_size=4,
                                              num_epochs=1000)
eval_input_fn = tf.contrib.learn.io.numpy_input_fn(
    {"x":x_eval}, y_eval, batch_size=4, num_epochs=1000)

# We can invoke 1000 training steps by invoking the  method and passing the
# training data set.
estimator.fit(input_fn=input_fn, steps=1000)

# Here we evaluate how well our model did.
train_loss = estimator.evaluate(input_fn=input_fn)
eval_loss = estimator.evaluate(input_fn=eval_input_fn)
print("train loss: %r"% train_loss)
print("eval loss: %r"% eval_loss)


 

没有评论:

发表评论

leetcode 17

17.   Letter Combinations of a Phone Number Medium Given a string containing digits from   2-9   inclusive, return all possible l...