python-numpy-方差、相關係數
阿新 • • 發佈:2019-01-08
# Array of differences to mean: differences differences=versicolor_petal_length-np.mean(versicolor_petal_length) # Square the differences: diff_sq diff_sq=np.square(differences) # Compute the mean square difference: variance_explicit variance_explicit=np.mean(diff_sq) # Compute the variance using NumPy: variance_np variance_np=np.var(versicolor_petal_length) # Print the results print(variance_explicit,variance_np)
def pearson_r(x, y): """Compute Pearson correlation coefficient between two arrays.""" # Compute correlation matrix: corr_mat corr_mat=np.corrcoef(x,y) # Return entry [0,1] return corr_mat[0,1] # Compute Pearson correlation coefficient for I. versicolor: r r=pearson_r(versicolor_petal_length, versicolor_petal_width) # Print the result print(r)