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

This commit is contained in:
2024-11-01 10:26:31 +08:00
parent ab3c74b657
commit c6a7ae4dba
+51 -52
View File
@@ -1,14 +1,59 @@
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
id = "202210423130" id = "202210423130"
name = "董秋" name = "董秋"
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
for i in range(iterations):
z = np.dot(X, weights)
predictions = 1 / (1 + np.exp(-z))
gradient = np.dot(X.T, (predictions - y)) / m
# L2正则化
gradient += (lambda_reg / m) * weights
weights -= learning_rate * gradient
# 动态调整学习率,逐渐减小
learning_rate *= 0.99 # 每次迭代将学习率乘以0.99
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
prediction_prob = 1 / (1 + np.exp(-z))
return 1 if prediction_prob >= 0.5 else 0
def load_data(filepath): def load_data(filepath):
data = [] data = []
labels = [] labels = []
@@ -44,52 +89,6 @@ def preprocess_data(X):
return scaler.fit_transform(X) return scaler.fit_transform(X)
def train_logreg(X_train, y_train):
"""
逻辑回归训练函数,使用网格搜索优化超参数。
Args:
- X_train (numpy array): 特征数据。
- y_train (numpy array): 标签数据。
Returns:
- LogisticRegression: 训练得到的最佳模型。
"""
# 定义要调优的超参数范围
param_grid = {
'C': [0.001, 0.01, 0.1, 1, 10, 100], # 正则化参数
'solver': ['liblinear', 'lbfgs'], # 求解器
'max_iter': [100, 500, 1000] # 最大迭代次数
}
# 创建逻辑回归模型
log_reg = LogisticRegression()
# 创建网格搜索对象
grid_search = GridSearchCV(estimator=log_reg, param_grid=param_grid, cv=5, scoring='accuracy')
# 进行网格搜索
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def predict_logreg(inX, weights):
"""
逻辑回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
prediction_prob = 1 / (1 + np.exp(-z))
return 1 if prediction_prob >= 0.5 else 0
if __name__ == "__main__": if __name__ == "__main__":
# 加载数据集 # 加载数据集
X, y = load_data("./data/horse-colic.data") X, y = load_data("./data/horse-colic.data")
@@ -98,9 +97,9 @@ if __name__ == "__main__":
# 使用 train_test_split 打乱并随机抽取数据 # 使用 train_test_split 打乱并随机抽取数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练逻辑回归模型 # 训练对率回归模型
best_model = train_logreg(X_train, y_train) weights = train_logreg(X_train, y_train, learning_rate=0.1, iterations=1000, lambda_reg=0.01)
# 测试单个数据 # 测试单个数据
y_pred = best_model.predict(X_test[11].reshape(1, -1)) # 进行预测时需要调整输入形状 y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred[0]}, 实际结果: {y_test[11]}") print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")