generated from LufsX/Experiment-LogReg
Compare commits
9
Commits
888866080b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28749fc571 | ||
|
|
a454e2e79a | ||
|
|
a7c4a74c46 | ||
|
|
c73871005a | ||
|
|
02d09c2ab6 | ||
|
|
ad305dda21 | ||
|
|
e995be40a3 | ||
|
|
4a8a3dad9b | ||
|
|
9d6226e04b |
+32
-86
@@ -1,11 +1,8 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
|
||||
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
|
||||
from sklearn.model_selection import train_test_split, GridSearchCV
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
@@ -22,100 +19,49 @@ from sklearn.svm import SVC
|
||||
- numpy: 2.1.1
|
||||
"""
|
||||
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423221"
|
||||
name = "廖子豪"
|
||||
|
||||
def load_data(filepath):
|
||||
file = open(filepath)
|
||||
fr = file.readlines()
|
||||
data_list = []
|
||||
y = []
|
||||
for data in fr:
|
||||
data = data.strip()
|
||||
data = data.split(' ')
|
||||
data_25 = data[24]
|
||||
y.append(data[22])
|
||||
del data[-1]
|
||||
del data[26]
|
||||
del data[25]
|
||||
del data[24]
|
||||
del data[23]
|
||||
del data[22]
|
||||
del data[2]
|
||||
for i in data_25:
|
||||
data.append(i)
|
||||
data = [0 if data_elem == '?' else float(data_elem) for data_elem in data]
|
||||
data_list.append(data)
|
||||
data_number = len(y)
|
||||
y_train = np.array([1 if y[j] == '2' or y[j] == '3' else 0 for j in range(data_number)])
|
||||
X = np.array(data_list)
|
||||
X_train = np.insert(X, 0, 1, axis=1) # 添加偏置项
|
||||
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
|
||||
labels = data[:, -1].astype(int)
|
||||
features = data[:, :-1]
|
||||
|
||||
# 将标签转换为二分类问题
|
||||
labels = np.where((labels == 2) | (labels == 3), 1, 0)
|
||||
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
X= scaler.fit_transform(X)
|
||||
features = scaler.fit_transform(features)
|
||||
|
||||
return features, labels
|
||||
|
||||
return X_train, y_train
|
||||
def train_logreg(X, y, random_state=42):
|
||||
# 使用 GridSearchCV 进行参数调优
|
||||
param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'penalty': ['l1', 'l2']}
|
||||
model = LogisticRegression(solver='liblinear', random_state=random_state)
|
||||
grid_search = GridSearchCV(model, param_grid, cv=5)
|
||||
grid_search.fit(X, y)
|
||||
return grid_search.best_estimator_
|
||||
|
||||
def train_logreg(X, y, numIter=1000, learning_rate=0.06, batch_size=128, lambda_reg=0.01):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
for j in range(numIter):
|
||||
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]]
|
||||
z = np.dot(batch_X, weights)
|
||||
h = 1 / (1 + np.exp(-z))
|
||||
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)
|
||||
weights += learning_rate * gradient
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
z = np.dot(inX, weights)
|
||||
prob = 1 / (1 + np.exp(-z))
|
||||
return 1 if prob >= 0.5 else 0
|
||||
def predict_logreg(inX, model):
|
||||
return int(model.predict([inX])[0])
|
||||
|
||||
# 示例使用
|
||||
if __name__ == "__main__":
|
||||
# 加载训练数据和测试数据
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
# 训练模型
|
||||
model = train_logreg(X_train, y_train, random_state=42)
|
||||
|
||||
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
|
||||
# 进行预测
|
||||
y_pred = [predict_logreg(x, model) for x in X_test]
|
||||
|
||||
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 = 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
|
||||
|
||||
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}")
|
||||
|
||||
# 随机森林模型
|
||||
param_grid = {
|
||||
'n_estimators': [100, 200, 300],
|
||||
'max_depth': [5, 10, 15],
|
||||
'learning_rate': [0.01, 0.05, 0.1]
|
||||
}
|
||||
rf = RandomForestClassifier()
|
||||
grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5, scoring='accuracy')
|
||||
grid_search.fit(X_train, y_train)
|
||||
best_rf = grid_search.best_estimator_
|
||||
print("Best parameters:", grid_search.best_params_)
|
||||
print("Best accuracy:", grid_search.best_score_)
|
||||
# 计算准确率
|
||||
accuracy = np.mean(y_pred == y_test)
|
||||
print(f"Test Accuracy: {accuracy:.2f}")
|
||||
Reference in New Issue
Block a user