From 79bb3985dd854848252c9c0244712390da999d02 Mon Sep 17 00:00:00 2001 From: Ulysses-ui <3233559397@qq.com> Date: Sun, 3 Nov 2024 13:52:32 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/function.py b/function.py index 103d776..7bbcff0 100644 --- a/function.py +++ b/function.py @@ -26,10 +26,6 @@ name = "刘子豪" # 这里写自己的代码实现 -def sigmoid(z): - return 1 / (1 + np.exp(-z)) #用于将数据转化成一个0 - 1之间的概率值 - - def train_logreg(X, y, other_params="你自己设置一些其它参数"): """ 对率回归训练函数。 @@ -44,11 +40,14 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): """ m, n = X.shape weights = np.zeros(n) + for _ in range(iterations): - predictions = sigmoid(np.dot(X, weights)) + z = np.dot(X, weights) + predictions = 1 / (1 + np.exp(-z)) # 计算sigmoid errors = y - predictions gradient = np.dot(X.T, errors) / m weights += learning_rate * gradient + return weights @@ -63,7 +62,8 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - probability = sigmoid(np.dot(inX, weights)) + z = np.dot(inX, weights) + probability = 1 / (1 + np.exp(-z)) return 1 if probability >= 0.5 else 0 @@ -84,17 +84,14 @@ def load_data(filepath): with open(filepath, 'r') as file: for line in file: fields = line.strip().split() - # 检查是否有缺失值,并排除不符合行长度要求的数据 if '?' in fields or len(fields) < 2: continue try: - # 假设特征在前面,标签在最后一列 data.append([float(x) for x in fields[:-1]]) labels.append(int(fields[-1])) except ValueError: - # 如果无法转换为浮点数或整数,跳过该行 continue - # 返回值需要是两个NumPy数组 + return np.array(data), np.array(labels)