generated from LufsX/Experiment-LogReg
This commit is contained in:
+18
-43
@@ -31,18 +31,7 @@ import numpy as np
|
||||
def sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.005, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
def train_logreg(X, y, learning_rate, iterations):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
bias = 0
|
||||
@@ -56,38 +45,16 @@ def train_logreg(X, y, learning_rate=0.005, iterations=1000):
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
z = np.dot(inX, weights)
|
||||
h = sigmoid(z)
|
||||
return 1 if h >= 0.5 else 0
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
# 清理无效数据
|
||||
cleaned_line = line.strip().replace('?', '0')
|
||||
values = [float(x) for x in cleaned_line.split()]
|
||||
# 处理目标变量
|
||||
if values[22] in [2, 3]:
|
||||
values[22] = 0
|
||||
new_values = values[:2] + values[3:23]
|
||||
@@ -98,15 +65,23 @@ def load_data(filepath):
|
||||
return X, y
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 训练对率回归模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
best_learning_rate = None
|
||||
best_accuracy = 0
|
||||
learning_rates = [0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01]
|
||||
iterations = 1000
|
||||
for lr in learning_rates:
|
||||
weights = train_logreg(X_train, y_train, learning_rate=lr, iterations=iterations)
|
||||
correct_count = 0
|
||||
for i in range(len(X_test)):
|
||||
y_pred = predict_logreg(X_test[i], weights)
|
||||
if y_pred == y_test[i]:
|
||||
correct_count += 1
|
||||
accuracy = correct_count / len(X_test)
|
||||
if accuracy > best_accuracy:
|
||||
best_accuracy = accuracy
|
||||
best_learning_rate = lr
|
||||
best_weights = train_logreg(X_train, y_train, learning_rate=best_learning_rate, iterations=iterations)
|
||||
y_pred = predict_logreg(X_test[11], best_weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
Reference in New Issue
Block a user