<jupyter_start><jupyter_text>皮爾遜相關係數```購物問卷調查實例詢問消費者2019年對於整個購物的滿意度，以及針對調查對象詢問今年再次繼續購買商品的次數。平均滿意度為8平均再次購買次數12```![](images/pearson.PNG)<jupyter_code>import numpy as np

x = np.array([8, 9, 10, 7, 8, 9, 5, 7, 9, 8])
y = np.array([12, 15, 16, 18, 6, 11, 3, 12, 11, 16])             

x_mean = np.mean(x)
y_mean = np.mean(y)

print(x_mean)
print(y_mean)

xi_x = [v - x_mean for v in x]
yi_y = [v - y_mean for v in y]

data1 = [0] * 10
data2 = [0] * 10
data3 = [0] * 10

for i in range(len(x)):
    data1[i] = xi_x[i] * yi_y[i]
    data2[i] = pow(xi_x[i], 2)
    data3[i] = pow(yi_y[i], 2)
    
v1 = np.sum(data1)
v2 = np.sum(data2)
v3 = np.sum(data3)

r = v1 / (pow(v2, 0.5) * pow(v3, 0.5))
print('coefficient = {}'.format(r))<jupyter_output>8.0
12.0
coefficient = 0.5050762722761054<jupyter_text>繪製消費者滿意度與再購買次數的散佈圖<jupyter_code>import numpy as np
import matplotlib.pyplot as plt

x = np.array([8, 9, 10, 7, 8, 9, 5, 7, 9, 8])
y = np.array([12, 15, 16, 18, 6, 11, 3, 12, 11, 16])             
x_mean = np.mean(x)
y_mean = np.mean(y)
xpt1 = np.linspace(0, 12, 12)      
ypt1 = [y_mean for xp in xpt1]          # 平均購買次數
ypt2 = np.linspace(0, 20, 20)
xpt2 = [x_mean for yp in ypt2]          # 平均滿意度

plt.scatter(x, y)                       # 滿意度 vs 購買次數
plt.plot(xpt1, ypt1, 'g')               # 平均購買次數
plt.plot(xpt2, ypt2, 'b')               # 平均滿意度
plt.grid()
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17693409742120345, 'fraction_numerical': 0.09813753581661891, 'mean_word_length': 2.9914285714285715, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '202181', 'license': 'MIT', 'n_tokens_mistral': 905, 'n_tokens_neox': 811, 'n_words': 155, 'path': 'Unit03/1_Pearson_correlation_coefficient.ipynb', 'repo_name': 'appletime81/IMLP', 'size': '1396'}