diff --git a/function.py b/function.py index 6913a9f..87e4d73 100644 --- a/function.py +++ b/function.py @@ -41,83 +41,63 @@ name = "李劲" """ -def classify(input_vector, dataSet, labels, k=3): # 设置 k 的默认值为 3 - """ - KNN 分类算法,使用马氏距离。 - - Args: - - input_vector (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,选择距离最小的 k 个样本进行投票。 - - Returns: - - int: 预测的分类标签。 - """ - # 计算训练数据集的均值向量 - mean_vec = np.mean(dataSet, axis=0) - - # 计算训练数据集的协方差矩阵 - cov_mat = np.cov(dataSet, rowvar=False) - - # 计算输入样本到所有训练样本的马氏距离 - # 注意:mahalanobis 函数要求输入二维数组,因此需要对 input_vector 进行 reshape - # 同时,dataSet 也需要是二维数组,如果它是三维的(例如有多个特征图),则需要先展平 - inv_covmat = np.linalg.inv(cov_mat) # 计算协方差矩阵的逆 - distances = [] - for row in dataSet: - dist = mahalanobis(input_vector.reshape(1, -1), row.reshape(1, -1), inv_covmat) - distances.append(dist) - - # 选择距离最小的 k 个样本的索引 - k_indices = np.argsort(distances)[:k] - - # 选择这些样本对应的标签 - k_nearest_labels = [labels[i] for i in k_indices] - - # 返回出现次数最多的标签 - from collections import Counter - most_common = Counter(k_nearest_labels).most_common(1) - return most_common[0][0] - -def load_dataset(directory): - """ - 从文件夹中加载数据,并返回特征数据和标签数据。 - 这里假设文件夹中的每个文件都是一个二值图像,文件名包含了标签信息。 - - Args: - - directory (str): 数据文件夹路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ - data = [] - labels = [] - for filename in os.listdir(directory): - if filename.endswith(".txt"): # 假设图像数据以文本形式存储,且文件名包含标签 - label = int(filename.split('_')[0]) # 从文件名中提取标签,这里假设文件名格式为 "label_xxx.txt" - img_vector = img_to_vector(os.path.join(directory, filename)) - data.append(img_vector) - labels.append(label) - return np.array(data), np.array(labels) - -def img_to_vector(filename): - """ - 将二值图像(以文本形式存储)转换为向量。 - 这里假设图像数据是以空格分隔的 0 和 1 组成的字符串。 - - Args: - - filename (str): 图像文件路径。 - - Returns: - - np.array: 二值图像向量。 - """ - with open(filename, 'r') as f: - img_str = f.read().strip() - img_vector = np.array([int(char) for char in img_str]).reshape(1, -1) - return img_vector.flatten() # 展平为一维向量 +python +复制代码 + def classify(input_vector, dataSet, labels, k=3): + cov_matrix = np.cov(dataSet, rowvar=False) + + inv_cov_matrix = np.linalg.inv(cov_matrix) + + diffMat = dataSet - input_vector + + left_term = np.dot(diffMat, inv_cov_matrix) + + mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1)) + + k_indices = np.argsort(mahalanobis_distances)[:k] + + k_nearest_labels = [labels[i] for i in k_indices] + + most_common = max(set(k_nearest_labels), key=k_nearest_labels.count) + + return most_common + +python +复制代码 + def load_dataset(directory): + + features = [] + + labels = [] + + for filename in os.listdir(directory): + + if filename.endswith(".txt"): + + filepath = os.path.join(directory, filename) + + label = int(filename.split('_')[0]) + + image_vector = img_to_vector(filepath) + + features.append(image_vector) + + labels.append(label) + + return np.array(features), np.array(labels) + +python +复制代码 + def img_to_vector(filename): + + with open(filename) as file: + + lines = file.readlines() + + image_vector = np.array([int(char) for line in lines for char in line.strip()]) + + return image_vector if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改