generated from LufsX/Experiment-LogReg
This commit is contained in:
+30
-6
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
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):
|
||||
predictions = np.array([predict_logreg(x, weights) for x in X_val])
|
||||
accuracy = np.mean(predictions == y_val)
|
||||
return accuracy
|
||||
def predict_logreg(inX, weights):
|
||||
inX = np.insert(inX, 0, 1) # 添加偏置项
|
||||
z = np.dot(inX, weights)
|
||||
h = sigmoid(z)
|
||||
return 1 if h >= 0.5 else 0
|
||||
|
||||
|
||||
"""
|
||||
对率回归预测函数。
|
||||
@@ -83,6 +85,28 @@ def evaluate_model(X_val, y_val, weights):
|
||||
Returns:
|
||||
- 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__":
|
||||
# 加载数据并分割为训练集和验证集
|
||||
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]
|
||||
|
||||
Reference in New Issue
Block a user