本文共 2410 字,大约阅读时间需要 8 分钟。
线性回归是很常见的一种回归,线性回归可以用来预测或者分类,主要解决线性问题。相关知识可看“相关阅读”。
在TensorFlow中进行线性回归处理重点是将样本和样本特征矩阵化。
单特征回归模型为:y=wx+b
构建模型
X = tf.placeholder(tf.float32, [None, 1])w = tf.Variable(tf.zeros([1, 1]))b = tf.Variable(tf.zeros([1]))y = tf.matmul(X, w) + bY = tf.placeholder(tf.float32, [None, 1])
构建成本函数
cost = tf.reduce_mean(tf.square(Y-y))
梯度下降最小化成本函数,梯度下降步长为0.01
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
完整代码,迭代次数为10000
import tensorflow as tfX = tf.placeholder(tf.float32, [None, 1])w = tf.Variable(tf.zeros([1, 1]))b = tf.Variable(tf.zeros([1]))y = tf.matmul(X, w) + bY = tf.placeholder(tf.float32, [None, 1])# 成本函数 sum(sqr(y_-y))/ncost = tf.reduce_mean(tf.square(Y-y))# 用梯度下降训练train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost)init = tf.initialize_all_variables()sess = tf.Session()sess.run(init)x_train = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]y_train = [[10],[11.5],[12],[13],[14.5],[15.5],[16.8],[17.3],[18],[18.7]]for i in range(10000): sess.run(train_step, feed_dict={X: x_train, Y: y_train})print("w:%f" % sess.run(w))print("b:%f" % sess.run(b))
多特征回归模型为:y=(w1x1+w2x2+...+wnxn)+b,写为y=wx+b。
y为m行1列矩阵,x为m行n列矩阵,w为n行1列矩阵。TensorFlow中用如下来表示模型。
构建模型
X = tf.placeholder(tf.float32, [None, n])w = tf.Variable(tf.zeros([n, 1]))b = tf.Variable(tf.zeros([1]))y = tf.matmul(X, w) + bY = tf.placeholder(tf.float32, [None, 1])
构建成本函数
cost = tf.reduce_mean(tf.square(Y-y))
梯度下降最小化成本函数,梯度下降步长为0.01
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
完整代码,迭代次数为10000
import tensorflow as tfX = tf.placeholder(tf.float32, [None, 2])w = tf.Variable(tf.zeros([2, 1]))b = tf.Variable(tf.zeros([1]))y = tf.matmul(X, w) + bY = tf.placeholder(tf.float32, [None, 1])# 成本函数 sum(sqr(y_-y))/ncost = tf.reduce_mean(tf.square(Y-y))# 用梯度下降训练train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost)init = tf.initialize_all_variables()sess = tf.Session()sess.run(init)x_train = [[1, 2], [2, 1], [2, 3], [3, 5], [1, 3], [4, 2], [7, 3], [4, 5], [11, 3], [8, 7]]y_train = [[7], [8], [10], [14], [8], [13], [20], [16], [28], [26]]for i in range(10000): sess.run(train_step, feed_dict={X: x_train, Y: y_train})print("w0:%f" % sess.run(w[0]))print("w1:%f" % sess.run(w[1]))print("b:%f" % sess.run(b))
在线性回归中,TensorFlow可以很方便地利用矩阵进行多特征的样本训练。
========广告时间========
鄙人的新书《Tomcat内核设计剖析》已经在京东销售了,有需要的朋友可以到 进行预定。感谢各位朋友。
=========================
欢迎关注: