更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 31s

This commit is contained in:
2024-11-02 16:12:55 +08:00
parent 745eecef4a
commit 43013d8766
+3 -11
View File
@@ -28,7 +28,7 @@ name = "邓龙树"
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import StandardScaler
def sigmoid(intX): #激活函数,逻辑回归中,将线性组合转换为概率 def sigmoid(intX): # 激活函数,逻辑回归中,将线性组合转换为概率
return 1.0 / (1 + np.exp(-intX)) return 1.0 / (1 + np.exp(-intX))
def train_logreg(X, y, numIter=150): # 训练逻辑回归模型的函数,使用梯度下降算法。 def train_logreg(X, y, numIter=150): # 训练逻辑回归模型的函数,使用梯度下降算法。
@@ -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}")