Python Libraries for Machine Learning on iOS

in

To set the stage why you might want to use Python for machine learning on iOS in the first place. Well, if you’re like me, you love the power of Python for data analysis and modeling, but you also have an iPhone that you need to do some serious computing with. And while Apple has made great strides in recent years to make their devices more capable of running machine learning models, sometimes you just want to use what you know best Python!

So how can we get started? Well, there are a few different ways to run Python on iOS, but the easiest and most popular method is by using an app called “Pythonista”. This app allows us to write and execute Python code directly on our iPhones or iPads. It’s like having a mini-laptop in your pocket!

To get started with Pythonista, you can download it from the App Store for $9.99 (or free if you have an active subscription to their “Power User” plan). Once you have the app installed, open it up and create a new file by tapping on the plus sign in the bottom right corner of the screen.

Now some popular Python libraries for machine learning that we can use with Pythonista. One of the most popular is “scikit-learn”, which provides a wide range of tools for data preprocessing, model selection, and evaluation. To install scikit-learn in Pythonista, you can simply copy and paste this code into your new file:

# Import necessary libraries
import requests # Importing the requests library to make HTTP requests
from io import BytesIO # Importing the BytesIO class from the io library to handle binary data
import zipfile # Importing the zipfile module to handle zip files
import os # Importing the os module to interact with the operating system

# Define the URL to download scikit-learn from
url = "https://scipy.org/download/scikit-learn"

# Make a GET request to the URL and store the response in a variable
response = requests.get(url)

# Create a BytesIO object to store the binary data from the response
zip_data = BytesIO(response.content)

# Use the zipfile module to extract the zip file from the BytesIO object
with zipfile.ZipFile(BytesIO(response.content)) as z:
    # Loop through the files in the zip file
    for file in z.namelist():
        # Check if the file name contains "sklearn" and ends with ".tar.gz"
        if "sklearn" in file and ".tar.gz" in file:
            # Open a new file to write the zip file to
            with open("scikit-learn.zip", 'wb') as f:
                # Write the zip file to the new file
                f.write(z.read(file))
            # Break out of the loop once the file is found
            break

# Use the os module to run a system command to unzip the downloaded file and remove it afterwards
os.system('unzip scikit-learn.zip && rm scikit-learn.zip')

# Add the path to the scikit-learn library to the system path
import sys
sys.path.append('/private/var/mobile/Containers/Bundle/Application/B27D5C9A-13F0-4E68-ABCD-FEEDFACEDEADBEEF/Pythonista3.app/Frameworks/Python.framework/Versions/Current/lib/python3.9')

# Import the scikit-learn library
import sklearn as skl

This code downloads the latest version of scikit-learn from their website, extracts it into a folder on your device, and adds that folder to Pythonista’s search path so we can import it in our scripts.

Now let’s say we want to use scikit-learn to load a dataset from the web and train a simple linear regression model on it. Here’s some sample code that demonstrates how this can be done:

# Import necessary libraries
import pandas as pd # Importing pandas library for data manipulation and analysis
from sklearn.linear_model import LinearRegression # Importing LinearRegression model from scikit-learn library
from sklearn.metrics import mean_squared_error # Importing mean_squared_error function from scikit-learn library

# Define the URL of the dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets-for-ML-Courses/master/Bike-Sharing-Demand/hourly.csv"

# Read the dataset into a pandas dataframe
df = pd.read_csv(url)

# Select the features and target variable for the model
X = df[['temp', 'atemp']] # Features are temperature and adjusted temperature
y = df['count'] # Target variable is the number of bike rentals

# Create an instance of the LinearRegression model
model = LinearRegression()

# Train the model using the features and target variable
model.fit(X, y)

# Make predictions using the trained model
predictions = model.predict([[10, 5]]) # Predicting the number of bike rentals for a temperature of 10 and adjusted temperature of 5

# Calculate the mean squared error of the model
print("MSE:", mean_squared_error(df['count'].iloc[:-1], model.predict(X))) # Comparing the actual and predicted values of the target variable to evaluate the performance of the model

This code downloads a dataset of bike sharing demand from GitHub and trains a linear regression model on it using scikit-learn’s “LinearRegression” class. It then prints the mean squared error (MSE) between the predicted values and the actual values for the first 90% of the data.

And that’s it! With Pythonista, you can now run machine learning models on your iPhone or iPad using popular libraries like scikit-learn. It may not be as powerful as a full-blown laptop or desktop computer, but sometimes all we need is a little bit of computing power in our pocket to get the job done.

SICORPS