diff --git a/function.py b/function.py index 48dac4a..fb0fb6d 100644 --- a/function.py +++ b/function.py @@ -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__": # 以下代码可用于测试,可自行随意修改