generated from LufsX/Experiment-LogReg
This commit is contained in:
+2
-10
@@ -45,7 +45,6 @@ def train_logreg(X, y, numIter=150): # 训练逻辑回归模型的函数,使
|
|||||||
del(dataIndex[randIndex])
|
del(dataIndex[randIndex])
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
|
|
||||||
def predict_logreg(X, weights):
|
def predict_logreg(X, weights):
|
||||||
z = np.dot(X, weights)
|
z = np.dot(X, weights)
|
||||||
h = sigmoid(z)
|
h = sigmoid(z)
|
||||||
@@ -55,8 +54,6 @@ def load_data(filepath):
|
|||||||
data = []
|
data = []
|
||||||
labels = []
|
labels = []
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f:
|
||||||
lines = f.readlines()
|
|
||||||
for line in lines:
|
|
||||||
for line in f:
|
for line in f:
|
||||||
line = line.strip().split()
|
line = line.strip().split()
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
if len(line) >= 1 and line[-1].isdigit():
|
||||||
@@ -66,23 +63,17 @@ def load_data(filepath):
|
|||||||
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
labels = np.array(labels)
|
||||||
target_variable = labels
|
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||||
target_variable[np.logical_or(target_variable == 2, target_variable == 3)] = 0
|
|
||||||
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
||||||
scaler = StandardScaler()
|
scaler = StandardScaler()
|
||||||
data = scaler.fit_transform(data)
|
data = scaler.fit_transform(data)
|
||||||
|
|
||||||
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
|
||||||
|
|
||||||
return data, target_variable
|
return data, target_variable
|
||||||
|
|
||||||
|
|
||||||
def accuracy(X, y, weights):
|
def accuracy(X, y, weights):
|
||||||
predictions = predict_logreg(X, weights)
|
predictions = predict_logreg(X, weights)
|
||||||
return np.mean(predictions == y)
|
return np.mean(predictions == y)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X_train, y_train = load_data("./horse-colic.data")
|
X_train, y_train = load_data("./horse-colic.data")
|
||||||
X_test, y_test = load_data("./horse-colic.test")
|
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)
|
final_accuracy = accuracy(X_test, y_test, final_weights)
|
||||||
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user