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

This commit is contained in:
2024-11-07 16:43:41 +08:00
parent 03660a0777
commit 1071f5edea
+38 -7
View File
@@ -23,50 +23,81 @@ import numpy as np
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423xxx"
name = "test_name"
id = "202210423113"
name = "杨文强"
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
- learning_rate (float): 学习率,控制每次更新的步长。
- iterations (int): 迭代次数。
Returns:
- numpy array: 训练得到的权重。
"""
# 初始化权重
m, n = X.shape
weights = np.zeros(n)
bias = 0
# 梯度下降
for i in range(iterations):
# 计算线性模型
z = np.dot(X, weights) + bias
# 应用sigmoid函数
predictions = 1 / (1 + np.exp(-z))
# 计算梯度
dw = (1/m) * np.dot(X.T, (predictions - y))
db = (1/m) * np.sum(predictions - y)
def predict_logreg(inX, weights):
# 更新权重和偏置
weights -= learning_rate * dw
bias -= learning_rate * db
return weights, bias
def predict_logreg(inX, weights, bias):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
- bias (float): 训练得到的偏置。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights) + bias
prediction = 1 / (1 + np.exp(-z))
return 1 if prediction >= 0.5 else 0 # 分类阈值为0.5
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件中加载数据。
Args:
- directory (str): 数据文件路径。
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=' ')
X = data[:, :-1] # 所有列,除了最后一列
y = data[:, -1] # 只取最后一列作为标签
return X, y
if __name__ == "__main__":