計算N×M(建議維度大於100*100)的0,1矩陣均勻分布程度,值由0到1表示不均勻到均勻
import numpy as np
def make_rand_matrix(side=20): # 制作隨機矩陣,用於測試
a = np.random.random((side,side))
for i in range(0,side):
for j in range(0,side):
if a[i,j]>0.3:
a[i,j] = 1
else:
a[i,j] = 0
return a
def get_min_std_matrix(A): # 制作最分布均勻矩陣
sum_ = sum(sum(A))
[x_side, y_side] = A.shape
B = np.zeros((x_side,y_side))
long_ = int(x_side*y_side/sum_)
cnt = 0
for i in range(0,x_side):
for j in range(0,y_side):
cnt = cnt + 1
if cnt%long_ == 0:
B[i,j] = 1
return B
def get_max_std_matrix(A): # 制作分布最不均勻矩陣
sum_ = sum(sum(A))
[x_side, y_side] = A.shape
B = np.zeros((x_side,y_side))
cnt = 0
for i in range(0,x_side):
for j in range(0,y_side):
B[i,j] = 1
cnt = cnt + 1
if cnt >= sum_:
break
return B
def get_rand_std(rand_matrix): # 輸入矩陣為0,1矩陣,計算矩陣分布均勻程度
sum_ = sum(sum(rand_matrix))
[x_side, y_side] = rand_matrix.shape
fit_x_side = int(x_side/10)
fit_y_side = int(y_side/10)
location_p = []
for i in range(0, x_side-10, int(fit_x_side/2)): # 讓每個元素被掃描兩次(規則自己隨便定,保證元素都被掃描到就行)
for j in range(0,y_side-10, int(fit_y_side/2)):
temp_matrix = rand_matrix[i:i+10,j:j+10]
cnt_p = sum(sum(temp_matrix))
location_p.append(cnt_p)
std = np.std(location_p)
return std
def get_stand_std(A): # 將均勻程度分布在0,1之間,1表示分布最均勻
if sum(sum(A)) == 0:
print('不得傳入全0矩陣')
exit()
A_max = get_max_std_matrix(A)
A_min = get_min_std_matrix(A)
A_std = get_rand_std(A)
A_max_std = get_rand_std(A_max)
A_min_std = get_rand_std(A_min)
if A_std < A_min_std:
return 1
else:
return max(0,(A_max_std-A_std)/(A_max_std-A_min_std))
if __name__ == "__main__":
# 當矩陣為0或者1元素過少,計算分布沒有意義
A = make_rand_matrix(100) # numpy產生隨機0,1矩陣均勻程度在0.9~1之間
print(get_stand_std(A))
