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

This commit is contained in:
cy
2024-10-24 16:57:04 +08:00
parent b5e77650d7
commit 9de7c1d155
+26 -6
View File
@@ -21,12 +21,14 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423117"
name = "程悦"
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
@@ -38,7 +40,14 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
for i in range(iterations):
z = np.dot(X, weights)
h = sigmoid(z)
gradient = np.dot(X.T, (h - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
@@ -51,7 +60,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
h = sigmoid(z)
return 1 if h > 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
@@ -65,7 +76,16 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip().split()
line_data = [1] + [float(i) for i in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
return np.array(data), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改