标签:
我现在什么都不知道,打算开始学习tensorflow作为机器学习入门的开始。
昨天完成了对tensorflow官方入门介绍的学习,了解了tensorflow的基本原理和编程方法。我们在进行tensorflow编程时,程序的逻辑是:建立数据流图-->初始化变量-->运行程序。下面就每一步进行介绍。
import tensorflow as tf # Create a Constant op that produces a 1x2 matrix. The op is # added as a node to the default graph. # # The value returned by the constructor represents the output # of the Constant op. matrix1 = tf.constant([[3., 3.]]) # Create another Constant that produces a 2x1 matrix. matrix2 = tf.constant([[2.],[2.]]) # Create a Matmul op that takes ‘matrix1‘ and ‘matrix2‘ as inputs. # The returned value, ‘product‘, represents the result of the matrix # multiplication. product = tf.matmul(matrix1, matrix2)
上面一段代码就创建了简单的图界面,节点的输入是两个常量矩阵,即在创建节点时已经给出了输入值,节点的输出是两个矩阵的乘积。当然,我们还可以用变量表示节点的输入,如步骤2的 代码所示
import tensorflow as tf import numpy as np # Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3 x_data = np.random.rand(100).astype(np.float32) y_data = x_data * 0.1 + 0.3 # Try to find values for W and b that compute y_data = W * x_data + b # (We know that W should be 0.1 and b 0.3, but Tensorflow will # figure that out for us.) W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) b = tf.Variable(tf.zeros([1])) y = W * x_data + b # Minimize the mean squared errors. loss = tf.reduce_mean(tf.square(y - y_data)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) # Before starting, initialize the variables. We will ‘run‘ this first. init = tf.initialize_all_variables() # Launch the graph. sess = tf.Session() sess.run(init)
1 import tensorflow as tf 2 import numpy as np 3 #输入已经给出 4 x_data = np.random.rand(100).astype(np.float32) 5 y_data = x_data * 0.1 + 0.3 6 7 W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) 8 b = tf.Variable(tf.zeros([1])) 9 y = W * x_data + b 10 11 # Minimize the mean squared errors. 12 loss = tf.reduce_mean(tf.square(y - y_data)) 13 optimizer = tf.train.GradientDescentOptimizer(0.5) 14 train = optimizer.minimize(loss) 15 16 # Before starting, initialize the variables. We will ‘run‘ this first. 17 init = tf.initialize_all_variables() 18 19 # Launch the graph. 20 sess = tf.Session() 21 sess.run(init) 22 23 # Fit the line. 24 for step in range(201): 25 sess.run(train) 26 if step % 20 == 0: 27 #我们需要计算W和b的值,将他们作为run的参数 28 print(step, sess.run(W), sess.run(b)) 29 30 # Learns best fit is W: [0.1], b: [0.3]
对于使用变量代表输入的程序,需要将变量赋值并作为run的参数:
#定义了变量,未经性赋值 input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.mul(input1, input2) with tf.Session() as sess: #运行时,以字典形式传入变量的值 print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
tensorflow学习笔记一——just get started
标签:
原文地址:http://www.cnblogs.com/ThingToForget/p/5639977.html