generated from LufsX/Experiment-LogReg
This commit is contained in:
+66
-31
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
|
||||
import pandas as pd
|
||||
import os
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
@@ -25,36 +25,63 @@ id = "202210423201"
|
||||
name = "陈瑞琪祥"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
# 定义 Sigmoid 函数
|
||||
import numpy as np
|
||||
|
||||
# 定义 Sigmoid 函数
|
||||
def sigmoid(z):
|
||||
"""
|
||||
Sigmoid函数,用于将线性输出转换为概率值。
|
||||
"""
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
# 定义对率回归的训练函数
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n) # 初始化权重为0
|
||||
for i in range(iterations):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认为0.01。
|
||||
- iterations (int): 迭代次数,默认为1000。
|
||||
|
||||
Returns:
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
"""
|
||||
# 初始化权重
|
||||
weights = np.zeros(X.shape[1])
|
||||
# 学习率和迭代次数
|
||||
lr = learning_rate
|
||||
n_iterations = iterations
|
||||
|
||||
for i in range(n_iterations):
|
||||
# 计算模型预测值
|
||||
predictions = sigmoid(np.dot(X, weights))
|
||||
linear_model = np.dot(X, weights)
|
||||
y_predicted = sigmoid(linear_model)
|
||||
|
||||
# 计算梯度
|
||||
gradient = np.dot(X.T, (predictions - y)) / m
|
||||
gradient = np.dot(X.T, (y_predicted - y)) / len(y)
|
||||
|
||||
# 更新权重
|
||||
weights -= learning_rate * gradient
|
||||
weights -= lr * gradient
|
||||
|
||||
return weights
|
||||
|
||||
# 定义预测函数
|
||||
def predict_logreg(inX, weights):
|
||||
prob = sigmoid(np.dot(inX, weights))
|
||||
if prob > 0.5:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
"""
|
||||
对率回归预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算线性组合
|
||||
linear_output = np.dot(inX, weights)
|
||||
# 应用sigmoid函数
|
||||
probability = sigmoid(linear_output)
|
||||
# 预测类别
|
||||
return 1 if probability > 0.5 else 0
|
||||
|
||||
# 定义数据加载函数
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据。
|
||||
@@ -63,20 +90,28 @@ def load_data(filepath):
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
- X (np.array): 特征数据。
|
||||
- y (np.array): 标签数据。
|
||||
"""
|
||||
# 使用np.genfromtxt加载数据,并将'?'替换为np.nan
|
||||
data = np.genfromtxt(filepath, delimiter=' ', skip_header=1, filling_values=np.nan)
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(filepath):
|
||||
raise FileNotFoundError(f"文件 {filepath} 不存在")
|
||||
|
||||
# 使用pandas读取数据,将问号替换为NaN
|
||||
data = pd.read_csv(filepath, header=None, na_values='?')
|
||||
|
||||
# 将所有列转换为数值类型,非数值列将被设置为NaN
|
||||
data = data.apply(pd.to_numeric, errors='coerce')
|
||||
|
||||
# 丢弃完全为NaN的行
|
||||
data = data.dropna()
|
||||
|
||||
# 分离特征和标签
|
||||
features = data[:, 1:-1] # 假设除了第一列和最后一列外,其余都是特征
|
||||
labels = data[:, -1] # 假设最后一列是标签
|
||||
|
||||
# 将标签转换为整数类型
|
||||
labels = labels.astype(int)
|
||||
|
||||
return features, labels
|
||||
X = data.iloc[:, :-1].values
|
||||
y = data.iloc[:, -1].values
|
||||
|
||||
return X, y
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
|
||||
Reference in New Issue
Block a user