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

This commit is contained in:
2024-10-24 17:04:17 +08:00
parent f0a2ae281b
commit e96a20408d
+19 -2
View File
@@ -21,8 +21,8 @@ import numpy as np
""" """
请在这里填写学号和姓名,不填写即成绩无效。 请在这里填写学号和姓名,不填写即成绩无效。
""" """
id = "202210423xxx" id = "202210423204"
name = "test_name" name = "陈垣豪"
# 这里写自己的代码实现 # 这里写自己的代码实现
@@ -38,6 +38,17 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape # m: 样本数, n: 特征数
weights = np.zeros(n) # 初始化权重
# 训练逻辑回归模型
for _ in range(iterations):
z = np.dot(X, weights) # 线性组合
predictions = 1 / (1 + np.exp(-z)) # 计算预测值,直接使用 sigmoid 公式
# 更新权重
weights += learning_rate * (1/m) * np.dot(X.T, (y - predictions))
return weights
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
@@ -51,6 +62,8 @@ def predict_logreg(inX, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
prob = 1 / (1 + np.exp(-np.dot(inX, weights))) # 直接使用 sigmoid 公式计算概率
return 1 if prob >= 0.5 else 0 # 根据阈值返回标签
# 这里也写自己的代码实现 # 这里也写自己的代码实现
@@ -65,6 +78,10 @@ def load_data(filepath):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
data = np.loadtxt(filepath, delimiter=',', dtype=float, skiprows=1)
X = data[:, :-1] # 所有列,除了最后一列
y = data[:, -1] # 最后一列作为标签
return X, y
if __name__ == "__main__": if __name__ == "__main__":