generated from LufsX/Experiment-LogReg
This commit is contained in:
+8
-1
@@ -21,7 +21,9 @@ def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lam
|
|||||||
"""对率回归训练函数。"""
|
"""对率回归训练函数。"""
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
|
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
|
||||||
for _ in range(iterations):
|
print("开始训练对率回归模型")
|
||||||
|
|
||||||
|
for i in range(iterations):
|
||||||
indices = np.random.permutation(m)
|
indices = np.random.permutation(m)
|
||||||
X_shuffled = X[indices]
|
X_shuffled = X[indices]
|
||||||
y_shuffled = y[indices]
|
y_shuffled = y[indices]
|
||||||
@@ -32,6 +34,9 @@ def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lam
|
|||||||
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
|
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
|
if i % 1000 == 0: # 每1000次迭代打印一次信息
|
||||||
|
print(f"迭代 {i}: 当前权重形状: {weights.shape}")
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
@@ -46,6 +51,7 @@ def load_data(filepath):
|
|||||||
raise FileNotFoundError(f"文件 {filepath} 不存在!")
|
raise FileNotFoundError(f"文件 {filepath} 不存在!")
|
||||||
|
|
||||||
data, labels = [], []
|
data, labels = [], []
|
||||||
|
print(f"加载数据中: {filepath}")
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
line = line.strip().split()
|
line = line.strip().split()
|
||||||
@@ -66,6 +72,7 @@ def load_data(filepath):
|
|||||||
data = np.delete(data, indices_to_remove, axis=1)
|
data = np.delete(data, indices_to_remove, axis=1)
|
||||||
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
|
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
|
||||||
|
|
||||||
|
print(f"数据加载成功,数据形状: {data.shape}, 标签形状: {target_variable.shape}")
|
||||||
return data, target_variable
|
return data, target_variable
|
||||||
|
|
||||||
def k_fold_cross_validation(X, y, k=5, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
def k_fold_cross_validation(X, y, k=5, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
||||||
|
|||||||
Reference in New Issue
Block a user