← Blog Teaching 9 min

Data science and AI programming languages

Python? R? Java? What's the difference, and why does it matter for data science?

October 15, 2024

Every data scientist hears it eventually, the first time someone asks “but why not Java?”

The short answer: libraries.

The long answer: read on.

Why do data scientists program at all?

Not all programmers are data scientists. But in the industry today, most data scientists are programmers. Why?

Precedence goes back to the wild-wild-west days of data science, when packages and algorithms weren’t widely supported and data scientists had to “hack” their way through custom modeling algorithms. Over time, support for the field grew, with a key milestone being the release of scikit-learn 1.0 in 2021 (14 years and 24 beta releases later). Today, many no-code/low-code solutions exist (Dataiku, DataRobot, etc.) built on the foundations of these open-source packages. Furthermore, the foundations of these have enabled some very powerful package integration, such as that with MLflow, a model experimentation and tracking tool.

Counterintuitive to the above, the emphasis on the programming domain has not diminished in the field of data science, it has simply shifted focus. The field continues to evolve at a very rapid pace, and well-structured packages are always playing catch-up. So while utilities for traditional modeling, such as regression techniques and forest ensembles, are very well built out, the leading edge of the field is critically dependent on data scientists who know how to engineer their way through a problem. For example, constructing and training a neural network has a much higher technical demand.

Here’s some code I wrote to build a very simple neural network.

# Function to create model, required for KerasClassifier
def create_model():
    # create model
    model = Sequential()
    model.add(Dense(731, input_shape=(731,), activation='relu'))
    model.add(Dense(50, activation='relu'))
    model.add(Dense(3, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

# fix random seed for reproducibility
seed = 7
tf.random.set_seed(seed)

# create model
model = KerasClassifier(model=create_model, verbose=0)

# define the grid search parameters
batch_size = [10, 40, 100]
epochs = [10, 50, 100]
param_grid = dict(batch_size=batch_size, epochs=epochs)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3, scoring='accuracy')
grid_result = grid.fit(X_train_tfxm, np.array(y_train).flatten())

# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))

Compared to the exact same code for a CatBoost classifier:

# Model Pipeline
model = CatBoostClassifier(iterations=500, learning_rate=0.08, depth=10)

# Grid Search
grid_search = GridSearchCV(estimator=model,
                           param_grid=param_grid,
                           scoring='f1',
                           cv=3)
grid_search.fit(X_train, np.ravel(y_train))

# Results
print("Best: %f using %s" % (grid_search.best_score_, grid_search.best_params_))

What do data scientists need in a programming language?

Technically speaking, data scientists could program in any language. Let’s take Java for example.

Here’s a code snippet for creating a logistic regression model in Java:

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.math3.analysis.ParametricUnivariateFunction;
import org.apache.commons.math3.analysis.function.Logistic;
import org.apache.commons.math3.fitting.SimpleCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoint;

public class LogisticFit {
    public static void main(String[] args) {
        double[] xvalues = new double[]{-6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
        /*
         * These are Y values for values of x for a "standard" logistic equation
         */
        double[] yvalues = new double[]{0.002472623, 0.006692851, 0.01798621, 0.047425873, 0.119202922,
            0.268941421, 0.5, 0.731058579, 0.880797078, 0.952574127, 0.98201379, 0.993307149, 0.997527377};

        List<WeightedObservedPoint> weightedObservedPoints = new ArrayList<>();
        for (int x = 0; x < yvalues.length; x++) {
            weightedObservedPoints.add(new WeightedObservedPoint(1.0, xvalues[x], yvalues[x]));
        }

        /* Starting Estimates */
        /* Lower asymptote. A reasonable estimate is the minimum observed value */
        double a = yvalues[0]; // assumes observations are sorted
        /* Upper asymptote. The 'carrying capacity'. A reasonable estimate is the maximum observed value */
        double k = yvalues[yvalues.length - 1];
        /* Growth rate. For a standard logistic curve this is 1 so 1 is a reasonable estimate */
        double b = 1.0;
        /* Parameter that affects near which asymptote maximum growth occurs. 1.0 if we assume the curve is symmetric */
        double n = 1.0;
        /* Parameter that affects the position of the curve along the ordinate axis. */
        double q = 1.0;
        /*
         * Abscissa of maximum growth. The x value where inflection point of the curve occurs. The value of x when the
         * population is halfway to the maximum. A reasonable estimate is halfway along the x axis if we assume symmetry
         */
        double m = xvalues[xvalues.length / 2];

        double[] estimates = new double[]{k, m, b, q, a, n};

        /* the logistic function we want to fit */
        ParametricUnivariateFunction logisticFunction = new Logistic.Parametric();

        SimpleCurveFitter curveFitter = SimpleCurveFitter.create(logisticFunction, estimates);
        final double[] fit = curveFitter.fit(weightedObservedPoints);

        System.out.println("estimated k = " + fit[0] + ", True value = 1.0");
        System.out.println("estimated m = " + fit[1] + ", True value = 0.0");
        System.out.println("estimated b = " + fit[2] + ", True value = 1.0");
        System.out.println("estimated q = " + fit[3] + ", True value = 1.0");
        System.out.println("estimated a = " + fit[4] + ", True value = 0.0");
        System.out.println("estimated n = " + fit[5] + ", True value = 1.0");
        System.out.println("value of y at estimated curve inflection point (m) = " + logisticFunction.value(m, fit));
    }
}

Here’s how you could create that same model in Python:

from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression

# load your data
x, y = sklearn_to_df(load_breast_cancer())
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

# create and score your model
lr = CustomLogisticRegression()
lr.fit(x_train, y_train, epochs=150)
preds = lr.predict(x_test)
accuracy_score(y_test, preds)

What do they prefer?

In one word: libraries, libraries, libraries.

But also:

  • Code simplicity for fast experimentation
  • A language that lends itself well to functional scripting, for experimentation
  • For deployment and sophisticated applications (such as reinforcement learning), a language that can perform in the object-oriented paradigm
  • Code efficiency and speed, which become important on large datasets and complex models

So… why Python?

Libraries.

Pandas: data handling

Pandas is an open-source Python library mainly used to process large datasets by supporting loading, organization, manipulation, modeling, and analysis of data sets. It allows high-performance management of data using its powerful data structures. Pandas allows cleaning of messy datasets, enabling them to be more readable and relevant. With its DataFrame object, Pandas can provide default and custom indexing. Pandas provides tools for loading data into in-memory data objects from various file formats.

scikit-learn: machine learning

The scikit-learn library of Python contains a wide range of supervised and unsupervised learning algorithms that work on a consistent Python interface. Some of the machine learning functions that scikit-learn can handle include classification, regression, clustering, dimensionality reduction, model selection, and preprocessing.

NumPy: numerics

NumPy is short for “Numerical Python.” It is a Python library that is used for working with arrays. NumPy allows a developer to perform mathematical and logical operations on an array. NumPy also supports functions for working with Fourier transforms and routines for shape manipulation. It also has built-in functions for operations related to linear algebra, matrices, and random number generation. NumPy is often used along with Matplotlib and SciPy as a replacement for MATLAB.

Matplotlib: visualization

Matplotlib is an open-source Python library that is used to enhance visualization by providing graph plotting tools. Matplotlib allows the creation of 2D graphs and plots using Python scripts. The Matplotlib library also helps to make visualization more appealing in that it supports colors and color maps. It also allows the creation of animated and interactive visualizations in Python.

SciPy: scientific computing

SciPy is an open-source scientific library of Python used to solve complex scientific and mathematical problems. The SciPy library is built to work on top of the NumPy extension. SciPy allows for user-friendly and effective functions for numerical integration and optimization.

Seaborn: visualization

Seaborn is a Python library based on Matplotlib for the purpose of data visualization. It provides a high-level interface for drawing attractive and informative statistical graphics. It also defines simple high-level functions for common statistical plot types and integrates with the functionality provided by Pandas DataFrames.

PyTorch: deep learning

PyTorch is an open-source tool based on the Torch library. It has a range of libraries that provide computer vision, machine learning, and natural language processing tools. It is easy to learn and to use. PyTorch can seamlessly integrate with the Python data science stack, including NumPy. PyTorch provides a framework to build computational graphs and change them at runtime. It also offers simplified preprocessors and custom data loaders.

Keras: deep learning

Keras is an open-source library that is used for neural networks and machine learning. It works with neural network building blocks like layers, objectives, activation functions, and optimizers. Keras has features to work on images and text. Keras also supports convolutional and recurrent neural networks in addition to standard neural networks.

TensorFlow: deep learning

TensorFlow is an open-source library used for machine learning. The primary use of TensorFlow is for the training and inference of deep neural networks. It is a symbolic math library based on data flow and differentiable programming. TensorFlow comes with a flexible and elaborate ecosystem of tools, libraries, and resources that allows developers to easily build and deploy ML-powered applications.

Today, R and Java have equivalent packages and library support. But industry standards, popularity, and market availability also play a key role. Python leads at the moment.

Grouped bar chart of the share of survey respondents using each language from 2018 to 2022. Python sits above 90 percent every year and climbs to about 96 percent in 2022. SQL is second at 54 to 61 percent. R falls from about 46 percent in 2018 to about 28 percent in 2022. Java, JavaScript, C, and C++ each stay under 14 percent.

Share of survey respondents using each language, by year. Python leads and keeps growing.

Note: R is used widely, but the application is primarily in academia. Python dominates the deployable application market.

At one point, Julia, released in 2011, was an evolving language in the market. But due to its steep learning curve, it has not picked up a lion’s share of the popularity.

Python, R, and Java: a direct comparison

PythonRJava
Programming paradigmHigh-level functional or object-oriented languageHigh-level functional languageHigh-level object-oriented language
Code simplicityClose to human languageConvoluted at timesLearning curve
Lines of codeMinimalMostly minimalVerbose
SupportStrong open source communityNiche academic communityStrong open source community
SpeedFastNot ideal for scaleFastest
IntegrationExtremely versatileNarrow applicabilityExtremely versatile
Field popularityWidely available skillsetDomain specificNiche hire

But what about parallel compute?

In a world of ever-growing data and algorithm complexity (think LLMs), it becomes increasingly difficult (and time consuming!) to thread through a single machine. Such tasks need to leverage multiple machines in order to manipulate data in a distributed fashion. This is where Databricks and Apache Spark come in. However, Python is not natively equipped to leverage all of the parallel compute capabilities within Spark. To perform dataset manipulations in a distributed fashion, we must use either PySpark or Scala as a programming language. Most data scientists prefer PySpark due to its package support (ML algorithms) and similarity to Python syntax.

PySpark is the Python API for Apache Spark. It enables you to perform real-time, large-scale data processing in a distributed environment using Python. It also provides a PySpark shell for interactively analyzing your data.

PySpark: The Apache Spark community released a tool called PySpark specific to Python to support Apache Spark from Python. PySpark allows one to interface with Resilient Distributed Datasets (RDDs) in Apache Spark and the Python programming language. This is done using the Py4J library, which is integrated within PySpark and allows Python to dynamically interface with JVM projects.

Here’s a comparison summary from a Databricks contributor:

PySpark: the Python API for Spark

  • Python API for Spark: PySpark allows you to harness the simplicity of Python while leveraging the power of Apache Spark.
  • Data scientists’ choice: Data scientists often prefer PySpark due to Python’s ease of use, rich libraries (such as Pandas), and extensive ecosystem.
  • Model training and exploration: Use PySpark for model training, exploratory data analysis, and machine learning tasks.
  • Interactive development: It’s great for interactive development and prototyping.
  • Community support: The Python community provides a wealth of resources and packages.

Note: While PySpark is user-friendly, it may not be as performant as Scala for certain operations.

Scala: runs on the JVM

  • Pure-bred object-oriented language: Scala runs on the JVM and is a versatile language with strong functional programming capabilities.
  • Performance: For large-scale data processing, Scala often offers better performance than PySpark.
  • Legacy codebases: If you have a legacy codebase written in Scala with useful utilities, you can run Scala code directly from PySpark.
  • ETL jobs and performance-critical tasks: Use Scala for ETL jobs, performance-critical tasks, and custom Spark functions.
  • ML engineers and data engineers: Scala is well-suited for ML engineers and data engineers who focus on robust, efficient code.

Note: Scala may have a steeper learning curve, but it excels in performance-critical scenarios.

What’s next?

Quantum computing: an introduction to the quantum programming language Q# and Azure Quantum.