generated from LufsX/Experiment-LogReg
This commit is contained in:
+21
-1
@@ -1,5 +1,6 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
from sklearn.preprocessing import StandardScaler # 导入标准化库
|
from sklearn.preprocessing import StandardScaler # 导入标准化库
|
||||||
|
|
||||||
# 学号和姓名
|
# 学号和姓名
|
||||||
@@ -100,6 +101,18 @@ def k_fold_cross_validation(X, y, k=5, learning_rate=0.001, iterations=10000, ba
|
|||||||
|
|
||||||
return np.mean(accuracies)
|
return np.mean(accuracies)
|
||||||
|
|
||||||
|
def evaluate_model(X_test, y_test, weights):
|
||||||
|
"""基于测试集计算模型的分类精度和执行时间"""
|
||||||
|
start_time = time.time() # 记录开始时间
|
||||||
|
y_pred = [predict_logreg(X_test[i], weights) for i in range(len(y_test))] # 对所有测试样本进行预测
|
||||||
|
end_time = time.time() # 记录结束时间
|
||||||
|
|
||||||
|
# 计算分类精度
|
||||||
|
accuracy = np.mean(np.array(y_pred) == y_test) # 分类精度
|
||||||
|
execution_time = end_time - start_time # 执行时间
|
||||||
|
|
||||||
|
return accuracy, execution_time
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
try:
|
try:
|
||||||
@@ -129,6 +142,13 @@ if __name__ == "__main__":
|
|||||||
# 训练对率回归模型
|
# 训练对率回归模型
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1500)
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1500)
|
||||||
|
|
||||||
|
# 基于测试集进行性能评估
|
||||||
|
accuracy, execution_time = evaluate_model(X_test, y_test, weights)
|
||||||
|
|
||||||
|
# 输出分类精度和执行时间
|
||||||
|
print(f"基于测试集的分类精度: {accuracy * 100:.2f}%")
|
||||||
|
print(f"基于测试集的执行时间: {execution_time:.4f} 秒")
|
||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"测试样本 11 的预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
|
|||||||
Reference in New Issue
Block a user