generated from LufsX/Experiment-LogReg
This commit is contained in:
+29
-9
@@ -1,6 +1,7 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.ensemble import RandomForestClassifier
|
from sklearn.ensemble import RandomForestClassifier
|
||||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||||
|
from sklearn.metrics import accuracy_score, f1_score
|
||||||
|
|
||||||
id = "202210423104"
|
id = "202210423104"
|
||||||
name = "张钦诚"
|
name = "张钦诚"
|
||||||
@@ -11,29 +12,48 @@ def load_data(filepath):
|
|||||||
for line in file:
|
for line in file:
|
||||||
line_data = line.strip().split()
|
line_data = line.strip().split()
|
||||||
if line_data:
|
if line_data:
|
||||||
|
try:
|
||||||
data.append([float(x) if x != '?' else np.nan for x in line_data])
|
data.append([float(x) if x != '?' else np.nan for x in line_data])
|
||||||
|
except ValueError as e:
|
||||||
|
print(f"Error processing line: {line}. Error: {e}")
|
||||||
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]
|
|
||||||
y = data[:, -1]
|
X = data[:, :-1] # 特征
|
||||||
|
y = data[:, -1] # 标签
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
def preprocess_data(X):
|
def preprocess_data(X, scaler=None, poly=None):
|
||||||
|
if scaler is None:
|
||||||
scaler = StandardScaler()
|
scaler = StandardScaler()
|
||||||
X_standardized = scaler.fit_transform(X)
|
X_standardized = scaler.fit_transform(X)
|
||||||
|
else:
|
||||||
|
X_standardized = scaler.transform(X)
|
||||||
|
|
||||||
|
if poly is None:
|
||||||
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
|
else:
|
||||||
|
X_poly = poly.transform(X_standardized)
|
||||||
|
|
||||||
|
return X_poly, scaler, poly
|
||||||
|
|
||||||
def train_logreg(X, y):
|
def train_logreg(X, y):
|
||||||
X_processed = preprocess_data(X) # 预处理训练数据
|
X_processed, scaler, poly = preprocess_data(X) # 预处理训练数据
|
||||||
model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42)
|
model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42)
|
||||||
model.fit(X_processed, y)
|
model.fit(X_processed, y)
|
||||||
return model # 返回训练好的模型
|
return model, scaler, poly # 返回训练好的模型及预处理器
|
||||||
|
|
||||||
def predict_logreg(model, X):
|
def predict_logreg(model, X, scaler, poly):
|
||||||
X_processed = preprocess_data(X) # 预处理测试数据
|
# 确保输入数据是一个 numpy 数组
|
||||||
return model.predict(X_processed)[0] # 返回预测结果
|
if len(X.shape) == 1:
|
||||||
|
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求
|
||||||
|
X_processed, _, _ = preprocess_data(X, scaler, poly) # 预处理测试数据
|
||||||
|
return model.predict(X_processed)[0] # 确保 model 是训练好的模型
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X, y = load_data("./data/horse-colic.data")
|
X, y = load_data("./data/horse-colic.data")
|
||||||
|
model, scaler, poly = train_logreg(X, y) # 训练模型
|
||||||
|
y_pred = [predict_logreg(model, sample, scaler, poly) for sample in X] # 预测
|
||||||
|
print(f"Accuracy: {accuracy_score(y, y_pred):.2f}")
|
||||||
|
print(f"F1 Score: {f1_score(y, y_pred, average='weighted'):.2f}")
|
||||||
|
|||||||
Reference in New Issue
Block a user