更新 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
+15 -27
View File
@@ -1,5 +1,6 @@
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]):
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)
def scale_features(X):
mean = np.mean(X, axis=0)
std = np.std(X, axis=0)
std[std == 0] = 1
scaled_X = (X - mean) / std
return scaled_X
def train_logreg(X, y):
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
m, n = X.shape
weights = np.zeros(n)
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
model = LogisticRegression(solver='liblinear')
model.fit(X_scaled, y)
def predict_logreg(inX, weights):
prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0
return model
def predict_logreg(model, inX):
prediction = model.predict(inX)
return prediction
if __name__ == "__main__":
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
X_train_scaled = scale_features(X_train)
X_test_scaled = scale_features(X_test)
weights = train_logreg(X_train_scaled, y_train, learning_rate=0.01, iterations=1000)
model = train_logreg(X_train, y_train)
# 测试模型
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)
print(f"Accuracy: {accuracy}")