Tensorflow实现第一个简单的机器学习demo
2017-11-25 16:40
399 查看
昨天写了Tensorflow的初体验,感觉不错,再接再励,就把官方教程上的机器学习demo码出来自己看看,总结总结。
这是官方教程上的第一个机器学习的教程,做一个简单求线性函数,的斜率W和Bias的demo,用的方法是梯度下降法,就是从变化速度最快的方向优化系数,具体的方法讲解我还需要回忆和复习,在tensorflow里这类算法已经成熟的打包了,直接调用就好。
在demo程序里我增加了部分我的理解注释,这样看起来会更容易明白。
看起来太简单了~~所以到现在的入门是极其兴奋的,加油!
官网还有两个例子,第二个和第三个例子是将模型封装成了函数,两个放在一起可以互为参考和学习。
下面这个例子是将上面的过程进行了函数封装,两者对比一下可以进一步学习模块化的python编程。
这是官方教程上的第一个机器学习的教程,做一个简单求线性函数,的斜率W和Bias的demo,用的方法是梯度下降法,就是从变化速度最快的方向优化系数,具体的方法讲解我还需要回忆和复习,在tensorflow里这类算法已经成熟的打包了,直接调用就好。
在demo程序里我增加了部分我的理解注释,这样看起来会更容易明白。
import tensorflow as tf # Model parameters(原始参数) W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) # Model input and output(占位符,声明变量) x = tf.placeholder(tf.float32) linear_model = W*x + b y = tf.placeholder(tf.float32) # loss (损失函数,相减的平方再求和) loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares # optimizer (最小下降法的步长为0.01) optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) # training data (数据) x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3] # training loop (训练过程) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong for i in range(1000): sess.run(train, {x: x_train, y: y_train}) # evaluate training accuracy curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) print 4000 ("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
看起来太简单了~~所以到现在的入门是极其兴奋的,加油!
官网还有两个例子,第二个和第三个例子是将模型封装成了函数,两个放在一起可以互为参考和学习。
# NumPy is often used to load, manipulate and preprocess data. import numpy as np import tensorflow as tf # Declare list of features. We only have one numeric feature. There are many # other types of columns that are more complicated and useful. feature_columns = [tf.feature_column.numeric_column("x", shape=[1])] # An estimator is the front end to invoke training (fitting) and evaluation # (inference). There are many predefined types like linear regression, # linear classification, and many neural network classifiers and regressors. # The following code provides an estimator that does linear regression. estimator = tf.estimator.LinearRegressor(feature_columns=feature_columns) # TensorFlow provides many helper methods to read and set up data sets. # Here we use two data sets: one for training and one for evaluation # We have to tell the function how many batches # of data (num_epochs) we want and how big each batch should be. x_train = np.array([1., 2., 3., 4.]) y_train = np.array([0., -1., -2., -3.]) x_eval = np.array([2., 5., 8., 1.]) y_eval = np.array([-1.01, -4.1, -7, 0.]) input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True) train_input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False) eval_input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False) # We can invoke 1000 training steps by invoking the method and passing the # training data set. estimator.train(input_fn=input_fn, steps=1000) # Here we evaluate how well our model did. train_metrics = estimator.evaluate(input_fn=train_input_fn) eval_metrics = estimator.evaluate(input_fn=eval_input_fn) print("train metrics: %r"% train_metrics) print("eval metrics: %r"% eval_metrics)
下面这个例子是将上面的过程进行了函数封装,两者对比一下可以进一步学习模块化的python编程。
import numpy as np import tensorflow as tf #函数封装 def model_fn(features,labels,mode): W = tf.get_variable("W",[1],dtype = tf.float64) b = tf.get_variable("b",[1],dtype = tf.float64) y = W*features["x"] + b loss = tf.reduce_sum(tf.square(y - labels)) global_step = tf.train.get_global_step() optimizer = tf.train.GradientDescentOptimizer(0.01) train = tf.group(optimizer.minimize(loss),tf.assign_add(global_step,1)) return tf.estimator.EstimatorSpec(mode = mode,predictions = y,loss = loss,train_op = train) estimator = tf.estimator.Estimator(model_fn = model_fn) x_train = np.array([1., 2., 3., 4.]) y_train = np.array([0., -1., -2., -3.]) x_eval = np.array([2., 5., 8., 1.]) y_eval = np.array([-1.01, -4.1, -7., 0.]) input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True) train_input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False) eval_input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False) # train estimator.train(input_fn=input_fn, steps=1000) # Here we evaluate how well our model did. train_metrics = estimator.evaluate(input_fn=train_input_fn) eval_metrics = estimator.evaluate(input_fn=eval_input_fn) print("train metrics: %r"% train_metrics) print("eval metrics: %r"% eval_metrics)
相关文章推荐
- java实现一个简单的机器学习和数据挖掘的demo
- 使用tensorflow实现conditional-gan简单小demo
- tensorflow实现简单神经网络层逼近一个二次函数的demo
- TensorFlow入门:第一个机器学习Demo
- 深度学习3:TensorFlow第一个简单Demo
- 使用tensorflow实现gan简单小demo
- 第一个wxWidgets Demo简单实现,及VC2008下的环境设置!
- 关于使用Java实现的简单网络爬虫Demo
- Demo之JavaEE的使用Ajax简单实现Google的Suggestion
- Tensorflow简单CNN实现
- tensorflow实现softmax回归(softmax regression)——简单的MNIST识别(第一课)
- 实现计时器 的简单demo
- spring注解方式实现Cache的简单Demo
- 学习SSH时的练习demo,实现分页和登录等简单功能
- TensorFlow实现简单的全连接网络(十三)
- jdbc的简单实现demo
- TensorFlow:实战Google深度学习框架(二)实现简单神经网络
- java+html5的websocket简单实现BS聊天DEMO实例
- 小白学习机器学习---第五章:神经网络简单模型python实现
- Swift实现断点续传,Demo简单易懂,没有太多复杂模块和逻辑,完整体现断点续传的原理