diff --git a/function.py b/function.py index 409b1ac..96be51b 100644 --- a/function.py +++ b/function.py @@ -21,8 +21,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423204" +name = "陈垣豪" # 这里写自己的代码实现 @@ -38,6 +38,17 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ + m, n = X.shape # m: 样本数, n: 特征数 + weights = np.zeros(n) # 初始化权重 + + # 训练逻辑回归模型 + for _ in range(iterations): + z = np.dot(X, weights) # 线性组合 + predictions = 1 / (1 + np.exp(-z)) # 计算预测值,直接使用 sigmoid 公式 + # 更新权重 + weights += learning_rate * (1/m) * np.dot(X.T, (y - predictions)) + + return weights def predict_logreg(inX, weights): @@ -51,6 +62,8 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ + prob = 1 / (1 + np.exp(-np.dot(inX, weights))) # 直接使用 sigmoid 公式计算概率 + return 1 if prob >= 0.5 else 0 # 根据阈值返回标签 # 这里也写自己的代码实现 @@ -65,6 +78,10 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ + data = np.loadtxt(filepath, delimiter=',', dtype=float, skiprows=1) + X = data[:, :-1] # 所有列,除了最后一列 + y = data[:, -1] # 最后一列作为标签 + return X, y if __name__ == "__main__":