generated from LufsX/Experiment-LogReg
This commit is contained in:
+30
-3
@@ -21,12 +21,12 @@ import numpy as np
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423217"
|
||||
name = "吴俊煯"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
@@ -38,7 +38,23 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
bias = 0
|
||||
|
||||
for _ in range(iterations):
|
||||
for idx, x_i in enumerate(X):
|
||||
linear_output = np.dot(x_i, weights) + bias
|
||||
y_predicted = 1 / (1 + np.exp(-linear_output))
|
||||
|
||||
# 计算误差
|
||||
error = y[idx] - y_predicted
|
||||
|
||||
# 更新权重和偏置
|
||||
weights += learning_rate * error * x_i
|
||||
bias += learning_rate * error
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
@@ -51,7 +67,11 @@ def predict_logreg(inX, weights):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
linear_output = np.dot(inX, weights)
|
||||
y_predicted = 1 / (1 + np.exp(-linear_output))
|
||||
|
||||
# 将输出转换为分类标签
|
||||
return 1 if y_predicted >= 0.5 else 0
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
@@ -65,7 +85,14 @@ def load_data(filepath):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = np.loadtxt(filepath, delimiter=',')
|
||||
X = data[:, :-1]
|
||||
y = data[:, -1]
|
||||
|
||||
# 将标签转换为0和1(假设原始标签为1和2)
|
||||
y = np.where(y == 1, 0, 1)
|
||||
|
||||
return X, y
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
|
||||
Reference in New Issue
Block a user