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

This commit is contained in:
2024-10-31 11:35:25 +08:00
parent a173560a87
commit 18df987e0a
+37 -24
View File
@@ -1,9 +1,8 @@
# function.py
import numpy as np
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 function.py 中实现对率回归算法。
@@ -17,28 +16,54 @@ import numpy as np
- numpy: 2.1.1
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423118"
name = "刘国庆"
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.genfromtxt(filepath, delimiter=',', missing_values='?', filling_values=np.nan)
data = data[~np.isnan(data).any(axis=1)] # Remove rows with NaN values
X = data[:, :-1] # All columns except the last one
y = data[:, -1] # Last column
return X, y
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): 学习率。
- iterations (int): 迭代次数。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n) # Initialize weights
for _ in range(iterations):
z = np.dot(X, weights) # Linear combination
predictions = sigmoid(z) # Apply sigmoid
# Update weights using gradient ascent
weights += (learning_rate / m) * np.dot(X.T, (y - predictions))
return weights
def predict_logreg(inX, weights):
"""
@@ -51,21 +76,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
z = np.dot(inX, weights)
prediction_prob = sigmoid(z)
return 1 if prediction_prob >= 0.5 else 0
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改