更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 31s

This commit is contained in:
2024-11-03 20:14:40 +08:00
parent 16e100ba57
commit 5372fc9005
+38 -23
View File
@@ -32,38 +32,53 @@ from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
# 读取数据
data_path = './data/horse-colic.data'
data = pd.read_csv(data_path, header=None, delim_whitespace=True, na_values='?')
def load_data(file_path):
# 读取数据
data = pd.read_csv(file_path, header=None, delim_whitespace=True, na_values='?')
# 处理缺失值(用0填充)
data.fillna(0, inplace=True)
# 选择特征和目标变量
# 去掉特征3和特征24~28
features = data.iloc[:, :-5].values # 假设最后一列是目标变量,前面的都是特征
target = data.iloc[:, -1].values
# 处理缺失值(用0填充)
data.fillna(0, inplace=True)
# 将目标变量中的2和3合并为0
target[target == 2] = 0
target[target == 3] = 0
# 选择特征和目标变量
# 去掉特征3和特征24~28
features = data.iloc[:, :-5].values # 假设最后一列是目标变量,前面的都是特征
target = data.iloc[:, -1].values
# 将目标变量转换为二进制分类(0或1)
target = (target == 1).astype(int)
# 将目标变量中的2和3合并为0
target[target == 2] = 0
target[target == 3] = 0
return features, target
# 将目标变量转换为二进制分类(0或1)
target = (target == 1).astype(int)
def train_logreg(X_train, y_train):
# 训练逻辑回归模型
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
return model
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
def predict_logreg(model, X_test):
# 进行预测
return model.predict(X_test)
# 训练对率回归模型
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
# 主程序
data_path = './data/horse-colic.data'
features, target = load_data(data_path)
# 预测并评估模型
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# 训练模型
model = train_logreg(X_train, y_train)
# 预测并评估模型
y_pred = predict_logreg(model, X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
print("Classification Report:")
print(report)