generated from LufsX/Experiment-LogReg
This commit is contained in:
+3
-11
@@ -28,7 +28,7 @@ name = "邓龙树"
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
def sigmoid(intX): #激活函数,逻辑回归中,将线性组合转换为概率
|
||||
def sigmoid(intX): # 激活函数,逻辑回归中,将线性组合转换为概率
|
||||
return 1.0 / (1 + np.exp(-intX))
|
||||
|
||||
def train_logreg(X, y, numIter=150): # 训练逻辑回归模型的函数,使用梯度下降算法。
|
||||
@@ -45,7 +45,6 @@ def train_logreg(X, y, numIter=150): # 训练逻辑回归模型的函数,使
|
||||
del(dataIndex[randIndex])
|
||||
return weights
|
||||
|
||||
|
||||
def predict_logreg(X, weights):
|
||||
z = np.dot(X, weights)
|
||||
h = sigmoid(z)
|
||||
@@ -55,8 +54,6 @@ 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():
|
||||
@@ -66,23 +63,17 @@ def load_data(filepath):
|
||||
|
||||
data = np.array(data)
|
||||
labels = np.array(labels)
|
||||
target_variable = labels
|
||||
target_variable[np.logical_or(target_variable == 2, target_variable == 3)] = 0
|
||||
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)
|
||||
|
||||
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")
|
||||
@@ -97,3 +88,4 @@ if __name__ == "__main__":
|
||||
|
||||
final_accuracy = accuracy(X_test, y_test, final_weights)
|
||||
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user