generated from LufsX/Experiment-LogReg
This commit is contained in:
+6
-29
@@ -1,5 +1,4 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.model_selection import train_test_split, cross_val_score
|
|
||||||
from sklearn.ensemble import RandomForestClassifier
|
from sklearn.ensemble import RandomForestClassifier
|
||||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||||
|
|
||||||
@@ -19,17 +18,14 @@ def load_data(filepath):
|
|||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
data = np.nan_to_num(data, nan=np.nanmean(data, axis=0))
|
data = np.nan_to_num(data, nan=np.nanmean(data, axis=0))
|
||||||
|
|
||||||
# 将最后一列作为标签,其他列作为特征
|
# 这里需要根据具体数据格式调整
|
||||||
X = data[:, :-1]
|
X = data[:, :-1] # 特征
|
||||||
y = data[:, -1]
|
y = data[:, -1] # 标签
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
def preprocess_data(X):
|
def preprocess_data(X):
|
||||||
# 标准化特征
|
|
||||||
scaler = StandardScaler()
|
scaler = StandardScaler()
|
||||||
X_standardized = scaler.fit_transform(X)
|
X_standardized = scaler.fit_transform(X)
|
||||||
|
|
||||||
# 增加多项式特征
|
|
||||||
poly = PolynomialFeatures(degree=2, include_bias=False)
|
poly = PolynomialFeatures(degree=2, include_bias=False)
|
||||||
X_poly = poly.fit_transform(X_standardized)
|
X_poly = poly.fit_transform(X_standardized)
|
||||||
return X_poly
|
return X_poly
|
||||||
@@ -40,28 +36,9 @@ def train_logreg(X, y):
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
def predict_logreg(model, X):
|
def predict_logreg(model, X):
|
||||||
return model.predict(X)
|
# X 应该是一个单独的样本,确保它的形状是 (1, n_features)
|
||||||
|
return model.predict(X.reshape(1, -1))[0]
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X, y = load_data("./data/horse-colic.data")
|
X, y = load_data("./data/horse-colic.data")
|
||||||
|
# 这里可能需要确保调用和处理的逻辑符合你的数据处理需求
|
||||||
# 数据集划分
|
|
||||||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
||||||
|
|
||||||
# 数据预处理
|
|
||||||
X_train_processed = preprocess_data(X_train)
|
|
||||||
X_test_processed = preprocess_data(X_test)
|
|
||||||
|
|
||||||
# 训练模型
|
|
||||||
model = train_logreg(X_train_processed, y_train)
|
|
||||||
|
|
||||||
# 交叉验证
|
|
||||||
cv_scores = cross_val_score(model, X_train_processed, y_train, cv=5)
|
|
||||||
print(f"交叉验证准确率: {np.mean(cv_scores) * 100:.2f}%")
|
|
||||||
|
|
||||||
# 预测
|
|
||||||
y_pred = predict_logreg(model, X_test_processed)
|
|
||||||
|
|
||||||
# 计算正确率
|
|
||||||
accuracy = np.mean(y_pred == y_test)
|
|
||||||
print(f"测试出的正确率: {accuracy * 100:.2f}%")
|
|
||||||
|
|||||||
Reference in New Issue
Block a user