双色球预测算法(Java),——森林机器学习、时间序列

最近AI很火,老想着利用AI的什么算法,干点什么有意义的事情。其中之一便想到了双色球,然后让AI给我预测,结果基本都是简单使用随机算法列出了几个数字。

额,,,,咋说呢,双色球确实是随机的,但是,如果只是随机,我用你AI干嘛,直接写个随机数就行了嘛。

于是乎,问了下市面上的一些预测算法,给出了俩,一个是:森林机器学习,一个是时间序列。

然后,我让它给我把这俩算法写出来,给是给了,但是,,,无力吐槽。

于是,在我和它的共同配合下,这俩算法的java版诞生了,仅供参考:

森林机器学习:
package com.ruoyi.web.controller.test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import lombok.val;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import weka.classifiers.Classifier;
import weka.classifiers.trees.RandomForest;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;

public class LotteryPredictor {

    public static void main(String[] args) throws Exception {
        String csvFilePath = "D:\\12.csv"; // 请替换为你的CSV文件的绝对路径

        // Step 1: Read historical data from CSV
        List<int[]> historicalData = readCSV(csvFilePath);

        // Step 2: Prepare data for Weka
        Instances trainingData = prepareTrainingData(historicalData);

        // Step 3: Train RandomForest model
        Classifier model = new RandomForest();
        model.buildClassifier(trainingData);

        // Step 4: Make a prediction
        int[] prediction = predictNextNumbers(model, trainingData);

        // Output the prediction
        System.out.println("Predicted numbers: ");
        for (int num : prediction) {
            System.out.print(num + " ");
        }
    }

    private static List<int[]> readCSV(String csvFilePath) throws Exception {
        List<int[]> data = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFilePath), StandardCharsets.UTF_8))) {
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withDelimiter(',').withTrim());
            for (CSVRecord record : csvParser) {
                if(record.size() == 1) {
                    val rec = record.get(0).split(","); // Remove non-numeric characters
                    int[] row = new int[rec.length];
                    for (int i = 0; i < rec.length; i++) {
                        String value = rec[i].replaceAll("[^0-9]", ""); // Remove non-numeric characters
                        if (!value.isEmpty()) {
                            row[i] = Integer.parseInt(value);
                        }
                    }
                    data.add(row);
                }
                else {
                    int[] row = new int[record.size()];
                    for (int i = 0; i < record.size(); i++) {
                        String value = record.get(i).replaceAll("[^0-9]", ""); // Remove non-numeric characters
                        if (!value.isEmpty()) {
                            row[i] = Integer.parseInt(value);
                        }
                    }
                    data.add(row);
                }

            }
        }
        return data;
    }

    private static Instances prepareTrainingData(List<int[]> historicalData) {
        // Define attributes
        ArrayList<Attribute> attributes = new ArrayList<>();
        for (int i = 0; i < historicalData.get(0).length; i++) {
            attributes.add(new Attribute("num" + (i + 1)));
        }

        // Create dataset
        Instances dataset = new Instances("LotteryData", attributes, historicalData.size());
        dataset.setClassIndex(dataset.numAttributes() - 1);

        // Add data
        for (int[] row : historicalData) {
            dataset.add(new DenseInstance(1.0, toDoubleArray(row)));
        }

        return dataset;
    }

    private static double[] toDoubleArray(int[] intArray) {
        double[] doubleArray = new double[intArray.length];
        for (int i = 0; i < intArray.length; i++) {
            doubleArray[i] = intArray[i];
        }
        return doubleArray;
    }

    private static int[] predictNextNumbers(Classifier model, Instances trainingData) throws Exception {
        int numAttributes = trainingData.numAttributes();
        Set<Integer> predictedNumbers = new HashSet<>();

        while (predictedNumbers.size() < numAttributes) {
            DenseInstance instance = new DenseInstance(numAttributes);
            instance.setDataset(trainingData);

            for (int i = 0; i < numAttributes; i++) {
                instance.setValue(i, Math.random() * 33 + 1); // Random values for prediction
            }

            double prediction = model.classifyInstance(instance);
            int predictedNumber = (int) Math.round(prediction);

            // Ensure the predicted number is within the valid range and not a duplicate
            if (predictedNumber >= 1 && predictedNumber <= 33) {
                predictedNumbers.add(predictedNumber);
            }
        }

        int[] predictionArray = new int[numAttributes];
        int index = 0;
        for (int num : predictedNumbers) {
            predictionArray[index++] = num;
        }

        return predictionArray;
    }
}
时间序列算法:
package com.ruoyi.web.controller.test;
import lombok.val;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.deeplearning4j.nn.api.Model;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerMinMaxScaler;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.lossfunctions.LossFunctions;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LotteryPredictor3 {

    public static void main(String[] args) throws Exception {
        String csvFilePath = "D:\\12.csv"; // 请替换为你的CSV文件的绝对路径

        // Step 1: Read historical data from CSV
        List<int[]> historicalData = readCSV(csvFilePath);

        // Step 2: Prepare data for time series analysis
        double[][] timeSeriesData = prepareTimeSeriesData(historicalData);

        // Step 3: Train neural network model
        MultiLayerNetwork model = trainModel(timeSeriesData);

        // Step 4: Make a prediction
        int[] redBallPrediction = predictRedBalls(model, timeSeriesData);
        int blueBallPrediction = predictBlueBall(model, timeSeriesData);

        // Output the prediction
        System.out.println("Predicted numbers: ");
        for (int num : redBallPrediction) {
            System.out.print(num + " ");
        }
        System.out.println("Blue ball: " + blueBallPrediction);
    }

    private static List<int[]> readCSV(String csvFilePath) throws Exception {
        List<int[]> data = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFilePath), StandardCharsets.UTF_8))) {
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withDelimiter(',').withTrim());
            for (CSVRecord record : csvParser) {
                if(record.size() == 1) {
                    val rec = record.get(0).split(","); // Remove non-numeric characters
                    int[] row = new int[rec.length];
                    for (int i = 0; i < rec.length; i++) {
                        String value = rec[i].replaceAll("[^0-9]", ""); // Remove non-numeric characters
                        if (!value.isEmpty()) {
                            row[i] = Integer.parseInt(value);
                        }
                    }
                    data.add(row);
                }else {
                    int[] row = new int[record.size()];
                    for (int i = 0; i < record.size(); i++) {
                        String value = record.get(i).replaceAll("[^0-9]", ""); // Remove non-numeric characters
                        if (!value.isEmpty()) {
                            row[i] = Integer.parseInt(value);
                        }
                    }
                    data.add(row);
                }

            }
        }
        return data;
    }

    private static double[][] prepareTimeSeriesData(List<int[]> historicalData) {
        // Flatten the historical data into a 2D array
        double[][] timeSeriesData = new double[historicalData.size()][];
        for (int i = 0; i < historicalData.size(); i++) {
            timeSeriesData[i] = new double[historicalData.get(i).length];
            for (int j = 0; j < historicalData.get(i).length; j++) {
                timeSeriesData[i][j] = historicalData.get(i)[j];
            }
        }
        return timeSeriesData;
    }

    private static MultiLayerNetwork trainModel(double[][] timeSeriesData) {
        int numInputs = timeSeriesData[0].length;
        int numOutputs = numInputs;
        int numHiddenNodes = 10;

        MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
                .updater(new Adam(0.01))
                .list()
                .layer(0, new DenseLayer.Builder().nIn(numInputs).nOut(numHiddenNodes)
                        .activation(Activation.RELU)
                        .build())
                .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.MSE)
                        .activation(Activation.IDENTITY)
                        .nIn(numHiddenNodes).nOut(numOutputs).build())
                .build();

        MultiLayerNetwork model = new MultiLayerNetwork(conf);
        model.init();
        model.setListeners(new ScoreIterationListener(10));

        // Prepare the data
        INDArray input = Nd4j.create(timeSeriesData);
        INDArray output = Nd4j.create(timeSeriesData);
        DataSet dataSet = new DataSet(input, output);

        // Normalize the data
        NormalizerMinMaxScaler scaler = new NormalizerMinMaxScaler(0, 1);
        scaler.fit(dataSet);
        scaler.transform(dataSet);

        // Train the model
        for (int i = 0; i < 2000; i++) {
            model.fit(dataSet);
        }

        return model;
    }

    private static int[] predictRedBalls(MultiLayerNetwork model, double[][] timeSeriesData) {
        INDArray input = Nd4j.create(timeSeriesData);
        INDArray output = model.output(input);
        double[] lastPrediction = output.getRow(output.rows() - 1).toDoubleVector();

        Set<Integer> predictedNumbers = new HashSet<>();
        for (double num : lastPrediction) {
            int scaledNum = (int) Math.round(num * 32) + 1; // Scale back to 1-33 range
            if (scaledNum >= 1 && scaledNum <= 33) {
                predictedNumbers.add(scaledNum);
            }
            if (predictedNumbers.size() == 6) {
                break;
            }
        }

        // Ensure we have exactly 6 unique numbers
        while (predictedNumbers.size() < 6) {
            int randomNum = (int) (Math.random() * 33) + 1;
            predictedNumbers.add(randomNum);
        }

        int[] predictionArray = new int[6];
        int index = 0;
        for (int num : predictedNumbers) {
            predictionArray[index++] = num;
        }

        return predictionArray;
    }

    private static int predictBlueBall(MultiLayerNetwork model, double[][] timeSeriesData) {
        INDArray input = Nd4j.create(timeSeriesData);
        INDArray output = model.output(input);
        double lastPrediction = output.getDouble(output.rows() - 1);

        // Predict blue ball number
        int blueBallPrediction = (int) Math.round(lastPrediction * 15) + 1; // Scale back to 1-16 range
        if (blueBallPrediction < 1) blueBallPrediction = 1;
        if (blueBallPrediction > 16) blueBallPrediction = 16;

        return blueBallPrediction;
    }
}

对比了下,时间序列的相对容易让人相信,机器学习,不知道咋评价,大家可以试试。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱码社长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值