1
我有這個函數,計算相關矩陣和預期工作,但我試圖使它更有效率,擺脫循環,但我'這樣做很麻煩。我下面的功能:我怎樣才能擺脫循環,並使我的相關矩陣功能更有效
def correlation(X):
N = X.shape[0] # num of rows
D = X.shape[1] # num of cols
covarianceMatrix = np.cov(X) # start with covariance matrix
# use covarianceMatrix to create size of M
M = np.zeros([covarianceMatrix.shape[0], covarianceMatrix.shape[1]])
for i in range(covarianceMatrix.shape[0]):
for j in range(covarianceMatrix.shape[1]):
corr = covarianceMatrix[i, j]/np.sqrt(np.dot(covarianceMatrix[i, i], covarianceMatrix[j, j]))
M[i,j] = corr
return M
什麼將使用numpy的是執行這個計算更有效的方式,而不是使用其內置它的功能,如corrcoef()。
這是否工作是否正確?至少有兩個標量的'np.dot'似乎很奇怪。 – MSeifert