Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Analytics API: Difference between revisions

From MoodleDocs
(→‎How to create a model: language cleanup)
(→‎Define the problem: softened reference to pedagogy)
Line 199: Line 199:
=== Define the problem ===
=== Define the problem ===


Start by defining what you want to predict (the target) and the subjects of these predictions (the samples). You can find the descriptions of these concepts above. This definition should have some basis in pedagogy. For example, the included model [https://docs.moodle.org/34/en/Students_at_risk_of_dropping_out Students at risk of dropping out] is based on the Community of Inquiry theoretical framework, and attempts to predict that students will complete a course based on indicators designed to represent the three components of the CoI framework (teaching presence, social presence, and cognitive presence). Start by being clear about how the target will be defined. It must be trained using known examples. This means that if, for example, you want to predict the final grade of a course per student, the courses being used to train the model must include accurate final grades.
Start by defining what you want to predict (the target) and the subjects of these predictions (the samples). You can find the descriptions of these concepts above. The API can be used for all kinds of models, though if you want to predict something like "student success," this definition should probably have some basis in pedagogy. (For example, the included model [https://docs.moodle.org/34/en/Students_at_risk_of_dropping_out Students at risk of dropping out] is based on the Community of Inquiry theoretical framework, and attempts to predict that students will complete a course based on indicators designed to represent the three components of the CoI framework (teaching presence, social presence, and cognitive presence)). Start by being clear about how the target will be defined. It must be trained using known examples. This means that if, for example, you want to predict the final grade of a course per student, the courses being used to train the model must include accurate final grades.


=== Choose the analyser ===
=== Choose the analyser ===

Revision as of 16:47, 13 November 2017

Summary

The Moodle Analytics API allows Moodle site managers to define prediction models that combine indicators and a target. The target is the event we want to predict. The indicators are what we think will lead to an accurate prediction of the target. Moodle is able to evaluate these models and, if the prediction accuracy is high enough, Moodle internally trains a machine learning algorithm by using calculations based on the defined indicators within the site data. Once new data that matches the criteria defined by the model is available, Moodle starts predicting the probability that the target event will occur. Targets are free to define what actions will be performed for each prediction, from sending messages or feeding reports to building new adaptive learning activities.

An obvious example of a model you may be interested in is prevention of students at risk of dropping out: Lack of participation or bad grades in previous activities could be indicators, and the target would be whether the student is able to complete the course or not. Moodle calculates these indicators and the target for each student in a finished course and predicts which students are at risk of dropping out in ongoing courses.

API components

This diagram shows the main components of the analytics API and the interactions between them.

Inspire API components.png

Data flow

The diagram below shows the different stages data goes through, from the data a Moodle site contains to actionable insights.

Inspire data flow.png

API classes diagram

This is a summary of the API classes and their relationships. It groups the different parts of the framework that can be extended by 3rd parties to create your own prediction models.

Analytics API classes diagram (summary).svg

(Click on the image to expand, it is an SVG)

Built-in models

People use Moodle in very different ways and even courses on the same site can vary significantly. Moodle core will only include models that have been proven to be good at predicting in a wide range of sites and courses. Moodle 3.4 provides two built-in models:

To diversify the samples and to cover a wider range of cases, the Moodle HQ research team is collecting anonymised Moodle site datasets from collaborating institutions and partners to train the machine learning algorithms with them. The models that Moodle is shipped with will obviously better at predicting on the sites of participating institutions, although some other datasets are used as test data for the machine learning algorithm to ensure that the models are good enough to predict accurately in any Moodle site. If you are interested in collaborating please contact Elizabeth Dalton at [elizabeth@moodle.com] to get information about the process.

Even if the models we include in Moodle core are already trained by Moodle HQ, each different site will continue training that site machine learning algorithms with its own data, which should lead to better prediction accuracy over time.

Concepts

The following definitions are included for people not familiar with machine learning concepts:

Training

This is the process to be run on a Moodle site before being able to predict anything. This process records the relationships found in site data from the past so the analytics system can predict what is likely to happen under the same circumstances in the future. What we train are machine learning algorithms.

Samples

The machine learning backends we use to make predictions need to know what sort of patterns to look for, and where in the Moodle data to look. A sample is a set of calculations we make using a collection of Moodle site data. These samples are unrelated to testing data or phpunit data, and they are identified by an id matching the data element on which the calculations are based. The id of a sample can be any Moodle entity id: a course, a user, an enrolment, a quiz attempt, etc. and the calculations the sample contains depend on that element. Each type of Moodle entity used as a sample helps develop the predictions that involve that kind of entity. For example, samples based on Quiz attempts will help develop the potential insights that the analytics might offer that are related to the Quiz attempts by a particular group of students. See Analytics_API#Analyser for more information on how analyser classes define what is in a sample.

Prediction model

As explained above, a prediction model is a combination of indicators and a target. System models can be viewed in Site administration > Analytics > Analytics models.

The relationship between indicators and targets is stored in analytics_models database table.

The class \core_analytics\model manages all of a model's related actions. evaluate(), train() and predict() forward the calculated indicators to the machine learning backends. \core_analytics\model delegates all heavy processing to analysers and machine learning backends. It also manages prediction models evaluation logs.

\core_analytics\model class is not expected to be extended.

Static models

Some prediction models do not need a powerful machine learning algorithm behind them processing large quantities of data to make accurate predictions. There are obvious events that different stakeholders may be interested in knowing that we can easily calculate. These *Static model* predictions are directly calculated based on indicator values. They are based on the assumptions defined in the target, but they should still be based on indicators so all these indicators can still be reused across different prediction models. For this reason, static models are not editable through Site administration > Analytics > Analytics models user interface.

Some examples of possible static models:

  • Courses without teaching activity
  • Courses with students submissions requiring attention and no teachers accessing the course
  • Courses that started 1 month ago and never accessed by anyone
  • Students that have never logged into the system
  • ....

Moodle could already generate notifications for the examples above using the Events system, but there are some benefits on doing it using the Moodle analytics API:

  • Everything is easier and faster to code from a dev point of view as the analytics subsystem provides APIs for everything
  • New Indicators will be part of the core indicators pool that researchers (and 3rd party developers in general) can reuse in their own models
  • Existing core indicators can be reused as well (the same indicators used for insights that depend on machine learning backends)
  • Notifications are displayed using the core insights system, which is also responsible of sending the notifications and all related actions.
  • The Analytics API tracks user actions after viewing the predictions, so we can know if insights result in actions, which insights are not useful, etc. User responses to insights could themselves be defined as an indicator.

Analyser

Analysers are responsible for creating the dataset files that will be sent to the machine learning processors. They are coded as PHP classes. Moodle core includes some analysers that you can use in your models.

The base class \core_analytics\local\analyser\base does most of the work. It contains a key abstract method, get_all_samples(). This method is what defines what elements are included in a sample for the analyser. A sample can be composed of instances of any moodle entity: a course, a user, an enrolment, a quiz attempt... Samples are nothing by themselves, just a list of ids with related data. They are used in calculations once they are combined with the target and the indicator classes.

Other analyser class responsibilities:

  • Define the context of the predictions
  • Discard invalid data
  • Filter out already trained samples
  • Include the time factor (time range processors, explained below)
  • Forward calculations to indicators and target classes
  • Record all calculations in a file
  • Record all analysed sample ids in the database

If you are introducing a new analyser, there is an important non-obvious fact you should know about: for scalability reasons, all calculations at course level are executed in per-course basis and the resulting datasets are merged together once all site courses analysis is complete. This is for performance reasons: depending on the sites' size it could take hours to complete the analysis of the entire site. This is a good way to break the process up into pieces when a sample consists of many large, complex elements (e.g. courses). When coding a new analyser you need to decide if you want to extend \core_analytics\local\analyser\by_course (your analyser will process a list of courses) or \core_analytics\local\analyser\sitewide (your analyser will receive just one analysable element, the site)

Target

Targets are the key element that defines the model. As a PHP class, targets represent the event the model is attempting to predict (the dependent variable) and the calculations used to predict it. They also define the actions to perform depending on the received predictions.

Targets are specific to analysers, because analysers provide them with the samples they need. Analysers are separate entities from targets because analysers can be reused across different targets. Each target needs to specify which analyser it is using, to define the context of the predictions. Here are a few examples to clarify the difference between analysers, samples and targets:

  • Target: 'students at risk of dropping out'. Analyser provides sample: 'course enrolments'
  • Target: 'spammer'. Analyser provides sample: 'site users'
  • Target: 'ineffective course'. Analyser provides sample: 'courses'
  • Target: 'difficulties to pass a specific quiz'. Analyser provides sample: 'quiz attempts in a specific quiz'

A callback defined by the target will be executed once new predictions start coming so each target have control over the prediction results.

The API supports binary classification, multiclass classification and regression, but the machine learning backends included in core do not yet support multiclass classification or regression, so only binary classifications will be initially fully supported. See MDL-59044 and MDL-60523 for more information.

Although there is no technical restriction against using core targets in your own models, in most cases each model will implement a new target. One possible case in which targets might be reused would be to create a new model using the same target and a different sets of indicators, for A/B testing

Insights

Another aspect controlled by targets is insight generation. Insights represent predictions made about a specific element of the sample within the context of the analyser model. This context will be used to notify users with moodle/analytics:listinsights capability (the teacher role by default) about new insights being available. These users will receive a notification with a link to the predictions page where all predictions of that context are listed.

A set of suggested actions will be available for each prediction. In cases like Students at risk of dropping out the actions can be things like sending a message to the student, viewing the student's course activity report, etc.

Indicator

The indicator PHP class is responsible for calculating the indicator (predictor value or independent variable) using the provided sample. Moodle core includes a set of indicators that can be used in your models without additional PHP coding (unless you want to extend their functionality).

Indicators are not limited to a single analyser like targets are. This makes indicators easier to reuse in different models. Indicators specify a minimum set of data they need to perform the calculation. The indicator developer should also make an effort to imagine how the indicator will work when different analysers are used. For example an indicator named Posts in any forum could be initially coded for a Shy students in a course target; this target would use course enrolments analyser, so the indicator developer knows that a course and an enrolment will be provided by that analyser, but this indicator can be easily coded so the indicator can be reused by other analysers like courses or users'. In this case the developer can chose to require course or user, and the name of the indicator would change according to that. For example, User posts in any forum could be used in a user-based model like Inactive users; Posts in any of the course forums could be used in a course-based model like Low participation courses.

The calculated value can go from -1 (minimum) to 1 (maximum). This requirement prevents the creation of "raw number" indicators like absolute number of write actions, because we must limit the calculation to a range, e.g. -1 = 0 actions, -0.33 = some basic activity, 0.33 = activity, 1 = plenty of activity. Raw counts of an event like "posts to a forum" must be calculated in a proportion of an expected number of posts. There are several ways of doing this. One is to define a minimum desired number of events, e.g. 3 posts in a forum represents "some" activity, 6 posts represents adequate activity, and 10 or more posts represents the maximum expected activity. Another way is to compare the number of events per individual user to the mean or median value of events by all users in the same context, using statistical values. For example, a value of 0 would represent that the student posted the same number of posts as the mean of all student posts in that context; a value of -1 would indicate that the student is 2 or 3 standard deviations below the mean, and a +1 would indicate that the student is 2 or 3 standard deviations above the mean. (Note that this kind of comparative calculation has implications in pedagogy: it suggests that there is a ranking of students from best to worst, rather than a defined standard all students can reach.)

Time splitting methods

A time splitting method is what defines when the system will calculate predictions and the portion of activity logs that will be considered for those predictions. They are coded as PHP classes and Moodle core includes some time splitting methods you can use in your models.

In some cases the time factor is not important and we just want to classify a sample. This is relatively simple. Things get more complicated when we want to predict what will happen in future. For example, predictions about Students at risk of dropping out are not useful once the course is over or when it is too late for any intervention.

Calculations involving time ranges can be a challenging aspect of some prediction models. Indicators need to be designed with this in mind and we need to include time-dependent indicators within the calculated indicators so machine learning algorithms are smart enough to avoid mixing calculations belonging to the beginning of the course with calculations belonging to the end of the course.

There are many different ways to split up a course into time ranges: in weeks, quarters, 8 parts, ten parts (tenths), ranges with longer periods at the beginning and shorter periods at the end... And the ranges can be accumulative (each one inclusive from the beginning of the course) or only from the start of the time range.

The time-splitting methods included in Moodle 3.4 assume that there is a fixed start and end date for each course, so the course can be divided into segments of equal length. This allows courses of different lengths to be included in the same prediction model, but makes these time-splitting methods useless for courses without fixed start or end dates, e.g. self-paced courses. These courses might instead use fixed time lengths such as weeks to define the boundaries of prediction calculations.

Machine learning backends

They process the datasets generated from the calculated indicators and targets. They are a new plugin type with a common interface:

  • Evaluate a provided prediction model
  • Train a machine learning algorithm with the existing site data
  • Predict targets based on previously trained algorithms

The communication between prediction processors and Moodle is through files because the code that will process the dataset can be written in PHP, in Python, in other languages or even use cloud services. This needs to be scalable so they are expected to be able to manage big files and train algorithms reading input files in batches if necessary.

Design

The system is designed as a Moodle subsystem and API. It lives in analytics/. All analytics base classes are located here.

Machine learning backends is a new Moodle plugin type. They are stored in lib/mlbackend.

Uses of the analytics API are located in different Moodle components, being core (lib/classes/analytics) the component that hosts general purpose uses of the API.

Extension points

This API aims to be as extendable as possible. Any moodle component, including third party plugins, is be able to define indicators, targets, analysers and time splitting processors.

An example of a possible extension would be a plugin with indicators that fetch student academic records from the Universities' student information system; the site admin could build a new model on top of the built-in 'students at risk of drop out detection' adding the SIS indicators to improve the model accuracy or for research purposes.

Moodle components (core subsystems, core plugins and 3rd party plugins) will be able to add and/or redefine any of the entities involved in all the data modeling process.

Some of the base classes to extend or follow as example:

  • \core_analytics\local\analyser\base
  • \core_analytics\local\time_splitting\base
  • \core_analytics\local\indicator\base
  • \core_analytics\local\target\base
  • \core_analytics\analysable

Interfaces

Predictor

This is the basic interface to be implemented by machine learning backends. Two main types are currently supported, classifiers and regressors. Both of these are supervised algorithms. Each type includes methods to train, predict and evaluate datasets.

Classifier

A classifier sorts input into two or more categories, based on analysis of the indicators. This is frequently used in binary predictions, e.g. course completion vs. dropout. This machine learning algorithm is "supervised": It requires a training data set of elements whose classification is known (e.g. courses in the past with a clear definition of whether the student has dropped out or not). This is an interface to be implemented by machine learning backends that support classification. It extends the Predictor interface.

Regressor

A regressor predicts the value of an outcome (or dependent) variable based on analysis of the indicators. This value can represent an integer, such as a final grade in a course, or a probability, such as the likelihood a student is to pass a course. This machine learning algorithm is "supervised": It requires a training data set of elements whose classification is known (e.g. courses in the past with a clear definition of whether the student has dropped out or not). This is an interface to be implemented by machine learning backends that support regression. It extends Predictor interface.

Analysable

Analysable items are those elements in Moodle that form the context in which samples will occur and be analysed to calculate predictions. In most of the cases an analysable will be a course, although it can also be the site or any other Moodle element, e.g. an activity.

Moodle core include two analysers \core_analytics\course and \core_analytics\site. They need to provide an id, a name, a \context and get_start() and get_end() methods. Read related comments above in #Analyser.

Calculable

Both indicators and targets must implement this interface. It defines the data element to be used in calculations, whether as independent (indicator) or dependent (target) variables.

It is already implemented by \core_analytics\local\indicator\base and \core_analytics\local\target\base but you can still code targets or indicators from the \core_analytics\calculable base if you need more control.

How to create a model

Define the problem

Start by defining what you want to predict (the target) and the subjects of these predictions (the samples). You can find the descriptions of these concepts above. The API can be used for all kinds of models, though if you want to predict something like "student success," this definition should probably have some basis in pedagogy. (For example, the included model Students at risk of dropping out is based on the Community of Inquiry theoretical framework, and attempts to predict that students will complete a course based on indicators designed to represent the three components of the CoI framework (teaching presence, social presence, and cognitive presence)). Start by being clear about how the target will be defined. It must be trained using known examples. This means that if, for example, you want to predict the final grade of a course per student, the courses being used to train the model must include accurate final grades.

Choose the analyser

The next decision should be how many predictions you want to get for each sample (e.g. just one prediction before the course starts or a prediction every week). A single prediction for each sample is simpler than multiple predictions at different points in time in terms of how deep into the API you will need to go to code it.

These are not absolute statements, but in general:

  • If you want a single prediction for each sample at a specific point in time you can reuse a sitewide analyser or define your own and control samples validity through your target's is_valid_sample() method.
  • If you want multiple predictions at different points in time for each sample reuse an analysable element or define your own (extending \core_analytics\analysable) and reuse or define your own analyser to retrieve these analysable elements. You can control analysers validity through your target's is_valid_analysable() method.
  • If you want predictions at activity level use a "by_course" analyser as otherwise you may have scalability problems (imagine storing in memory calculations for each grade_grades record in your site, though processing elements by courses help as we clean memory after each course is processed)

This decision is important because:

  • Time splitting methods are applied to analysable time start and time end (e.g. Quarters can split the duration of a course in 4 parts).
  • Prediction results are grouped by analysable in the admin interface to list predictions.
  • By default, insights are notified to users with moodle/analytics:listinsights capability at analysable level (though this is only a default behaviour you can overwrite in your target).

Note that the existing time splitting methods are proportional to the length of the course, e.g. quarters, tenths, etc. This allows courses with different lengths to be included in the same sample, but requires courses to have defined start and end dates. Other time splitting methods are possible which do not depend on the defined length of the course, e.g. weekly. These would be more appropriate for self-paced courses without fixed start and end dates.

You do not need to require a single time splitting method at this stage, and they can be changed whenever the model is trained. You do need to define whether the model will make a single prediction or multiple predictions per analysable.

Create the target

Targets can be reused between models if the analyser remains the same, though generally you will want to create a new target, since you could easily alter an existing model with target by changing the indicators and time splitters. Targets must extend \core_analytics\local\target\base or its main child class \core_analytics\local\target\binary. Even if Moodle core includes \core_analytics\local\target\discrete and \core_analytics\local\target\linear Moodle 3.4 machine learning backends only support binary classifications. So unless you are using your own machine learning backend you need to extend \core_analytics\local\target\binary.

Create the model

You can create the model by specifying at least its target and, optionally, a set of indicators and a time splitting method:

   // Instantiate the target: classify users as spammers
   $target = \core_analytics\manager::get_target('\mod_yours\analytics\target\spammer_users');
   // Instantiate indicators: two different indicators that predict that the user is a spammer
   $indicator1 = \core_analytics\manager::get_indicator('\mod_yours\analytics\indicator\posts_straight_after_new_account_created');
   $indicator2 = \core_analytics\manager::get_indicator('\mod_yours\analytics\indicator\posts_contain_important_viagra');
   $indicators = array($indicator1->get_id() => $indicator1, $indicator2->get_id() => $indicator2);
   // Create the model.
   $model = \core_analytics\model::create($target, $indicators, '\core\analytics\time_splitting\single_range');

Models are disabled by default because you may be interested in evaluating how good the model is at predicting before enabling them. You can enable models using Moodle UI or the analytics API:

   $model->enable();

Indicators

You already know the analyser your target needs (the analyser is what provides samples) and, more or less, what time splitting method may be better for you. You can now select a list of indicators that you think will lead to accurate predictions. You may need to create your own indicators specific to the target you want to predict.

You can use "'Site administration > Analytics > Analytics models"' to see the list of available indicators and add some of them to your model.

API usage examples

This is a list of prediction models and how they could be coded using the Analytics API:

Students at risk of dropping out (based on student's activity, included in Moodle 3.4)

  • Time splitting: quarters, quarters accumulative, deciles, deciles accumulative...
  • Analyser samples: student enrolments (analysable elements are courses)
  • target::is_valid_analysable
    • For prediction = ongoing courses
    • For training = finished courses with activity
  • target::is_valid_sample = true
  • Based on assumptions (static): no, predictions should be based on finished courses data


Not engaging course contents (based on the course contents)

  • Time splitting: single range
  • Analyser samples: courses (the analysable elements is the site)
  • target::is_valid_analysable = true
  • target::is_valid_sample
    • For prediction = the course is close to the start date
    • For training = no training
  • Based on assumptions (static): yes, a simple look at the course activities should be enough (e.g. are the course activities engaging?)


No teaching (courses close to the start date without a teacher assigned, included in Moodle 3.4)

  • Time splitting: single range
  • Analyser samples: courses (the analysable elements is the site) it would also work using course as analysable
  • target::is_valid_analysable = true
  • target::is_valid_sample
    • For prediction = course close to the start date
    • For training = no training
  • Based on assumptions (static): yes, just check if there are teachers


Late assignment submissions (based on student's activity)

  • Time splitting: close to the analysable end date (1 week before, X days before...)
  • Analyser samples: assignment submissions (analysable elements are activities)
  • target::is_valid_analysable
    • For prediction = the assignment is open for submissions
    • For training = past assignment due date
  • target::is_valid_sample = true
  • Based on assumptions (static): no, predictions should be based on previous students activity


Spam users (based on suspicious activity)

  • Time splitting: 2 parts, one after 4h since user creation and another one after 2 days (just an example)
  • Analyser samples: users (analysable elements are users)
  • target::is_valid_analysable = true
  • target::is_valid_sample
    • For prediction = 4h or 2 days passed since the user was created
    • For training = 2 days passed since the user was created (spammer flag somewhere recorded to calculate target = 1, otherwise no spammer)
  • Based on assumptions (static): no, predictions should be based on users activity logs, although this could also be done as a static model


Students having a bad time

  • Time splitting: quarters accumulative or deciles accumulative
  • Analyser samples: student enrolments (analysable elements are courses)
  • target::is_valid_analysable
    • For prediction = ongoing and course activity
    • For training = finished courses
  • target::is_valid_sample = true
  • Based on assumptions (static): no, ideally it should be based on previous cases


Course not engaging for students (checking student's activity)

  • Time splitting: quarters, quarters accumulative, deciles...
  • Analyser samples: course (analysable elements are courses)
  • target::is_valid_analysable = true
  • target::is_valid_sample
    • For prediction = ongoing course
    • For training = finished courses
  • Based on assumptions (static): no, it should be based on activity logs


Student will fail a quiz (based on things like other students quiz attempts, the student in other activities, number of attempts to pass the quiz...)

  • Time splitting: single range
  • Analyser samples: student grade on an activity, aka grade_grades id (analysable elements are courses)
  • target::is_valid_analysable
    • For prediction = ongoing course with quizzes
    • For training = ongoing course with quizzes
  • target::is_valid_sample
    • For prediction = more than the X% of the course students attempted the quiz and the sample (a student) has not attempted it yet
    • For training = the student has attempted the quiz at least X times (X because if after X attempts has not passed counts as failed) or the student passed the quiz
  • Based on assumptions (static): no, it is based on previous students records

Clustered environments

'analytics/outputdir' setting can be used by Moodle sites with multiple frontend nodes to specify a shared directory across nodes. This directory can be used by machine learning backends to store trained algorithms (its internal variables weights and stuff like that) to use them later to get predictions. Moodle cron lock will prevent multiple executions of the analytics tasks that train machine learning algorithms and get predictions from them.