generated from LufsX/Experiment-LogReg
This commit is contained in:
+15
-8
@@ -1,9 +1,9 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.impute import SimpleImputer
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
@@ -28,12 +28,10 @@ id = "202210423201"
|
||||
name = "陈瑞琪祥"
|
||||
|
||||
|
||||
|
||||
# Sigmoid 函数
|
||||
# 这里写自己的代码实现
|
||||
def sigmoid(x):
|
||||
return 1 / (1 + np.exp(-x))
|
||||
|
||||
# 逻辑回归训练函数
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.01):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
@@ -44,13 +42,11 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.01)
|
||||
weights -= learning_rate * gradient
|
||||
return weights
|
||||
|
||||
# 逻辑回归预测函数
|
||||
def predict_logreg(inX, weights):
|
||||
linear_output = np.dot(inX, weights)
|
||||
probability = sigmoid(linear_output)
|
||||
return 1 if probability > 0.5 else 0
|
||||
|
||||
# 数据预处理函数
|
||||
def preprocess_data(X, y):
|
||||
# 合并目标变量的类别
|
||||
y[y == 2] = 0
|
||||
@@ -62,42 +58,53 @@ def preprocess_data(X, y):
|
||||
|
||||
return X, y
|
||||
|
||||
# 加载数据函数
|
||||
def load_data(filepath):
|
||||
# 使用Pandas读取数据,可以更好地处理缺失值和字符串
|
||||
try:
|
||||
data = pd.read_csv(filepath, header=None, sep=r'\s+', on_bad_lines='skip')
|
||||
except pd.errors.ParserError as e:
|
||||
print(f"Error parsing file: {e}")
|
||||
return None, None
|
||||
|
||||
# 将'?'替换为np.nan
|
||||
data.replace('?', np.nan, inplace=True)
|
||||
|
||||
# 使用SimpleImputer填充缺失值
|
||||
imputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=0)
|
||||
data.iloc[:, :-1] = imputer.fit_transform(data.iloc[:, :-1])
|
||||
|
||||
# 将所有列转换为数值类型
|
||||
for col in data.columns[:-1]:
|
||||
data[col] = pd.to_numeric(data[col], errors='coerce')
|
||||
|
||||
X = data.iloc[:, :-1].values
|
||||
y = data.iloc[:, -1].values.astype(int)
|
||||
|
||||
# 预处理数据
|
||||
X, y = preprocess_data(X, y)
|
||||
|
||||
return X, y
|
||||
|
||||
# 主函数
|
||||
def main():
|
||||
X_train, y_train = load_data("D:/data/horse/horse-colic.data")
|
||||
X_test, y_test = load_data("D:/data/horse/horse-colic.test")
|
||||
|
||||
if X_train is not None and X_test is not None:
|
||||
# 特征缩放
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# 训练模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, regularization=0.1)
|
||||
|
||||
# 预测测试集
|
||||
y_pred = [predict_logreg(x, weights) for x in X_test]
|
||||
|
||||
# 计算准确率
|
||||
accuracy = np.mean(y_pred == y_test)
|
||||
print(f"准确率: {accuracy}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user