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

This commit is contained in:
2024-10-31 16:36:14 +08:00
parent fbd28e611b
commit 7d4f661ff0
+8 -25
View File
@@ -42,20 +42,16 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
m, n = X.shape
weights = np.zeros(n)
for _ in range(iterations):
# 计算预测值
z = np.dot(X, weights)
predictions = 1 / (1 + np.exp(-z))
# 计算损失的梯度
gradient = np.dot(X.T, (predictions - y)) / m
# 更新权重
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
@@ -67,40 +63,27 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
z = np.dot(inX, weights)
prediction_prob = 1 / (1 + np.exp(-z))
return 1 if prediction_prob >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
data = []
labels = []
with open(filepath, 'r') as f:
for line in f:
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
data.append(values[:-1])
labels.append(values[-1])
data.append(values[:-1]) # 特征
labels.append(values[-1]) # 标签
except ValueError:
continue
return np.array(data), np.array(labels)
def preprocess_data(filepath):
# 加载数据
X, y = load_data(filepath)
# 特征缩放
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 拆分数据集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改