generated from LufsX/Experiment-LogReg
This commit is contained in:
+52
-26
@@ -4,7 +4,6 @@ from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.metrics import accuracy_score, roc_auc_score, f1_score
|
||||
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.svm import SVC
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
@@ -13,95 +12,122 @@ id = "202210423221"
|
||||
name = "廖子豪"
|
||||
|
||||
def load_data(filepath):
|
||||
"""Load data from a text file for model training."""
|
||||
"""Load and preprocess data from specified file."""
|
||||
with open(filepath) as file:
|
||||
fr = file.readlines()
|
||||
|
||||
data_list = []
|
||||
y = []
|
||||
|
||||
for data in fr:
|
||||
data = data.strip().split(' ')
|
||||
data_25 = data[24] # Preserving the 25th element for later use
|
||||
y.append(data[22]) # Using 23rd element as the target value
|
||||
|
||||
# Remove unnecessary elements and convert to float, handle missing values
|
||||
numerical_data = [0 if elem == '?' else float(elem) for i, elem in enumerate(data) if i not in [24, 22, 26]]
|
||||
data_list.append(numerical_data)
|
||||
|
||||
data_number = len(y)
|
||||
y_train = np.array([1 if label in ['2', '3'] else 0 for label in y]) # Binary classification
|
||||
|
||||
# Keep the necessary fields
|
||||
y.append(data[22]) # Target value
|
||||
# Remove unnecessary columns
|
||||
data = [data[i] for i in range(len(data)) if i not in [2, 22, 24, 25, 26]]
|
||||
|
||||
# Convert to float, replacing '?' with 0
|
||||
data_processed = [0 if elem == '?' else float(elem) for elem in data]
|
||||
data_list.append(data_processed)
|
||||
|
||||
y_train = np.array([1 if label in ['2', '3'] else 0 for label in y])
|
||||
X = np.array(data_list)
|
||||
|
||||
# Add bias term (intercept)
|
||||
X = np.insert(X, 0, 1, axis=1)
|
||||
|
||||
return X, y_train
|
||||
|
||||
def train_logreg(X, y, numIter=1000, learning_rate=0.06, batch_size=128, lambda_reg=0.01):
|
||||
def train_logreg(X, y, numIter=1000, learning_rate=0.01, batch_size=128, lambda_reg=0.01):
|
||||
"""Train a logistic regression model using mini-batch gradient descent."""
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
|
||||
for j in range(numIter):
|
||||
# Shuffle data indices
|
||||
dataIndex = np.random.permutation(m)
|
||||
|
||||
for i in range(0, m, batch_size):
|
||||
end = min(i + batch_size, m)
|
||||
batch_X = X[dataIndex[i:end]]
|
||||
batch_y = y[dataIndex[i:end]]
|
||||
|
||||
# Compute predictions
|
||||
z = np.dot(batch_X, weights)
|
||||
h = 1 / (1 + np.exp(-z)) # Sigmoid function
|
||||
h = 1 / (1 + np.exp(-z)) # Sigmoid
|
||||
|
||||
# Compute gradient
|
||||
error = batch_y - h
|
||||
gradient = np.dot(batch_X.T, error) / len(batch_y)
|
||||
reg_term = 2 * lambda_reg * weights
|
||||
gradient -= reg_term / len(batch_y) # Regularization
|
||||
|
||||
# Update weights
|
||||
weights += learning_rate * gradient
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""Make a prediction using the logistics regression model."""
|
||||
"""Make a prediction using the logistic regression model."""
|
||||
z = np.dot(inX, weights)
|
||||
prob = 1 / (1 + np.exp(-z))
|
||||
return 1 if prob >= 0.5 else 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Load train and test data
|
||||
# Data loading
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# Standardize the data
|
||||
# Standardize the features
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# Split train data into training and validation sets
|
||||
# Split training data into training and validation sets
|
||||
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
|
||||
|
||||
# Train the logistic regression model
|
||||
# Logistic regression training and evaluation
|
||||
best_weights = None
|
||||
best_auc = 0
|
||||
|
||||
for iter in range(1, 1001):
|
||||
weights = train_logreg(X_train, y_train, numIter=iter, learning_rate=0.01, lambda_reg=0.1)
|
||||
y_pred = [predict_logreg(x, weights) for x in X_val]
|
||||
|
||||
# AUC score for validation predictions
|
||||
auc = roc_auc_score(y_val, y_pred)
|
||||
|
||||
if auc > best_auc:
|
||||
best_auc = auc
|
||||
best_weights = weights
|
||||
|
||||
if iter > 10 and auc == best_auc:
|
||||
break
|
||||
|
||||
# Make predictions and evaluate test accuracy
|
||||
# Predictions on the test set
|
||||
y_pred_test = [predict_logreg(x, best_weights) for x in X_test]
|
||||
accuracy_test = accuracy_score(y_test, y_pred_test)
|
||||
print(f"Test Accuracy: {accuracy_test}")
|
||||
|
||||
# Example for a Random Forest model
|
||||
# Random Forest model example
|
||||
rf = RandomForestClassifier(n_estimators=100, random_state=42)
|
||||
rf.fit(X_train, y_train)
|
||||
rf_accuracy = rf.score(X_test, y_test)
|
||||
print(f"Random Forest Test Accuracy: {rf_accuracy}")
|
||||
|
||||
# Example for Gradient Boosting model
|
||||
# Gradient Boosting model example
|
||||
gb_clf = GradientBoostingClassifier()
|
||||
gb_clf.fit(X_train, y_train)
|
||||
y_pred_gb = gb_clf.predict(X_test)
|
||||
gb_accuracy = accuracy_score(y_test, y_pred_gb)
|
||||
yf_pred_gb = gb_clf.predict(X_test)
|
||||
gb_accuracy = accuracy_score(y_test, yf_pred_gb)
|
||||
print(f"Gradient Boosting Test Accuracy: {gb_accuracy}")
|
||||
|
||||
# Evaluate performance with F1 score
|
||||
f1 = f1_score(y_test, y_pred_gb)
|
||||
print(f"F1 Score: {f1}")
|
||||
# Cross-validation for Gradient Boosting
|
||||
scores = cross_val_score(gb_clf, X_train, y_train, cv=5, scoring='accuracy')
|
||||
print("Cross-validation scores:", scores)
|
||||
print("Average cross-validation score:", np.mean(scores))
|
||||
|
||||
# F1 score evaluation
|
||||
f1 = f1_score(y_test, yf_pred_gb)
|
||||
print("F1 Score:", f1)
|
||||
Reference in New Issue
Block a user