generated from LufsX/Experiment-LogReg
This commit is contained in:
+74
-39
@@ -1,51 +1,86 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
def load_data(filepath):
|
# 填写学号和姓名
|
||||||
for delimiter in [',', ' ', '\t']:
|
id = "202210423118"
|
||||||
try:
|
name = "刘国庆"
|
||||||
data = np.genfromtxt(filepath, delimiter=delimiter, missing_values='?', filling_values=np.nan)
|
|
||||||
if data.ndim < 2 or data.shape[1] < 2:
|
|
||||||
continue
|
|
||||||
data = data[~np.isnan(data).any(axis=1)]
|
|
||||||
if data.size == 0:
|
|
||||||
print(f"Error: No valid data after removing NaN rows in file '{filepath}'.")
|
|
||||||
return None, None
|
|
||||||
X = data[:, :-1]
|
|
||||||
y = data[:, -1]
|
|
||||||
if X.shape[0] != y.shape[0]:
|
|
||||||
print(f"Error: Feature and label count mismatch in file '{filepath}'")
|
|
||||||
return None, None
|
|
||||||
print(f"Loaded data from '{filepath}': {X.shape[0]} samples, {X.shape[1]} features.")
|
|
||||||
return X, y
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error loading data with delimiter '{delimiter}': {e}")
|
|
||||||
print(f"Error: File '{filepath}' may be empty or improperly formatted.")
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
|
# Sigmoid函数
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1 / (1 + np.exp(-z))
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.01, epochs=1000):
|
# 数据加载函数
|
||||||
X = np.c_[np.ones(X.shape[0]), X]
|
def load_data(filepath):
|
||||||
weights = np.zeros(X.shape[1])
|
"""
|
||||||
for epoch in range(epochs):
|
从文件中加载数据,处理缺失值,将 ? 替换为 NaN 并填充缺失值。
|
||||||
z = np.dot(X, weights)
|
|
||||||
predictions = sigmoid(z)
|
Args:
|
||||||
gradient = np.dot(X.T, (predictions - y)) / y.size
|
- filepath (str): 数据文件路径。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 特征数据。
|
||||||
|
- np.array: 标签数据。
|
||||||
|
"""
|
||||||
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan)
|
||||||
|
nan_columns = np.isnan(data)
|
||||||
|
col_means = np.nanmean(data, axis=0)
|
||||||
|
data[nan_columns] = np.take(col_means, np.where(nan_columns)[1])
|
||||||
|
|
||||||
|
X = data[:, :-1]
|
||||||
|
y = data[:, -1]
|
||||||
|
return X, y
|
||||||
|
|
||||||
|
# 对率回归训练函数
|
||||||
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
|
"""
|
||||||
|
对率回归训练函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- X (np.array): 特征数据。
|
||||||
|
- y (np.array): 标签数据。
|
||||||
|
- learning_rate (float): 学习率。
|
||||||
|
- iterations (int): 迭代次数。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 训练得到的权重和偏置(合并为一个数组)。
|
||||||
|
"""
|
||||||
|
n_samples, n_features = X.shape
|
||||||
|
X = np.c_[X, np.ones(n_samples)] # 添加偏置项
|
||||||
|
weights = np.zeros(n_features + 1)
|
||||||
|
|
||||||
|
for _ in range(iterations):
|
||||||
|
y_pred = sigmoid(np.dot(X, weights))
|
||||||
|
gradient = np.dot(X.T, (y_pred - y)) / n_samples
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
|
# 对率回归预测函数
|
||||||
def predict_logreg(X, weights):
|
def predict_logreg(X, weights):
|
||||||
X = np.c_[np.ones(X.shape[0]), X]
|
"""
|
||||||
probabilities = sigmoid(np.dot(X, weights))
|
对率回归预测函数,支持单个或多个样本。
|
||||||
return (probabilities >= 0.5).astype(int)
|
|
||||||
|
|
||||||
# Load data and train model
|
Args:
|
||||||
data_file_path = 'path_to_your_data/horse-colic.data' # Update with your actual path
|
- X (np.array): 输入待分类的样本,可以是单个样本或样本集。
|
||||||
X, y = load_data(data_file_path)
|
- weights (np.array): 训练得到的权重和偏置。
|
||||||
if X is not None and y is not None:
|
|
||||||
weights = train_logreg(X, y)
|
|
||||||
predictions = predict_logreg(X, weights)
|
|
||||||
print("Weights:", weights)
|
|
||||||
print("Predictions:", predictions)
|
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 预测的分类标签 (0 或 1)。
|
||||||
|
"""
|
||||||
|
if X.ndim == 1:
|
||||||
|
X = X.reshape(1, -1)
|
||||||
|
X = np.c_[X, np.ones(X.shape[0])]
|
||||||
|
y_pred = sigmoid(np.dot(X, weights))
|
||||||
|
return (y_pred >= 0.5).astype(int)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 加载训练集和测试集
|
||||||
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
|
# 训练对率回归模型
|
||||||
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
|
|
||||||
|
# 预测测试集并计算准确率
|
||||||
|
predictions = predict_logreg(X_test, weights)
|
||||||
|
accuracy = np.mean(predictions == y_test)
|
||||||
|
print(f"预测准确率: {accuracy * 100:.2f}%")
|
||||||
|
|||||||
Reference in New Issue
Block a user