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

This commit is contained in:
cy
2024-10-26 12:41:01 +08:00
parent b0969e36df
commit 0a341ee5fb
+15 -17
View File
@@ -34,8 +34,6 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率。
- iterations (int): 迭代次数。
Returns:
- numpy array: 训练得到的权重。
@@ -64,10 +62,9 @@ def predict_logreg(inX, weights):
h = sigmoid(z)
return 1 if h > 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,处理缺失值,并修改指定的特征。
从文件中加载数据,填充缺失值,并进行特征处理。
Args:
- filepath (str): 数据文件路径。
@@ -83,24 +80,25 @@ def load_data(filepath):
for line in lines:
line = line.strip().split()
if len(line) >= 1 and line[-1].isdigit():
# 处理缺失值,用0填充
line_data = [1 if i == 0 else (0 if x == '?' else float(x)) for i, x in enumerate(line[:-1])]
# 修改特征23(索引为22,因为索引从0开始)
if int(line[22]) in [2, 3]:
line_data[22] = 0 # 将2和3合并为0(表示死亡)
else:
line_data[22] = 1 # 1表示存活
# 去掉特征3(索引为2)和特征24到28(索引为23到28)
line_data = line_data[:2] + line_data[3:23] + line_data[29:]
# 将缺失值 '?' 填充为 0,并转换为浮点数
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
return np.array(data), np.array(labels)
data = np.array(data)
labels = np.array(labels)
# 选择特征,合并目标变量
target_variable = labels
target_variable[(target_variable == 2) | (target_variable == 3)] = 0 # 合并死亡和安乐死为0
# 去掉特征3和特征24~28
data = np.delete(data, [2] + list(range(23, 28)), axis=1) # 特征3的索引是2,特征24-28的索引是23-27
return data, target_variable
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")