用TensorFlow實現(xiàn)戴明回歸算法的示例
如果最小二乘線性回歸算法最小化到回歸直線的豎直距離(即,平行于y軸方向),則戴明回歸最小化到回歸直線的總距離(即,垂直于回歸直線)。其最小化x值和y值兩個方向的誤差,具體的對比圖如下圖。
線性回歸算法和戴明回歸算法的區(qū)別。左邊的線性回歸最小化到回歸直線的豎直距離;右邊的戴明回歸最小化到回歸直線的總距離。
線性回歸算法的損失函數(shù)最小化豎直距離;而這里需要最小化總距離。給定直線的斜率和截距,則求解一個點到直線的垂直距離有已知的幾何公式。代入幾何公式并使TensorFlow最小化距離。
損失函數(shù)是由分子和分母組成的幾何公式。給定直線y=mx+b,點(x0,y0),則求兩者間的距離的公式為:

# 戴明回歸
#----------------------------------
#
# This function shows how to use TensorFlow to
# solve linear Deming regression.
# y = Ax + b
#
# We will use the iris data, specifically:
# y = Sepal Length
# x = Petal Width
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create graph
sess = tf.Session()
# Load the data
# iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
iris = datasets.load_iris()
x_vals = np.array([x[3] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])
# Declare batch size
batch_size = 50
# Initialize placeholders
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
# Create variables for linear regression
A = tf.Variable(tf.random_normal(shape=[1,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))
# Declare model operations
model_output = tf.add(tf.matmul(x_data, A), b)
# Declare Demming loss function
demming_numerator = tf.abs(tf.subtract(y_target, tf.add(tf.matmul(x_data, A), b)))
demming_denominator = tf.sqrt(tf.add(tf.square(A),1))
loss = tf.reduce_mean(tf.truediv(demming_numerator, demming_denominator))
# Declare optimizer
my_opt = tf.train.GradientDescentOptimizer(0.1)
train_step = my_opt.minimize(loss)
# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)
# Training loop
loss_vec = []
for i in range(250):
rand_index = np.random.choice(len(x_vals), size=batch_size)
rand_x = np.transpose([x_vals[rand_index]])
rand_y = np.transpose([y_vals[rand_index]])
sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
loss_vec.append(temp_loss)
if (i+1)%50==0:
print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
print('Loss = ' + str(temp_loss))
# Get the optimal coefficients
[slope] = sess.run(A)
[y_intercept] = sess.run(b)
# Get best fit line
best_fit = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)
# Plot the result
plt.plot(x_vals, y_vals, 'o', label='Data Points')
plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)
plt.legend(loc='upper left')
plt.title('Sepal Length vs Pedal Width')
plt.xlabel('Pedal Width')
plt.ylabel('Sepal Length')
plt.show()
# Plot loss over time
plt.plot(loss_vec, 'k-')
plt.title('L2 Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('L2 Loss')
plt.show()
結(jié)果:
本文的戴明回歸算法與線性回歸算法得到的結(jié)果基本一致。兩者之間的關(guān)鍵不同點在于預(yù)測值與數(shù)據(jù)點間的損失函數(shù)度量:線性回歸算法的損失函數(shù)是豎直距離損失;而戴明回歸算法是垂直距離損失(到x軸和y軸的總距離損失)。
注意,這里戴明回歸算法的實現(xiàn)類型是總體回歸(總的最小二乘法誤差)??傮w回歸算法是假設(shè)x值和y值的誤差是相似的。我們也可以根據(jù)不同的理念使用不同的誤差來擴展x軸和y軸的距離計算。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- tensorflow實現(xiàn)簡單邏輯回歸
- Tensorflow使用支持向量機擬合線性回歸
- TensorFlow實現(xiàn)iris數(shù)據(jù)集線性回歸
- 用TensorFlow實現(xiàn)lasso回歸和嶺回歸算法的示例
- 詳解用TensorFlow實現(xiàn)邏輯回歸算法
- TensorFlow實現(xiàn)Softmax回歸模型
- 運用TensorFlow進行簡單實現(xiàn)線性回歸、梯度下降示例
- 用tensorflow構(gòu)建線性回歸模型的示例代碼
- 用tensorflow實現(xiàn)彈性網(wǎng)絡(luò)回歸算法
- TensorFlow實現(xiàn)Logistic回歸
相關(guān)文章
Pycharm使用之設(shè)置代碼字體大小和顏色主題的教程
今天小編就為大家分享一篇Pycharm使用之設(shè)置代碼字體大小和顏色主題的教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python機器學(xué)習(xí)Logistic回歸原理推導(dǎo)
這篇文章主要為大家介紹了python機器學(xué)習(xí)Logistic回歸原理推導(dǎo),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Python基本數(shù)據(jù)結(jié)構(gòu)之字典類型dict用法分析
這篇文章主要介紹了Python基本數(shù)據(jù)結(jié)構(gòu)之字典類型dict用法,結(jié)合實例形式分析了Python字典類型dict概念、原理、定義及基本使用技巧,需要的朋友可以參考下2019-06-06
詳解Python中import模塊導(dǎo)入的實現(xiàn)原理
這篇文章主要給大家介紹了Python中import模塊導(dǎo)入的實現(xiàn)原理,主要從什么是模塊,import搜索路徑以及導(dǎo)入原理這三個方面給大家介紹,感興趣的小伙伴跟著小編一起來看看吧2023-08-08
簡單實現(xiàn)Python爬取網(wǎng)絡(luò)圖片
這篇文章主要教大家如何簡單實現(xiàn)Python爬取網(wǎng)絡(luò)圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
詳解Numpy擴充矩陣維度(np.expand_dims, np.newaxis)和刪除維度(np.squeeze)的方
這篇文章主要介紹了詳解Numpy擴充矩陣維度(np.expand_dims, np.newaxis)和刪除維度(np.squeeze)的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

