利用Chaquopy在安卓项目中运行机器学习代码(以mlxtend调用Apriori为例)

  前言:大创需要在一个安卓项目中运行Apriori算法,展示关联分析结果,现总结如下。

一、gradle配置

1.项目gradle

在项目目录下的build.gradle文件中加入:

maven {
    
     url "https://chaquo.com/maven" }

以及

classpath "com.chaquo.python:gradle:9.1.0"

位置如下所示:
在这里插入图片描述
关于版本的问题:
在这里插入图片描述
我的python版本是3.8,Gradle版本是4.0.1,所以我选择最新的9.1.0版本。

2.app下的gradle

首先在第二行加上:

apply plugin: 'com.chaquo.python'

然后指定abi:

ndk {
    
    
    // 指定abi,如需在模拟器调试,增加"x86",否则指定"armeabi-v7a"即可
    abiFilters "armeabi-v7a", "x86"
 }

如下所示:
在这里插入图片描述

最后开始python环境配置,我选择了Anaconda下的Python环境:

python {
    
    
            // 指定python路径
    buildPython "F:/Anaconda3/envs/py38/python.exe"
    pip {
    
    
         //options "--index-url", "https://mirrors.aliyun.com/pypi/simple/"
        options "--extra-index-url", "https://pypi.tuna.tsinghua.edu.cn/simple/"
        install "numpy==1.17.4"
        install "pandas==0.25.3"
        install "scikit-learn==0.22.1"
        install "mlxtend"
        install "pymysql==1.0.2"
    }
}

  pip里面的内容可以先不管,这个是后面写Apriori算法要用的。所有配置完成之后点击Sync,下载好相关的文件即可。

二、Android中调用Python文件

  第一步Gradle配置完成后,项目main文件夹下会出现一个python文件夹,如下所示:
在这里插入图片描述
  我将实现apriori算法的py文件hello.py以及相应的数据文件df_politics.csv都放在了python文件夹下,这里要注意,只能放在python文件夹下。

hello.py:

import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import association_rules
from mlxtend.frequent_patterns import apriori
from os.path import dirname, join

def finals():
    filename = join(dirname(__file__), "df_politics.csv")
    print(filename)
    df = pd.read_csv(filename, encoding='utf8', dtype=str)
    df_arr = df.values.tolist()

    te = TransactionEncoder()  # 定义模型
    df_tf = te.fit_transform(df_arr)
    df = pd.DataFrame(df_tf, columns=te.columns_)

    frequent_itemsets = apriori(df, min_support=0.05, use_colnames=True)  # use_colnames=True表示使用元素名字,默认的False使用列名代表元素
    frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)  # 频繁项集可以按支持度排序
    association_rule = association_rules(frequent_itemsets, metric='confidence',
                                         min_threshold=0.7)  # metric可以有很多的度量选项,返回的表列名都可以作为参数
    association_rule.sort_values(by='confidence', ascending=False, inplace=True)  # 关联规则可以按leverage排序
    # print('关联规则:')
    print(association_rule)
    association_rule = association_rule.reset_index(drop=True)

这里大家可能会发现,书写代码时会有很多出错提示,如下所示:
在这里插入图片描述
不过没问题,这是因为Chaquopy没有与Python Community Edition插件集成,代码没有问题,只要你第一步pip那些包时没有报错就行。

接下来是调用,调用分为两步:

  1. 初始化
void initPython(){
    
    
    if (!Python.isStarted()) {
    
    
        Python.start(new AndroidPlatform(this));
    }
}
  1. 调用
void callPythonCode() {
    
    
    Python py = Python.getInstance();
    PyObject pyObject = py.getModule("hello").callAttr("finals");
}

注意,若finals()函数由返回值,那么pyObject就是返回值,如果返回值是一个String,我们想获取这个返回值只需要:

String returnString = pyObject.toString();

三、可能出现的一些问题

  1. Chaquopy给AS添加Python环境时提示:No Python interpreter configured for the module
  2. 解决Chaquopy在AS中pip安装过慢的问题
  3. Chaquopy在AS中pip时报错error: CCompiler.compile: Chaquopy cannot compile native code
  4. Chaquopy读取Android项目python目录下的文件

猜你喜欢

转载自blog.csdn.net/Cyril_KI/article/details/113037843
今日推荐