diff --git a/function.py b/function.py index 87e4d73..c0e9816 100644 --- a/function.py +++ b/function.py @@ -41,64 +41,34 @@ name = "李劲" """ -python -复制代码 - def classify(input_vector, dataSet, labels, k=3): +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 - 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 +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 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 - +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__": # 以下代码可用于测试,可自行随意修改 train_data, train_labels = load_dataset("trainingDigits")