generated from LufsX/Experiment-LogReg
This commit is contained in:
+37
-28
@@ -1,9 +1,10 @@
|
|||||||
# function.py
|
|
||||||
import os
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from sklearn.preprocessing import MinMaxScaler
|
from sklearn.preprocessing import MinMaxScaler
|
||||||
from sklearn.model_selection import train_test_split
|
from sklearn.model_selection import train_test_split
|
||||||
|
from sklearn.impute import SimpleImputer
|
||||||
|
|
||||||
"""
|
"""
|
||||||
实验说明:
|
实验说明:
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||||
@@ -17,14 +18,16 @@ from sklearn.model_selection import train_test_split
|
|||||||
- Python: 3.10.12
|
- Python: 3.10.12
|
||||||
- numpy: 2.1.1
|
- numpy: 2.1.1
|
||||||
"""
|
"""
|
||||||
# Sigmoid 函数
|
# Sigmoid 函数
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1 / (1 + np.exp(-z))
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423223"
|
id = "202210423223"
|
||||||
name = "李顺潮"
|
name = "李顺潮"
|
||||||
|
|
||||||
# 对率回归训练函数
|
# 对率回归训练函数
|
||||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
X = np.hstack((np.ones((X.shape[0], 1)), X)) # 在特征前添加一列全为1的列
|
X = np.hstack((np.ones((X.shape[0], 1)), X)) # 在特征前添加一列全为1的列
|
||||||
@@ -33,50 +36,56 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
|
|
||||||
for _ in range(iterations):
|
for _ in range(iterations):
|
||||||
z = np.dot(X, weights)
|
z = np.dot(X, weights)
|
||||||
predictions = 1 / (1 + np.exp(-z))
|
predictions = sigmoid(z) # 使用sigmoid函数
|
||||||
gradient = np.dot(X.T, (predictions - y)) / m
|
gradient = np.dot(X.T, (predictions - y)) / m
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
# 对率回归预测函数
|
# 对率回归预测函数
|
||||||
# 对率回归预测函数,支持多类分类
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
inX = np.insert(inX, 0, 1) # 在特征前添加1作为偏置项
|
inX = np.insert(inX, 0, 1) # 在特征前添加1作为偏置项
|
||||||
prob = 1 / (1 + np.exp(-np.dot(inX, weights)))
|
prob = sigmoid(np.dot(inX, weights)) # 使用sigmoid函数
|
||||||
|
|
||||||
if prob < 0.5:
|
return 1 if prob >= 0.5 else 0
|
||||||
return 0
|
|
||||||
elif prob >= 0.5 and prob < 1.0:
|
|
||||||
return 1
|
|
||||||
else:
|
|
||||||
return 2 # 确保返回3个类别中的一个
|
|
||||||
|
|
||||||
# 从文件中加载数据
|
|
||||||
|
# 从文件中加载数据
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data = pd.read_csv(filepath, header=None, na_values='?', delim_whitespace=True)
|
data = pd.read_csv(filepath, header=None, na_values='?', delim_whitespace=True)
|
||||||
data.fillna(0, inplace=True)
|
|
||||||
|
# 使用更合理的缺失值填充策略,例如用均值或中位数填充
|
||||||
|
imputer = SimpleImputer(strategy='mean') # 使用均值填充
|
||||||
|
data = pd.DataFrame(imputer.fit_transform(data))
|
||||||
|
|
||||||
|
|
||||||
X = data.iloc[:, :-1].to_numpy() # 特征
|
X = data.iloc[:, :-1].to_numpy() # 特征
|
||||||
y = data.iloc[:, -1].to_numpy() # 标签
|
y = data.iloc[:, -1].to_numpy().astype(int) # 标签,确保y是整数类型
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
# 准确率计算函数
|
# 准确率计算函数
|
||||||
def calculate_accuracy(X, y, weights):
|
def calculate_accuracy(X, y, weights):
|
||||||
predictions = np.array([predict_logreg(x, weights) for x in X])
|
predictions = np.array([predict_logreg(x, weights) for x in X])
|
||||||
accuracy = np.mean(predictions == y)
|
accuracy = np.mean(predictions == y)
|
||||||
return accuracy
|
return accuracy
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集和测试集
|
# 加载训练集和测试集
|
||||||
X_train, y_train = load_data("E:\\Edge站内文件下载\\病马数据集\\horse-colic.data")
|
X_train, y_train = load_data("E:\\Edge站内文件下载\\病马数据集\\horse-colic.data")
|
||||||
X_test, y_test = load_data( "E:\\Edge站内文件下载\\病马数据集\\horse-colic.test")
|
X_test, y_test = load_data("E:\\Edge站内文件下载\\病马数据集\\horse-colic.test")
|
||||||
|
|
||||||
# 训练对率回归模型
|
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
|
||||||
|
|
||||||
# 测试单个数据
|
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
||||||
|
|
||||||
|
# 特征缩放 (可选,但建议尝试)
|
||||||
|
scaler = MinMaxScaler()
|
||||||
|
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=10000) #增加迭代次数
|
||||||
|
|
||||||
|
# 测试单个数据
|
||||||
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
|
|
||||||
# 计算并输出模型的准确率
|
# 计算并输出模型的准确率
|
||||||
accuracy = calculate_accuracy(X_test, y_test, weights)
|
accuracy = calculate_accuracy(X_test, y_test, weights)
|
||||||
|
|||||||
Reference in New Issue
Block a user