Question: I need help properly updating centroids in Java, here is my current method: protected List updateCentroids ( List ratings, double [ ] [ ] centroids,

I need help properly updating centroids in Java, here is my current method:
protected List updateCentroids(List ratings, double[][] centroids, int[] assignments, int K){
double[][] newCentroids = new double[K][ratings.get(0).length];
int[] counts = new int[K];
for (int i =0; i < ratings.size(); i++){
int cluster = assignments[i];
counts[cluster]++;
for (int j =0; j < ratings.get(i).length; j++){
newCentroids[cluster][j]+= ratings.get(i)[j];
}
}
for (int i =0; i < K; i++){
if (counts[i]>0){
for (int j =0; j < newCentroids[i].length; j++){
newCentroids[i][j]/= counts[i];
}
}
centroids[i]= newCentroids[i];
}
return Arrays.asList(newCentroids);
}
and here is the unit test: @Test
public void testCentroidsUpdateCorrectly(){
Project.SongClusterer clusterer = Project.SongClusterer();
List ratings = Arrays.asList(
new double[]{0,2},
new double[]{1,0},
new double[]{1,2}
);
double[][] initialCentroids ={{0,0},{1,1}};
int[] assignments ={0,1,0};
List updatedCentroids = clusterer.updateCentroids(ratings, initialCentroids, assignments, 2);
double[][] expectedCentroids ={{1,2},{1,0}};
for (int i =0; i < updatedCentroids.size(); i++){
assertArrayEquals(expectedCentroids[i], updatedCentroids.get(i),0.01, "Centroids should be updated correctly.");
}
}
and finally, when i run it against the test it says "Failed to map supported failure 'org.opentest4j.AssertionFailedError: Centroids should be updated correctly. ==> array contents differ at index [0], expected: <1.0> but was: <0.5>' with mapper"
please help me fix this method, and do not use AI, gpt4 does not understand the issue, I will upvote if you can help me get it working properly!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!