使用法线方程的未加权线性回归

时间:2019-02-28 12:33:26

标签: python machine-learning linear-regression

我对作业有疑问:

使用法线方程在= sin(2)+上实施线性回归(= T),并在同一图形上绘制由拟合得出的数据和直线。 (请记住包括拦截项。)

我做了什么

我正在使用以下代码生成数据

#  Generate synthetic data for  = sin(2) +  
import numpy as np
import math 
import random

m = 100 # number of training examples
e = 0.0008 * np.asarray(random.sample(range(0,1000),m)) # random noise

x = np.arange(-1, 1, 2 / m) # x-axis
y = np.sin(2 * np.pi * x) + e # y-axis
#print(x)
#print(y)

以及以下内容,以寻找最佳的theta和预测值(y值)

# normal equation --> theta_best = (x.T . x)^(-1) . xT . y
x_b = np.c_[np.ones((m, 1)), x] # set bias term to 1 for each sample  
theta_best = np.linalg.inv(x_b.T.dot(x_b)).dot(x_b.T).dot(y) 
#print(theta_best)

#  = T . 
test_x = np.array([[0], [2]])  
test_x_b = np.c_[np.ones((2, 1)), test_x]  
prediction = test_x_b.dot(theta_best.T) 
#print(prediction)

最后通过以下步骤绘制数据

plt.plot(test_x, prediction, "r-")  
plt.plot(x, y, "b.")

下面是带有数据和线enter image description here

的结果图

我的问题

  1. 记住要包含拦截词的含义是什么,我该如何添加呢?
  2. 尽管我对这个领域非常陌生,但结果预测对我来说似乎极为糟糕,但是我在执行正常功能方面做错了什么吗?

任何建议或指导将不胜感激。

0 个答案:

没有答案