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

This commit is contained in:
2024-11-13 19:21:10 +08:00
parent cc22acf866
commit 0dfcedab02
+39 -35
View File
@@ -23,50 +23,54 @@ import numpy as np
姓名请直接**填写中文** 姓名请直接**填写中文**
例如: name = "张三" 例如: name = "张三"
""" """
id = "202210423xxx" id = "202210423113"
name = "test_name" name = "杨文强"
import os
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# 这里写自己的代码实现 def sigmoid(z):
def train_logreg(X, y, other_params="你自己设置一些其它参数"): """计算sigmoid函数"""
""" return 1.0 / (1 + np.exp(-z))
对率回归训练函数。
Args: def compute_gradient(X_batch, y_batch, weights, lambda_reg):
- X (numpy array): 特征数据。 """计算梯度,包含L2正则化"""
- y (numpy array): 标签数据。 z = np.dot(X_batch, weights)
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 h = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
gradient += (lambda_reg / len(y_batch)) * weights # L2正则化
return gradient
Returns: def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
- numpy array: 训练得到的权重。 """逻辑回归训练函数。"""
""" m, n = X.shape
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
print("开始训练逻辑回归模型")
for i in range(iterations):
indices = np.random.permutation(m)
X_shuffled = X[indices]
y_shuffled = y[indices]
for j in range(0, m, batch_size):
X_batch = X_shuffled[j:j + batch_size]
y_batch = y_shuffled[j:j + batch_size]
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
weights -= learning_rate * gradient
if i % 1000 == 0: # 每1000次迭代打印一次信息
print(f"迭代 {i}: 当前权重形状: {weights.shape}")
return weights
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
""" """逻辑回归预测函数。"""
对率回归预测函数。 z = np.dot(inX, weights)
h = sigmoid(z)
Args: return 1 if h >= 0.5 else 0
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
if __name__ == "__main__": if __name__ == "__main__":