tensorflow 实现 正规方程求解线性回归
2017-12-09 20:47
525 查看
正规方程是用一个方程去求解线性回归问题,是最小二乘法的矩阵形式。在吴恩达的机器学习课程上也有提及。
这里写一个简单的用tensorflow实现的方法。参考《Tensorflow机器学习实战指南》
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 20:16:39 2017
@author: www
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
#准备数据
x_vals = np.linspace(0, 10, 100)
y_vals = 2 * x_vals + np.random.normal(0, 1, 100)
sess = tf.Session()
x_vals_column = np.transpose(np.matrix(x_vals))
one_column = np.transpose(np.matrix(np.repeat(1, 100)))
A = np.column_stack((x_vals_column, one_column))
b = np.transpose(np.matrix(y_vals))
#转化为张量
A_tensor = tf.constant(A)
b_tensor = tf.constant(b)
#使用正规方程法
A_temp = tf.matmul(tf.transpose(A_tensor), A_tensor)
A_temp = tf.matrix_inverse(A_temp)
A_temp = tf.matmul(A_temp, tf.transpose(A_tensor))
solution = tf.matmul(A_temp, b_tensor)
solution_eval = sess.run(solution)
#得到系数,截距
slope = solution_eval[0][0]
intercept = solution_eval[1][0]
print('slope'+str(slope))
print('intercept'+str(intercept))
#画图显示
best_fit = []
for i in x_vals:
best_fit.append(slope * i + intercept)
plt.plot(x_vals, y_vals, 'o', label ='Data')
plt.plot(x_vals, best_fit, 'r-', label ='Best fit line')
plt.legend(loc = 'upper left')
plt.show()
这里写一个简单的用tensorflow实现的方法。参考《Tensorflow机器学习实战指南》
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 20:16:39 2017
@author: www
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
#准备数据
x_vals = np.linspace(0, 10, 100)
y_vals = 2 * x_vals + np.random.normal(0, 1, 100)
sess = tf.Session()
x_vals_column = np.transpose(np.matrix(x_vals))
one_column = np.transpose(np.matrix(np.repeat(1, 100)))
A = np.column_stack((x_vals_column, one_column))
b = np.transpose(np.matrix(y_vals))
#转化为张量
A_tensor = tf.constant(A)
b_tensor = tf.constant(b)
#使用正规方程法
A_temp = tf.matmul(tf.transpose(A_tensor), A_tensor)
A_temp = tf.matrix_inverse(A_temp)
A_temp = tf.matmul(A_temp, tf.transpose(A_tensor))
solution = tf.matmul(A_temp, b_tensor)
solution_eval = sess.run(solution)
#得到系数,截距
slope = solution_eval[0][0]
intercept = solution_eval[1][0]
print('slope'+str(slope))
print('intercept'+str(intercept))
#画图显示
best_fit = []
for i in x_vals:
best_fit.append(slope * i + intercept)
plt.plot(x_vals, y_vals, 'o', label ='Data')
plt.plot(x_vals, best_fit, 'r-', label ='Best fit line')
plt.legend(loc = 'upper left')
plt.show()
相关文章推荐
- 机器学习(四)正规方程求解线性回归问题、正规方法与梯度法的优劣
- Matlab梯度下降及正规方程实现多变量的线性回归
- 机器学习:用正规方程法求解线性回归
- tensorflow实现线性回归(矩阵解法)
- Tensorflow学习笔记(一):初识TensorFlow——实现线性回归
- [深度学习] (2):实现简单的线性回归(使用TensorFlow优化)
- 牛顿法和SGD求解方程的理解和简单实现
- 线性回归、梯度下降以及运用TensorFlow进行简单实现
- Tensorflow实现线性回归
- 梯度下降法求解线性回归之python实现
- Linear Regression(线性回归)(二)—正规方程(normal equations)
- c语言实现,用最小二乘法求解方程数多于未知变量的线性方程组的最适解(即矛盾方程组)
- tensorflow实战一---基于线性回归简单实现mnist手写体识别
- tensorflow 实现线性回归
- 机器学习-线性回归-正规方程
- 使用tensorflow实现线性回归
- TensorFlow实现线性回归
- 用tensorflow实现线性回归和相应的损失函数的运用
- 基于Tensorflow实现基本的线性回归(Linear regression)
- 用TensorFlow实现iris数据集线性回归