diff --git a/function.py b/function.py index 43750f7..cd63d15 100644 --- a/function.py +++ b/function.py @@ -5,9 +5,7 @@ name = "魏明帅" def train_logreg(X, y, learning_rate=0.01, iterations=1000): m, n = X.shape - # 添加偏置项 - X = np.c_[np.ones((m, 1)), X] - weights = np.zeros(n + 1) + weights = np.zeros(n) for _ in range(iterations): for i in range(m): @@ -31,20 +29,31 @@ def load_data(filepath): with open(filepath, 'r') as f: for line in f: values = line.strip().split() + # 跳过包含 '?' 的行 if '?' in values: continue + # 将标签和特征转换为浮点数 y.append(float(values[-1])) X.append([float(x) for x in values[:-1]]) - # 特征缩放 X_array = np.array(X) - X_scaled = (X_array - np.mean(X_array, axis=0)) / np.std(X_array, axis=0) - return X_scaled, np.array(y).reshape(-1, 1) + y_array = np.array(y).reshape(-1, 1) + + # 特征缩放,处理标准差为零的特征 + stds = np.std(X_array, axis=0) + means = np.mean(X_array, axis=0) + X_scaled = (X_array - means) / np.where(stds == 0, 1, stds) + + return X_scaled, y_array if __name__ == "__main__": X_train, y_train = load_data("./data/horse-colic.data") X_test, y_test = load_data("./data/horse-colic.test") + # 添加偏置项 + X_train = np.c_[np.ones((X_train.shape[0], 1)), X_train] + X_test = np.c_[np.ones((X_test.shape[0], 1)), X_test] + weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) y_pred = predict_logreg(X_test[11], weights) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") \ No newline at end of file