Tensorflow Ubuntu16.04上安装及CPU运行Tensorboard、CNN、RNN图文教程(转载)

转载自http://blog.csdn.net/wizen641372472/article/details/72675549

Tensorflow Ubuntu16.04上安装及CPU运行tensorboard、CNN、RNN图文教程

Ubuntu16.04系统安装

       ①安装VMware Workstation,把下载好的懒人版系统Tensorflow_Ubuntu16.04.rar解压,用VMware Workstation打开,如图:
       
       ②开机密码:111111
                                                

  • 建议使用双系统的Ubuntu,因为虚拟机有点卡,如果你用的是懒人版的备份系统,你可以直接跳到tensorflow测试运行步骤了。

python3.5安装

1.ubuntu16.04系统会自带python2.7,请不要卸载它。不同版本的Python可以共存在一个系统上。Ctrl+Alt+T打开终端输入命令:python


可查看当前版本(exit()退出python编辑)。若卸载之后,桌面系统会被影响。

2.依次输入命令并回车(如有密码验证,输入密码,回车):

  • $ sudo add-apt-repository ppa:fkrull/deadsnakes

  • $ sudo apt-get update

  • $ sudo apt-get install python3.5
  • $ sudo cp /usr/bin/python /usr/bin/python_bak,先备份
  • $ sudo rm /usr/bin/python,删除
  • $ sudo ln -s /usr/bin/python3.5 /usr/bin/python,默认设置成python3.5,重建软链接这样在终端中输入python默认就是 3.5版本了

Tensorflow安装

1.安装python3-pip

$ sudo apt-get install python3-pip 


输入后会出现一串代码,然后问是否继续,输入y回车。


2.安装tensorflow

sudo pip3 install tensorflow

(1)若出现红色可选择重复此步操作或下载安装:



  • 网盘下载: 链接:http://pan.baidu.com/s/1eSOQ5zG 密码:aqkr

(2)把下载好的文件放到home目录下,可通过ls查看到



①执行安装tensorflow,若出现红色可选择重复此步操作。

$  sudo pip3 install tensorflow-1.2.0rc0-cp35-cp35m-manylinux1_x86_64.whl 


安装成功界面如下:


安装Komodo编辑工具(类似于windows下的notepad++)

1.下载
2.把下载好的文件放到home目录下,解压该文件(在文件上右击执行“提取到此处”),可通过ls查看到



①打开Komodo-Edit-10.2.1-17670-linux-x86_64文件夹

$ cd Komodo-Edit-10.2.1-17670-linux-x86_64/


②输入  sudo ./install.sh  安装Komodo-Edit,安装完成后,搜索Komodo”即可打开该软件


Tensorflow测试运行


1.tensorboard.py


  1. """ 
  2. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly. 
  3. """  
  4. from __future__ import print_function  
  5. import tensorflow as tf  
  6. import numpy as np  
  7.   
  8.   
  9. def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):  
  10.     # add one more layer and return the output of this layer  
  11.     layer_name = 'layer%s' % n_layer  
  12.     with tf.name_scope(layer_name):  
  13.         with tf.name_scope('weights'):  
  14.             Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')  
  15.             tf.summary.histogram(layer_name + '/weights', Weights)  
  16.         with tf.name_scope('biases'):  
  17.             biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')  
  18.             tf.summary.histogram(layer_name + '/biases', biases)  
  19.         with tf.name_scope('Wx_plus_b'):  
  20.             Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)  
  21.         if activation_function is None:  
  22.             outputs = Wx_plus_b  
  23.         else:  
  24.             outputs = activation_function(Wx_plus_b, )  
  25.         tf.summary.histogram(layer_name + '/outputs', outputs)  
  26.     return outputs  
  27.   
  28.   
  29. # Make up some real data  
  30. x_data = np.linspace(-11300)[:, np.newaxis]  
  31. noise = np.random.normal(00.05, x_data.shape)  
  32. y_data = np.square(x_data) - 0.5 + noise  
  33.   
  34. # define placeholder for inputs to network  
  35. with tf.name_scope('inputs'):  
  36.     xs = tf.placeholder(tf.float32, [None1], name='x_input')  
  37.     ys = tf.placeholder(tf.float32, [None1], name='y_input')  
  38.   
  39. # add hidden layer  
  40. l1 = add_layer(xs, 110, n_layer=1, activation_function=tf.nn.relu)  
  41. # add output layer  
  42. prediction = add_layer(l1, 101, n_layer=2, activation_function=None)  
  43.   
  44. # the error between prediciton and real data  
  45. with tf.name_scope('loss'):  
  46.     loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),  
  47.                                         reduction_indices=[1]))  
  48.     tf.summary.scalar('loss', loss)  
  49.   
  50. with tf.name_scope('train'):  
  51.     train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  
  52.   
  53. sess = tf.Session()  
  54. merged = tf.summary.merge_all()  
  55.   
  56. writer = tf.summary.FileWriter("logs/", sess.graph)  
  57.   
  58. init = tf.global_variables_initializer()  
  59. sess.run(init)  
  60.   
  61. for i in range(1000):  
  62.     sess.run(train_step, feed_dict={xs: x_data, ys: y_data})  
  63.     if i % 50 == 0:  
  64.         result = sess.run(merged,  
  65.                           feed_dict={xs: x_data, ys: y_data})  
  66.         writer.add_summary(result, i)  
  67.   
  68. # direct to the local dir and run this in terminal:  
  69. # $ tensorboard --logdir logs  

①在home目录建立tensorflower文件夹,把tensorboard.py放入该目录下,运行如下命令:

$ cd tensorflow/
$ python  tensorboard.py 

②此时tensorflow文件夹下将产生一个logs文件夹,然后输入命令能产生查看tensorboard的网址:

$ tensorboard --logdir logs

运行如下图所示:



③打开  http://ubuntu:6006即可查看,loss曲线:


④神经网络图:

⑤每一层的weights和biases变化情况


2.CNN.py


  1. """ 
  2. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly. 
  3. """  
  4. from __future__ import print_function  
  5. import tensorflow as tf  
  6. from tensorflow.examples.tutorials.mnist import input_data  
  7. # number 1 to 10 data  
  8. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)  
  9.   
  10. def compute_accuracy(v_xs, v_ys):  
  11.     global prediction  
  12.     y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})  
  13.     correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))  
  14.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  15.     result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})  
  16.     return result  
  17.   
  18. def weight_variable(shape):  
  19.     initial = tf.truncated_normal(shape, stddev=0.1)  
  20.     return tf.Variable(initial)  
  21.   
  22. def bias_variable(shape):  
  23.     initial = tf.constant(0.1, shape=shape)  
  24.     return tf.Variable(initial)  
  25.   
  26. def conv2d(x, W):  
  27.     # stride [1, x_movement, y_movement, 1]  
  28.     # Must have strides[0] = strides[3] = 1  
  29.     return tf.nn.conv2d(x, W, strides=[1111], padding='SAME')  
  30.   
  31. def max_pool_2x2(x):  
  32.     # stride [1, x_movement, y_movement, 1]  
  33.     return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')  
  34.   
  35. # define placeholder for inputs to network  
  36. xs = tf.placeholder(tf.float32, [None784])/255.   # 28x28  
  37. ys = tf.placeholder(tf.float32, [None10])  
  38. keep_prob = tf.placeholder(tf.float32)  
  39. x_image = tf.reshape(xs, [-128281])  
  40. # print(x_image.shape)  # [n_samples, 28,28,1]  
  41.   
  42. ## conv1 layer ##  
  43. W_conv1 = weight_variable([5,51,32]) # patch 5x5, in size 1, out size 32  
  44. b_conv1 = bias_variable([32])  
  45. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32  
  46. h_pool1 = max_pool_2x2(h_conv1)                                         # output size 14x14x32  
  47.   
  48. ## conv2 layer ##  
  49. W_conv2 = weight_variable([5,53264]) # patch 5x5, in size 32, out size 64  
  50. b_conv2 = bias_variable([64])  
  51. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64  
  52. h_pool2 = max_pool_2x2(h_conv2)                                         # output size 7x7x64  
  53.   
  54. ## fc1 layer ##  
  55. W_fc1 = weight_variable([7*7*641024])  
  56. b_fc1 = bias_variable([1024])  
  57. # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]  
  58. h_pool2_flat = tf.reshape(h_pool2, [-17*7*64])  
  59. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  
  60. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
  61.   
  62. ## fc2 layer ##  
  63. W_fc2 = weight_variable([102410])  
  64. b_fc2 = bias_variable([10])  
  65. prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  
  66.   
  67.   
  68. # the error between prediction and real data  
  69. cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),  
  70.                                               reduction_indices=[1]))       # loss  
  71. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
  72.   
  73. sess = tf.Session()  
  74. # important step  
  75. # tf.initialize_all_variables() no long valid from  
  76. # 2017-03-02 if using tensorflow >= 0.12  
  77. if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:  
  78.     init = tf.initialize_all_variables()  
  79. else:  
  80.     init = tf.global_variables_initializer()  
  81. sess.run(init)  
  82.   
  83. for i in range(1000):  
  84.     batch_xs, batch_ys = mnist.train.next_batch(100)  
  85.     sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})  
  86.     if i % 50 == 0:  
  87.         print(compute_accuracy(  
  88.             mnist.test.images, mnist.test.labels))  



3.RNN.py


  1. """ 
  2. This code is a modified version of the code from this link: 
  3. https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py 
  4.  
  5. His code is a very good one for RNN beginners. Feel free to check it out. 
  6. """  
  7. import tensorflow as tf  
  8. from tensorflow.examples.tutorials.mnist import input_data  
  9.   
  10. # set random seed for comparing the two result calculations  
  11. tf.set_random_seed(1)  
  12.   
  13. # this is data  
  14. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)  
  15.   
  16. # hyperparameters  
  17. lr = 0.001      #learning rate  
  18. training_iters = 100000  
  19. batch_size = 128  
  20.   
  21. n_inputs = 28   # MNIST data input (img shape: 28*28)  
  22. n_steps = 28    # time steps  
  23. n_hidden_units = 128   # neurons in hidden layer  
  24. n_classes = 10      # MNIST classes (0-9 digits)  
  25.   
  26. # tf Graph input  
  27. x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])  
  28. y = tf.placeholder(tf.float32, [None, n_classes])  
  29.   
  30. # Define weights  
  31. weights = {  
  32.     # (28, 128)  
  33.     'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),  
  34.     # (128, 10)  
  35.     'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))  
  36. }  
  37. biases = {  
  38.     # (128, )  
  39.     'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),  
  40.     # (10, )  
  41.     'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))  
  42. }  
  43.   
  44.   
  45. def RNN(X, weights, biases):  
  46.     # hidden layer for input to cell  
  47.     ########################################  
  48.   
  49.     # transpose the inputs shape from  
  50.     # X ==> (128 batch * 28 steps, 28 inputs)  
  51.     X = tf.reshape(X, [-1, n_inputs])  
  52.   
  53.     # into hidden  
  54.     # X_in = (128 batch * 28 steps, 128 hidden)  
  55.     X_in = tf.matmul(X, weights['in']) + biases['in']  
  56.     # X_in ==> (128 batch, 28 steps, 128 hidden)  
  57.     X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])  
  58.   
  59.     # cell  
  60.     ##########################################  
  61.   
  62.     # basic LSTM Cell.  
  63.     if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:  
  64.         cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)  
  65.     else:  
  66.         cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units)  
  67.     # lstm cell is divided into two parts (c_state, h_state)  
  68.     init_state = cell.zero_state(batch_size, dtype=tf.float32)  
  69.   
  70.     # You have 2 options for following step.  
  71.     # 1: tf.nn.rnn(cell, inputs);  
  72.     # 2: tf.nn.dynamic_rnn(cell, inputs).  
  73.     # If use option 1, you have to modified the shape of X_in, go and check out this:  
  74.     # https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py  
  75.     # In here, we go for option 2.  
  76.     # dynamic_rnn receive Tensor (batch, steps, inputs) or (steps, batch, inputs) as X_in.  
  77.     # Make sure the time_major is changed accordingly.  
  78.     outputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)  
  79.   
  80.     # hidden layer for output as the final results  
  81.     #############################################  
  82.     # results = tf.matmul(final_state[1], weights['out']) + biases['out']  
  83.   
  84.     # # or  
  85.     # unpack to list [(batch, outputs)..] * steps  
  86.     if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:  
  87.         outputs = tf.unpack(tf.transpose(outputs, [102]))    # states is the last outputs  
  88.     else:  
  89.         outputs = tf.unstack(tf.transpose(outputs, [1,0,2]))  
  90.     results = tf.matmul(outputs[-1], weights['out']) + biases['out']    # shape = (128, 10)  
  91.   
  92.     return results  
  93.   
  94.   
  95. pred = RNN(x, weights, biases)  
  96. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))  
  97. train_op = tf.train.AdamOptimizer(lr).minimize(cost)  
  98.   
  99. correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))  
  100. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))  
  101.   
  102. with tf.Session() as sess:  
  103.     # tf.initialize_all_variables() no long valid from  
  104.     # 2017-03-02 if using tensorflow >= 0.12  
  105.     if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:  
  106.         init = tf.initialize_all_variables()  
  107.     else:  
  108.         init = tf.global_variables_initializer()  
  109.     sess.run(init)  
  110.     step = 0  
  111.     while step * batch_size < training_iters:  
  112.         batch_xs, batch_ys = mnist.train.next_batch(batch_size)  
  113.         batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])  
  114.         sess.run([train_op], feed_dict={  
  115.             x: batch_xs,  
  116.             y: batch_ys,  
  117.         })  
  118.         if step % 20 == 0:  
  119.             print(sess.run(accuracy, feed_dict={  
  120.             x: batch_xs,  
  121.             y: batch_ys,  
  122.             }))  
  123.         step += 1  



ps:如想详细了解以上代码的具体讲解可参看: https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/
或者网盘下载视频:链接: http://pan.baidu.com/s/1i57P1hN 密码:rxgh,以上代码均在该视频学习指导下完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值