机器学习进阶笔记之一 | TensorFlow安装与入门

开发 开发工具 深度学习
TensorFlow是Google基于DistBelief进行研发的第二代人工智能学习系统,被广泛用于语音识别或图像识别等多项机器深度学习领域。其命名来源于本身的运行原理。Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow代表着张量从图象的一端流动到另一端计算过程,是将复杂的数据结构传输至人工智能神经网中进行分析和处理的过程。

[[185581]]

引言

TensorFlow是Google基于DistBelief进行研发的第二代人工智能学习系统,被广泛用于语音识别或图像识别等多项机器深度学习领域。其命名来源于本身的运行原理。Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow代表着张量从图象的一端流动到另一端计算过程,是将复杂的数据结构传输至人工智能神经网中进行分析和处理的过程。

TensorFlow完全开源,任何人都可以使用。可在小到一部智能手机、大到数千台数据中心服务器的各种设备上运行。

『机器学习进阶笔记』系列是将深入解析TensorFlow系统的技术实践,从零开始,由浅入深,与大家一起走上机器学习的进阶之路。

CUDA与TensorFlow安装

按以往经验,TensorFlow安装一条pip命令就可以解决,前提是有fq工具,没有的话去找找墙内别人分享的地址。而坑多在安装支持gpu,需预先安装英伟达的cuda,这里坑比较多,推荐使用ubuntu deb的安装方式来安装cuda,run.sh的方式总感觉有很多问题,cuda的安装具体可以参考。 注意链接里面的tensorflow版本是以前的,tensorflow 现在官方上的要求是cuda7.5+cudnnV4,请在安装的时候注意下。

Hello World

  1. import tensorflow as tf 
  2.  hello = tf.constant('Hello, TensorFlow!'
  3.  sess = tf.Session() 
  4.  print sess.run(hello) 

首先,通过tf.constant创建一个常量,然后启动Tensorflow的Session,调用sess的run方法来启动整个graph。

接下来我们做下简单的数学的方法:

  1. import tensorflow as tf 
  2.  a = tf.constant(2) 
  3.  b = tf.constant(3) 
  4.  with tf.Session() as sess: 
  5.      print "a=2, b=3" 
  6.      print "Addition with constants: %i" % sess.run(a+b) 
  7.      print "Multiplication with constants: %i" % sess.run(a*b) 
  8.  # output 
  9.  a=2, b=3 
  10.  Addition with constants: 5 
  11.  Multiplication with constants: 6 

接下来用tensorflow的placeholder来定义变量做类似计算:

placeholder的使用见https://www.tensorflow.org/versions/r0.8/api_docs/python/io_ops.html#placeholder

  1. import tensorflow as tf 
  2. a = tf.placeholder(tf.int16) 
  3. b = tf.placeholder(tf.int16) 
  4. add = tf.add(a, b) 
  5. mul = tf.mul(a, b) 
  6. with tf.Session() as sess: 
  7.     # Run every operation with variable input 
  8.     print "Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}) 
  9.     print "Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}) 
  10. output
  11. Addition with variables: 5 
  12. Multiplication with variables: 6 
  13. matrix1 = tf.constant([[3., 3.]]) 
  14. matrix2 = tf.constant([[2.],[2.]]) 
  15. with tf.Session() as sess: 
  16.     result = sess.run(product) 
  17.     print result 

线性回归

以下代码来自GitHub - aymericdamien/TensorFlow-Examples: TensorFlow Tutorial and Examples for beginners,仅作学习用

  1. activation = tf.add(tf.mul(X, W), b) 
  2.  
  3. # Minimize the squared errors 
  4. cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples) #L2 loss 
  5. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #Gradient descent 
  6.  
  7. # Initializing the variables 
  8. init = tf.initialize_all_variables() 
  9.  
  10. # Launch the graph 
  11. with tf.Session() as sess: 
  12.     sess.run(init) 
  13.  
  14.     # Fit all training data 
  15.     for epoch in range(training_epochs): 
  16.         for (x, y) in zip(train_X, train_Y): 
  17.             sess.run(optimizer, feed_dict={X: x, Y: y}) 
  18.  
  19.         #Display logs per epoch step 
  20.         if epoch % display_step == 0: 
  21.             print "Epoch:"'%04d' % (epoch+1), "cost=", \ 
  22.                 "{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \ 
  23.                 "W=", sess.run(W), "b=", sess.run(b) 
  24.  
  25.     print "Optimization Finished!" 
  26.     print "cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), \ 
  27.           "W=", sess.run(W), "b=", sess.run(b) 
  28.  
  29.     #Graphic display 
  30.     plt.plot(train_X, train_Y, 'ro', label='Original data'
  31.     plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line'
  32.     plt.legend() 
  33.     plt.show() 

逻辑回归

  1. import tensorflow as tf 
  2.  # Import MINST data 
  3.  from tensorflow.examples.tutorials.mnist import input_data 
  4.  mnist = input_data.read_data_sets("/tmp/data/", one_hot=True
  5.  
  6.  # Parameters 
  7.  learning_rate = 0.01 
  8.  training_epochs = 25 
  9.  batch_size = 100 
  10.  display_step = 1 
  11.  
  12.  # tf Graph Input 
  13.  x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784 
  14.  y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes 
  15.  
  16.  # Set model weights 
  17.  W = tf.Variable(tf.zeros([784, 10])) 
  18.  b = tf.Variable(tf.zeros([10])) 
  19.  
  20.  # Construct model 
  21.  pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax 
  22.  
  23.  # Minimize error using cross entropy 
  24.  cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1)) 
  25.  # Gradient Descent 
  26.  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 
  27.  
  28.  # Initializing the variables 
  29.  init = tf.initialize_all_variables() 
  30.  
  31.  # Launch the graph 
  32.  with tf.Session() as sess: 
  33.      sess.run(init) 
  34.  
  35.      # Training cycle 
  36.      for epoch in range(training_epochs): 
  37.          avg_cost = 0. 
  38.          total_batch = int(mnist.train.num_examples/batch_size) 
  39.          # Loop over all batches 
  40.          for i in range(total_batch): 
  41.              batch_xs, batch_ys = mnist.train.next_batch(batch_size) 
  42.              # Run optimization op (backprop) and cost op (to get loss value) 
  43.              _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, 
  44.                                                            y: batch_ys}) 
  45.              # Compute average loss 
  46.              avg_cost += c / total_batch 
  47.          # Display logs per epoch step 
  48.          if (epoch+1) % display_step == 0: 
  49.              print "Epoch:"'%04d' % (epoch+1), "cost=""{:.9f}".format(avg_cost) 
  50.  
  51.      print "Optimization Finished!" 
  52.  
  53.      # Test model 
  54.      correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) 
  55.      # Calculate accuracy 
  56.      accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
  57.      print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}) 
  58.  
  59.      # result : 
  60.      Epoch: 0001 cost= 29.860467369 
  61.      Epoch: 0002 cost= 22.001451784 
  62.      Epoch: 0003 cost= 21.019925554 
  63.      Epoch: 0004 cost= 20.561320320 
  64.      Epoch: 0005 cost= 20.109135756 
  65.      Epoch: 0006 cost= 19.927862290 
  66.      Epoch: 0007 cost= 19.548687116 
  67.      Epoch: 0008 cost= 19.429119071 
  68.      Epoch: 0009 cost= 19.397068211 
  69.      Epoch: 0010 cost= 19.180813479 
  70.      Epoch: 0011 cost= 19.026808132 
  71.      Epoch: 0012 cost= 19.057875510 
  72.      Epoch: 0013 cost= 19.009575057 
  73.      Epoch: 0014 cost= 18.873240641 
  74.      Epoch: 0015 cost= 18.718575359 
  75.      Epoch: 0016 cost= 18.718761925 
  76.      Epoch: 0017 cost= 18.673640560 
  77.      Epoch: 0018 cost= 18.562128253 
  78.      Epoch: 0019 cost= 18.458205289 
  79.      Epoch: 0020 cost= 18.538211225 
  80.      Epoch: 0021 cost= 18.443384213 
  81.      Epoch: 0022 cost= 18.428727668 
  82.      Epoch: 0023 cost= 18.304270616 
  83.      Epoch: 0024 cost= 18.323529782 
  84.      Epoch: 0025 cost= 18.247192113 
  85.      Optimization Finished! 
  86.      (10000, 784) 
  87.      Accuracy 0.9206 

这里有个小插曲,ipython notebook在一个notebook打开时,一直在占用GPU资源,可能是之前有一个notebook一直打开着,然后占用着GPU资源,然后在计算Accuracy的”InternalError: Dst tensor is not initialized.” 然后找了github上面也有这个问题InternalError: Dst tensor is not initialized.,可以肯定是GPU的memory相关的问题,所以就尝试加上tf.device(‘/cpu:0’),将Accuracy这步拉到cpu上计算,但是又出现OOM的问题,***nvidia-smi时,发现有一个python脚本一直占用3g多的显存,把它kill之后恢复了,之前还比较吐槽怎么可能10000*784个float就把显存撑爆呢,原来是自己的问题。

这里逻辑回归,model是一个softmax函数用来做多元分类,大概意思是选择10当中***预测概率***作为最终的分类。

其实基本的tensorflow没有特别好讲的,语法的课程什么可以去看看基本的文档,之后我会找一点经典有趣的tensorflow的代码应用来看看,毕竟『show me the code 』才是程序猿应有的态度。

【本文是51CTO专栏机构作者“大U的技术课堂”的原创文章,转载请通过微信公众号(ucloud2012)联系作者】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO
相关推荐

2018-03-15 11:50:53

机器学习入门Tensorflow

2021-01-11 05:18:11

机器学习

2022-11-04 11:52:36

机器学习

2011-04-12 14:28:52

XML

2022-02-16 15:32:58

FlexUI框架容器组件

2016-11-01 15:32:43

深度学习

2021-11-02 09:40:50

TensorFlow机器学习人工智能

2019-11-21 14:01:37

Python数据挖掘机器学习

2018-04-23 11:11:52

数据挖掘机器学习Python

2018-12-29 08:00:00

机器学习TensorFlowKubeflow

2017-05-17 08:24:08

TensorFlow机器学习线性回归

2022-06-09 16:48:10

TensorFlow机器学习

2016-11-28 09:24:08

Python内存技巧

2020-08-25 10:30:59

TensorFlow数据机器学习

2019-03-08 09:28:42

Google 开源技术

2018-09-10 14:38:16

编程语言TensorFlow.机器学习

2020-05-19 14:29:50

机器学习TensorFlow

2010-07-07 08:33:09

SQL Server学

2017-03-02 14:18:14

Go机器学习Gorgonia

2013-12-02 13:59:22

jQueryUI
点赞
收藏

51CTO技术栈公众号