generated from LufsX/Experiment-LogReg
This commit is contained in:
+3
-3
@@ -21,7 +21,6 @@ def load_data(filepath):
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan)
|
||||
# 填充缺失值为列均值
|
||||
col_means = np.nanmean(data, axis=0)
|
||||
inds = np.where(np.isnan(data))
|
||||
data[inds] = np.take(col_means, inds[1])
|
||||
@@ -48,7 +47,6 @@ def train_logreg(X, y, learning_rate=0.01, iterations=500):
|
||||
X = np.c_[X, np.ones(n_samples)] # 添加偏置项
|
||||
weights = np.zeros(n_features + 1)
|
||||
|
||||
# 向量化梯度下降
|
||||
for _ in range(iterations):
|
||||
y_pred = sigmoid(np.dot(X, weights))
|
||||
gradient = np.dot(X.T, (y_pred - y)) / n_samples
|
||||
@@ -68,7 +66,9 @@ def predict_logreg(X, weights):
|
||||
Returns:
|
||||
- np.array: 预测的分类标签 (0 或 1)。
|
||||
"""
|
||||
X = np.c_[X, np.ones(X.shape[0])]
|
||||
if X.ndim == 1: # 如果是单个样本
|
||||
X = X.reshape(1, -1)
|
||||
X = np.c_[X, np.ones(X.shape[0])] # 添加偏置项
|
||||
y_pred = sigmoid(np.dot(X, weights))
|
||||
return (y_pred >= 0.5).astype(int)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user