Template
101 lines
2.4 KiB
Python
101 lines
2.4 KiB
Python
import numpy as np
|
|
from sklearn.preprocessing import StandardScaler
|
|
|
|
"""
|
|
请在这里填写学号和姓名,不填写即成绩无效。
|
|
"""
|
|
id = "202210423224"
|
|
name = "吴杨洋"
|
|
|
|
|
|
def sigmoid(z):
|
|
"""
|
|
Sigmoid 激活函数。
|
|
"""
|
|
return 1 / (1 + np.exp(-z))
|
|
|
|
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|
"""
|
|
对率回归训练函数。
|
|
|
|
Args:
|
|
- X (numpy array): 特征数据。
|
|
- y (numpy array): 标签数据。
|
|
- learning_rate (float): 学习率,默认为0.01。
|
|
- iterations (int): 迭代次数,默认为1000。
|
|
|
|
Returns:
|
|
- weights (numpy array): 训练得到的权重。
|
|
"""
|
|
m, n = X.shape
|
|
weights = np.zeros(n)
|
|
for i in range(iterations):
|
|
linear_model = np.dot(X, weights)
|
|
y_predicted = sigmoid(linear_model)
|
|
gradient = np.dot(X.T, (y_predicted - y)) / m
|
|
weights -= learning_rate * gradient
|
|
return weights
|
|
|
|
|
|
def predict_logreg(inX, weights):
|
|
"""
|
|
对率回归预测函数。
|
|
|
|
Args:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- weights (numpy array): 训练得到的权重。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
linear_model = np.dot(inX, weights)
|
|
y_predicted = sigmoid(linear_model)
|
|
return 1 if y_predicted > 0.5 else 0
|
|
|
|
|
|
def load_data(filepath):
|
|
"""
|
|
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
|
|
|
Args:
|
|
- filepath (str): 数据文件路径。
|
|
|
|
Returns:
|
|
- X (np.array): 特征数据。
|
|
- y (np.array): 标签数据。
|
|
"""
|
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float)
|
|
X = data[:, :-1]
|
|
y = data[:, -1]
|
|
return X, y
|
|
|
|
|
|
def main():
|
|
# 加载训练集
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
|
|
# 加载测试集
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
|
|
# 标准化特征数据
|
|
scaler = StandardScaler()
|
|
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=1000)
|
|
|
|
# 测试单个数据
|
|
correct_predictions = 0
|
|
for i in range(X_test.shape[0]):
|
|
y_pred = predict_logreg(X_test[i], weights)
|
|
if y_pred == y_test[i]:
|
|
correct_predictions += 1
|
|
|
|
accuracy = correct_predictions / X_test.shape[0]
|
|
print(f"Accuracy: {accuracy:.2f}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |