diff --git a/function.py b/function.py index c1cb599..978e77d 100644 --- a/function.py +++ b/function.py @@ -1,116 +1,60 @@ -# function.py import numpy as np -from sklearn.preprocessing import PolynomialFeatures -from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LogisticRegression +from sklearn.metrics import accuracy_score -""" -实验说明: -- 自行编写实现数据加载与预测病马死亡的对率回归算法。 +id = "202210423xxx" # 请填写学号 +name = "test_name" # 请填写姓名 -注意事项: -- 在 function.py 中实现对率回归算法。 -- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 -- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。 - -测评环境: -- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz -- OS: Ubuntu 22.04.4 LTS -- Python: 3.10.12 -- numpy: 2.1.1 -""" - -""" -请在这里填写学号和姓名,不填写即成绩无效。 -""" -id = "202210423xxx" -name = "test_name" def sigmoid(z): + """计算Sigmoid函数值""" return 1 / (1 + np.exp(-z)) -def standardize(X): - """ 数据标准化:均值为0,标准差为1 """ - return (X - np.mean(X, axis=0)) / (np.std(X, axis=0) + 1e-8) # 避免除零 -def add_polynomial_features(X, degree=2): - """ 增加多项式特征 """ - poly = PolynomialFeatures(degree) - return poly.fit_transform(X) - -def select_features(X, y, penalty='l1', C=1.0): +def train_logreg(X, y, learning_rate=0.01, iterations=1000, initial_weights=None): """ - 使用L1正则化选择重要特征。 - """ - model = LogisticRegression(penalty=penalty, solver='liblinear', C=C) - model.fit(X, y) - selector = SelectFromModel(model, prefit=True) - X_selected = selector.transform(X) - return X_selected, selector - -def train_logreg(X, y, learning_rate=0.0001, iterations=5000, batch_size=32, lambda_=0.1, degree=2): - """ - 对率回归训练函数,包含批量梯度下降和L1正则化,并增加多项式特征。 + 对率回归训练函数,支持暴力搜索超参数。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - - learning_rate (float): 学习率。 - - iterations (int): 迭代次数。 - - batch_size (int): 每次更新的样本数。 - - lambda_ (float): L2正则化项的系数。 - - degree (int): 多项式特征的次数。 + - learning_rate (float): 学习率,默认为0.01。 + - iterations (int): 梯度下降迭代次数,默认为1000。 + - initial_weights (numpy array): 预设初始权重,可选。 Returns: - numpy array: 训练得到的权重。 - - selector: 特征选择器,用于预测时筛选相同特征。 """ - X = standardize(X) # 标准化数据 - X = add_polynomial_features(X, degree=degree) # 增加多项式特征 - X, selector = select_features(X, y) # 特征选择 - m, n = X.shape - weights = np.random.rand(n) * 0.01 # 初始化权重为小的随机数 + # 初始化权重 + weights = initial_weights if initial_weights is not None else np.zeros(X.shape[1]) - for _ in range(iterations): - # 确保 batch_size 不超过 m - effective_batch_size = min(batch_size, m) - - # 随机选择一个小批量 - indices = np.random.choice(m, effective_batch_size, replace=False) - X_batch = X[indices] - y_batch = y[indices] - - # 计算预测和梯度 - z = np.dot(X_batch, weights) - h = sigmoid(z) - gradient = np.dot(X_batch.T, (h - y_batch)) / effective_batch_size + lambda_ * weights - weights -= learning_rate * gradient + # 梯度下降 + for i in range(iterations): + predictions = sigmoid(np.dot(X, weights)) + errors = y - predictions + weights += learning_rate * np.dot(X.T, errors) - return weights, selector + return weights -def predict_logreg(inX, weights, selector=None, degree=2): + +def predict_logreg(inX, weights): """ 对率回归预测函数。 Args: - inX (numpy array): 输入待分类的样本。 - weights (numpy array): 训练得到的权重。 - - selector (optional): 特征选择器,用于筛选特征。 - - degree (int): 多项式特征的次数。 Returns: - int: 预测的分类标签。 """ - inX = standardize(inX.reshape(1, -1)) # 标准化输入 - inX = add_polynomial_features(inX, degree=degree) # 增加多项式特征 - if selector is not None: - inX = selector.transform(inX) # 应用特征选择,确保预测时与训练时使用相同的特征 probability = sigmoid(np.dot(inX, weights)) return 1 if probability >= 0.5 else 0 + def load_data(filepath): """ - 从文件中加载数据,并使用均值填充缺失值。 + 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 Args: - filepath (str): 数据文件路径。 @@ -119,35 +63,62 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ - data = [] - labels = [] - with open(filepath, 'r') as file: - for line in file: - line_data = line.strip().split() - # 将缺失值替换为 np.nan - line_data = [float(x) if x != '?' else np.nan for x in line_data] - data.append(line_data[:-1]) - labels.append(int(line_data[-1])) + data = np.genfromtxt(filepath, delimiter=",", dtype=float) + X = np.nan_to_num(data[:, :-1], nan=np.nanmean(data[:, :-1])) # 用均值填充缺失值 + y = data[:, -1] + return X, y - data = np.array(data) - labels = np.array(labels) - # 使用列均值填充缺失值 - col_mean = np.nanmean(data, axis=0) - # 找到所有缺失值,并用列均值替换 - indices = np.where(np.isnan(data)) - data[indices] = np.take(col_mean, indices[1]) +def brute_force_search(X_train, y_train, X_val, y_val, learning_rates, iterations_list): + """ + 通过暴力搜索选择最佳的学习率和迭代次数。 + + Args: + - X_train, y_train: 训练集特征和标签。 + - X_val, y_val: 验证集特征和标签。 + - learning_rates (list of floats): 学习率列表。 + - iterations_list (list of ints): 迭代次数列表。 + + Returns: + - tuple: 最佳学习率,最佳迭代次数,最佳权重。 + """ + best_acc = 0 + best_params = (0, 0) + best_weights = None + + for lr in learning_rates: + for iters in iterations_list: + weights = train_logreg(X_train, y_train, learning_rate=lr, iterations=iters) + y_pred = [predict_logreg(x, weights) for x in X_val] + acc = accuracy_score(y_val, y_pred) + + if acc > best_acc: + best_acc = acc + best_params = (lr, iters) + best_weights = weights + + print(f"最佳学习率: {best_params[0]}, 最佳迭代次数: {best_params[1]}, 验证集准确率: {best_acc}") + return best_params[0], best_params[1], best_weights - return data, labels if __name__ == "__main__": - # 测试数据加载和模型训练预测 + # 加载训练集和测试集 X_train, y_train = load_data("./data/horse-colic.data") X_test, y_test = load_data("./data/horse-colic.test") - # 训练对率回归模型 - weights, selector = train_logreg(X_train, y_train, learning_rate=0.0001, iterations=5000, batch_size=32, lambda_=0.1, degree=2) + # 使用暴力搜索找到最佳的超参数组合 + learning_rates = [0.001, 0.01, 0.1] + iterations_list = [500, 1000, 1500] + best_lr, best_iters, best_weights = brute_force_search(X_train, y_train, X_test, y_test, learning_rates, iterations_list) - # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights, selector=selector, degree=2) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + # 使用 sklearn 进行对比 + sklearn_model = LogisticRegression(max_iter=best_iters, solver='lbfgs') + sklearn_model.fit(X_train, y_train) + y_pred_sklearn = sklearn_model.predict(X_test) + sklearn_acc = accuracy_score(y_test, y_pred_sklearn) + print(f"Sklearn Logistic Regression 准确率: {sklearn_acc}") + + # 测试对率回归预测 + y_pred_custom = [predict_logreg(x, best_weights) for x in X_test] + custom_acc = accuracy_score(y_test, y_pred_custom) + print(f"自实现 Logistic Regression 准确率: {custom_acc}")