Creating an Instance

This tutorial shows the very first step in using Java-ML. It will show you how to create Instances which are the default way to represent a sample of real world data.

The main way to represent data is the DenseInstance which requires a value for each attribute of an Instance. In most scenarios this representation of the data will suffice. In case your data is sparse, you can also put your data in a SparseInstance which requires less memory in case of sparse data (less than 10% attributes set).

How to create a DenseInstance
[Documented source code]

The block of code below will create an Instance with ten attributes. The values of these attributes are one through ten. The class label of this Instance is not set.

  1. /* values of the attributes. */
  2. double[] values = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  3. /*
  4.   * The simplest incarnation of the DenseInstance constructor will only
  5.   * take a double array as argument an will create an instance with given
  6.   * values as attributes and no class value set. For unsupervised machine
  7.   * learning techniques this is probably the most convenient constructor.
  8.   */
  9. Instance instance = new DenseInstance(values);

To create an Instance with ten attributes, with values one through ten and with the class label "positive" we can use the following code. Note that the class label can be any object.

  1. /* values of the attributes. */
  2. double[] values = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  3. /* Create and an Instance with the above values and its class label set to "positive" */
  4. Instance instance = new DenseInstance(values,"positive");

How to create a SparseInstance
[Documented source code]
To create a SparseInstance you just have to specify the number of attributes that the Instance has and then you set the particular attributes values. The example below creates an Instance with 10 attributes. Next, we set the value of attributes with index one, three and seven to particular values.

  1. /*
  2.   * Here we will create an instance with 10 attributes, but will only set
  3.   * the attributes with index 1,3 and 7 with a value.
  4.   */
  5. /* Create instance with 10 attributes */
  6. Instance instance = new SparseInstance(10);
  7. /* Set the values for particular attributes */
  8. instance.put(1, 1.0);
  9. instance.put(3, 2.0);
  10. instance.put(7, 4.0);