pandas讀取分析保險數據

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
年齡分佈直方圖爲(前十個年齡段)
在這裏插入圖片描述

  1. 利用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)
  1. 進行數據升維,利用多項式迴歸進行數據升維,意在將x和y之間的非線性關係轉化爲線性關係從而利用線性算法進行建模
#利用多項式迴歸進行數據升維,意在將x和y之間的非線性關係轉化爲線性關係從而利用線性算法進行建模
poly_features = PolynomialFeatures(degree=3, include_bias=False)
X_poly = poly_features.fit_transform(x)
  1. 傳入數據訓練
#傳入升維後的X和y進行訓練
reg.fit(X_poly, y)
#打印權重參數和偏置項
print(reg.coef_)
print(reg.intercept_)
  1. 調用模型預測,繪製真實值和預測值的散點圖以觀測模型預測效果
#調用模型預測
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()

輸出散點圖如下:
在這裏插入圖片描述
由圖可見,由於只進行了數據升維的預處理所以預測效果並不理想

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章