更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 13s

This commit is contained in:
2024-11-03 16:15:01 +08:00
parent c0e10e7635
commit b32dc0220d
+30 -6
View File
@@ -23,12 +23,12 @@ import numpy as np
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423xxx"
name = "test_name"
id = "202210423105"
name = "魏明帅"
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
@@ -40,7 +40,19 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
for _ in range(iterations):
for i in range(m):
x_i = X[i]
y_i = y[i]
z = np.dot(x_i, weights)
h = 1 / (1 + np.exp(-z))
error = y_i - h
weights += learning_rate * error * x_i
return weights
def predict_logreg(inX, weights):
"""
@@ -53,7 +65,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
h = 1 / (1 + np.exp(-z))
return 1 if h >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
@@ -67,7 +81,17 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
with open(filepath, 'r') as f:
lines = f.readlines()
X = []
y = []
for line in lines:
values = line.strip().split()
y.append(int(values[-1]))
X.append([float(x) for x in values[:-1]])
return np.array(X), np.array(y)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改