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

This commit is contained in:
wzy
2024-10-26 12:20:04 +08:00
parent ee44dd971c
commit a9fb7b5eaa
+30 -6
View File
@@ -1,6 +1,6 @@
# function.py # function.py
import numpy as np import numpy as np
from sklearn.model_selection import train_test_split import random
""" """
实验说明: 实验说明:
@@ -68,10 +68,12 @@ def train_logreg(X, y, learning_rate=0.001, iterations=1000, batch_size=32, init
""" """
def evaluate_model(X_val, y_val, weights): def predict_logreg(inX, weights):
predictions = np.array([predict_logreg(x, weights) for x in X_val]) inX = np.insert(inX, 0, 1) # 添加偏置项
accuracy = np.mean(predictions == y_val) z = np.dot(inX, weights)
return accuracy h = sigmoid(z)
return 1 if h >= 0.5 else 0
""" """
对率回归预测函数。 对率回归预测函数。
@@ -83,6 +85,28 @@ def evaluate_model(X_val, y_val, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
def evaluate_model(X_val, y_val, weights):
predictions = np.array([predict_logreg(x, weights) for x in X_val])
accuracy = np.mean(predictions == y_val)
return accuracy
def split_train_val(X, y, val_size=0.2):
# 确保数据是随机打乱的
shuffled_indices = list(range(X.shape[0]))
random.shuffle(shuffled_indices)
X_shuffled = X[shuffled_indices]
y_shuffled = y[shuffled_indices]
# 计算验证集的大小
val_count = int(X.shape[0] * val_size)
# 分割数据集
X_val = X_shuffled[:val_count]
y_val = y_shuffled[:val_count]
X_train = X_shuffled[val_count:]
y_train = y_shuffled[val_count:]
return X_train, X_val, y_train, y_val
# 这里也写自己的代码实现 # 这里也写自己的代码实现
@@ -119,7 +143,7 @@ def load_data(filepath):
if __name__ == "__main__": if __name__ == "__main__":
# 加载数据并分割为训练集和验证集 # 加载数据并分割为训练集和验证集
X, y = load_data("./data/horse-colic.data") X, y = load_data("./data/horse-colic.data")
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42) X_train, X_val, y_train, y_val = split_train_val(X, y)
# 模型调优参数 # 模型调优参数
learning_rates = [0.01, 0.001, 0.0001] learning_rates = [0.01, 0.001, 0.0001]