当前位置:Gxlcms > Python > 用TensorFlow实现戴明回归算法的示例

用TensorFlow实现戴明回归算法的示例

时间:2021-07-01 10:21:17 帮助过:51人阅读

这篇文章主要介绍了关于用TensorFlow实现戴明回归算法的示例,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

如果最小二乘线性回归算法最小化到回归直线的竖直距离(即,平行于y轴方向),则戴明回归最小化到回归直线的总距离(即,垂直于回归直线)。其最小化x值和y值两个方向的误差,具体的对比图如下图。


线性回归算法和戴明回归算法的区别。左边的线性回归最小化到回归直线的竖直距离;右边的戴明回归最小化到回归直线的总距离。

线性回归算法的损失函数最小化竖直距离;而这里需要最小化总距离。给定直线的斜率和截距,则求解一个点到直线的垂直距离有已知的几何公式。代入几何公式并使TensorFlow最小化距离。

损失函数是由分子和分母组成的几何公式。给定直线y=mx+b,点(x0,y0),则求两者间的距离的公式为:

  1. # 戴明回归
  2. #----------------------------------
  3. #
  4. # This function shows how to use TensorFlow to
  5. # solve linear Deming regression.
  6. # y = Ax + b
  7. #
  8. # We will use the iris data, specifically:
  9. # y = Sepal Length
  10. # x = Petal Width
  11. import matplotlib.pyplot as plt
  12. import numpy as np
  13. import tensorflow as tf
  14. from sklearn import datasets
  15. from tensorflow.python.framework import ops
  16. ops.reset_default_graph()
  17. # Create graph
  18. sess = tf.Session()
  19. # Load the data
  20. # iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
  21. iris = datasets.load_iris()
  22. x_vals = np.array([x[3] for x in iris.data])
  23. y_vals = np.array([y[0] for y in iris.data])
  24. # Declare batch size
  25. batch_size = 50
  26. # Initialize placeholders
  27. x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
  28. y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
  29. # Create variables for linear regression
  30. A = tf.Variable(tf.random_normal(shape=[1,1]))
  31. b = tf.Variable(tf.random_normal(shape=[1,1]))
  32. # Declare model operations
  33. model_output = tf.add(tf.matmul(x_data, A), b)
  34. # Declare Demming loss function
  35. demming_numerator = tf.abs(tf.subtract(y_target, tf.add(tf.matmul(x_data, A), b)))
  36. demming_denominator = tf.sqrt(tf.add(tf.square(A),1))
  37. loss = tf.reduce_mean(tf.truep(demming_numerator, demming_denominator))
  38. # Declare optimizer
  39. my_opt = tf.train.GradientDescentOptimizer(0.1)
  40. train_step = my_opt.minimize(loss)
  41. # Initialize variables
  42. init = tf.global_variables_initializer()
  43. sess.run(init)
  44. # Training loop
  45. loss_vec = []
  46. for i in range(250):
  47. rand_index = np.random.choice(len(x_vals), size=batch_size)
  48. rand_x = np.transpose([x_vals[rand_index]])
  49. rand_y = np.transpose([y_vals[rand_index]])
  50. sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
  51. temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
  52. loss_vec.append(temp_loss)
  53. if (i+1)%50==0:
  54. print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
  55. print('Loss = ' + str(temp_loss))
  56. # Get the optimal coefficients
  57. [slope] = sess.run(A)
  58. [y_intercept] = sess.run(b)
  59. # Get best fit line
  60. best_fit = []
  61. for i in x_vals:
  62. best_fit.append(slope*i+y_intercept)
  63. # Plot the result
  64. plt.plot(x_vals, y_vals, 'o', label='Data Points')
  65. plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)
  66. plt.legend(loc='upper left')
  67. plt.title('Sepal Length vs Pedal Width')
  68. plt.xlabel('Pedal Width')
  69. plt.ylabel('Sepal Length')
  70. plt.show()
  71. # Plot loss over time
  72. plt.plot(loss_vec, 'k-')
  73. plt.title('L2 Loss per Generation')
  74. plt.xlabel('Generation')
  75. plt.ylabel('L2 Loss')
  76. plt.show()

结果:



本文的戴明回归算法与线性回归算法得到的结果基本一致。两者之间的关键不同点在于预测值与数据点间的损失函数度量:线性回归算法的损失函数是竖直距离损失;而戴明回归算法是垂直距离损失(到x轴和y轴的总距离损失)。

注意,这里戴明回归算法的实现类型是总体回归(总的最小二乘法误差)。总体回归算法是假设x值和y值的误差是相似的。我们也可以根据不同的理念使用不同的误差来扩展x轴和y轴的距离计算。

相关推荐:

用TensorFlow实现多类支持向量机的示例代码

TensorFlow实现非线性支持向量机的实现方法

以上就是用TensorFlow实现戴明回归算法的示例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行