1可选实验:使用Scikit-Learn进行线性回归

1.1工具

2线性回归封闭式解决方案

Scikit-learn 的线性回归模型实现了一种封闭式的线性回归。

2.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') X_train = np.array([1.0, 2.0])
#features y_train = np.array([300, 500]) #target value
2.2创建并适应模型

linear_model = LinearRegression() #X must be a 2-D Matrix
linear_model.fit(X_train.reshape(-1, 1), y_train)

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
2.3参数视图

W 和 b 参数在 scikit-learn 中称为“系数”和“截距”。
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.]
2.4预测

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}")

Prediction on training set: [300. 500.] Prediction for 1200 sqft house:
\$240100.00
3另一个实例

# load the dataset X_train, y_train = load_house_data() X_features =
['size(sqft)','bedrooms','floors','age'] linear_model = LinearRegression()
linear_model.fit(X_train, y_train) b = linear_model.intercept_ w =
linear_model.coef_ print(f"w = {w:}, b = {b:0.2f}") 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}")

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) w
= [ 0.27 -32.62 -67.25 -1.47], b = 220.42 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

GitHub

Gitee