diff --git a/function.py b/function.py index 852db3c..501b1aa 100644 --- a/function.py +++ b/function.py @@ -28,60 +28,24 @@ name = "廖子豪" # 这里写自己的代码实现 def load_data(filepath): - """ - 从文件中加载数据。 - - Args: - - filepath (str): 数据文件路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ try: - # 使用 numpy 的 genfromtxt 函数加载数据,自动处理缺失值 - # 指定空格作为分隔符 data = np.genfromtxt(filepath, delimiter=' ', dtype=float, filling_values=np.nan) - - print(f"Loaded data shape: {data.shape}") # 调试打印数据形状 - - # 检查数据是否为一维数组 + print(f"Loaded data shape: {data.shape}") if data.ndim == 1: raise ValueError("数据加载后为一维数组,预期为二维数组。请检查数据文件格式。") - - # 检查数据文件中是否有足够的列 if data.shape[1] < 2: raise ValueError("数据文件中没有足够的列。每行至少需要包含一个特征和一个标签。") - - # 分离特征和标签 - X = data[:, :-1] # 所有行,除了最后一列 - y = data[:, -1] # 所有行,只有最后一列 - - # 填充缺失值,这里使用每列的均值来填充 + X = data[:, :-1] + y = data[:, -1] X = np.nan_to_num(X, nan=np.nanmean(X, axis=0)) - return X, y except Exception as e: print(f"Error loading data: {e}") - # 返回空数组而不是None,以避免后续代码中出现错误 return np.empty((0, 0)), np.empty(0) def train_logreg(X, y, learning_rate=0.01, iterations=1000): - """ - 对率回归训练函数。 - - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - learning_rate (float): 学习率,默认为0.01。 - - iterations (int): 迭代次数,默认为1000。 - - Returns: - - numpy array: 训练得到的权重。 - """ m, n = X.shape - # 添加偏置项 - X = np.c_[np.ones((m, 1)), X] + X = np.c_[np.ones((m, 1)), X] # 添加偏置项 weights = np.zeros(n + 1) for _ in range(iterations): for i in range(m): @@ -91,46 +55,23 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000): return weights def predict_logreg(inX, weights): - """ - 对率回归预测函数。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - Returns: - - int: 预测的分类标签。 - """ - # 确保输入样本是二维数组 if inX.ndim == 1: - inX = inX.reshape(1, -1) # 将一维数组转换为二维数组 - - # 添加偏置项 - inX = np.hstack([np.ones((inX.shape[0], 1)), inX]) # 在特征向量的开头添加偏置项 + inX = inX.reshape(1, -1) + inX = np.c_[np.ones((1, 1)), inX] # 添加偏置项 z = np.dot(inX, weights) y_pred = 1 / (1 + np.exp(-z)) return 1 if y_pred > 0.5 else 0 if __name__ == "__main__": - # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") - - # 加载测试集 X_test, y_test = load_data("./data/horse-colic.test") - # 特征缩放 scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) - # 训练对率回归模型 weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) - # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") - - # 评估模型 y_pred_all = [predict_logreg(X_test[i], weights) for i in range(len(X_test))] accuracy = np.mean(y_pred_all == y_test) print(f"Accuracy: {accuracy}") \ No newline at end of file