1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.linear_model import ElasticNet from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import r2_score
def deal_data(): boston = load_boston() df = pd.DataFrame(boston.data, columns=boston.feature_names) df['result'] = boston.target data = np.array(df) return data[:, :-1], data[:, -1]
def train_model(features, labels): model = ElasticNet(l1_ratio=0.7) model.fit(features, labels) return model
def estimate_model(y_true, y_pred): MSE = mean_squared_error(y_true, y_pred) RMSE = np.sqrt(MSE) MAE = mean_absolute_error(y_true, y_pred) R2 = r2_score(y_true, y_pred) indicators = {"MSE": MSE, "RMSE":RMSE, "MAE":MAE, "R2":R2} return indicators
def visualization(y_true, y_pred, model): plt.plot(range(y_true.shape[0]), y_true, "b-") plt.plot(range(y_true.shape[0]), y_pred, "r-.") plt.legend(["original value", "predicted value"]) plt.xlabel("samples", fontsize="15") plt.ylabel("y", fontsize="15")
plt.show()
if __name__ == "__main__": x, y = deal_data() x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3,random_state=0) model = train_model(x_train, y_train) y_pred = model.predict(x_test) print("y test:", y_test[:10]) print("y pred:", y_pred[:10]) indicators = estimate_model(y_test, y_pred) print("MSE:", indicators["MSE"]) print("RMSE:", indicators["RMSE"]) print("MAE:", indicators["MAE"]) print("R2:", indicators["R2"]) visualization(y_test, y_pred, model)
|