diff --git a/function.py b/function.py index 409b1ac..ed72c73 100644 --- a/function.py +++ b/function.py @@ -21,12 +21,12 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423201" +name = "陈瑞琪祥" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ 对率回归训练函数。 @@ -38,7 +38,22 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ - + # 初始化权重 + weights = np.zeros(X.shape[1]) + + # 学习率和迭代次数 + learn_rate = learning_rate + niterations = iterations + + # 梯度上升 + for i in range(niterations): + # 计算梯度 + gradient = np.dot(X.T, (sigmoid(np.dot(X, weights)) - y)) / X.shape[0] + + # 更新权重 + weights += learn_rate * gradient + + return weight def predict_logreg(inX, weights): """ @@ -51,7 +66,14 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - +# 计算概率 + prob = sigmoid(np.dot(inX, weights)) + + # 预测分类 + if prob > 0.5: + return 1 + else: + return 0 # 这里也写自己的代码实现 def load_data(filepath): @@ -65,6 +87,8 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ + data = np.loadtxt(filepath, delimiter=',', skiprows=1) + return data[:, :-1], data[:, -1] if __name__ == "__main__":