Machine Learning Apps with Swift as Backend & Python ML Models

  • Duplicate development efforts in Apps Development to consume same trained models
  • Separate Trained Models for different OS — High maintenance cost
  • Vapor 4
  • Python3
  • t2.large instance
python — v2.7python3 — v3.8 (or any other version of python v3)
brew install python
export PYTHON_LIBRARY=/usr/bin/python3
source ~/.zshrc
pip3 install joblib
pip3 install pandas
pip3 install -U scikit-learn scipy matplotlib
.package(url: “https://github.com/pvieito/PythonKit.git", .branch(“master”))
resources: [.copy(“Python/HeartRiskModel.sav”)],
import PythonKitclass HeartRiskPythonModel {/// URL of model assuming it was installed in the same bundle as this class    class var urlOfModelInThisBundle : String {        let _ = Bundle(for: self)        return Bundle.module.path(forResource: “HeartRiskModel”, ofType:”sav”)!    }}
let joblib = Python.import(“joblib”)let heartModelPath = HeartRiskPythonModel.urlOfModelInThisBundlelet heartRiskModel = joblib.load(heartModelPath)
let user_data = [[body.age, body.sex, body.cp, body.trestbps, body.chol, body.fbs, body.restecg, body.thalach, body.exang, body.oldpeak, body.slope, body.ca, body.thal]]let predection = heartRiskModel.predict(user_data)let predection_prob = heartRiskModel.predict_proba(user_data)
  • You always need to map Python Models into CoreML models
sudo apt updatesudo apt upgradesudo apt install binutils git gnupg2 libc6-dev libcurl4 libedit2 libgcc-9-dev libpython2.7 libsqlite3-0 libstdc++-9-dev libxml2 libz3-dev pkg-config tzdata zlib1g-devwget https://swift.org/builds/swift-5.3.3-release/ubuntu2004/swift-5.3.3-RELEASE/swift-5.3.3-RELEASE-ubuntu20.04.tar.gztar xzf swift-5.3.3-RELEASE-ubuntu20.04.tar.gzsudo mv swift-5.3.3-RELEASE-ubuntu20.04 /usr/share/swiftecho "export PATH=/usr/share/swift/usr/bin:$PATH" >> ~/.bashrcsource  ~/.bashrcswift --version
vapor run serve — hostname 0.0.0.0 — port 80

--

--

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