generated from LufsX/Experiment-LogReg
This commit is contained in:
+14
-4
@@ -19,16 +19,17 @@ from itertools import product
|
|||||||
- numpy: 2.1.1
|
- numpy: 2.1.1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423117"
|
id = "202210423117"
|
||||||
name = "程悦"
|
name = "程悦"
|
||||||
|
|
||||||
|
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1.0 / (1 + np.exp(-z))
|
return 1.0 / (1 + np.exp(-z))
|
||||||
|
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, regularization=None, lambda_reg=0.1):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, regularization=None, lambda_reg=0.1):
|
||||||
"""
|
"""
|
||||||
对率回归训练函数。
|
对率回归训练函数。
|
||||||
@@ -68,6 +69,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, regul
|
|||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
"""
|
"""
|
||||||
对率回归预测函数。
|
对率回归预测函数。
|
||||||
@@ -83,6 +85,7 @@ def predict_logreg(inX, weights):
|
|||||||
h = sigmoid(z)
|
h = sigmoid(z)
|
||||||
return 1 if h > 0.5 else 0
|
return 1 if h > 0.5 else 0
|
||||||
|
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
"""
|
"""
|
||||||
从文件中加载数据,填充缺失值,并进行特征处理。
|
从文件中加载数据,填充缺失值,并进行特征处理。
|
||||||
@@ -121,17 +124,24 @@ def load_data(filepath):
|
|||||||
|
|
||||||
return data, target_variable
|
return data, target_variable
|
||||||
|
|
||||||
|
def accuracy(X, y, weights):
|
||||||
|
predictions = [predict_logreg(sample, weights) for sample in X]
|
||||||
|
return np.mean(predictions == y) # 计算准确率
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
# 以下代码可用于测试,可自行随意修改
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./horse-colic.data")
|
||||||
|
|
||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./horse-colic.test")
|
||||||
|
|
||||||
# 训练对率回归模型
|
# 训练对率回归模型
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.15, iterations=500, batch_size=32, regularization='L1',
|
weights = train_logreg(X_train, y_train, learning_rate=0.2, iterations=200, batch_size=32, regularization='L1',
|
||||||
lambda_reg=0.15)
|
lambda_reg=0.15)
|
||||||
|
# 计算并输出准确率
|
||||||
|
acc = accuracy(X_test, y_test, weights)
|
||||||
|
print(f"模型的准确率: {acc:.2f}")
|
||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
|
|||||||
Reference in New Issue
Block a user