generated from LufsX/Experiment-LogReg
This commit is contained in:
+26
-6
@@ -21,12 +21,12 @@ import numpy as np
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423130"
|
||||
name = "董秋"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
@@ -38,7 +38,21 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
|
||||
for _ in range(iterations):
|
||||
# 计算预测值
|
||||
z = np.dot(X, weights)
|
||||
predictions = 1 / (1 + np.exp(-z))
|
||||
|
||||
# 计算损失的梯度
|
||||
gradient = np.dot(X.T, (predictions - y)) / m
|
||||
|
||||
# 更新权重
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
@@ -51,7 +65,10 @@ def predict_logreg(inX, weights):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
|
||||
z = np.dot(inX, weights)
|
||||
prediction_prob = 1 / (1 + np.exp(-z))
|
||||
|
||||
return 1 if prediction_prob >= 0.5 else 0
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
@@ -65,7 +82,10 @@ def load_data(filepath):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
|
||||
data = np.loadtxt(filepath, delimiter=',', dtype=float)
|
||||
X = data[:, :-1] # 特征数据
|
||||
y = data[:, -1] # 标签数据
|
||||
return X, y
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
|
||||
Reference in New Issue
Block a user