generated from LufsX/Experiment-kNN
This commit is contained in:
+29
-29
@@ -41,24 +41,20 @@ def classify(input_vector, dataSet, labels, k=2):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
num_samples = dataSet.shape[0]
|
||||
mu = np.mean(dataSet, axis = 0)
|
||||
cov = np.cov(dataSet.T)
|
||||
try:
|
||||
inv_cov = np.linalg.inv(cov)
|
||||
except np.linalg.LinAlgError:
|
||||
# 如果协方差矩阵不可逆,使用伪逆
|
||||
inv_cov = np.linalg.pinv(cov)
|
||||
distances = []
|
||||
for i in range(num_samples):
|
||||
diff = (input_vector - dataSet[i])
|
||||
distance = np.sqrt(np.dot(np.dot(diff, inv_cov), diff.T))
|
||||
distances.append(distance)
|
||||
distances = np.array(distances)
|
||||
sorted_indices = np.argsort(distances)
|
||||
k_nearest_labels = [labels[i] for i in sorted_indices[:k]]
|
||||
unique_labels, counts = np.unique(k_nearest_labels, return_counts = True)
|
||||
return unique_labels[np.argmax(counts)]
|
||||
dataSet_size = dataSet.shape[0]
|
||||
# 计算欧氏距离
|
||||
diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet
|
||||
sq_diff_mat = diff_mat ** 2
|
||||
sq_distances = sq_diff_mat.sum(axis=1)
|
||||
distances = np.sqrt(sq_distances)
|
||||
# 对距离进行排序
|
||||
sorted_indices = distances.argsort()
|
||||
class_count = {}
|
||||
for i in range(k):
|
||||
vote_label = labels[sorted_indices[i]]
|
||||
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
||||
sorted_class_count = sorted(class_count.items(), key=lambda x: x[1], reverse=True)
|
||||
return sorted_class_count[0][0]
|
||||
|
||||
|
||||
def img_to_vector(filename):
|
||||
@@ -72,9 +68,13 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
with open(filename, 'r') as f:
|
||||
lines = f.readlines()
|
||||
return np.array([int(char) for line in lines for char in line.strip()])
|
||||
return_vector = np.zeros((1, 1024))
|
||||
with open(filename) as f:
|
||||
for i in range(32):
|
||||
line = f.readline()
|
||||
for j in range(32):
|
||||
return_vector[0, 32 * i + j] = int(line[j])
|
||||
return return_vector
|
||||
|
||||
|
||||
def load_dataset(directory):
|
||||
@@ -88,15 +88,15 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
data_set = []
|
||||
labels = []
|
||||
for filename in os.listdir(directory):
|
||||
if filename.endswith(".txt"):
|
||||
label = int(filename[0])
|
||||
vector = img_to_vector(os.path.join(directory, filename))
|
||||
data.append(vector)
|
||||
labels.append(label)
|
||||
return np.array(data), np.array(labels)
|
||||
for root, dirs, files in os.walk(directory):
|
||||
for file in files:
|
||||
if file.endswith('.txt'):
|
||||
label = int(file.split('_')[0])
|
||||
labels.append(label)
|
||||
data_set.append(img_to_vector(os.path.join(root, file)))
|
||||
return np.array(data_set).reshape(len(data_set), -1), np.array(labels)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user