Recently, I found a fun Python library, which can transform the trained machine learning model into Java, C, JavaScript, Go, Ruby, VBA native code, so that even students who know nothing about Python and machine learning can feel the magic of prediction.

Let’s look at the effect

It feels like there are other things you can do with this little thing, but it’s not clear what the scenarios are. At the time of writing this article, I knew nothing about Excel VBA. Baidu started to use it a few times. Now I can also write some functions and procedures in VBA, which is probably the biggest gain.

m2cgen

M2cgen (Model 2 Code Generator) is a lightweight Code Generator that converts trained machine learning models into native Code without relying on libraries.

M2cgen currently supports a lot of models, common and common include:

Method of use

M2cgen installation is very easy, direct PIP:

pip install m2cgen
Copy the code

Use, first train a model with XGBClassifier

# import packages import pandas as pd import numpy as np import os re from random import sample from sklearn import datasets from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics Import accuracy_score import pickle import M2Cgen as M2C seed = 2020 test_size = 0.3x_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed) # fit model on training data model = XGBClassifier() model.fit(X_train, y_train)Copy the code

Convert the model to VBA

code = m2c.export_to_visual_basic(model, function_name = 'pred')
Copy the code

VBA, which stands for Visual Basic for Applications, is a standard macro language. It is usually used to implement functions not provided in Excel, write custom functions, and realize automation functions. VBA cannot run independently and can only be invoked by Office software (such as Word and Excel).

The resulting VBA looks like this:

To be honest, I was too lazy to dig into VBA, so I changed the code to process. I won’t post it here, but I posted the modified code on Github. VBA god can help, welcome to submit PR.

Github.com/tjxj/excel2…

Want to save trouble students directly to copy

Excel

Click “Development Tools” in the Excel menu (if you don’t have the development tools TAB, please refer to: Where is the Excel Development Tools TAB? Click Visual Basic in the code TAB, or Alt + F11 to call:

Click insert – module and paste in the modified VBA code

Save and exit, then go back to the sheet page and open the Tool-Insert-buttonAfter editing the text, right-click on the macro and select the one we just saved.And then everything was OK.

The End