generated from LufsX/Experiment-LogReg
This commit is contained in:
+10
-7
@@ -1,4 +1,3 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
@@ -35,12 +34,13 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
||||
- learning_rate (float): 学习率,默认为0.01。
|
||||
- iterations (int): 迭代次数,默认为1000。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
m, n = X.shape
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
|
||||
for _ in range(iterations):
|
||||
@@ -54,6 +54,7 @@ m, n = X.shape
|
||||
|
||||
return weights
|
||||
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
@@ -65,23 +66,24 @@ def predict_logreg(inX, weights):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
z = np.dot(inX, weights)
|
||||
z = np.dot(inX, weights)
|
||||
h = 1 / (1 + np.exp(-z))
|
||||
return 1 if h >= 0.5 else 0
|
||||
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
with open(filepath, 'r') as f:
|
||||
with open(filepath, 'r') as f:
|
||||
lines = f.readlines()
|
||||
|
||||
X = []
|
||||
@@ -93,6 +95,7 @@ with open(filepath, 'r') as f:
|
||||
|
||||
return np.array(X), np.array(y)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
@@ -106,4 +109,4 @@ if __name__ == "__main__":
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
Reference in New Issue
Block a user