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

This commit is contained in:
2024-10-24 17:24:52 +08:00
parent b3f2263587
commit f5a05cfcf8
+27 -12
View File
@@ -21,24 +21,37 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423222"
name = "邓龙树"
import numpy as np
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def sigmoid(z):
"""计算sigmoid函数"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
- learning_rate (float): 学习率,默认值为0.01。
- iterations (int): 迭代次数,默认值为1000。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n) # 初始化权重
for _ in range(iterations):
z = np.dot(X, weights)
predictions = sigmoid(z)
error = predictions - y
gradient = np.dot(X.T, error) / m
weights -= learning_rate * gradient # 更新权重
return weights
def predict_logreg(inX, weights):
"""
@@ -51,24 +64,26 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
probability = sigmoid(np.dot(inX, weights))
return 1 if probability >= 0.5 else 0 # 二分类阈值为0.5
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件中加载数据。
Args:
- directory (str): 数据文件路径。
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=',')
X = data[:, :-1] # 假设最后一列是标签
y = data[:, -1]
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")