How to set the initial centroids of KMColourSegmenter in OpenIMAJ library? - java

I want to measure the time that KMColourSegmenter, in OpenIMAJ library, takes to perform the clustering.
If I didn't make the initial centroids fixed, rather than random, I can't make the measure the performance; because it will change every time, give different number of iterations , and vary in time to execute the clustering.
So how to make the initial centroids fixed i.e. setting them manually?
Update:
#Jon Thanks for the answer, I am trying to implement what you said. Could you check it, especially the "clusters" array I think this array doesn't make sense to initialize. Please, correct me if I am wrong.
public class MyFloatKMeansInit extends FloatKMeansInit{
#Override
public void initKMeans(DataSource<float[]> bds, float[][] clusters) throws IOException {
// TODO Auto-generated method stub
for (int i = 0; i < bds.size(); i++) {
for (int j = 0; j < bds.getData(i).length; j++) {
clusters[i][j]=bds.getData(i)[j];
}
}
}
}
public class MyKMColourSegmenter extends KMColourSegmenter{
public MyKMColourSegmenter(FloatArrayBackedDataSource bds, ColourSpace colourSpace, int K) throws IOException {
super(colourSpace, K);
MyFloatKMeansInit myFloatKMeansInit = new MyFloatKMeansInit();
float[][] clusters = new float[K][];//#######I think there is something wrong here
myFloatKMeansInit.initKMeans(bds, clusters);
this.kmeans.setInit(myFloatKMeansInit);
// TODO Auto-generated constructor stub
}
}

You'll have to implement this yourself; create a subclass of KMColourSegmenter and create a constructor that takes in the centroids, as well as any parameters needed by your choice of constructor in the KMColourSegmenter super class. Then in your constructor, after the call to super, use the this.kmeans.setInit() method to set a initialisation to use you predefined centroids. You'll need to implement a custom FloatKMeansInit subclass that lets you set the centroids externally, but this should be trivial as it only requires implementing a single method.
Update in response to amended question:
You shouldn't call initKMeans directly; that happens behind the scenes when you run the algorithm. You also need to populate the centroids array with the centroids initial centroids you want rather than from the bds. For example (untested):
public class MyFloatKMeansInit extends FloatKMeansInit{
private float [][] mycentroids;
public MyFloatKMeansInit(float [][] mycentroids) {//modifying data type here
this.mycentroids = mycentroids;
}
#Override
public void initKMeans(DataSource<float[]> bds, float[][] clusters) throws IOException {
for (int i = 0; i < mycentroids.length; i++) {
for (int j = 0; j < mycentroids[i].length; j++) {
clusters[i][j]=mycentroids[i][j]; //could use arraycopy instead
}
}
}
}
public class MyKMColourSegmenter extends KMColourSegmenter{
public MyKMColourSegmenter(ColourSpace colourSpace, float[][] mycentroids) throws IOException {
super(colourSpace, mycentroids.length);
MyFloatKMeansInit myFloatKMeansInit = new MyFloatKMeansInit(mycentroids);
this.kmeans.setInit(myFloatKMeansInit);
}
}

Related

Is Java application performance dependent on passing of variables to method?

Maybe this is trivial question for experienced programmers but i wonder if there is any significant performance difference (with big or very big amount of data in collection) between two difference approaches of passing variables?
I've made a tests but with rather small data structures and i don't see any significant differences. Additionally i am not sure if these differences aren't caused by interferences from other applications run in background.
Class with collection:
public class TestCollection
{
ArrayList<String[]> myTestCollection = new ArrayList<String[]>();
public TestCollection()
{
fillCollection();
}
private void fillCollection()
{
// here is fillng with big amount of data
}
public ArrayList<String[]> getI()
{
return myTestCollection;
}
}
And methods that operate on collection:
public class Test
{
static TestCollection tc = new TestCollection();
public static void main(String[] args)
{
new Test().approach_1(tc);
new Test().approach_2(tc.getI());
}
public void approach_1(TestCollection t)
{
for (int i = 0; i < tc.getI().size(); i++)
{
// some actions with collection using tc.getI().DOSOMETHING
}
}
public void approach_2(ArrayList<String[]> t)
{
for (int i = 0; i < t.size(); i++)
{
// some actions with collection using t.DOSOMETHING
}
}
}
Regards.
No, there is no real difference here.
Java passes object references to methods, not copies of the entire object. This is similar to the pass by reference concept in other languages (although we are actually passing an object reference to the called method, passed by value).
If you come from a C programming background it's important to understand this!
And, some tips - firstly, it's better practise to declare your list as List<...> rather than ArrayList<...>, like this:
List<String[]> myTestCollection = new ArrayList<String[]>();
And secondly, you can use the improved for loop on lists, like this:
// first case
for (String[] s : tc.getI()) { /* do something */ }
// second case
for (String[] s : t) { /* do something */ }
Hope this helps :)

Stub an interface

I have to build against an interface. To test I need to override 3 methods of an interface.
I searched for examples but wasn't able to find something that works and is well explained. I don't have a preference regarding a Mocking Framework, just suggest what suits my use case the best.
I need to stub this functionality and do not want to have 400 lines of unused overrides.
public class StubInventory implements Inventory
{
private final ItemStack[] contents;
public StubInventory (int size)
{
contents = new ItemStack[size];
}
#Override
public void setItem (int index, ItemStack item)
{
contents[index] = item;
}
#Override
public ItemStack getItem (int index)
{
return contents[index];
}
#Override
public void clear ()
{
Arrays.fill(contents, null);
}
//<-- Insert 400 lines of unused #Override's here
}
Update:
The getters and especially the setters are used by my code and have to work. The values are not predefined. The values will be set by my code and my test code will verify the result.
mockInventory = mock(Inventory.class);
//Not "nice" but will probably work
for (int i = 0; i < size * 9; i++)
when(mockInventory.getItem(i)).thenReturn(contents[i]);
//This is where the problem is. I need to take item (ItemStack)
// and set it in my stubbed class. Basically I need to access the parameter.
for (int i = 0; i < size * 9; i++)
when(mockInventory.setItem(i, item)).then(contents[i] = item);
Try Mockito. It is really stable and convenient for most cases. For example, you could write:
Inventory inventory = Mockito.mock(Inventory.class);
Mockito.when(inventory.getItem(Mockito.any())).thenReturn(somePresetItemStack);
You should use static import on Mockito.* methods for better readability:
import static org.Mockito.*;
You can easily do this with mockito. Have a look at the examples. What you want to do is a basic mocking job.

Stack Trace Logger

I need to write a parent Java class that classes using recursion can extend. The parent class will be be able to realize whenever the call stack changes ( you enter a method, temporarily leave it to go to another method call, or you are are finsihed with the method ) and then print it out. I want it to print on the console, but clear the console as well every time so it shows the stack horizantaly so you can see the height of each stack to see what popped off and what popped on... Also print out if a baseline was reached for recursive functions.
First. How can I using the StackTraceElements and Thread classes to detect automatically whenever the stack has popped or pushed an element on without calling it manually?
Second, how would I do the clearing thing?
For instance , if I had the code:
public class recursion(int i)
{
private static void recursion(int i)
{
if(i < 10)
System.out.println('A');
else
{
recursion(i / 10 );
System.out.println('B');
}
}
public static void main(String[] argv)
{
recursion(102);
}
}
It would need to print out the stack when entering main(), when entering recursion(102) from main(), when it enters recursion(102 / 10), which is recursion(10), from recursion(102), when it enters recursion(10 / 10), which is recursion(1) from recursion(10). Print out a message out when it reaches the baseline recursion(1).. then print out the stacks of reversed revisitation of function recursion(10), recursion(102) and main(). finally print out we are exiting main().
Thread class allows managing OS threads, it does not have anything to do with the call-stack. StackTraceElement represents a stack-frame but you need a StackTrace to get to it.
You are looking for a notification for when the stack-trace changes, for example a frame is added (a method is entered) or removed (a method is exited).
By far the most appropriate tool for this task is AspectJ. It lets you define advices (a kind of method) that gets called (besides other cases) when other methods are entered or existed. These triggers that result in the advices getting called are called pointcuts -- they can be method entry, exit and the methods can be described using wildcards: the pointcut MyClass.get* applies to all get methods of MyClass.
I started to write my own before seeing your answer. It is simplistic in form but the shell is:
package stackTraceLogger;
import java.util.ArrayList;
public class StackTraceLogger
{
static final int MAX_ROW = Integer.MAX_VALUE;
static final int MAX_COLUMN = Integer.MAX_VALUE;
static public ArrayList<ArrayList<String>> stringTrace;
//private ArrayList<ArrayList<StackTraceElement>> stack;
public StackTraceLogger()
{
stringTrace = new ArrayList< ArrayList <String>>();
//stack = new ArrayList<ArrayList<StackTraceElement>>();
}
static public void addStack(StackTraceElement[] inputTrace)
{
int size = inputTrace.length;
// make an ArrayList with the strings of all the StrackTraceElements
ArrayList<String> str = new ArrayList<>(size);
for(int i = 0; i < size; i++)
{
str.add(i,inputTrace[i].getMethodName());
}
// Add the ArrayList to the 2D ArrayList of the stacks
}
static public void printTrace()
{
/* if(stringTrace.get(0).size() > 0)
{
for(int i = 0; i < stringTrace.size(); i++)
{
System.out.println(stringTrace.get(i));
for(int j = 0; j < stringTrace.get(j).size(); j++)
System.out.println(stringTrace.get(i).get(j));
}
}*/
}
static private ArrayList<String> convertToArrayList(StackTraceElement[] inputTrace)
{
ArrayList<String> strTrace = new ArrayList<>();
for(int j = 0; j < inputTrace.length; j++ )
strTrace.add(inputTrace[j].getMethodName());
return strTrace;
}
}

Having trouble understanding how to maintain state using classes

I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.

Using Array of Objects in Parameters, Inheritance in Parameters

I have the class Building and the sub-classes Barracks and House. Now I have an array of houses and barracks defined like this:
public House[] arrSHouse;
public Barracks[] arrBarr;
Now my code is designed such that I when I want to create a house, a house will follow my mouse in the applet. This way works:
for(int h = 0; h < arrSHouse.length; h ++)
{
if(arrSHouse[h].held == true)
{
arrSHouse[h].isAlive = true;
arrSHouse[h].xpos = e.getX()-8;
arrSHouse[h].ypos = e.getY()-20;
}
}
However, I want to make my code more efficient by making a method that will allow me to input an array, such as arrBarr, which is an array of Barracks, and do the same things as the method shown above. This is my attempt:
public void buildingFollowMouse(Building[]type, MouseEvent e)
{
for(int a = 0; a < type.length; a ++)
{
if(type[a].held == true)
{
type[a].isAlive = true;
type[a].xpos = e.getX()-8;
type[a].ypos = e.getY()-20;
}
}
}
However, this doesn't work. The only way that this works is if I say:
public void buildingFollowMouse(House[]type, MouseEvent e)
as the parameters and say:
buildingFollowMouse(arrSHouse, e);
This of course would mean writing another method for the barracks method.
I just want to know a way that I can input a sub-class of Building in my parameter and have it work the same way that it worked above with the House for-loop with any other Building I decide to make. How can I do this?

Categories