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

This commit is contained in:
2024-10-26 12:45:11 +08:00
parent ce7f269fcc
commit abf074b24f
+21 -9
View File
@@ -27,18 +27,18 @@ name = "章程鸿"
# 这里写自己的代码实现
import numpy as np
from sklearn.preprocessing import StandardScaler
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def train_logreg(X, y, learning_rate=0.01, iterations=5000):
"""
对率回归训练函数。
逻辑回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
@@ -57,7 +57,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def predict_logreg(inX, weights):
"""
对率回归预测函数。
逻辑回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
@@ -70,13 +70,12 @@ def predict_logreg(inX, weights):
h = sigmoid(z)
return 1 if h >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件中加载数据。
Args:
- directory (str): 数据文件路径。
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
@@ -86,20 +85,33 @@ def load_data(filepath):
with open(filepath, 'r') as file:
for line in file:
# 清理无效数据
cleaned_line = line.strip().replace('?', '0') # 将问号替换为0
cleaned_line = line.strip().replace('?', '0') # 将问号替换为 0
data.append([float(x) for x in cleaned_line.split()]) # 转换为浮点数
data = np.array(data)
X = data[:, :-1]
y = data[:, -1]
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 训练逻辑回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.005, iterations=5000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)