我对作业有疑问:
使用法线方程在= 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.")
的结果图
我的问题
任何建议或指导将不胜感激。