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

This commit is contained in:
2024-10-31 15:07:31 +08:00
parent 4e237d1407
commit 54c6999863
+36 -10
View File
@@ -21,24 +21,35 @@ import numpy as np
""" """
请在这里填写学号和姓名,不填写即成绩无效。 请在这里填写学号和姓名,不填写即成绩无效。
""" """
id = "202210423xxx" id = "202210423213"
name = "test_name" name = "熊浩燃"
# 这里写自己的代码实现 # 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"): def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
""" """
对率回归训练函数。 对率回归训练函数。
Args: Args:
- X (numpy array): 特征数据。 - X (numpy array): 特征数据。
- y (numpy array): 标签数据。 - y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 - learning_rate (float): 学习率。
- iterations (int): 迭代次数。
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape
weights = np.zeros(n)
for _ 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): def predict_logreg(inX, weights):
""" """
@@ -51,7 +62,8 @@ def predict_logreg(inX, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
probability = sigmoid(np.dot(inX, weights))
return 1 if probability >= 0.5 else 0
# 这里也写自己的代码实现 # 这里也写自己的代码实现
def load_data(filepath): def load_data(filepath):
@@ -59,19 +71,33 @@ def load_data(filepath):
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args: Args:
- directory (str): 数据文件路径。 - filepath (str): 数据文件路径。
Returns: Returns:
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
data = []
labels = []
with open(filepath, 'r') as file:
for line in file:
line_data = line.strip().split()
if '?' not in line_data: # 忽略缺失值的行
data.append([float(x) for x in line_data[:-1]])
labels.append(int(float(line_data[-1])))
return np.array(data), np.array(labels)
if __name__ == "__main__": if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改 # 测试数据加载和模型训练预测
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data") X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
# 加载测试集 # 加载测试集
X_test, y_test = load_data("./data/horse-colic.test") X_test, y_test = load_data("./data/horse-colic.test")