import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
# data = iris.data
# print(data[0])
# print(data[2])
# print(type(iris.data))
# print(iris.data.shape)
# LenRow, LenColumn = iris.data.shape
# print("LenRow={}".format(LenRow))
# print("LenColumn={}".format(LenColumn))
def Distance(datarow_1,datarow_2):
a = len(datarow_1)
b = len(datarow_2)
distance = 0
term = 0
if a != b:
return None
else:
for i in range(0,a):
term += (datarow_1[i] - datarow_2[i]) ** 2
distance = np.sqrt(term)
return distance
def DistanceMatrix(data):
LenRow, LenColumn = data.shape
Dis_Mat = np.zeros((LenRow,LenRow))
for i in range(0,LenRow):
for j in range(0,LenRow):
if i < j:
Dis_Mat[i,j]=Dis_Mat[j,i] = Distance(data[i],data[j])
return Dis_Mat
if __name__ == "__main__":
# data = iris.data
# dis = Distance(data[0],data[3])
# print(dis)
Dis_Mat = DistanceMatrix(iris.data)
print(type(Dis_Mat))
print(Dis_Mat[2,3])
print(Dis_Mat[3,2])
print(Dis_Mat[4,5])
print(Dis_Mat[5,4])
print(Dis_Mat[1,1])
print(Dis_Mat[12,12])
给聚类算法做准备