import numpy as np import pandas as pd # 填写学号和姓名 id = "20221042323" name = "李顺潮" def train_logreg(X, y, other_params="你自己设置一些其它参数", learning_rate=0.01, num_iterations=1000): """ 对率回归训练函数。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - other_params (str): 其它参数,这里暂未使用。 - learning_rate (float): 学习率。 - num_iterations (int): 迭代次数。 Returns: - numpy array: 训练得到的权重。 """ # 添加偏置项 X_b = np.c_[np.ones((X.shape[0], 1)), X] # 添加一列1作为偏置项 m, n = X_b.shape weights = np.zeros(n) # 梯度下降 for iteration in range(num_iterations): y_pred_prob = 1 / (1 + np.exp(-np.dot(X_b, weights))) dw = (1 / m) * np.dot(X_b.T, (y_pred_prob - y)) weights -= learning_rate * dw return weights def predict_logreg(inX, weights): """ 对率回归预测函数。 Args: - inX (numpy array): 输入待分类的样本。 - weights (numpy array): 训练得到的权重。 Returns: - int: 预测的分类标签。 """ # 添加偏置项 inX_b = np.c_[1, inX] y_pred_prob = 1 / (1 + np.exp(-np.dot(inX_b, weights))) return 1 if y_pred_prob > 0.5 else 0 def load_data(filepath): """ 从文件中加载数据。 Args: - filepath (str): 数据文件路径。 Returns: - np.array: 特征数据。 - np.array: 标签数据。 """ # 使用 pandas 加载数据,假设数据使用空格分隔,并且我们想要跳过第一列(可能是标识符) df = pd.read_csv(filepath, delim_whitespace=True, header=None) # 假设最后一列是标签,将其转换为 0 和 1 df.iloc[:, -1] = df.iloc[:, -1].apply(lambda x: 1 if x == 2 else 0) # 将缺失值(如 '?')替换为 NaN,然后删除包含 NaN 的行(或者选择其他处理方式) df.replace('?', np.nan, inplace=True) df.dropna(inplace=True) # 提取特征和标签 X = df.iloc[:, :-1].values # 特征 y = df.iloc[:, -1].values # 标签 return X, y if __name__ == "__main__": # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") # 数据标准化 scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) # 训练模型 weights = train_logreg(X_train_scaled, y_train) # 测试预测(这里示例性地选择一个样本进行预测) sample_index = 0 # 选择第一个样本进行预测 y_pred = predict_logreg(X_train_scaled[sample_index], weights) print(f"预测结果: {y_pred}, 实际结果: {y_train[sample_index]}")