Files
Experiment-LogReg/function.py
T
2024-11-02 20:58:13 +08:00

103 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
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(X, weights):
"""
对率回归预测函数。
Args:
- X (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- numpy array: 预测的分类标签。
"""
linear_model = np.dot(X, weights)
y_predicted = sigmoid(linear_model)
return (y_predicted > 0.5).astype(int)
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
Args:
- filepath (str): 数据文件路径。
Returns:
- X (np.array): 特征数据。
- y (np.array): 标签数据。
"""
# 使用 np.genfromtxt 加载数据,并且忽略文件中不能转换为 float 的行
# 更新分隔符为逗号,根据实际格式来修改,通常csv用',',txt文件则可能用'\t'或者' '来分隔
data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan)
# 删除所有包含缺失值的行
data = data[~np.isnan(data).any(axis=1)]
# 确保数据的正确性: 不同于训练集的标签列
if data.ndim == 1:
data = np.array([data])
# 假设最后一列为标签
X = data[:, :-1] # 特征
y = data[:, -1] # 标签
return X, y
if __name__ == "__main__":
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 确保训练集和测试集特征数量匹配
if X_train.shape[1] != X_test.shape[1]:
raise ValueError("训练集和测试集特征数量不匹配!")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试多个数据
y_pred = predict_logreg(X_test, weights)
# 输出部分预测结果
for i in range(min(10, len(y_pred))): # 只输出前10个预测结果
print(f"预测结果: {y_pred[i]}, 实际结果: {y_test[i]}")