Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Khám phá tương quan (Correlation) trong Python


Tương quan (Correlation) đo lường mối quan hệ giữa 2 biến. Mối quan hệ mạnh: thay đổi biến này dự đoán được thay đổi biến kia. Biến thiên dương hoặc âm. Hệ số tương quan từ -1 đến +1.

  • +1 hoặc gần: tương quan dương, cùng chiều.
  • -1 hoặc gần: tương quan âm, ngược chiều.
  • 0 hoặc gần: không tương quan.

Có nhiều cách đo, có sẵn trong numpy/scipy.stats.

Tương quan Spearman

Đo mức độ liên quan tuyến tính. Dùng scipy.stats.spearmanr(). Phổ biến nhất.

Ví dụ

from numpy.random import randn, seed
from scipy.stats import spearmanr

seed(1)
data_input1 = 20 * randn(1000) + 100
data_input2 = data_input1 + (10 * randn(1000) + 50)
correlation = spearmanr(data_input1, data_input2)
print(correlation)

Kết quả

SpearmanrResult(correlation=0.8724050484050484, pvalue=1.58425746359e-312)

Tương quan Pearson

Cách khác đo liên quan tuyến tính. Dùng scipy.stats.pearsonr().

Ví dụ

from numpy.random import randn, seed
from scipy.stats import pearsonr

seed(1)
data1 = 20 * randn(1000) + 100
data2 = data1 + (10 * randn(1000) + 50)
correlation, _ = pearsonr(data1, data2)
print('Pearson correlation: %.3f' % correlation)

Kết quả

Pearson correlation: 0.888