尚學堂百戰程序員:機器學習之線性迴歸
線性迴歸的定義:線性迴歸在假設特證滿足線性關係,根據給定的訓練數據訓練一個模型,並用此模型進行預測。
簡單線性迴歸的實現
手動生成五個點 (1,1),(2,3),(3,2),(4,3),(5,5) (1,1),(2,3),(3,2),(4,3),(5,5)(1,1),(2,3),(3,2),(4,3),(5,5) 求一條最佳直線來擬合這五個點
#SimpleLinearRegression.py
import numpy as np
class SimpleLinearRegression1:
def __init__(self):
"""初始化Simple Linear Regression模型"""
self.a_ = None
self.b_ = None
def fit(self, x_train, y_train):
"""根據訓練數據集x_train, y_train訓練 SimpleLinearRegression模型"""
assert x_train.ndim == 1,\
"Simple Linear Regressor can only solve single feature training data."
assert len(x_train) == len(y_train),\
"the size of x_train must be equal to the size of y_train"
x_mean = np.mean(x_train)
y_mean = np.mean(y_train)
num = 0.0
d = 0.0
for x,y in zip(x_train, y_train):
num += (x - x_mean) * (y - y_mean)
d += (x - x_mean) ** 2 self.a_ = num/d
self.b_ = y_mean - self.a_ * x_mean
return self
def predict(self, x_predict):
"""給定待預測數據集x_predict,返回x_predict的結果向量"""
assert x_predict.ndim == 1,\
"Simple Linear Regressor can only solve single feature training data."
assert self.a_ is not None and self.b_ is not None,\
"must fit before predict!"
return np.array([self._predict(x) for x in x_predict])
def _predict(self, x_single):
"""給定單個待預測數據x_single,返回x_single的預測結果"""
return self.a_ * x_single + self.b_
def __repr__(self):
return "SimpleLinearRegression1()"
*****************************************************************************
#test.py
import numpy as np
from SimpleLinearRegression import SimpleLinearRegression1
import matplotlib.pyplot as plt
x = np.array([1.,2.,3.,4.,5.])
y = np.array([1.,3.,2.,3.,5.])
x_predict = 6 reg1= SimpleLinearRegression1()
reg1.fit(x, y)
y_predict = reg1.predict(np.array([x_predict]))
print(y_predict)
y_hat = reg1.a_ * x + reg1.b_
plt.scatter(x, y)
plt.plot(x, y_hat, color = 'r')
plt.axis([0,6,0,6])
plt.show()
“我們相信人人都可以成爲一個IT大神,現在開始,選擇一條陽光大道,助你入門,學習的路上不再迷茫。這裏是北京尚學堂,初學者轉行到IT行業的聚集地。"
查看原文 >>