generated from LufsX/Experiment-LogReg
This commit is contained in:
+54
-88
@@ -26,40 +26,19 @@ name = "邓龙树"
|
|||||||
|
|
||||||
# user_cod
|
# user_cod
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
"""Sigmoid 激活函数。"""
|
"""Sigmoid 激活函数。"""
|
||||||
return 1 / (1 + np.exp(-z))
|
return 1.0 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def train_logreg(X, y, other_params=None):
|
|
||||||
"""
|
|
||||||
对率回归训练函数。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- X (numpy array): 特征数据。
|
|
||||||
- y (numpy array): 标签数据。
|
|
||||||
- other_params (dict): 其它参数,可选设置。
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- numpy array: 训练得到的权重。
|
|
||||||
"""
|
|
||||||
if other_params is None:
|
|
||||||
other_params = {
|
|
||||||
'learning_rate': 0.1,
|
|
||||||
'iterations': 2000,
|
|
||||||
'lambda_reg': 0.01,
|
|
||||||
'batch_size': 32
|
|
||||||
}
|
|
||||||
|
|
||||||
learning_rate = other_params.get('learning_rate', 0.1)
|
|
||||||
iterations = other_params.get('iterations', 2000)
|
|
||||||
lambda_reg = other_params.get('lambda_reg', 0.01)
|
|
||||||
batch_size = other_params.get('batch_size', 32)
|
|
||||||
|
|
||||||
|
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, reg_lambda=0.01):
|
||||||
|
"""训练逻辑回归模型的函数,使用梯度下降算法。"""
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值
|
weights = np.random.randn(n) * 0.01 # 初始化权重
|
||||||
|
best_weights = weights.copy()
|
||||||
|
best_accuracy = 0
|
||||||
|
wait = 0
|
||||||
|
|
||||||
for i in range(iterations):
|
for i in range(iterations):
|
||||||
indices = np.random.permutation(m)
|
indices = np.random.permutation(m)
|
||||||
@@ -69,86 +48,73 @@ def train_logreg(X, y, other_params=None):
|
|||||||
for j in range(0, m, batch_size):
|
for j in range(0, m, batch_size):
|
||||||
X_batch = X_shuffled[j:j + batch_size]
|
X_batch = X_shuffled[j:j + batch_size]
|
||||||
y_batch = y_shuffled[j:j + batch_size]
|
y_batch = y_shuffled[j:j + batch_size]
|
||||||
|
|
||||||
z = np.dot(X_batch, weights)
|
z = np.dot(X_batch, weights)
|
||||||
predictions = sigmoid(z)
|
h = sigmoid(z)
|
||||||
gradient = np.dot(X_batch.T, (predictions - y_batch)) / X_batch.shape[0] + (lambda_reg / m) * weights
|
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) + reg_lambda * weights
|
||||||
|
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
if i % 100 == 0:
|
# 计算训练集准确率
|
||||||
print(f"Iteration {i}, Learning Rate: {learning_rate}")
|
train_accuracy = accuracy(X, y, weights)
|
||||||
|
if train_accuracy > best_accuracy:
|
||||||
|
best_accuracy = train_accuracy
|
||||||
|
best_weights = weights.copy()
|
||||||
|
wait = 0
|
||||||
|
else:
|
||||||
|
wait += 1
|
||||||
|
|
||||||
return weights
|
# 如果准确率没有提高,提前停止
|
||||||
|
if wait > 50:
|
||||||
|
break
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
return best_weights
|
||||||
"""
|
|
||||||
对率回归预测函数。
|
|
||||||
|
|
||||||
Args:
|
def predict_logreg(X, weights):
|
||||||
- inX (numpy array): 输入待分类的样本。
|
"""预测函数。"""
|
||||||
- weights (numpy array): 训练得到的权重。
|
z = np.dot(X, weights)
|
||||||
|
h = sigmoid(z)
|
||||||
Returns:
|
return np.where(h > 0.5, 1, 0)
|
||||||
- int: 预测的分类标签。
|
|
||||||
"""
|
|
||||||
z = np.dot(inX, weights)
|
|
||||||
prediction_prob = sigmoid(z)
|
|
||||||
return 1 if prediction_prob >= 0.5 else 0
|
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
"""
|
"""加载数据函数。"""
|
||||||
从文件中加载数据。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- filepath (str): 数据文件路径。
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- np.array: 特征数据。
|
|
||||||
- np.array: 标签数据。
|
|
||||||
"""
|
|
||||||
data = []
|
data = []
|
||||||
labels = []
|
labels = []
|
||||||
|
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
values = line.strip().replace('?', '0').split()
|
line = line.strip().split()
|
||||||
try:
|
if len(line) >= 1 and line[-1].isdigit():
|
||||||
values = [float(v) for v in values]
|
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
|
||||||
if values[22] == 2 or values[22] == 3:
|
data.append(line_data)
|
||||||
labels.append(0)
|
labels.append(int(line[-1]))
|
||||||
data.append(values[:2] + values[3:23])
|
|
||||||
elif values[22] == 1:
|
|
||||||
labels.append(1)
|
|
||||||
data.append(values[:2] + values[3:23])
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
labels = np.array(labels)
|
||||||
|
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||||
|
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
||||||
|
|
||||||
|
scaler = StandardScaler()
|
||||||
|
data = scaler.fit_transform(data)
|
||||||
|
|
||||||
return data, 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_train, y_train = load_data("./data/horse-colic.data")
|
X_test, y_test = load_data("./horse-colic.test")
|
||||||
|
|
||||||
# 加载测试集
|
# 特征标准化
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
scaler = StandardScaler()
|
||||||
|
X_train = scaler.fit_transform(X_train)
|
||||||
|
X_test = scaler.transform(X_test)
|
||||||
|
|
||||||
# 训练对率回归模型
|
# 训练模型
|
||||||
other_params = {
|
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64, reg_lambda=0.01)
|
||||||
'learning_rate': 0.01,
|
|
||||||
'iterations': 1000,
|
# 计算测试集准确率
|
||||||
'lambda_reg': 0.01,
|
final_accuracy = accuracy(X_test, y_test, final_weights)
|
||||||
'batch_size': 32
|
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
||||||
}
|
|
||||||
weights = train_logreg(X_train, y_train, other_params=other_params)
|
|
||||||
|
|
||||||
# 测试单个数据
|
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
||||||
|
|||||||
Reference in New Issue
Block a user