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

This commit is contained in:
2024-11-02 23:15:11 +08:00
parent 995fb5ed87
commit c7d9e1dc38
+52 -7
View File
@@ -21,24 +21,44 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423203"
name = "赵昊龙"
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def train_logreg(X, y, numIter=1000, learning_rate=0.01, lambda_reg=0.01):
"""
对率回归训练函数。
对率回归训练函数,加入L2正则化。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
- numIter (int): 迭代次数。默认为1000。
- learning_rate (float): 学习率。默认为0.01。
- lambda_reg (float): L2正则化参数。默认为0.01。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape # m: 样本数, n: 特征数
weights = np.zeros(n) # 参数初始化
for j in range(numIter):
dataIndex = np.random.permutation(m)
for i in range(0, m, 1): # 使用整个数据集进行梯度下降
end = i + 1
batch_X = X[dataIndex[i:end]]
batch_y = y[dataIndex[i:end]]
z = np.dot(batch_X, weights)
h = 1 / (1 + np.exp(-z)) # 计算h
error = batch_y - h # 计算误差
gradient = np.dot(batch_X.T, error) / len(batch_y) # 计算梯度
reg_term = 2 * lambda_reg * weights
gradient += reg_term / len(batch_y)
weights -= learning_rate * gradient # 更新权重
return weights
def predict_logreg(inX, weights):
"""
@@ -51,7 +71,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights) # 线性组合
prob = 1 / (1 + np.exp(-z)) # 计算概率
return 1 if prob >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
@@ -65,7 +87,30 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
with open(filepath, 'r') as file:
data_list = []
y_list = []
for line in file:
data = line.strip()
data = data.split(' ')
if '?' in data:
continue # 跳过包含 '?' 的行
data_25 = data[24]
y_list.append(data[22])
del data[-1]
del data[26]
del data[25]
del data[24]
del data[22]
del data[2]
for i in data_25:
data.append(i)
data = [0.0 if data_elem == '?' else float(data_elem) for data_elem in data]
data_list.append(data)
y_array = np.array([1 if label == '2' or label == '3' else 0 for label in y_list])
X_array = np.array(data_list)
X_array = np.insert(X_array, 0, 1, axis=1)
return X_array, y_array
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改