generated from LufsX/Experiment-LogReg
This commit is contained in:
+26
-5
@@ -1,10 +1,14 @@
|
||||
import numpy as np
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||
from sklearn.impute import SimpleImputer
|
||||
from sklearn.metrics import accuracy_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
id = "202210423104"
|
||||
name = "张钦诚"
|
||||
|
||||
|
||||
def load_data(filepath):
|
||||
data = []
|
||||
with open(filepath, 'r') as file:
|
||||
@@ -16,12 +20,14 @@ def load_data(filepath):
|
||||
except ValueError as e:
|
||||
print(f"Error processing line: {line}. Error: {e}")
|
||||
data = np.array(data)
|
||||
data = np.nan_to_num(data, nan=np.nanmean(data, axis=0))
|
||||
imputer = SimpleImputer(strategy='mean')
|
||||
data = imputer.fit_transform(data)
|
||||
|
||||
X = data[:, :-1] # 特征
|
||||
y = data[:, -1] # 标签
|
||||
y = data[:, -1] # 标签
|
||||
return X, y
|
||||
|
||||
|
||||
def preprocess_data(X):
|
||||
scaler = StandardScaler()
|
||||
X_standardized = scaler.fit_transform(X)
|
||||
@@ -29,18 +35,33 @@ def preprocess_data(X):
|
||||
X_poly = poly.fit_transform(X_standardized)
|
||||
return X_poly
|
||||
|
||||
|
||||
def train_logreg(X, y):
|
||||
X_processed = preprocess_data(X) # 预处理训练数据
|
||||
model = RandomForestClassifier(n_estimators=200, max_depth=20, random_state=42)
|
||||
model = RandomForestClassifier(n_estimators=200, max_depth=20, min_samples_split=5, random_state=42)
|
||||
model.fit(X_processed, y)
|
||||
return model # 返回训练好的模型
|
||||
|
||||
|
||||
def predict_logreg(X, model):
|
||||
# 确保输入数据是一个 numpy 数组
|
||||
if len(X.shape) == 1:
|
||||
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求
|
||||
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n)
|
||||
X_processed = preprocess_data(X) # 预处理测试数据
|
||||
return model.predict(X_processed)[0] # 确保 model 是训练好的模型
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
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)
|
||||
|
||||
# 训练模型
|
||||
model = train_logreg(X_train, y_train)
|
||||
|
||||
# 预测
|
||||
y_pred = model.predict(preprocess_data(X_test))
|
||||
|
||||
# 计算准确率
|
||||
accuracy = accuracy_score(y_test, y_pred)
|
||||
print(f"Accuracy: {accuracy:.2f}")
|
||||
|
||||
Reference in New Issue
Block a user