diff --git a/function.py b/function.py index 409b1ac..048eb99 100644 --- a/function.py +++ b/function.py @@ -21,12 +21,14 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423108" +name = "雷武" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def sigmoid(z): + return 1 / (1 + np.exp(-z)) +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ 对率回归训练函数。 @@ -38,9 +40,21 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ + m, n = X.shape + weights = np.zeros(n) + bias = 0 + for i in range(iterations): + linear_model = np.dot(X, weights) + bias + y_pred = sigmoid(linear_model) + dw = (1 / m) * np.dot(X.T, (y_pred - y)) + db = (1 / m) * np.sum(y_pred - y) -def predict_logreg(inX, weights): + weights -= learning_rate * dw + bias -= learning_rate * db + return weights, bias + +def predict_logreg(inX, weights, bias): """ 对率回归预测函数。 @@ -51,7 +65,9 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - + linear_model = np.dot(inX, weights) + bias + y_pred = sigmoid(linear_model) + return 1 if y_pred >= 0.5 else 0 # 这里也写自己的代码实现 def load_data(filepath): @@ -65,7 +81,10 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ - + data = np.loadtxt(filepath, delimiter=',') + X = data[:, :-1] + y = data[:, -1].astype(int) + return X, y if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改