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

This commit is contained in:
2024-11-12 11:24:08 +08:00
parent 7781907454
commit a80d78ecbb
+39 -15
View File
@@ -28,18 +28,52 @@ name = "test_name"
# 这里写自己的代码实现 # 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"): def sigmoid(z):
"""
Sigmoid 激活函数。
"""
return 1 / (1 + np.exp(-z))
def compute_cost(X, y, weights):
"""
计算交叉熵损失函数。
"""
m = len(y)
predictions = sigmoid(np.dot(X, weights))
cost = -1/m * (np.dot(y, np.log(predictions)) + np.dot((1 - y), np.log(1 - predictions)))
return cost
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
""" """
对率回归训练函数。 对率回归训练函数。
Args: Args:
- X (numpy array): 特征数据。 - X (numpy array): 特征数据。
- y (numpy array): 标签数据。 - y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 - learning_rate (float): 学习率,默认值 0.01。
- iterations (int): 迭代次数,默认值 1000。
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape # m 为样本数,n 为特征数
X = np.hstack([np.ones((m, 1)), X]) # 添加偏置项,X_0=1
weights = np.zeros(n + 1) # 初始化权重
for i in range(iterations):
# 计算预测值
predictions = sigmoid(np.dot(X, weights))
# 计算梯度
gradient = (1/m) * np.dot(X.T, (predictions - y))
# 更新权重
weights -= learning_rate * gradient
# 可选:每隔一定次数输出损失
if i % 100 == 0:
cost = compute_cost(X, y, weights)
print(f"Iteration {i}, Cost: {cost}")
return weights
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
@@ -53,22 +87,12 @@ def predict_logreg(inX, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
inX = np.hstack([1, inX]) # 添加偏置项
prediction_prob = sigmoid(np.dot(inX, weights)) # 计算预测概率
return 1 if prediction_prob >= 0.5 else 0 # 返回分类标签
# 这里也写自己的代码实现 # 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
if __name__ == "__main__": if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改 # 以下代码可用于测试,可自行随意修改
# 加载训练集 # 加载训练集