diff --git a/function.py b/function.py index 750a541..c69e451 100644 --- a/function.py +++ b/function.py @@ -23,8 +23,8 @@ import numpy as np 姓名请直接**填写中文** 例如: name = "张三" """ -id = "202210423xxx" -name = "test_name" +id = "202210423115" +name = "李煜锋" # 这里写自己的代码实现 @@ -40,7 +40,17 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ - +m, n = X.shape + weights = np.zeros(n) + + # 梯度下降法 + for _ in range(iterations): + linear_model = np.dot(X, weights) + predictions = 1 / (1 + np.exp(-linear_model)) # sigmoid函数 + # 更新权重 + weights += learning_rate * (1/m) * np.dot(X.T, (y - predictions)) + + return weights def predict_logreg(inX, weights): """ @@ -53,7 +63,24 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ +linear_model = np.dot(inX, weights) + prediction = 1 / (1 + np.exp(-linear_model)) # sigmoid函数 + return 1 if prediction >= 0.5 else 0 # 采用0.5作为阈值 +if __name__ == "__main__": + # 以下代码可用于测试,可自行随意修改 + # 加载训练集 + X_train, y_train = load_data("./horse-colic.data") + + # 加载测试集 + X_test, y_test = load_data("./horse-colic.test") + + # 训练对率回归模型 + weights = train_logreg(X_train, y_train) + + # 测试单个数据 + y_pred = predict_logreg(X_test[11], weights) + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") # 这里也写自己的代码实现 def load_data(filepath): @@ -67,7 +94,23 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ +# 使用空白作为分隔符读取数据 + data = pd.read_csv(filepath, sep='\s+', header=None, na_values='?') + + # 填充缺失值 + data.fillna(0, inplace=True) + # 处理目标变量,假设第 23 列是目标变量(索引 22) + data[22] = data[22].replace({2: 0, 3: 0}) + + # 去掉特征 3(索引 2)及特征 24~28(索引 23~27),如果这些列存在 + columns_to_drop = [2, 23, 24, 25, 26, 27] + data = data.drop(columns=[col for col in columns_to_drop if col in data.columns]) + + # 分离特征和标签 + X = data.drop(columns=[22]).to_numpy() # 特征数据 + y = data[22].to_numpy() # 标签数据 + return X, y if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改