Java调用python传数组并获取python返回的值 【在python中做线性回归预测,得到的结果传回java中】

任务:Java调用python文件,向java传数组,在python中做预测处理,最终获取python返回的值,传回java中

1、java代码

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class test {
    public static String coalType_list(List<Integer> list_one) {
        String arr = null;
        try {
            // 注意空格不要删除
            String sysPython = "F:\\python3.9\\python.exe ";
            String filePython = "E:\\py\\py.py ";
            Process proc = Runtime.getRuntime().exec(sysPython + filePython + list_one);// 执行py文件
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                arr = line;
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return arr;
    }

    public static void main(String[] args) throws Exception {
        List<Integer> list_one = new ArrayList<>();
        list_one.add(1114); // 野生
        list_one.add(1392152); // 栖息地-公顷
        list_one.add(104); // 圈养
        list_one.add(1985); // 年份

        list_one.add(1596);
        list_one.add(2305000);
        list_one.add(161);
        list_one.add(2004);

        list_one.add(1864);
        list_one.add(2580000);
        list_one.add(375);
        list_one.add(2015);
        String flag = gitar.coalType_list(list_one);
        System.out.println(flag);
    }
}

2、python代码

import numpy as np
import pandas as pd
from sklearn import linear_model # 线性回归
import sys as ss

# 数据获取
def Data_input():
    list_int = []
    for i in range(1, len(ss.argv)):
        temp_1 = ss.argv[i].replace(",","")
        temp_2 = temp_1.replace("[","")
        temp = temp_2.replace("]","")
        list_int.append(int(temp))
    return list_int


# 数据处理 + 训练集测试集生成
# [1114, 139, 104, 1985, 1596, 230, 161, 2004, 1864, 258, 375, 2015]
def Data_pro(list_int,n,year):
    # list_int 传入的数据list
    # n 数据的列数
    # year 预测的年份
    data = []
    for i in range(0,len(list_int),n):
        data_temp = []
        for j in range(n):
            data_temp.append(list_int[i+j])
        data.append(data_temp)

    data_temp = np.array(data)
    # 创建训练集
    train = pd.DataFrame(data_temp)
    train.columns = ['野生','栖息地','圈养','年份']
    # 创建预测集
    dict = {'野生':0, '栖息地':0, '圈养': 0, '年份':year}
    test = pd.DataFrame(dict,index=[0])
    return train,test

    
# 线性回归算法
def Algorithm(train,test):
    # 分割训练集和测试集
    x_train = train.iloc[:, 3:4].values
    y_train_1 = train.iloc[:, 0:1].values
    y_train_2 = train.iloc[:, 1:2].values
    y_train_3 = train.iloc[:, 2:3].values
    x_test = test.iloc[:, 3:4].values
    # 模型算法
    model = linear_model.LinearRegression()
    # 模型训练
    model_1 = model.fit(x_train, y_train_1) # 野生
    pre_1 = model_1.predict(x_test)	# 野生
    model_2 = model.fit(x_train, y_train_2) # 栖息地
    pre_2 = model_2.predict(x_test) # 栖息地
    model_3 = model.fit(x_train, y_train_3) # 圈养
    pre_3 = model_3.predict(x_test) # 圈养
    result = [int(pre_1),int(pre_2),int(pre_3),test["年份"][0]]
    return result

def main():
    # 数据获取
    # list_int = [] 
    list_int = [] 
    list_int = Data_input()
    # 数据处理 + 训练集测试集生成
    n = 4 # 列数
    year = 2030 # 年份
    train,test = Data_pro(list_int,n,year)
    result = Algorithm(train,test)
    print(result)
    # [2092-野生, 3010934-栖息地, 403-圈养, 2024-年份]

if __name__ == '__main__':
    main()


3、结果

在这里插入图片描述

4、B站演示视频链接

B站演示视频