欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于Tensorflow的戴明回归算法

程序员文章站 2024-03-22 09:40:58
...

1、戴明回归算法

戴明回归最小化,求的是点到回归直线的距离。具体是最小化x值和y值两个方向的误差。

2、Tensorflow实现戴明回归算法

(1)导入编程库,创建会话等

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets

sess = tf.Session()
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])

learning_rate = 0.05
batch_size = 50
x_data = tf.placeholder(shape=[None,1], dtype = tf.float32)
y_target = tf.placeholder(shape =[None,1],dtype = tf.float32)

A = tf.Variable(tf.random_normal(shape=[1,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))

model_output = tf.add(tf.matmul(x_data,A),b)

(2) 定义损失函数,即点到直线的距离公式

d=|y0(mx0+b)|m2+1

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))

(3) 初始化变量,声明优化器,遍历迭代

init = tf.global_variables_initializer()
sess.run(init)
my_opt = tf.train.GradientDescentOptimizer(learning_rate)
train_step = my_opt.minimize(loss)

loss_vec = []

for i  in range(2500):
    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)

(4)输出优化结构

[slope] = sess.run(A)
[y_intercept] = sess.run(b)

best_fit = []
for i in x_vals:
    best_fit.append(slope*i + y_intercept)    

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.show()
plt.plot(loss_vec,'k-')

5、运行结果

基于Tensorflow的戴明回归算法

基于Tensorflow的戴明回归算法