Tensorflow实现第一个简单的机器学习demo

昨天写了Tensorflow的初体验,感觉不错,再接再励,就把官方教程上的机器学习demo码出来自己看看,总结总结。


这是官方教程上的第一个机器学习的教程,做一个简单求线性函数,的斜率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("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)    

你可能感兴趣的:(深度学习之点滴)