更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Failing after 1m7s

This commit is contained in:
hao
2024-11-02 13:22:33 +08:00
parent ae55b9d670
commit c040aa276d
+16 -28
View File
@@ -1,5 +1,6 @@
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
""" """
实验说明: 实验说明:
@@ -32,43 +33,30 @@ def load_data(filepath):
# 将缺失值填充为每列的平均值 # 将缺失值填充为每列的平均值
for i in range(X.shape[1]): for i in range(X.shape[1]):
X[:, i] = np.where(np.isnan(X[:, i]), np.mean(X[:, i]), X[:, i]) X[:, i] = np.where(np.isnan(X[:, i]), np.nanmean(X[:, i]), X[:, i])
return X, y.astype(int) return X, y.astype(int)
def scale_features(X): def train_logreg(X, y):
mean = np.mean(X, axis=0) scaler = StandardScaler()
std = np.std(X, axis=0) X_scaled = scaler.fit_transform(X)
std[std == 0] = 1
scaled_X = (X - mean) / std model = LogisticRegression(solver='liblinear')
return scaled_X model.fit(X_scaled, y)
return model
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01): def predict_logreg(model, inX):
m, n = X.shape prediction = model.predict(inX)
weights = np.zeros(n) return prediction
for _ in range(iterations):
for i in range(m):
x_i = X[i]
y_i = y[i]
prediction = 1 / (1 + np.exp(-np.dot(x_i, weights)))
gradient = x_i * (prediction - y_i)
weights -= learning_rate * (gradient + lambda_reg * weights)
return weights
def predict_logreg(inX, weights):
prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0
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")
X_test, y_test = load_data("./data/horse-colic.test") X_test, y_test = load_data("./data/horse-colic.test")
X_train_scaled = scale_features(X_train) model = train_logreg(X_train, y_train)
X_test_scaled = scale_features(X_test)
weights = train_logreg(X_train_scaled, y_train, learning_rate=0.01, iterations=1000)
# 测试模型 # 测试模型
y_pred = [predict_logreg(x, weights) for x in X_test_scaled] y_pred = predict_logreg(model, X_test)
accuracy = np.mean(y_pred == y_test) accuracy = np.mean(y_pred == y_test)
print(f"Accuracy: {accuracy}") print(f"Accuracy: {accuracy}")