WeichenXu123 commented on code in PR #41383: URL: https://github.com/apache/spark/pull/41383#discussion_r1219433535
########## python/pyspark/mlv2/classification.py: ########## @@ -0,0 +1,309 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from pyspark.mlv2.base import _PredictorParams + +from pyspark.ml.param.shared import HasProbabilityCol + +import logging +from typing import Any, Union, List, Tuple, Callable +import numpy as np +import pandas as pd +import math +from pyspark.mlv2.base import Estimator, Model, Predictor, PredictionModel + +from pyspark.sql import DataFrame + +from pyspark.ml.common import inherit_doc +from pyspark.ml.torch.distributor import TorchDistributor +from pyspark.ml.param.shared import ( + HasMaxIter, + HasFitIntercept, + HasTol, + HasWeightCol, + HasSeed, +) +from pyspark.mlv2.common_params import ( + HasNumTrainWorkers, + HasBatchSize, + HasLearningRate, + HasMomentum, +) +from pyspark.sql.functions import lit, count, countDistinct + +import torch +import torch.nn as torch_nn +import torch.nn.functional as torch_fn + + +class _LogisticRegressionParams( + _PredictorParams, + HasMaxIter, + HasFitIntercept, + HasTol, + HasWeightCol, + HasNumTrainWorkers, + HasBatchSize, + HasLearningRate, + HasMomentum, + HasProbabilityCol, + HasSeed, +): + """ + Params for :py:class:`LogisticRegression` and :py:class:`LogisticRegressionModel`. + + .. versionadded:: 3.0.0 + """ + + pass + + +class _LinearNet(torch_nn.Module): + def __init__(self, num_features, num_classes, bias) -> None: + super(_LinearNet, self).__init__() + output_dim = num_classes + self.fc = torch_nn.Linear(num_features, output_dim, bias=bias, dtype=torch.float32) + + def forward(self, x: Any) -> Any: + output = self.fc(x) + return output + + +def _train_logistic_regression_model_worker_fn( + num_samples_per_worker, + num_features, + batch_size, + max_iter, + num_classes, + learning_rate, + momentum, + fit_intercept, + seed, +): + from pyspark.ml.torch.distributor import _get_spark_partition_data_loader + from torch.nn.parallel import DistributedDataParallel as DDP + import torch.distributed + import torch.optim as optim + + # TODO: add a setting seed param. + torch.manual_seed(seed) + + # TODO: support training on GPU + # TODO: support L1 / L2 regularization + torch.distributed.init_process_group("gloo") + + ddp_model = DDP( + _LinearNet(num_features=num_features, num_classes=num_classes, bias=fit_intercept) + ) + + loss_fn = torch_nn.CrossEntropyLoss() + + optimizer = optim.SGD(ddp_model.parameters(), lr=learning_rate, momentum=momentum) + data_loader = _get_spark_partition_data_loader( + num_samples_per_worker, + batch_size, + num_workers=0, + prefetch_factor=None, + ) + for i in range(max_iter): + ddp_model.train() + + step_count = 0 + + loss_sum = 0.0 + for x, target in data_loader: + optimizer.zero_grad() + output = ddp_model(x.to(torch.float32)) + loss = loss_fn(output, target.to(torch.long)) + loss.backward() + loss_sum += loss.detach().numpy() + optimizer.step() + step_count += 1 + + # TODO: early stopping + # When each epoch ends, computes loss on validation dataset and compare + # current epoch validation loss with last epoch validation loss, if + # less than provided `tol`, stop training. + + if torch.distributed.get_rank() == 0: + print(f"Progress: train epoch {i + 1} completes, train loss = {loss_sum / step_count}") + + if torch.distributed.get_rank() == 0: + return ddp_model.module.state_dict() + + return None + + +@inherit_doc +class LogisticRegression(Predictor["LogisticRegressionModel"], _LogisticRegressionParams): + """ + Logistic regression estimator. + + .. versionadded:: 3.5.0 + """ + + def __init__( + self, + *, + featuresCol: str = "features", + labelCol: str = "label", + predictionCol: str = "prediction", + probabilityCol: str = "probability", + maxIter: int = 100, + tol: float = 1e-6, + numTrainWorkers: int = 1, + batchSize: int = 32, + learningRate: float = 0.001, + momentum: float = 0.9, + seed: int = 0, + ): + super(_LogisticRegressionParams, self).__init__() + self._set( + featuresCol=featuresCol, + labelCol=labelCol, + predictionCol=predictionCol, + probabilityCol=probabilityCol, + maxIter=maxIter, + tol=tol, + numTrainWorkers=numTrainWorkers, + batchSize=batchSize, + learningRate=learningRate, + momentum=momentum, + seed=seed, + ) + + def _fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "LogisticRegressionModel": + if isinstance(dataset, pd.DataFrame): + # TODO: support pandas dataframe fitting + raise NotImplementedError("Fitting pandas dataframe is not supported yet.") Review Comment: I think `PySparkXXXError` is only used in pyspark core code. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
