• Stars
    star
    147
  • Rank 251,347 (Top 5 %)
  • Language
    PHP
  • License
    GNU Lesser Genera...
  • Created over 4 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Predict attribute values for your Laravel Eloquent models using machine learning!

🖥️🧠💪 Eloquent Attribute Value Prediction

❤️ Machine Learning For Laravel Developers! ❤️


With this package you'll be able to predict attribute values for your Laravel Eloquent models using the power of machine learning! 🌟

With an intuitive syntax you can predict the values of both categorical (string) and continuous (numeric) attributes. Take a look at the examples below.

$animal = new \App\Models\Animal();
$animal->size = 'small';
$animal->has_wings = false;
$animal->domesticated = true;

$animal->name = $animal->predict('name');

// 'cat'

$predictions = $animal->getPredictions('name');

// [
//   'cat' => 0.43,
//   'dog' => 0.40,
//   'bird' => 0.10,
//   'elephant => 0.9,
// ]

$house = new \App\Models\House();
$house->num_bedrooms = 3;
$house->num_bathrooms = 1;

$house->value = $house->predict('value');

// 180000

Installation

To install just run the following Composer command.

composer require divineomega/eloquent-attribute-value-prediction

After installation, you need to set up your model for attribute prediction.

Setup

Let's say you have an IrisFlowers table that contains data about each of three species of the Iris flower. In this example, we want to be able to predict the flower's species given the sepal length and width, and petal length and width.

First, we need to set up out IrisFlower model for attribut prediction.

This is done by adding the HasPredictableAttributes interface and PredictsAttributes trait to our model as shown below.

<?php

namespace App\Models;

use DivineOmega\EloquentAttributeValuePrediction\Interfaces\HasPredictableAttributes;
use DivineOmega\EloquentAttributeValuePrediction\Traits\PredictsAttributes;
use Illuminate\Database\Eloquent\Model;

class IrisFlower extends Model implements HasPredictableAttributes
{
    use PredictsAttributes;

}

We then need to tell our model which attributes we wish to predict. We do this by adding the registerPredictableAttributes() function.

In this example, we want to use predict the species attribute based on the sepal_length, sepal_width, petal_length, and petal_width attributes. This can be done by returning an array in the following format.

public function registerPredictableAttributes(): array
    {
        return [
            'species' => [
                'sepal_length',
                'sepal_width',
                'petal_length',
                'petal_width',
            ],
        ];
    }

You also need to add the attributes you are using to the $casts array. It is important that the machine learning algorithm knows the type of data stored in each attribute, and that it is consistent.

For our IrisFlower example, the following format is appropriate.

protected $casts = [
        'sepal_length' => 'float',
        'sepal_width' => 'float',
        'petal_length' => 'float',
        'petal_width' => 'float',
        'species' => 'string',
    ];

Training

Before you can make attribute value predictions, you must train a machine learning model on your data. As a general rule, the more data you provide your model, the better it will perform, and the more accurate it will be.

You can train your model(s) using the eavp:train Artisan command, as shown in the example below.

php artisan eavp:train \\App\\Models\\IrisFlower

One model will be trained for each of the attributes you wish to predict. When they are trained, they will be saved into the storage/eavp/model/ directory for future use.

Be aware that the training process can take some time to complete depending on the amount of data you are using, and the complexity of your machine learning model. Training progress will be output to the console where possible.

You can re-run this command (manually, or on a schedule) to re-train your machine learning model(s). Previously trained models will be replaced automatically.

Prediction

Once you have set up your Eloquent model, and trained your machine learning model(s), you can begin predicting attributes.

For example, to predict the species of an Iris flower, you can create a new IrisFlower object and populate a few of its known attributes, then call the predict method.

$flower = new \App\Models\IrisFlower();
$flower->sepal_length = 5.1;
$flower->sepal_width = 3.5;
$flower->petal_length = 1.4;
$flower->petal_width = 0.2;

$species = $flower->predict('species');  

The predict method should be passed the attribute name you wish to predict. It will then returns the prediction as a string or numeric type.

In our example, this should be the 'setosa' species, based on Iris flower data set.

Advanced

Prediction confidence

If you wish, you can also retrieve the machine learning model's confidence that a prediction is correct. This is done with the getPredictions method.

$flower = new \App\Models\IrisFlower();
$flower->sepal_length = 4.5;
$flower->sepal_width = 2.3;
$flower->petal_length = 1.3;
$flower->petal_width = 0.3;

$predictions = $flower->getPredictions('species');

/*
array:3 [
  "setosa" => 0.69785665879791
  "versicolor" => 0.30214334120209
  "virginica" => 0.0
]
*/

In this example, you can see that the machine learning model is ~70% confident the flower is a Setosa, ~30 confident the flower is a Versicolor, and 0% confident the flower is a Virginica.

Note that you can only use the getPredictions method if the attribute you are attempting to predict the value of is non-numeric.

Changing attribute estimators

By default, attribute values are predicted using K-d Neighbors. This is a more efficient form of a standard K Nearest Neighbors algorithm.

The machine learning algorithm that is used to predict your attribute values is known as an 'estimator'. If you wish, you can modify the estimator which is used for each attribute.

To do this, you need to add a registerEstimators method to your model.

public function registerEstimators(): array
{
    return [
        'species' => new MultilayerPerceptron([
            new Dense(50),
            new Dense(50),
        ]),
    ];
}

In the example above, we are changing the estimator for the species attribute to a multilayer perceptron classifier (neural network) with two densely connected hidden layers.

Under the hood, this package uses the Rubix ML library. This means you can use any estimator is supports.

See the Choosing an Estimator page for a list of all available estimators you can use for attribute prediction.

More Repositories

1

password_exposed

🔒 Password Exposed Helper Function - Check if a password has been exposed in a data breach.
PHP
215
star
2

uxdm

🔀 UXDM helps developers migrate data from one system or format to another.
PHP
166
star
3

artisan-menu

📝 Artisan Menu - Use Artisan via an elegant console GUI
PHP
148
star
4

php-ssh-connection

Provides an elegant syntax to connect to SSH servers and execute commands.
PHP
102
star
5

laravel-password-exposed-validation-rule

🔒 Laravel validation rule that checks if a password has been exposed in a data breach.
PHP
87
star
6

cachet.php

📛 PHP client library for the Cachet API
PHP
39
star
7

php-summary

📝 Automatically summarises text, using a naive summarisation algorithm
PHP
27
star
8

dates-timezone-conversion-trait

⏳🗺 Automatically convert an Eloquent model's dates to and from the current user's timezone
PHP
23
star
9

array_undot

array_undot (the opposite of the array_dot helper function) expands a dot notation array into a full multi-dimensional array.
PHP
22
star
10

DO-File-Cache

🗄️ PHP File-based Caching Library
PHP
17
star
11

php-reading-time

⏱ Calculates reading time for text
PHP
17
star
12

clippy-for-laravel

📎 Clippy for Laravel
PHP
16
star
13

laravel-last-activity

Stores the last activity time of users within your Laravel application
PHP
16
star
14

php-cli-progress-bar

⏱️ Progress bar for command line PHP scripts
PHP
16
star
15

cachet.js

📛 JavaScript client library for the Cachet API
HTML
15
star
16

php-hcl-parser

⚒🔀🐘 Parses HCL configuration files into PHP objects.
PHP
14
star
17

laravel-offensive-validation-rule

🤬🤭 Laravel validation rule that checks if a string is offensive.
PHP
13
star
18

laravel-multiple-choice

Package that provides multiple choice questions and answers
PHP
12
star
19

php-camel-caser

🐪💼 PHP Camel Caser - Lets you use built-in PHP functions in camel case
PHP
11
star
20

laravel-natural-where

Laravel Natural Where extends the Laravel query builder to allow expressing of where operators in natural language.
PHP
10
star
21

psr-18-guzzle-adapter

PSR-18 adapter for the Guzzle HTTP client
PHP
10
star
22

laravel-omega-search

Easily add an intelligent search engine to your Laravel powered website or web application
PHP
10
star
23

laravel-extendable-basket

🛒 Laravel Extendable Basket provides several abstract classes that implement basic ecommerce basket functionality
PHP
10
star
24

web-article-formatter

🌐🔀📰 Converts a webpage article into other formats, like PDF, markdown, JSON, plain text...
PHP
10
star
25

DO-File-Cache-PSR-6

🗄 PSR-6 adapter for DO File Cache
PHP
9
star
26

laravel-addresses

Laravel Addresses
PHP
9
star
27

php-countries

🌍 PHP Countries is a library that provides an elegant syntax to country data.
PHP
8
star
28

exiguous-ecommerce

🛒 A super simple ecommerce library, that uses flat files and takes a very minimalistic approach.
PHP
8
star
29

php-geolocation

PHP library that determines the country of an IP address
PHP
8
star
30

php-github-status-api

Programmatically determine if GitHub is working well, or experiencing issues
PHP
7
star
31

is_offensive

🤬🤭 Is Offensive Helper Function - Check if a string contains offensive words or variations of them
PHP
7
star
32

simple-neural-network-js

Simple Neural Network library (JavaScript)
JavaScript
7
star
33

SEO-Middleware

Middleware to redirect to HTTPS when in production, and remove www. from URLs
PHP
7
star
34

php-password-cracker

PHP package to crack passwords
PHP
6
star
35

php-file-sync

Synchronise files between multiple local or remote file systems
PHP
6
star
36

wikipedia-info-box-parser

Parses the info boxes on Wikipedia pages into an associative array
PHP
6
star
37

php-server-info

Gets metrics on a server via an SSH connection
PHP
5
star
38

dotenv-loader

Automatically load in a `.env` file from the root of your project into environment variables
PHP
5
star
39

json-key-value-store

A simple JSON based key value store
PHP
5
star
40

php-wikitext-parser

Parse Wikitext in PHP
PHP
5
star
41

laravel-password-security-audit

🔏 Artisan command to audit the security of your users' passwords
PHP
5
star
42

PhantomJS-Laravel-Testing

The PhantomJS Laravel Testing package allows you to easily test your Laravel application's JavaScript functionality.
PHP
5
star
43

laravel-malware-validation-rule

Scans uploaded files for viruses and other malware
PHP
5
star
44

slickwallet

Slick Wallet
JavaScript
5
star
45

laravel-route-restrictor

🚫 Laravel middleware to restrict a site or specific routes using HTTP basic authentication
PHP
5
star
46

laravel-geolocation-request

Laravel Geolocation Request
PHP
4
star
47

php-wikipedia-search

Easily search for articles on Wikipedia
PHP
4
star
48

Watchful-Eyes

Watchful Eyes - A JavaScript powered site monitor
JavaScript
4
star
49

php-postcodes

📬 This library handles various UK postcode related tasks
PHP
4
star
50

object_to_array

This PHP package provides an `object_to_array` helper function. You can use this function to convert an object to an array.
PHP
4
star
51

php-distance

Allows for calculation of many types of distance between points
PHP
4
star
52

laravel-domain-to-locale

Change your Laravel app's locale based on the domain name
PHP
4
star
53

php-word-info

PHP library to look up information about words
PHP
4
star
54

attempt

🔁 Attempt to run a function, automatically retrying if an exception occurs
PHP
3
star
55

twitter-to-mastodon-sync

A tool to sync Twitter tweets to a Mastodon account
PHP
3
star
56

uxdm-eloquent

🔀 Eloquent source and destination for the UXDM data migrator
PHP
3
star
57

sms-providers

Provides data on popular SMS providers
PHP
3
star
58

omega-search

Easily add an intelligent search engine to your website or web application
PHP
3
star
59

uxdm-spatie-data-transfer-object

🔀 Spatie Data Transfer Object source and destination for the UXDM data migrator
PHP
3
star
60

php-dot-net-ticks

⏱ PHP .NET Ticks helps you convert .NET ticks, a form of precise time measurement used by the .NET DateTime object.
PHP
3
star
61

uxdm-pdf-destination

PDF destination for the UXDM data migrator
PHP
2
star
62

ThisIsHowIRole

PHP role management system
PHP
2
star
63

omega-validator

Easy to use, framework independent data validator
PHP
2
star
64

email-structure-parser

📧 Parses the structure of multipart emails
PHP
2
star
65

WordScore

WordScore - A game in which each letter is worth a certain amount of points and you must take it in turns to guess the word with the highest score
Java
2
star
66

fuzzy-events

Perform actions based on a fuzzy string matches
PHP
2
star
67

php-languages

A tiny package to help convert between languages names (such as English, French, German) and various ISO language codes (such as en, fr, de).
PHP
2
star
68

symfony-password-exposed-bundle

🔒 Symfony bundle that checks if a password has been exposed in a data breach.
PHP
1
star
69

DecentMessaging

Decent Messaging - a decentralised encrypted messaging system platform
Java
1
star
70

uxdm-excel

🔀 Microsoft Excel source and destination for the UXDM data migrator
PHP
1
star
71

DecentChat

A decentralised chat application built on the Decent Messaging platform
JavaScript
1
star
72

translator

A simple PHP internationalisation library
PHP
1
star
73

php-base-search

Base interfaces/classes for searcher and search results
PHP
1
star
74

overflow-framework

PHP
1
star
75

php-reddit-search

Easily search for posts on Reddit
PHP
1
star
76

php-stackexchange-search

Easily search sites on the StackExchange network
PHP
1
star
77

js13k

Drawbacks - Our 2015 entry into http://js13kgames.com/
JavaScript
1
star
78

AutoTwit

A customisable Twitter bot that uses Markov chains and tries to act human
Java
1
star
79

eavp-demos

Demos for the Eloquent Attribute Value Prediction pacakge
PHP
1
star
80

one-hour-game-jam-236

HTML
1
star
81

uxdm-doctrine

Doctrine destination for the UXDM data migrator
PHP
1
star
82

password-suggester

PHP
1
star
83

neural-networks-experiment-two

Java
1
star
84

Soapsuds

Soapsuds is a PHP library that allows developers to easily create a SOAP web service from a regular class.
PHP
1
star
85

php-dcom

PHP Database Connection Object Manager
PHP
1
star