Java Introduction To Machine Learning Code Sheet
Java Introduction To Machine Learning Code Sheet
Definition: Machine Learning is a branch of AI that allows systems to learn and improve from
- Supervised Learning
- Unsupervised Learning
- Reinforcement Learning
Common Algorithms:
- Linear Regression
- Logistic Regression
- Decision Trees
- Neural Networks
2. Linear Regression
Definition: Linear regression is used to model the relationship between a dependent variable (y) and
regression.addData(new double[][] { {1, 1}, {2, 2}, {3, 2.5}, {4, 3.5} });
3. Logistic Regression
Definition: Logistic regression is used for binary classification problems. It predicts the probability of
a binary outcome.
import weka.classifiers.functions.Logistic;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
public class LogisticRegressionExample {
loader.setFile(new java.io.File("data.arff"));
data.setClassIndex(data.numAttributes() - 1);
logistic.buildClassifier(data);
Definition: KNN is a simple algorithm used for both classification and regression, where the output is
import weka.classifiers.lazy.IBk;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
public class KNNExample {
loader.setFile(new java.io.File("data.arff"));
data.setClassIndex(data.numAttributes() - 1);
knn.setKNN(3);
knn.buildClassifier(data);
5. Decision Trees
Definition: A decision tree is a flowchart-like structure where each internal node represents a
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
loader.setFile(new java.io.File("data.arff"));
data.setClassIndex(data.numAttributes() - 1);
tree.buildClassifier(data);
6. Neural Networks
relationships in a set of data through a process that mimics the way the human brain operates.
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.optimize.api.IterationListener;
import org.nd4j.linalg.factory.Nd4j;
.list()
.build());
model.init();
// Sample data
INDArray input = Nd4j.create(new double[] {1.0, 0.0, 1.0}, new int[]{1, 3});
System.out.println(output);
7. Model Evaluation
Definition: The process of assessing the performance of a machine learning model using various
metrics.
Common Evaluation Metrics:
- Accuracy
- Precision
- Recall
- F1-Score
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
loader.setFile(new java.io.File("data.arff"));
data.setClassIndex(data.numAttributes() - 1);
classifier.buildClassifier(data);