A toolbox of AI modules written in Swift: Graphs/Trees, Support Vector Machines, Neural Networks, PCA, K-Means, Genetic Algorithms

Overview

AIToolbox

A toolbox of AI modules written in Swift: Graphs/Trees, Linear Regression, Support Vector Machines, Neural Networks, PCA, KMeans, Genetic Algorithms, MDP, Mixture of Gaussians, Logistic Regression

This framework uses the Accelerate library to speed up computations, except the Linux package versions. Written for Swift 3.0. Earlier versions are Swift 2.2 compatible

SVM ported from the public domain LIBSVM repository See https://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information

The Metal Neural Network uses the Metal framework for a Neural Network using the GPU. While it works in preliminary testing, more work could be done with this class

Use the XCTest files for examples on how to use the classes

Playgrounds for Linear Regression, SVM, and Neural Networks are available. Now available in both macOS and iOS versions.

###New - Convolution Program For the Deep Network classes, please look at the Convolution project that uses the AIToolbox library to do image recognition.

New Swift Package - Mac and Linux compatible!

The package is a sub-set of the full framework. Classes that require GCD or LAPACK have not been ported. I am investigating LAPACK on Linux alternatives, and may someday figure out how to get libdispatch to compile on Ubuntu... Use this subdirectory to reference the package from your code.

Manual

I have started a manual for the framework. It is a work-in-progress, but adds some useful explanation to pieces of the framework. All protocols, structures, and enumerations are well defined. Class descriptions are there, but not class variables and methods.

Classes/Algorithms supported:

Graphs/Trees
    Depth-first search
    Breadth-first search
    Hill-climb search
    Beam Search
    Optimal Path search

Alpha-Beta (game tree)

Genetic Algorithms
    mutations
    mating
    integer/double alleles

Constraint Propogation
    i.e. 3-color map problem

Linear Regression
    arbitrary function in model
    regularization can be used
    convenience constructor for standard polygons
    Least-squares error

Non-Linear Regression
    parameter-delta
    Gradient-Descent
    Gauss-Newton

Logistic Regression
    Use any non-linear solution method
    Multi-class capability

Neural Networks
    multiple layers, several non-linearity models
    on-line and batch training
    feed-forward or simple recurrent layers can be mixed in one network
    simple network training using GPU via Apple's Metal
    LSTM network layer implemented - needs more testing
    gradient check routines

Support Vector Machine
    Classification
    Regression
    More-than-2 classes classification

K-Means
    unlabelled data grouping

Principal Component Analysis
    data dimension reduction

Markov Decision Process
    value iteration
    policy iteration
    fitted value iteration for continuous state MDPs - uses any Regression class for fit
            (see my MDPRobot project on github for an example use)
    Monte-Carlo (every-visit, and first-visit)
    SARSA

Gaussians
    Single variable
    Multivariate - with full covariance matrix or diagonal only

Mixture Of Gaussians
    Learn density function of a mixture of gaussians from data
    EM algorithm to converge model with data

Validation
    Use to select model or parameters of model
    Simple validation (percentage of data becomes test data)
    N-Fold validation

Deep-Network
    Convolution layers
    Pooling layers
    Fully-connected NN layers
    multi-threaded

Plotting
    NSView based MLView for displaying regression data, classification data, functions, and classifier areas!
    UIView based MLView for iOS applications, same as NSView based for macOS

Regression Plot Image Classification Plot Image

License

This framework is made available with the Apache license.

Contributions

See the contribution document for information on contributing to this framework

Comments
  • SVM Training error is: invalidModelType Error

    SVM Training error is: invalidModelType Error

    i ran the code which is svm.trainClassifier(...) however they always say that there is an error so i use the catch and print out what type of error is

    do {
    //            try svm.train(trainData)
        try svm.trainClassifier(trainData)
            }
            catch let error as Error {
                print("SVM Training error is: \(error)")
            }
    

    that and the result is 'invalidModelType' even though i set the type is

    let svm = SVMModel(problemType: .c_SVM_Classification, kernelSettings: KernelParameters(type: .linear, degree: 0, gamma: 0.5, coef0: 0.0))

    according to the instruction.

    Thanks for your help

    opened by heuism 20
  • Abort with payload

    Abort with payload

    New issue dear Kevin,

    Last week, i put the lib in successfully, But now it imported fine, but whenever i install the project by Xcode it always stuck here and said that abort with payload, which i dont get the reason why. At first i thought some of my project aren't working right. So i deleted and commented code and some thing like that. But everything still got this issue. Until i delete this subproject out of my project the code runs fine.

    Here is the error, i dont know what is this, and dont even now this is error or not.

    screen shot 2017-02-02 at 12 37 26 pm

    screen shot 2017-02-02 at 12 37 38 pm

    Thanks for your help

    opened by heuism 7
  • Can not import into Swift Project

    Can not import into Swift Project

    I have done exactly what the manual showed. But still. When i tried to import AIToolbox into Xcode project (my iphone application project) i couldn't do it?

    That would be nice to get your help. Thanks. screen shot 2017-01-24 at 12 16 15 pm

    opened by heuism 7
  • Crossplattform/Linux-Support?

    Crossplattform/Linux-Support?

    It would be great if there would be a package/version/branch which we can use with Open Swift projects. For example a server with vapor and the AIToolbox could be a great project. Any thoughts on this?

    opened by ZENTRALALEX 5
  • Can the input a discrete value?

    Can the input a discrete value?

    I haven't tested yet but i would like to ask if the input can be discrete value like 'Hot' 'Cold' 'Windy' instead of 1 2 3 or can say continuous value?

    Thanks a lot for your help

    opened by heuism 4
  • Possible to set Regularisation Strength in LogisticRegression

    Possible to set Regularisation Strength in LogisticRegression

    Firstly, This is amazing!. Thank you very much for this beautiful library.

    I've only just started exploring it for the last 6 hours so apologies if this is obvious but I wanted to check it was / wasn't possible to set regularisation strength for LogisticRegression? Or perhaps I'm just invoking it incorrectly: https://gist.github.com/AJamesPhillips/07471da4b4be0190d8e34bf357c3c431

    There are two tests with similar data (1 st input dimension uniform random distribution, 2 nd input dimension linear trend from 0 to 99, output dimension 0 if 2nd input dimension < 50 else 1). On the first small data test, the classifier usually predicts an output value of 1. On the second larger similar data set the tests fail randomly (I assume this is just overfitting).

    Many thanks! (and apologies if this is a stupid question, I'm new to this area in general, both swift and classifiers etc).

    opened by AJamesPhillips 4
  • Error in SVM classify

    Error in SVM classify

    The function classify in the classifier extension of the SVM model by default always throws an error. This is due to a simple logical error in line 128. For type checking, rather than a logical OR, I believe it should be a logical AND.

    opened by skomatin 3
  • SVM regressor predictOne()

    SVM regressor predictOne()

    While implementing your fabulous SVM class (as a regressor), I always fall upon an error while running predictOne(). The error happens here : "var sum = 0.0 for k in 0..<supportVectorCount[0] { sum += coefficients[0][coeffStart[0]+k] * kernelValue[coeffStart[0]+k] } for k in 0..<supportVectorCount[1] { sum += coefficients[0][coeffStart[1]+k] * kernelValue[coeffStart[1]+k] }" the vectorSupport exist, the totalSupportVector is >0. Yet the supportVectorCount is nil. Is it because I am in the regressor mode and not the classification mode ? I did not look at the classification cases yet. So, basically, the two "for in" instructions cited above will always fail.

    I came around this by creating a mock function like this : open func predictOneJY (_ inputs: [Double]) -> Double { var sum = 0.0 for i in 0..<totalSupportVectors { let kernelValue = Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[i]) sum += coefficients[0][i] * kernelValue } sum -= ρ[0] return sum } It returns the correct ouput AFAIK. But I wonder if there is something that I miss, and it is, in fact, my implementation that is faulty, or if the code of predictOne() could indeed be "streamlined" or "corrected" for the regressor cases. And thanks again for your magnificent and very useful project.

    opened by mente371 3
  • Implementation of correlation

    Implementation of correlation

    I implemented a simple correlation function borrowing heavily from Numpy's implementation (here and here). If this is something you'd like to see in the library would you like me to submit a pull request? I'm not yet sure where the best place for this is within the library.

    https://gist.github.com/AJamesPhillips/7ea56a3a217be300a5705a8109c73a5b

    Thanks

    opened by AJamesPhillips 3
  • PCA

    PCA

    i) Your library is great. ii) In the function "getReducedBasisVectorSet(_ data: MLDataSet)", at the end when you create the basisVectors matrice, should it not be basisVectors[(vector * initialDimension) + column] = vTranspose[vector + (column * initialDimension)] instead of basisVectors[(vector * reducedDimension) + column] = vTranspose[vector + (column * initialDimension)] ?

    opened by mente371 2
  • Contribution list / checklist

    Contribution list / checklist

    Hey! I came across this project and was wondering if you guys could build a checklist of TODOs etc for potential contributors.

    Something like

    • [ ] Benchmarks
    • [ ] CNNs
    • [ ] POMDPs ..etc?
    opened by codeOfRobin 2
  • load model with not plist file

    load model with not plist file

    When creating SVM init by function public init?(loadFrom path: String) svm is nil. because file model is not plist

    how to create svm model by other model file (attach file)?
    model.zip

    Thanks!

    opened by moddedayja 1
  • RNN>feedForward>SoftMax

    RNN>feedForward>SoftMax "sum" in wrong place?

    SoftMax output gives me all +inf's as results...

    Looking at the source (Recur...swift), it looks like the "sum" calculation is happening for activation function sigmoidWithCrossEntropy instead of softMax?

    Otherwise, "sum" just gets tossed away, while softMax is always dividing by 0.

    Line 808+:

    //  Run through the non-linearity
            var sum = 0.0
            for node in 0..<numNodes {
                switch (activation) {
                case .none:
                    h[node] = z[node]
                    break
                case .hyperbolicTangent:
                    h[node] = tanh(z[node])
                    break
                case .sigmoidWithCrossEntropy:
                    h[node] = 1.0 / (1.0 + exp(-z[node]))
                    sum += h[node] // ** <-- THIS... **
                    break
                case .sigmoid:
                    h[node] = 1.0 / (1.0 + exp(-z[node]))
                    break
                case .rectifiedLinear:
                    h[node] = z[node]
                    if (z[node] < 0) { h[node] = 0.0 }
                    break
                case .softSign:
                    h[node] = z[node] / (1.0 + abs(z[node]))
                    break
                case .softMax:
                    h[node] = exp(z[node])
                    sum += h[node] // ** <-- ..SHOULD BE HERE? **
                    break
                }
            }
    
            if (activation == .softMax) {
                var scale = 1.0 / sum       //  Do division once for efficiency  ** ~~BOOM~~ **
            .
            .
            .
    
    
    opened by headcrash13 0
  • SVM Training for one-class-svm doesn't work

    SVM Training for one-class-svm doesn't work

    When creating a One-Class SVM classifier (e.g. for the following data) do { try trainData.addDataPoint(input: [0.2, 0.9], dataClass:1) try trainData.addDataPoint(input: [0.8, 0.3], dataClass:1) try trainData.addDataPoint(input: [0.5, 0.6], dataClass:1) } //catch etc. let svm = SVMModel(problemType: .oneClassSVM, kernelSettings: KernelParameters(type: .radialBasisFunction, degree: 0, gamma: 0.5, coef0: 0.0)) svm.train(trainData)

    Throws Index out of range error in SVM.swift in two places: Line 1531 and Line 1197

    opened by borozanov 2
  • Example/Manual for Deep Convolutional Neural Net

    Example/Manual for Deep Convolutional Neural Net

    Would it be possible to add in an example/manual section for Deep Convolutional Neural Networks? I haven't seen any documentation for this, except for having to look through the source code itself, to understand how this works.

    opened by tanmayb123 4
  • DeepNetwork vs MetalNeuralNetwork

    DeepNetwork vs MetalNeuralNetwork

    Can i ask which one is better and the difference between these two?

    By the way, regarding SVM, can we choose between different kernels like Linear or something?

    Thanks @KevinCoble

    opened by heuism 1
  • Incremental Learning

    Incremental Learning

    Hi @KevinCoble,

    I got a thing to ask about incremental learning which i guess you have already known. So i dont know if this library support that idea or not?

    If yes, how can i use it? and which Algorithm is capable of doing so? As far as i know, this issue is really complicated so i am not too sure, however there is SVM with linear kernel that can do this thing.

    If no, Do you intend to make that as a feature in the future? Cause it seems relearn every time is not a really good way to do.

    Btw, if i want to check for the Precision, F-score, Recall and Accuracy and Validation how can i do that? I looked at the Test for Validation but it only showed the example for Regression so i dont know for sure.

    Thank for your help again @KevinCoble

    opened by heuism 0
Owner
Kevin Coble
Kevin Coble
A framework for building fast genetic algorithms in Swift.

Revolver is a framework for building fast genetic algorithms in Swift 3.0. Features Chromosomes: strings, trees Genetic operators: reproduction, mutat

Petr Mánek 27 Nov 17, 2022
Accelerated tensor operations and dynamic neural networks based on reverse mode automatic differentiation for every device that can run Swift - from watchOS to Linux

DL4S provides a high-level API for many accelerated operations common in neural networks and deep learning. It furthermore has automatic differentiati

Palle 87 Dec 29, 2022
Easily craft fast Neural Networks on iOS! Use TensorFlow models. Metal under the hood.

Bender Bender is an abstraction layer over MetalPerformanceShaders useful for working with neural networks. Contents Introduction Why did we need Bend

xmartlabs 1.7k Dec 24, 2022
DL4S provides a high-level API for many accelerated operations common in neural networks and deep learning.

DL4S provides a high-level API for many accelerated operations common in neural networks and deep learning. It furthermore has automatic differentiati

DL4S Team 2 Dec 5, 2021
Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Neural Networks

mtcnn-caffe Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Neural Networks. This project provide you a method to update mu

Weilin Cong 500 Oct 30, 2022
Automatic colorization using deep neural networks. Colorful Image Colorization. In ECCV, 2016.

Colorful Image Colorization [Project Page] Richard Zhang, Phillip Isola, Alexei A. Efros. In ECCV, 2016. + automatic colorization functionality for Re

Richard Zhang 3k Dec 27, 2022
BrainCore is a simple but fast neural network framework written in Swift.

BrainCore is a simple but fast neural network framework written in Swift. It uses Metal which makes it screamin' fast. If you want to see it

Alejandro Isaza 377 Jun 29, 2022
DeepInfant® is a Neural network system designed to predict whether and why your baby is crying.

DeepInfant DeepInfant® is a Neural network system designed to predict whether and why your baby is crying. DeepInfant uses artificial intelligence and

Skytells AI Research 14 Oct 19, 2022
Takes those cursed usernames you see on social networks and lets them be accessible to screen readers.

AccessibleAuthorLabel ?? Takes those cursed usernames you see on social networks and lets them be accessible to screen readers so everyone can partake

Christian Selig 40 Jan 25, 2022
Shallow and Deep Convolutional Networks for Saliency Prediction

Shallow and Deep Convolutional Networks for Saliency Prediction Paper accepted at 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVP

Image Processing Group - BarcelonaTECH - UPC 183 Jan 5, 2023
Deeper Depth Prediction with Fully Convolutional Residual Networks (FCRN)

Deeper Depth Prediction with Fully Convolutional Residual Networks By Iro Laina, Christian Rupprecht, Vasileios Belagiannis, Federico Tombari, Nassir

Iro Laina 1.1k Dec 22, 2022
CloneCorp - Data corpus for the evaluation of cross-language clone detection algorithms

CloneCorp - Data corpus for the evaluation of cross-language clone detection algorithms

FLAGlab 1 Jan 31, 2022
A Swift deep learning library with Accelerate and Metal support.

Serrano Aiming to offering popular and cutting edge techs in deep learning area on iOS devices, Serrano is developed as a tool for developers & resear

pcpLiu 51 Nov 17, 2022
MLKit is a simple machine learning framework written in Swift.

MLKit (a.k.a Machine Learning Kit) ?? MLKit is a simple machine learning framework written in Swift. Currently MLKit features machine learning algorit

Guled 152 Nov 17, 2022
A Swift library for creating and exporting CoreML Models in Swift

SwiftCoreMLTools A Swift Library for creating CoreML models in Swift. Work in progress This library expose a (function builder based) DSL as well as a

Jacopo Mangiavacchi 140 Dec 5, 2022
The Swift machine learning library.

Swift AI is a high-performance deep learning library written entirely in Swift. We currently offer support for all Apple platforms, with Linux support

Swift AI 5.9k Jan 2, 2023
Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy.

Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

null 80 Dec 21, 2022
A simple Swift package which acts as an OpenAI client for the GPT-3 API.

SwiftyGPT3 A simple Swift package which acts as an OpenAI client for GPT-3 brought to you by the Airgift Crew. Supports GPT-3 Codex! Requirements iOS

Airgift 23 Dec 25, 2022
A lightweight library to calculate tensors in Swift, which has similar APIs to TensorFlow's

TensorSwift TensorSwift is a lightweight library to calculate tensors, which has similar APIs to TensorFlow's. TensorSwift is useful to simulate calcu

Qoncept, Inc. 323 Oct 20, 2022