上篇介绍了TensorFlow基本概念和基本操作,本文将利用TensorFlow举例实现线性回归模型过程。
线性回归算法
线性回归算法是机器学习中典型监督学习算法,不同于分类算法,线性回归的输出是整个实数空间R(故也可用线性回归做分类)。关于线性回归网络资料很多,算法具体推演不做叙述,这里简要概括基本点。
目标函数y(不考虑噪声形式):
损失函数Loss:
求解方法梯度下降:
TensorFlow实现
代码
#!/usr/bin/pyton import tensorflow as tf import matplotlib.pyplot as plt import numpy as np tf.set_random_seed(1) np.random.seed(1) x = np.linspace(-1, 1, 100)[:, np.newaxis] #newaxis:增加一个维度 noise = np.random.normal(0, 0.1, size=x.shape) y = np.power(x, 2) + noise #plot data plt.scatter(x, y) plt.show() tf_x = tf.placeholder(tf.float32, x.shape) tf_y = tf.placeholder(tf.float32, y.shape) # neural network layers l1 = tf.layers.dense(tf_x, 10, tf.nn.relu) # hidden layer output = tf.layers.dense(l1, 1) # output layer loss = tf.losses.mean_squared_error(tf_y, output) # compute cost optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5) train_op = optimizer.minimize(loss) sess = tf.Session() # control training and others sess.run(tf.global_variables_initializer()) # initialize var in graph plt.ion() # # 打开交互模式
#begin training
for step in range(100): # train and net output _, l, pred = sess.run([train_op, loss, output], {tf_x: x, tf_y: y}) if step % 5 == 0: # plot and show learning process plt.cla() plt.scatter(x, y) plt.plot(x, pred, 'r-', lw=5) plt.text(0.5, 0, 'Loss=%.4f' % l, fontdict={'size': 20, 'color': 'red'}) plt.pause(0.1) plt.ioff() # 显示前关掉交互模式 plt.show()
结果
--------------------------------------
说明:本列为前期学习时记录,为基本概念和操作,不涉及深入部分。文字部分参考在文中注明,代码参考莫凡