generated from LufsX/Experiment-LogReg
This commit is contained in:
+46
-44
@@ -21,63 +21,65 @@ import numpy as np
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423206"
|
||||
name = "詹宇豪"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
def load_data(filepath, k_features=20):
|
||||
data, labels = [], []
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
line = line.strip().split()
|
||||
if line:
|
||||
features = [float(feature) if feature.replace('.', '', 1).isdigit() else np.nan for feature in line[:-1]]
|
||||
label = int(line[-1])
|
||||
data.append(features)
|
||||
labels.append(label)
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
data, labels = np.array(data), np.array(labels)
|
||||
imputer = SimpleImputer(strategy='mean')
|
||||
data = imputer.fit_transform(data)
|
||||
|
||||
mean, std_dev = data.mean(axis=0), data.std(axis=0)
|
||||
std_dev[std_dev == 0] = 1
|
||||
data = (data - mean) / std_dev
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
selector = SelectKBest(f_classif, k=k_features)
|
||||
data = selector.fit_transform(data, labels)
|
||||
|
||||
return data, labels
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
def sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
def train_logreg(X, y, initial_lr=0.005, iterations=5000, regularization=0.01, decay=0.0001):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
learning_rate = initial_lr
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
for i in range(iterations):
|
||||
predictions = sigmoid(np.dot(X, weights))
|
||||
errors = y - predictions
|
||||
gradient = (np.dot(X.T, errors) - regularization * weights) / m
|
||||
weights += learning_rate * gradient
|
||||
learning_rate = initial_lr / (1 + decay * i)
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(X, weights, threshold=0.5):
|
||||
probabilities = sigmoid(np.dot(X, weights))
|
||||
return (probabilities >= threshold).astype(int)
|
||||
|
||||
# 测试代码
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
X_train, y_train = load_data("./data/horse-colic.data", k_features=20)
|
||||
X_test, y_test = load_data("./data/horse-colic.test", k_features=20)
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
weights = train_logreg(X_train, y_train, initial_lr=0.005, iterations=5000, regularization=0.01, decay=0.0001)
|
||||
|
||||
# 训练对率回归模型
|
||||
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]}")
|
||||
y_pred = predict_logreg(X_test, weights, threshold=0.5)
|
||||
accuracy = np.mean(y_pred == y_test)
|
||||
print(f"测试集准确率: {accuracy:.2f}")
|
||||
Reference in New Issue
Block a user