generated from LufsX/Experiment-LogReg
This commit is contained in:
+20
-18
@@ -27,7 +27,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
weights = np.zeros(X.shape[1])
|
weights = np.zeros(X.shape[1])
|
||||||
|
|
||||||
# 梯度下降
|
# 梯度下降
|
||||||
for _ in range(iterations):
|
for i in range(iterations):
|
||||||
# 计算预测值
|
# 计算预测值
|
||||||
predictions = sigmoid(np.dot(X, weights))
|
predictions = sigmoid(np.dot(X, weights))
|
||||||
|
|
||||||
@@ -38,6 +38,11 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
gradient = np.dot(X.T, error) / len(y)
|
gradient = np.dot(X.T, error) / len(y)
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
|
# 每 100 次迭代输出一次损失
|
||||||
|
if i % 100 == 0:
|
||||||
|
loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
|
||||||
|
print(f"Iteration {i}, Loss: {loss:.4f}")
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
@@ -58,7 +63,7 @@ def predict_logreg(inX, weights):
|
|||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
"""
|
"""
|
||||||
从文件中加载数据,处理缺失数据,并将 '?' 替换为列的中位数。
|
从文件中加载数据,并处理 '?' 为每列的均值。
|
||||||
"""
|
"""
|
||||||
data = []
|
data = []
|
||||||
labels = []
|
labels = []
|
||||||
@@ -68,35 +73,27 @@ def load_data(filepath):
|
|||||||
line = line.strip().split()
|
line = line.strip().split()
|
||||||
if not line:
|
if not line:
|
||||||
continue
|
continue
|
||||||
|
# 将特征转换为浮点型,处理 '?' 为 NaN
|
||||||
# 将标签提取出来
|
features = [float(f) if f != '?' else np.nan for f in line[:-1]]
|
||||||
label = int(line[-1])
|
label = int(line[-1])
|
||||||
|
|
||||||
# 将特征转换为浮动数组,'?' 替换为 np.nan
|
|
||||||
features = line[:-1] # 去除标签部分
|
|
||||||
features = [float(f) if f != '?' else np.nan for f in features]
|
|
||||||
|
|
||||||
# 将数据和标签分别加入到列表
|
|
||||||
data.append(features)
|
data.append(features)
|
||||||
labels.append(label)
|
labels.append(label)
|
||||||
|
|
||||||
# 将列表转换为 numpy 数组
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
labels = np.array(labels)
|
||||||
|
|
||||||
# 计算每列的中位数,并用中位数替换 NaN
|
# 计算每列的均值,并用均值替换 NaN
|
||||||
col_medians = np.nanmedian(data, axis=0) # 计算每列的中位数
|
col_means = np.nanmean(data, axis=0) # 计算每列的均值
|
||||||
for i in range(data.shape[1]):
|
for i in range(data.shape[1]):
|
||||||
data[:, i] = np.where(np.isnan(data[:, i]), col_medians[i], data[:, i])
|
data[:, i] = np.where(np.isnan(data[:, i]), col_means[i], data[:, i])
|
||||||
|
|
||||||
# 对数据进行标准化 (均值为 0,标准差为 1)
|
# 标准化数据(均值为 0,标准差为 1)
|
||||||
means = np.mean(data, axis=0)
|
means = np.mean(data, axis=0)
|
||||||
stds = np.std(data, axis=0)
|
stds = np.std(data, axis=0)
|
||||||
data = (data - means) / stds
|
data = (data - means) / stds
|
||||||
|
|
||||||
return data, labels
|
return data, labels
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
@@ -104,9 +101,14 @@ if __name__ == "__main__":
|
|||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 训练对率回归模型
|
# 训练对率回归模型,增加迭代次数为 5000 次
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000)
|
||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
|
|
||||||
|
# 测试整体准确率
|
||||||
|
y_test_pred = np.array([predict_logreg(X_test[i], weights) for i in range(X_test.shape[0])])
|
||||||
|
accuracy = np.mean(y_test_pred == y_test)
|
||||||
|
print(f"测试集准确率: {accuracy:.4f}")
|
||||||
|
|||||||
Reference in New Issue
Block a user