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

This commit is contained in:
2024-11-02 13:47:23 +08:00
parent 1870d5310c
commit e6502d835d
+18 -17
View File
@@ -6,22 +6,22 @@ from sklearn.model_selection import train_test_split
id = "202210423130"
name = "董秋"
# 定义常量
IGNORE_ROWS = {2} | set(range(23, 28)) # 要忽略的行号
def sigmoid(z):
"""Sigmoid 激活函数。"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
"""逻辑回归训练函数,随机初始化权重,并在每次迭代前打乱数据。"""
m, n = X.shape
weights = np.random.randn(n) * 0.01 # 随机初始化权重
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值
for i in range(iterations):
# 每次迭代打乱数据
indices = np.random.permutation(m)
X, y = X[indices], y[indices]
X = X[indices]
y = y[indices]
z = np.dot(X, weights)
predictions = sigmoid(z)
@@ -33,32 +33,32 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
# 更新权重
weights -= learning_rate * gradient
# 动态调整学习率
# 动态调整学习率,逐渐减小
learning_rate *= 0.99
return weights
def predict_logreg(inX, weights):
"""逻辑回归预测函数。"""
z = np.dot(inX, weights)
prediction_prob = sigmoid(z)
return 1 if prediction_prob >= 0.5 else 0
def load_data(filepath):
"""加载数据并处理缺失值。"""
data, labels = [], []
data = []
labels = []
with open(filepath, 'r') as f:
for line_number, line in enumerate(f):
if line_number in IGNORE_ROWS: # 忽略特定行
continue
for line in f:
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
# 合并特征23的取值
if values[22] in [2, 3]: # 特征23(索引22)
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
labels.append(0) # 死亡
elif values[22] == 1:
labels.append(1) # 生存
@@ -66,26 +66,27 @@ def load_data(filepath):
continue # 无效标签,丢弃
# 用0填充缺失值
values = [0 if v == 0 else v for v in values] # 用0填充
values = [0 if v == 0 else v for v in values] # 直接用0填充
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
except ValueError as e:
print(f"Line {line_number} has an error: {e}") # 打印出错行信息
except ValueError:
continue
# 转换为numpy数组
data = np.array(data)
labels = np.array(labels)
return data, labels
def preprocess_data(X):
"""特征标准化。"""
scaler = StandardScaler()
return scaler.fit_transform(X)
if __name__ == "__main__":
# 加载数据集
X, y = load_data("./data/horse-colic.data")
# 归一化数据
X = preprocess_data(X)