TensorFlow[1]:概念和简例
简介
TensorFlow是一个实现机器学习算法的接口,也是执行机器学习算法的框架。使用数据流式图规划计算流程,可以将计算映射到不同的硬件和操作系统平台。
主要概念
TensorFlow的计算可以表示为有向图(directed graph),或者计算图(computation graph),计算图描述了数据的就算流程,其中每个运算操作(operation)作为一个节点(node),节点与节点之间连接称为边(edge)。在计算图变中流动(flow)的数据被称为张量(tensor),故称TensorFlow。
计算图实例[ref1]
具体说,在一次运算中[ref2]:
1. 使用图 (graph) 来表示计算任务:TensorFlow[2]:基本操作实例;
2. 在被称之为 会话 (Session)
的上下文 (context) 中执行图:TensorFlow[2]:基本操作实例;
3. 通过 变量 (Variable)
维护状态:TensorFlow[2]:基本操作实例。
代码实例
#!/usr/bin/pyton ''' A simple example(linear regression) to show the complete struct that how to run a tensorflow create_data -> create_tensorflow_struct->start session
create date: 2017/10/20
''' import tensorflow as tf import numpy as np #create data x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1 + 0.3 ###create tensorflow structure begin## Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) biases = tf.Variable(tf.zeros([1])) y = Weights*x_data + biases loss = tf.reduce_mean(tf.square(y-y_data)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) #when define variables, initialize must be called #init = tf.initialize_all_variables() ### create tensorflow structure end ### sess = tf.Session() #note: initialize_local_variables no more support in new version if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1: init = tf.initialize_all_variables() else: init = tf.global_variables_initializer() sess.run(init) for step in range(201): sess.run(train) if step % 20 == 0: #session controls all opertions and varilables print(step, sess.run(Weights), sess.run(biases)) sess.close()
计算结果:
————————————–
说明:关于TensorFlow有很多好的学习资源,本列为前期学习时记录,现整理为笔记,代码参考莫凡