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

This commit is contained in:
2024-11-03 17:08:20 +08:00
parent d8ee5acc42
commit 47b2cc1cbe
+33 -6
View File
@@ -1,4 +1,3 @@
# function.py
import numpy as np
"""
@@ -23,23 +22,32 @@ import numpy as np
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423xxx"
name = "test_name"
id = "202210423220"
name = "方子涵"
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
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):
linear_model = np.dot(X, weights)
y_predicted = 1 / (1 + np.exp(-linear_model))
gradient = np.dot(X.T, (y_predicted - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
@@ -53,6 +61,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
linear_model = np.dot(inX, weights)
y_predicted = 1 / (1 + np.exp(-linear_model))
return 1 if y_predicted > 0.5 else 0
# 这里也写自己的代码实现
@@ -61,18 +72,34 @@ def load_data(filepath):
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
with open(filepath, 'r') as file:
lines = file.readlines()
features = []
labels = []
for line in lines:
parts = line.strip().split(',')
label = int(parts[-1])
features.append([float(x) for x in parts[:-1]])
labels.append(label)
return np.array(features), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 训练模型
weights = train_logreg(X_train, y_train)
# 预测
predictions = [predict_logreg(X_train[i], weights) for i in range(X_train.shape[0])]
# 打印预测结果
print(predictions)
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")