TensorFlow基礎(1)——數據的輸入

TensorFlow客戶端以三種方式接收數據:

  • 使用佔位符placeholder,用python代碼在算法的每個步驟中提供數據。
  • 將數據預加載並存儲爲TensorFlow的張量
  • 搭建輸入管道

例:

代碼:

  1 #!/usr/bin/env python
  2 # encoding: utf-8
  3 import tensorflow as tf
  4 import numpy as np
  5 import os
  6 import matplotlib.pyplot as plt
  7 os.environ["CUDA_VISIBLE_DEVICES"] = "3" #指定所用的GPU編號
  8 #使用佔位符提供數據
  9 #以sigmoid爲例
 10 graph = tf.Graph()
 11 session = tf.InteractiveSession(graph=graph)
 12 x = tf.placeholder(shape=[1,10],dtype=tf.float32,name='x')
 13 W = tf.Variable(tf.random_uniform(shape=[10,5], minval=-0.1, maxval=0.1, dtype=tf.float32),name='W')
 14 b = tf.Variable(tf.zeros(shape=[5],dtype=tf.float32),name='b')
 15 h = tf.nn.sigmoid(tf.matmul(x,W) + b)
 16 tf.global_variables_initializer().run()
 17 h_eval = session.run(h,feed_dict={x: np.random.rand(1,10)})
 18 print('W: ', W)
 19 print('x: ', x)
 20 print('b: ', b)
 21 print('h_eval: ', h_eval)
 22 session.close()
 23  
 24 #使用張量提供數據
 25 # 定義圖結構
 26 graph = tf.Graph()
 27 session = tf.InteractiveSession(graph=graph)
 28 x = tf.constant(value=[[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]],dtype=tf.float32,name='x')
 29 W = tf.Variable(tf.random_uniform(shape=[10,5], minval=-0.1, maxval=0.1, dtype=tf.float32),name='W')
 30 b = 0.1 * tf.Variable(tf.ones(shape=[5],dtype=tf.float32),name='b')                                                                             
 31 op1 = tf.matmul(x,W)
 32 tf.global_variables_initializer().run()
 33 #想打印中間結果需要拆分操作單獨run
 34 res1 = session.run(op1)
 35 print('res1: ', res1)
 36 op2 = tf.add(res1, b)
 37 res2 = session.run(op2)
 38 print('res2: ', res2)
 39 op3 = tf.nn.relu(res2)
 40 res3 = session.run(op3)
 41 res4 = session.run([op1, op2, op3])
 42 res5, g, k = session.run([op1, op2, op3])
 43 print('res3: ', res3)
 44 print('res4: ', res4)
 45 print('res5: ', res5, g, k)
 46  
 47 session.close()

輸出結果:

直接打印無法得到預期的中間結果:

需使用session.run(operation)執行操作:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章