import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
#讀入資料
data = pd.read_csv('./data/insurance.csv')
# describe做簡單的統計摘要
print(data.describe())
# 采樣要均勻,檢視age字段有多少種數值,即各個年齡有多少個樣本
data_count = data['age'].value_counts()
print(data_count)
#繪制年齡分布柱狀圖
data_count[:10].plot(kind='bar')
plt.show()
#将柱狀圖儲存在本地
# plt.savefig('./temp')
輸出結果為:
統計摘要:
age bmi children charges
count 1338.000000 1338.000000 1338.000000 1338.000000
mean 39.207025 30.663397 1.094918 13270.422265
std 14.049960 6.098187 1.205493 12110.011237
min 18.000000 15.960000 0.000000 1121.873900
25% 27.000000 26.296250 0.000000 4740.287150
50% 39.000000 30.400000 1.000000 9382.033000
75% 51.000000 34.693750 2.000000 16639.912515
max 64.000000 53.130000 5.000000 63770.428010
年齡段統計:
18 69
19 68
51 29
45 29
46 29
47 29
48 29
50 29
52 29
20 29
26 28
54 28
53 28
25 28
24 28
49 28
23 28
22 28
21 28
27 28
28 28
31 27
29 27
30 27
41 27
43 27
44 27
40 27
42 27
57 26
34 26
33 26
32 26
56 26
55 26
59 25
58 25
39 25
38 25
35 25
36 25
37 25
63 23
60 23
61 23
62 23
64 22
Name: age, dtype: int64
年齡分布直方圖為(前十個年齡段)
利用data.corr()方法計算各字段的相關性,往往采用皮爾遜相關系數法
print(data.corr())
結果如下:
age bmi children charges
age 1.000000 0.109272 0.042469 0.299008
bmi 0.109272 1.000000 0.012759 0.198341
children 0.042469 0.012759 1.000000 0.067998
charges 0.299008 0.198341 0.067998 1.000000
表中數值為皮爾遜相關系數,該值越接近1表示二者越正相關,越接近-1表示二者越接近負相關(皮爾遜相關系數依賴于數值計算,故字段資料類型必須是數值)
2. 提取特征資料和目标資料并初步預處理
reg = LinearRegression()#執行個體化一個線性回歸對象
#取出特征資料
x = data[['age', 'sex', 'bmi', 'children', 'smoker', 'region']]
#取出目标資料
y = data['charges']
#将x,y的每一列應用to_numeric方法,即将字段類型為字元串的轉化為數值類型
x = x.apply(pd.to_numeric, errors='coerce')
y = y.apply(pd.to_numeric, errors='coerce')
#将x,y的空值填充為0
x.fillna(0, inplace=True)
y.fillna(0, inplace=True)
進行資料升維,利用多項式回歸進行資料升維,意在将x和y之間的非線性關系轉化為線性關系進而利用線性算法進行模組化
#利用多項式回歸進行資料升維,意在将x和y之間的非線性關系轉化為線性關系進而利用線性算法進行模組化
poly_features = PolynomialFeatures(degree=3, include_bias=False)
X_poly = poly_features.fit_transform(x)
傳入資料訓練
#傳入升維後的X和y進行訓練
reg.fit(X_poly, y)
#列印權重參數和偏置項
print(reg.coef_)
print(reg.intercept_)
調用模型預測,繪制真實值和預測值的散點圖以觀測模型預測效果
#調用模型預測
y_predict = reg.predict(X_poly)
#繪制真實值和預測值的散點圖以觀測預測效果
plt.plot(x['age'][:10], y[:10], 'b.')
plt.plot(X_poly[:10, 0], y_predict[:10], 'r.')
plt.show()
輸出散點圖如下:
由圖可見,由于隻進行了資料升維的預處理是以預測效果并不理想