基本同上节,但线性回归的拟合方式不同,这次不需要数据归一化和梯度下降,之前调的库sklearn.linear_model.SGDRegressor 和 sklearn.preprocessing.StandardScaler 没有派上用场,这次用到的是 sklearn.linear_model.LinearRegression.
numpy文档
scikit-learn中文社区 某些翻译明显机翻
scikit-learn官方
1.导入
import numpy as np
np.set_printoptions(precision=2)
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.preprocessing import StandardScaler
from lab_utils_multi import load_house_data
import matplotlib.pyplot as plt
dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0';
plt.style.use('./deeplearning.mplstyle')
2.载入数据
导入数据
X_train = np.array([1.0, 2.0]) #features
y_train = np.array([300, 500]) #target value
3.拟合数据
创建LinearRegression(这里是与上一节最大的区别,使用的拟合方式不同)对象后使用fit函数拟合数据
linear_model = LinearRegression()
#X must be a 2-D Matrix
linear_model.fit(X_train.reshape(-1, 1), y_train)
查看模型参数intercept_和coef_
b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
print(f"'manual' prediction: f_wb = wx+b : {1200*w + b}")
w = [200.], b = 100.00
'manual' prediction: f_wb = wx+b : [240100.]
4.预测
库中提供了函数predict
y_pred = linear_model.predict(X_train.reshape(-1, 1))
print("Prediction on training set:", y_pred)
X_test = np.array([[1200]])
print(f"Prediction for 1200 sqft house: ${linear_model.predict(X_test)[0]:0.2f}")
5.第2个例子_多特征输入
5.1 载入数据
# load the dataset
X_train, y_train = load_house_data()
X_features = ['size(sqft)','bedrooms','floors','age']
5.2 拟合
linear_model = LinearRegression()
linear_model.fit(X_train, y_train)
5.3 查看参数
b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
w = [ 0.27 -32.62 -67.25 -1.47], b = 220.42
5.4 预测
print(f"Prediction on training set:\n {linear_model.predict(X_train)[:4]}" )
print(f"prediction using w,b:\n {(X_train @ w + b)[:4]}")
print(f"Target values \n {y_train[:4]}")
x_house = np.array([1200, 3,1, 40]).reshape(-1,4)
x_house_predict = linear_model.predict(x_house)[0]
print(f" predicted price of a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old = ${x_house_predict*1000:0.2f}")
Prediction on training set:
[295.18 485.98 389.52 492.15]
prediction using w,b:
[295.18 485.98 389.52 492.15]
Target values
[300. 509.8 394. 540. ]
predicted price of a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old = $318709.09