下边代码使用python3,使用scikit-learn包的线性回归模型,做线性回归。
1 import pandas as pd 2 import numpy as np 3 import matplotlib.pyplot as plt 4 from sklearn import linear_model 5 6 7 def prepare_country_stats(oecd_bli, gdp_per_capita): 8 oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"] 9 oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value") 10 gdp_per_capita.rename(columns={"2015": "GDP per capita"}, inplace=True) 11 gdp_per_capita.set_index("Country", inplace=True) 12 full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita, 13 left_index=True, right_index=True) 14 full_country_stats.sort_values(by="GDP per capita", inplace=True) 15 remove_indices = [0, 1, 6, 8, 33, 34, 35] 16 keep_indices = list(set(range(36)) - set(remove_indices)) 17 return full_country_stats[["GDP per capita", \'Life satisfaction\']].iloc[keep_indices] 18 19 20 if __name__ == \'__main__\': 21 # Load Data 22 oecd_bli = pd.read_csv("dataset/oecd_bli_2015.csv", thousands=",") 23 gdp_per_capita = pd.read_csv("dataset/gdp_per_capita.csv", thousands=",", delimiter="\t", encoding="latin1", na_values="n/a") 24 25 # Gen Statics dat 26 country_stats = prepare_country_stats(oecd_bli, gdp_per_capita) 27 X = np.c_[country_stats["GDP per capita"]] 28 y = np.c_[country_stats["Life satisfaction"]] 29 30 # Visualize the data 31 country_stats.plot(kind="scatter", x="GDP per capita", y="Life satisfaction") 32 plt.show() 33 34 model = linear_model.LinearRegression() 35 model.fit(X, y) 36 37 testX = [[22587]] 38 print(model.predict(testX))