generated from LufsX/Experiment-LogReg
This commit is contained in:
+46
-67
@@ -22,13 +22,14 @@ import numpy as np
|
||||
id = "202210423118"
|
||||
name = "刘国庆"
|
||||
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
||||
|
||||
Args:
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
@@ -37,88 +38,66 @@ def load_data(filepath):
|
||||
try:
|
||||
data = np.genfromtxt(filepath, delimiter=',', missing_values='?', filling_values=np.nan)
|
||||
|
||||
# Check if data was loaded correctly
|
||||
if data.ndim == 1 and len(data) == 1 and np.isnan(data).any():
|
||||
print(f"数据加载错误: 文件 '{filepath}' 可能为空或格式不正确。")
|
||||
return None, None
|
||||
|
||||
# Remove rows with NaN values
|
||||
data = data[~np.isnan(data).any(axis=1)]
|
||||
data = data[~np.isnan(data).any(axis=1)]
|
||||
|
||||
if data.size == 0:
|
||||
print(f"数据加载错误: 文件 '{filepath}' 中没有有效数据。")
|
||||
return None, None
|
||||
|
||||
X = data[:, :-1] # All columns except the last one
|
||||
y = data[:, -1] # Last column
|
||||
|
||||
# Split into features and labels
|
||||
X = data[:, :-1] # Features
|
||||
y = data[:, -1] # Labels
|
||||
return X, y
|
||||
except Exception as e:
|
||||
print(f"数据加载错误: {e}")
|
||||
print(f"Error loading data: {e}")
|
||||
return None, None
|
||||
|
||||
|
||||
def sigmoid(z):
|
||||
"""计算 sigmoid 函数"""
|
||||
"""
|
||||
Sigmoid activation function.
|
||||
"""
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, epochs=1000):
|
||||
"""
|
||||
训练逻辑回归模型。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- X (np.array): 特征数据。
|
||||
- y (np.array): 标签数据。
|
||||
- learning_rate (float): 学习率。
|
||||
- iterations (int): 迭代次数。
|
||||
|
||||
- epochs (int): 训练的迭代次数。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
- np.array: 训练后的权重。
|
||||
"""
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n) # Initialize weights
|
||||
for _ in range(iterations):
|
||||
z = np.dot(X, weights) # Linear combination
|
||||
predictions = sigmoid(z) # Apply sigmoid
|
||||
# Update weights using gradient ascent
|
||||
weights += (learning_rate / m) * np.dot(X.T, (y - predictions))
|
||||
# Initialize weights
|
||||
X = np.c_[np.ones(X.shape[0]), X] # Add intercept term
|
||||
weights = np.zeros(X.shape[1])
|
||||
|
||||
# Gradient descent for logistic regression
|
||||
for epoch in range(epochs):
|
||||
z = np.dot(X, weights)
|
||||
predictions = sigmoid(z)
|
||||
|
||||
# Calculate the gradient
|
||||
gradient = np.dot(X.T, (predictions - y)) / y.size
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
|
||||
def predict_logreg(X, weights):
|
||||
"""
|
||||
使用逻辑回归模型进行预测。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
|
||||
- X (np.array): 特征数据。
|
||||
- weights (np.array): 训练得到的权重。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
- np.array: 预测的标签(0 或 1)。
|
||||
"""
|
||||
z = np.dot(inX, weights)
|
||||
prediction_prob = sigmoid(z)
|
||||
return 1 if prediction_prob >= 0.5 else 0
|
||||
X = np.c_[np.ones(X.shape[0]), X] # Add intercept term
|
||||
probabilities = sigmoid(np.dot(X, weights))
|
||||
return (probabilities >= 0.5).astype(int)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
|
||||
# 检查加载结果
|
||||
if X_train is None or y_train is None:
|
||||
print("训练集加载失败。请检查文件路径和文件内容。")
|
||||
exit(1)
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 检查加载结果
|
||||
if X_test is None or y_test is None:
|
||||
print("测试集加载失败。请检查文件路径和文件内容。")
|
||||
exit(1)
|
||||
|
||||
# 训练对率回归模型
|
||||
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]}")
|
||||
|
||||
Reference in New Issue
Block a user