Titanic SwiftUI+ML (English version)

In this article, I will try to explain a simple application using the turicreate framework to train a model and then use it to predict the percentage of chance of having survived the disaster of the Titanic. I obtained the data on the Kaggle platform , and all the code is on Github.

Part in Python

The turicreate framework uses Python, and I will use the Jupyter Notebook application through Anaconda. To download Anaconda, use this link. There find the download and do the same for your version of the operating system. I will use for macOS since later I will demonstrate the use on iOS. I hope you have access to the Apple system.

Anaconda Navigator
Anaconda Environment
pip install -U turicreate 
conda install -c conda-forge jupyterlab
  1. Let’s read the CSV data into a structure called SFrame.
  2. We will clean the data, excluding the empty values. (For an ML course, the ideal would be to arrange the data, but we will delete the lines with missing data for simplification)
  3. After that, we will divide the data into 80% and 20% into training data and test data. This test data will be useful later to evaluate the model.
  4. We are going to create two constants called target and an array called features. The target will be Survived, that is, whether the person survived or not. The features will be age, sex and class. If you want to test other features, feel free.
  5. In the next line, we will use turicreate magic and create the classifier.
  6. After this method, I put some others in the repository, to evaluate the model, in the case of one of the tests, the accuracy test, we had 76.92%, it is not perfect, but we can accept this without having had a lot of effort.
  7. Finally, we will use a method to export the model to CoreML, which is the one used in iOS to make predictions with the data placed.
# 1 
import turicreate as tc
# 2
data = tc.SFrame.read_csv('./data/train.csv')
# 3
data = data.dropna()
# 4
train, test = data.random_split(0.8)
# 5
target = 'Survived'
features = ['Pclass', 'Sex', 'Age']
# 6
model = tc.classifier.create(train, target=target, features=features)
# 7
predictions = model.classify(test)
metrics = model.evaluate(test)
# 8
model.export_coreml('Titanic.mlmodel')

Part in Swift

I will make the application as simple as possible, and for that, I will use the SwiftUI framework. In this part, I will go through the code more slowly, to explain a little what is happening here. Let’s start with the properties that we will use with @State.

import SwiftUI 
struct ContentView: View {
@State private var pclass = "3"
@State private var age = "36"
@State private var sex = "male"
@State private var result = 0.00
// more to come
private let sexs = ["male", "female"] 
private let pclasses = ["1", "2", "3"]
var body: some View {
NavigationView {
Form {
Section(header: Text ("Passager class")) {
Picker(selection: $pclass, label: Text("\(pclass)")) {
ForEach(pclasses, id: \ .self ) {
Text ("\ ($ 0) º")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Choose your sex")) {
Picker(selection: $sex, label: Text("\( sex)")) {
ForEach(sexs, id: \.self) {
Text("\($0)")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Put your age")) {
TextField("\(age)", text: $age)
.keyboardType(.numberPad)
}
Section(header: Text("Classify button")) {
Button(action: {
self.calculatePercentual()
}) {
Text("Press to classify")
}
}
Section(header: Text("Percentage")) {
Text("\(result, specifier:"%.2f")%")
}
}
.navigationBarTitle("Titanic SwiftUI ML")
}
  • Form: This structure works as a List specialized in receiving data, so it has a form face.
  • Section: Another structure to improve the aesthetics of the application, to place a header explaining a little the data that we will receive or action that we will perform.
  • Picker: First structure in this list that I put into collecting data. Here we have the use of the power of @State, the ones with the property with the $ starts, allows us to modify the struct attribute. This structure does what its name says, creates a Picker to choose from a data set, which saves in the selected variable.
  • ForEach: This structure is beneficial for going through the data and repeating some other View elements, and this is where we make use of the sexs and pclasses attributes that we created to go through this array and use each item of the collection inside the closure ForEach.
  • Text: Perhaps the most used structure in SwiftUI, because it is with it that we can put texts on the screen for the user.
  • TextField: Second structure to capture data presented and serves to type with the keyboard what we want to receive. Note that in this structure, I put a modifier so that the keyboard only accepts numbers, because as we want to receive the age, we do not wish to allow the user to type the age in a cursive way.
  • Button: Structure to act, which here will be to calculate the percentage of chance of survival.
func calculatePercentual() {
let model = Titanic()
if let pclass = Double(pclass) {
if let age = Double(age) {
do {
let prediction = try model.prediction(Pclass: pclass, Sex: sex , Age: age)
let probs = prediction.SurvivedProbability
if let prob = probs[1] {
result = prob * 100
}
} catch {
fatalError("\ (error)")
}
}
}
}
  1. Create the model from Titanic, which is a class automatically generated by Xcode when we imported the model into IDE.
  2. As the pclass attribute is a String, we had to transform it into Double, because that is what the model will accept.
  3. Here the same thing from above, but for age.
  4. We start a do-catch, as there is a possibility that the prediction is nil, so it is good practice to place it inside a do-catch.
  5. We use the model and the attributes captured in the @State to make the model prediction with the past data.
  6. We take the survival probabilities, which is an array, with keys 0 or 1, that is, zero died, and one is alive.
  7. Finally, we take the probability of surviving, that is, as above, 1.
  8. We put the result in the result property, which as it is a property with @State, will update our view automatically.
  9. Nothing
  10. Capturing the error
  11. We kill the application by printing the error.
  12. Other lines NOTHING
Home screen
Home screen
Prediction standard data
Prediction standard data
Prediction with other data
Prediction with other data

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store