TensorFlow学习笔记(1)----基础概念和程序的形式

本文介绍TensorFlow的基本概念,包括图、会话、张量等,并通过平面拟合、矩阵乘法等实例展示如何构建和运行计算图,同时涉及feed和fetch机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概念

graph:图,表示具体的计算任务
session:会话,图需要在会话中执行,一个会话可以包含很多图
tensor:张量,在此表示数据,类型是numpy::ndarray
variable:就是本意变量,图的重要组成部分
operation:简称op,是图中计算的节点,输入tensor计算后产生tensor
feed、fetch:意思是给图添加数据和获取图中的数据,因为训练过程中有些数据需要动态获得、临时给予数据

运行:
考虑到python运算的性能,肯定需要使用外部运算库,但是内外环境切换也是个很大的开销,TF如同其他主流机器学习工具,把程序通常组织成一个构建阶段一个执行阶段。构建就是说明需要一个怎样的网络模型,执行就是按照指定的优化训练模型,也包含检验输出等操作。可以看做先用python程序搭建模型,然后全部在python之外运行

2. 例子

2.1 平面拟合

需要拟合的平面:y = W1 * x1_data + W2*x2_data + b,其中,已知x1_data、x2_data和y,但是都包含一点噪声。

程序:

  1. import tensorflow as tf  
  2. import numpy as np  
  3.   
  4. # Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3  
  5. x1_data = np.random.rand(100).astype(np.float32)  
  6. x2_data = np.random.rand(100).astype(np.float32)  
  7. y_data = x1_data * 10 + x2_data * 5 + 3 + tf.random_uniform([100], -0.10.1)  
  8.   
  9. # Try to find values for W and b that compute y_data = W * x_data + b  
  10. # (We know that W should be 0.1 and b 0.3, but TensorFlow will  
  11. # figure that out for us.)  
  12.   
  13. # note: W b and y just statement/container  before initialization  
  14. W1 = tf.Variable(tf.random_uniform([1], -1.01.0))  
  15. W2 = tf.Variable(tf.random_uniform([1], -1.01.0))  
  16. b = tf.Variable(tf.zeros([1]))  
  17. y = W1 * x1_data + W2*x2_data + b  
  18.   
  19. # Minimize the mean squared errors.  
  20. loss = tf.reduce_mean(tf.square(y - y_data))  
  21. optimizer = tf.train.AdagradOptimizer(0.6)  
  22. train = optimizer.minimize(loss)  
  23.   
  24.   
  25. # Before starting, initialize the variables.  We will 'run' this first.  
  26. init = tf.initialize_all_variables()  
  27.   
  28. # Launch the graph.  
  29. sess = tf.Session()  
  30. sess.run(init)  
  31.   
  32.   
  33. # Fit the line.  
  34. for step in range(20001):  
  35.     sess.run(train)  
  36.     #if step % 20 == 0:  
  37.         #print(step, sess.run(W), sess.run(b),sess.run(loss))  
  38.           
  39. print(step, sess.run(W1), sess.run(W2), sess.run(b),sess.run(loss))  
  40. # Learns best fit is W: [0.1], b: [0.3]  
程序首先使用随机数产生需要拟合的数据,然后规定误差项和优化的方式,然后是训练并输出结果。优化方法有很多种不仅仅是AdagradOptimizer()。

2.2 矩阵相乘

两个比较大的矩阵相乘,分别使用GPU和CPU,比较运行时间

  1. import tensorflow as tf  
  2. import numpy as np  
  3.   
  4. #when put here the "cpu" is same as "gpu" , because it has been deploied on gpu or cpu  
  5. #select the fastest device automatically   
  6. #matrix1 = np.random.rand(20000,1500).astype(np.float32)  
  7. #matrix2 = np.random.rand(1500,20000).astype(np.float32)  
  8. #product = tf.matmul(matrix1, matrix2)  
  9.   
  10. with tf.Session() as sess3:  
  11.     with tf.device("/gpu:0"):#gpu 11.6s and cpu 20.2s  
  12.         matrix1 = np.random.rand(20000,1500).astype(np.float32)  
  13.         matrix2 = np.random.rand(1500,20000).astype(np.float32)  
  14.         product = tf.matmul(matrix1, matrix2)  
  15.         result = sess3.run(product)  

如果有GPU并且安装的是GPU版本的TF,程序默认是在GPU上运行的。通过指定"/gpu:0"或"/cpu:0"的形式,可以人为改变。GPU运行时间是11.6s,CPU是20.2s,节省了一些时间。

2.3 构建session的另一种方式

以上程序需要显示地使用sess.run(...)运行节点,想法自然,但TF也提供了另一种形式

  1. import tensorflow as tf  
  2. import numpy as np  
  3.   
  4. #deploy a session  
  5. sess = tf.InteractiveSession()  
  6.   
  7. #design the grape  
  8. matrix1 = np.random.rand(2000,1500).astype(np.float32)  
  9. matrix2 = np.random.rand(1500,2000).astype(np.float32)  
  10. product = tf.matmul(matrix1, matrix2)  
  11.   
  12. #run the operation  
  13. print product.eval()  
  14.   
  15. sess.close()  

2.4一个计数器--说明构建阶段和运行阶段

TF把很多操作都规定成内部的函数,先显式地规定网络,然后才是运行

  1. import tensorflow as tf  
  2.   
  3. #design the graph  
  4. state = tf.Variable(0, name="counter")  
  5.   
  6. one = tf.constant(1)  
  7. new_value = tf.add(state, one)  
  8. update = tf.assign(state, new_value)  
  9.   
  10. #initialization  
  11. init_op = tf.initialize_all_variables()  
  12.   
  13. #run   
  14. with tf.Session() as sess:  
  15.     sess.run(init_op)  
  16.     print sess.run(state)  
  17.   
  18.     for _ in range(3):  
  19.         sess.run(update)  
  20.         print sess.run(state)  

2.5获取数据fetch()

程序运行时需要获取一些数据,每个节点获取的数据可以理解为:对每个点单独有通路,从底部运行过来(实际不是这样,但数据同步行类似)

  1. import tensorflow as tf  
  2.   
  3. input1 = tf.constant(3.0)  
  4. input2 = tf.constant(2.0)  
  5. input3 = tf.constant(5.0)  
  6.   
  7. intermed = tf.add(input2, input3)  
  8. mul = tf.mul(input1, intermed)  
  9.   
  10. with tf.Session() as sess:  
  11.     result = sess.run([mul, intermed])  
  12.     print result  
  13.     result = sess.run([intermed])  
  14.     print result  

2.6填充数据feed()

随时给程序填充一些数据

  1. import tensorflow as tf  
  2. import numpy as np  
  3.   
  4. input1 = tf.placeholder(tf.float32,shape=(55))  
  5. input2 = tf.placeholder(tf.float32,shape=(55))  
  6. output = tf.matmul(input1, input2)#matmul is different mul  
  7.   
  8. with tf.Session() as sess:  
  9.     rand_array = np.ones([55])  
  10.     print sess.run([output], feed_dict={input1: rand_array,input2: rand_array})  

参考:

官方手册:https://www.tensorflow.org/versions/r0.10/get_started/index.html

中文社区:http://www.tensorfly.cn/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值