generated from LufsX/Experiment-LogReg
This commit is contained in:
+39
-24
@@ -28,14 +28,28 @@ name = "邓龙树"
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
def sigmoid(intX): #激活函数,逻辑回归中,将线性组合转换为概率
|
||||
return 1.0 / (1 + np.exp(-intX))
|
||||
|
||||
def train_logreg(X, y, numIter=150): #训练逻辑回归模型的函数,使用梯度下降算法。
|
||||
def sigmoid(z):
|
||||
"""Sigmoid 激活函数。"""
|
||||
return 1.0 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, reg_lambda=0.01):
|
||||
"""训练逻辑回归模型的函数,使用梯度下降算法。"""
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64):
|
||||
m, n = X.shape
|
||||
weights = np.random.randn(n) * 0.01 # 初始化权重
|
||||
weights = np.zeros(n) # 初始化权重为0而不是1
|
||||
for j in range(numIter):
|
||||
dataIndex = list(range(m))
|
||||
for i in range(m):
|
||||
alpha = 4 / (1.0 + j + i) + 0.01
|
||||
randIndex = int(np.random.uniform(0, len(dataIndex)))
|
||||
h = sigmoid(np.dot(X[randIndex], weights))
|
||||
error = y[randIndex] - h
|
||||
weights = weights + alpha * error * X[randIndex]
|
||||
del(dataIndex[randIndex])
|
||||
return weights
|
||||
weights = np.random.randn(n) * 0.01
|
||||
best_weights = weights.copy()
|
||||
best_accuracy = 0
|
||||
wait = 0
|
||||
@@ -50,7 +64,7 @@ def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, reg_l
|
||||
y_batch = y_shuffled[j:j + batch_size]
|
||||
z = np.dot(X_batch, weights)
|
||||
h = sigmoid(z)
|
||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) + reg_lambda * weights
|
||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
|
||||
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
@@ -63,23 +77,25 @@ def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, reg_l
|
||||
else:
|
||||
wait += 1
|
||||
|
||||
# 如果准确率没有提高,提前停止
|
||||
if wait > 50:
|
||||
break
|
||||
|
||||
return best_weights
|
||||
|
||||
|
||||
def predict_logreg(X, weights):
|
||||
"""预测函数。"""
|
||||
predictions = []
|
||||
for x in X:
|
||||
prob = sigmoid(np.dot(x, weights))
|
||||
predictions.append(1 if prob > 0.5 else 0)
|
||||
return predictions
|
||||
z = np.dot(X, weights)
|
||||
h = sigmoid(z)
|
||||
return np.where(h > 0.5, 1, 0)
|
||||
|
||||
def load_data(filepath):
|
||||
"""加载数据函数。"""
|
||||
data = []
|
||||
labels = []
|
||||
with open(filepath, 'r') as f:
|
||||
lines = f.readlines()
|
||||
for line in lines:
|
||||
for line in f:
|
||||
line = line.strip().split()
|
||||
if len(line) >= 1 and line[-1].isdigit():
|
||||
@@ -89,35 +105,34 @@ def load_data(filepath):
|
||||
|
||||
data = np.array(data)
|
||||
labels = np.array(labels)
|
||||
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||
|
||||
n_features = data.shape[1]
|
||||
columns_to_delete = [2] + list(range(23, min(28, n_features)))
|
||||
data = np.delete(data, columns_to_delete, axis=1)
|
||||
|
||||
target_variable = labels
|
||||
target_variable[np.logical_or(target_variable == 2, target_variable == 3)] = 0
|
||||
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
||||
scaler = StandardScaler()
|
||||
data = scaler.fit_transform(data)
|
||||
|
||||
|
||||
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||
|
||||
return data, target_variable
|
||||
|
||||
|
||||
def accuracy(X, y, weights):
|
||||
"""计算准确率。"""
|
||||
predictions = predict_logreg(X, weights)
|
||||
return np.mean(predictions == y)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
X_train, y_train = load_data("./horse-colic.data")
|
||||
X_test, y_test = load_data("./horse-colic.test")
|
||||
final_weights = train_logreg(X_train, y_train)
|
||||
|
||||
# 特征标准化
|
||||
# 标准化数据
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# 训练模型
|
||||
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64, reg_lambda=0.01)
|
||||
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
|
||||
|
||||
# 计算测试集准确率
|
||||
final_accuracy = accuracy(X_test, y_test, final_weights)
|
||||
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user