From 7cd0a8f7dbcf9f4cf55728b4db286b31248b0dc8 Mon Sep 17 00:00:00 2001 From: LufsX Date: Tue, 15 Oct 2024 20:43:50 +0800 Subject: [PATCH] use from import single function --- function.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index ea64374..63f8eeb 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ # function.py -import numpy as np import time +from numpy.linalg import inv +from numpy import sum, argpartition, bincount, argmax, cov, loadtxt """ 挑战说明: @@ -55,29 +56,29 @@ def classify0(inX, dataSet, labels, k=8, _cache={"VI": None}): # 管它三七二十一,直接用缓存 if _cache["VI"] is None: # 缓存数据集的协方差矩阵的逆 - _cache["VI"] = np.linalg.inv(np.cov(dataSet.T)) + _cache["VI"] = inv(cov(dataSet.T)) # 计算 inX 与数据集的差值 diff = dataSet - inX # 使用矩阵运算计算马氏距离 - distances = np.sum(diff @ _cache["VI"] * diff, axis=1) + distances = sum(diff @ _cache["VI"] * diff, axis=1) # 对距离排序,获取前 k 个最近的样本索引 - sortedDistIndices = np.argpartition(distances, 8)[:8] + sortedDistIndices = argpartition(distances, 8)[:8] # 统计前 k 个样本的标签 - classCount = np.bincount(labels[sortedDistIndices]) + classCount = bincount(labels[sortedDistIndices]) # 返回出现次数最多的标签 - return np.argmax(classCount) + return argmax(classCount) def load_data(file_path): """ 加载 TSV 格式数据文件。 """ - data = np.loadtxt(file_path, delimiter="\t") + data = loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) return features, labels