kaggle實戰-腫瘤數據統計分析

語言: CN / TW / HK

theme: smartblue

公眾號:尤而小屋
作者:Peter
編輯:Peter

大家好,我是Peter~

今天給大家帶來的是kaggle上面一份關於腫瘤數據的統計分析,適合初學者快速入門,主要內容包含:

  • 基於直方圖的頻數統計
  • 基於四分位法的異常點定位分析
  • 描述統計分析
  • 基於累計分佈函數的分析
  • 兩兩變量間分析
  • 相關性分析...

這也是第21篇kaggle實戰的文章,其他內容請移步至公眾號相關文章:

數據集

數據地址為:http://www.kaggle.com/code/kanncaa1/statistical-learning-tutorial-for-beginners/notebook

最初的數據來自UCI官網:http://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29

導入庫

In [1]:

```python import pandas as pd import numpy as np

import plotly.express as px import plotly.graph_objects as go

import seaborn as sns import matplotlib.pyplot as plt from scipy import stats plt.style.use("ggplot") import warnings warnings.filterwarnings("ignore") ```

In [2]:

基本信息

In [3]:

df.shape

Out[3]:

(569, 33)

In [4]:

df.isnull().sum()

Out[4]:

id 0 diagnosis 0 radius_mean 0 texture_mean 0 perimeter_mean 0 area_mean 0 smoothness_mean 0 compactness_mean 0 concavity_mean 0 concave points_mean 0 symmetry_mean 0 fractal_dimension_mean 0 radius_se 0 texture_se 0 perimeter_se 0 area_se 0 smoothness_se 0 compactness_se 0 concavity_se 0 concave points_se 0 symmetry_se 0 fractal_dimension_se 0 radius_worst 0 texture_worst 0 perimeter_worst 0 area_worst 0 smoothness_worst 0 compactness_worst 0 concavity_worst 0 concave points_worst 0 symmetry_worst 0 fractal_dimension_worst 0 Unnamed: 32 569 dtype: int64

刪除兩個對分析無效的字段:

In [5]:

df.drop(["Unnamed: 32", "id"],axis=1,inplace=True)

剩餘的全部的字段:

In [6]:

columns = df.columns columns

Out[6]:

Index(['diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean', 'concave points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se', 'texture_se', 'perimeter_se', 'area_se', 'smoothness_se', 'compactness_se', 'concavity_se', 'concave points_se', 'symmetry_se', 'fractal_dimension_se', 'radius_worst', 'texture_worst', 'perimeter_worst', 'area_worst', 'smoothness_worst', 'compactness_worst', 'concavity_worst', 'concave points_worst', 'symmetry_worst', 'fractal_dimension_worst'], dtype='object')

分析1:直方圖-Histogram

直方圖統計的是每個值出現的頻數

In [7]:

```

radius_mean:均值

m = plt.hist(df[df["diagnosis"] == "M"].radius_mean, bins=30, fc=(1,0,0,0.5), label="Maligant" # 惡性 ) b = plt.hist(df[df["diagnosis"] == "B"].radius_mean, bins=30, fc=(0,1,0,0.5), label="Bening" # 良性 ) plt.legend() plt.xlabel("Radius Mean Values") plt.ylabel("Frequency") plt.title("Histogram of Radius Mean for Bening and Malignant Tumors") plt.show() ```

小結:

  1. 惡性腫瘤的半徑平均值大多數是大於良性腫瘤
  2. 良性腫瘤(綠色)的分佈大致上呈現鍾型,符合正態分佈

分析2:異常離羣點分析

根據數據的4分位數來確定異常點。

In [8]:

``` data_b = df[df["diagnosis"] == "B"] # 良性腫瘤 data_m = df[df["diagnosis"] == "M"]

desc = data_b.radius_mean.describe() q1 = desc[4] q3 = desc[6]

iqr = q3 - q1

lower = q1 - 1.5iqr upper = q3 + 1.5iqr

正常範圍

print("正常範圍: ({0}, {1})".format(round(lower,4), round(upper,4))) 正常範圍: (7.645, 16.805) ```

In [9]:

```

異常點

print("Outliers:", data_b[(data_b.radius_mean < lower) | (data_b.radius_mean > upper)].radius_mean.values) Outliers: [ 6.981 16.84 17.85 ] ```

分析3:箱型圖定位異常

從箱型圖能夠直觀地看到數據的異常點

In [10]:

```python

基於Plotly

fig = px.box(df, x="diagnosis", y="radius_mean", color="diagnosis")

fig.show() ```

```python

基於seaborn

melted_df = pd.melt(df, id_vars = "diagnosis", value_vars = ['radius_mean', 'texture_mean'])

plt.figure(figsize=(15,10))

sns.boxplot(x="variable", y="value", hue="diagnosis", data=melted_df )

plt.show() ```

分析4:描述統計分析describe

良性腫瘤數據data_b的描述統計信息:

```python

針對腫瘤半徑:radius_mean

print("mean: ",data_b.radius_mean.mean()) print("variance: ",data_b.radius_mean.var()) print("standart deviation (std): ",data_b.radius_mean.std()) print("describe method: ",data_b.radius_mean.describe())

----------------

mean: 12.14652380952381 variance: 3.170221722043872 standart deviation (std): 1.7805116461410389 describe method: count 357.000000 mean 12.146524 std 1.780512 min 6.981000 25% 11.080000 50% 12.200000 75% 13.370000 max 17.850000 Name: radius_mean, dtype: float64 ```

分析5:CDF分析(CDF累計分佈函數)

CDF:Cumulative distribution function,中文名稱是累計分佈函數,表示的是變量取值小於或者等於x的概率。P(X <= x)

In [15]:

``` plt.hist(data_b.radius_mean, bins=50, fc=(0,1,0,0.5), label="Bening", normed=True, cumulative=True )

data_sorted=np.sort(data_b.radius_mean) y = np.arange(len(data_sorted)) / float(len(data_sorted) - 1)

plt.title("CDF of Bening Tumor Radius Mean") plt.plot(data_sorted,y,color="blue")

plt.show() ```

分析6:效應值分析-Effect size

Effect size描述的是兩組數據之間的差異大小。值越大,説明兩組數據的差異越明顯。

一般規定為:

  • <0.2:效應小
  • [0.2,0.8]:中等效應
  • >0.8:大效應

在這裏分析的是良性和惡性腫瘤的radius_mean的值差異性

In [16]:

``` diff = data_m.radius_mean.mean() - data_b.radius_mean.mean()

var_b = data_b.radius_mean.var() var_m = data_m.radius_mean.var()

var = (len(data_b) * var_b + len(data_m) * var_m) / float(len(data_b) + len(data_m))

effect_size = diff / np.sqrt(var)

print("Effect Size: ", effect_size) Effect Size: 2.2048585165041428 ```

很明顯:這兩組數據之間存在明顯的效應;也和之間的結論吻合:良性腫瘤和惡性腫瘤的半徑均值彼此間差異大

分析7:兩兩變量間的關係

兩個變量

使用散點圖結合柱狀圖來表示

In [17]:

plt.figure(figsize = (15,10)) sns.jointplot(df.radius_mean, df.area_mean, kind="reg") plt.show()

可以看到這兩個特徵是正相關的

多個變量

In [18]:

```python sns.set(style="white")

df1 = df.loc[:,["radius_mean","area_mean","fractal_dimension_se"]]

g = sns.PairGrid(df1,diag_sharey = False,) g.map_lower(sns.kdeplot,cmap="Blues_d") g.map_upper(plt.scatter) g.map_diag(sns.kdeplot,lw =3)

plt.show() ```

分析8:相關性分析-熱力圖

In [19]:

```python corr = df.corr() # 相關係數

f,ax = plt.subplots(figsize=(18,8))

sns.heatmap(corr, # 相關係數 annot=True,
linewidths=0.5, fmt=".1f", ax=ax )

ticks的旋轉角度

plt.xticks(rotation=90) plt.yticks(rotation=0)

標題

plt.title('Correlation Map')

保存

plt.savefig('graph.png') plt.show() ```

分析9:協方差分析

協方差是衡量兩個變量的變化趨勢:

  • 如果它們變化方向相同,協方差最大
  • 如果它們是正交的,則協方差為零
  • 如果指向相反的方向,則協方差為負數

In [20]:

```

協方差矩陣

np.cov(df.radius_mean, df.area_mean) ```

Out[20]:

array([[1.24189201e+01, 1.22448341e+03], [1.22448341e+03, 1.23843554e+05]])

In [21]:

```

兩個變量的協方差值

df.radius_mean.cov(df.area_mean) ```

Out[21]:

1224.483409346457

In [22]:

```

兩個變量的協方差值

df.radius_mean.cov(df.fractal_dimension_se) ```

Out[22]:

-0.0003976248576440629

分析10:Pearson Correlation

假設有兩個數組,AB,則皮爾遜相關係數定義為:

Pearson=cov(A,B)std(A)∗std(B)

In [23]:

p1 = df.loc[:,["area_mean","radius_mean"]].corr(method= "pearson") p2 = df.radius_mean.cov(df.area_mean)/(df.radius_mean.std()*df.area_mean.std()) print('Pearson Correlation Metric: \n',p1) Pearson Correlation Metric: area_mean radius_mean area_mean 1.000000 0.987357 radius_mean 0.987357 1.000000

In [24]:

print('Pearson Correlation Value: \n', p2) Pearson Correlation Value: 0.9873571700566132

分析11:Spearman's Rank Correlation

Spearman's Rank Correlation,中文可以稱之為:斯皮爾曼下的排序相關性。

皮爾遜相關係數在求解的時候,需要變量之間是線性的,且大體上是正態分佈的

但是如果當數據中存在異常值,或者變量的分佈不是正態的,最好不要使用皮爾遜相關係數。

在這裏採用基於斯皮爾曼的排序相關係數。

In [25]:

``` df_rank = df.rank()

spearman_corr = df_rank.loc[:,["area_mean","radius_mean"]].corr(method= "spearman")

spearman_corr # 基於斯皮爾曼的係數矩陣 ```

Out[25]:

| | area_mean | radius_mean | | ----------: | --------: | ----------: | | area_mean | 1.000000 | 0.999602 | | radius_mean | 0.999602 | 1.000000 |

對比皮爾遜相關係數和斯皮爾曼係數:

  1. 現有數據下,斯皮爾曼相關性比皮爾遜相關係數要大一點
  2. 當數據中存在異常離羣點的時候,斯皮爾曼相關性係數擁有更好的魯棒性

數據獲取

關注公眾號【尤而小屋】後台回覆腫瘤,可以獲取本文數據集,僅供學習使用。