更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 13s

This commit is contained in:
2024-11-05 20:07:30 +08:00
parent 100859f9b2
commit 4091a45632
+18 -102
View File
@@ -26,114 +26,30 @@ import numpy as np
id = "202210423113" id = "202210423113"
name = "杨文强" name = "杨文强"
# 这里写自己的代码实现
# 1. 数据加载函数
def load_data(filepath):
"""
从文件中加载数据,处理缺失值 '?' 为 NaN,并将其替换为列的均值或其他方法。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 读取数据,使用 `?` 替换为 np.nan
data = np.genfromtxt(filepath, delimiter=' ', dtype=str) # 读取为字符串类型
data[data == '?'] = np.nan # 将 '?' 替换为 NaN
# 将数据转换为浮动类型
data = data.astype(float)
# 处理缺失值:用列的均值替换缺失值
# 计算每列的均值(跳过 NaN)
col_means = np.nanmean(data, axis=0)
# 用列均值填充 NaN 值
# np.where 检查哪里是 NaN,并用对应列的均值替换
inds = np.where(np.isnan(data))
data[inds] = np.take(col_means, inds[1])
# 特征数据:去掉最后一列
X = data[:, :-1]
# 标签数据:最后一列是标签
y = data[:, -1]
return X, y
# 2. 训练对率回归模型的函数
def sigmoid(z): def sigmoid(z):
"""
Sigmoid激活函数,常用于逻辑回归模型。
Args:
- z (numpy array): 输入的值。
Returns:
- numpy array: Sigmoid函数的输出。
"""
return 1 / (1 + np.exp(-z)) 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, iterations=1000):
""" m, n = X.shape
对率回归训练函数。 weights = np.zeros(n)
bias = 0
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率。
- iterations (int): 训练的迭代次数。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape # 获取样本数m和特征数n
X = np.hstack((np.ones((m, 1)), X)) # 添加偏置项(常数项)
weights = np.zeros(n + 1) # 初始化权重(包括偏置项)
for _ in range(iterations): for _ in range(iterations):
# 预测值 z = np.dot(X, weights) + bias
z = np.dot(X, weights) # 计算线性模型的输出 h = sigmoid(z)
y_pred = sigmoid(z) # 使用sigmoid得到概率值 cost = (-1/m) * np.sum(y*np.log(h) + (1-y)*np.log(1-h))
dw = (1/m) * np.dot(X.T, (h - y))
# 计算梯度 db = (1/m) * np.sum(h - y)
error = y_pred - y weights -= learning_rate * dw
gradient = np.dot(X.T, error) / m bias -= learning_rate * db
# 更新权重
weights -= learning_rate * gradient
return weights return weights
# 3. 预测函数
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
""" z = np.dot(inX, weights)
对率回归预测函数。 h = sigmoid(z)
return 1 if h > 0.5 else 0
Args: def load_data(filepath):
- inX (numpy array): 输入待分类的样本。 data = np.loadtxt(filepath, delimiter=',')
- weights (numpy array): 训练得到的权重。 X = data[:, :-1]
y = data[:, -1]
Returns: return X, y
- int: 预测的分类标签。
"""
inX = np.hstack((np.ones((1, 1)), inX)) # 添加偏置项
prob = sigmoid(np.dot(inX, weights)) # 计算概率
return 1 if prob >= 0.5 else 0 # 如果概率大于等于0.5,则预测为1,否则预测为0
# 测试代码
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)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")