First ML Code on Gradient descent!

Hii there,

Hmm… my first program exceeding 20 lines.

Basically, it is a gradient descent problem (don’t know much about it ๐Ÿ˜› ). As I am taking Machine Learning course on Cousera I wanna solve some problems on ML. I found some AI problems (don’t know much about this too) on HakerRank site and started solving this one. This guy is an output of my 5 hours of work. ๐Ÿ˜€

import java.util.Scanner;

public class houseCosts {
	public static void main(String[] args){
		Scanner in = new Scanner(;
		int n = in.nextInt();
		int m = in.nextInt();
		float[][] x = new float[n+2][m];
		float[] t = new float[n+1];                       
		float[] temp = new float[n+1];
		float alpha = (float) 0.3;                      //alpha
		for(int j = 0; j<m; j++){
			for(int i=1; i<n+2; i++){
				x[i][j] = in.nextFloat();
				//System.out.println("x "+i+" "+j+"= "+x[i][j]);
		int num = in.nextInt();
		float[][] out = new float[n+1][num];
		for(int j = 0; j<num; j++){
			for(int i=1; i<n+1; i++){
				out[i][j] = in.nextFloat();
				//System.out.println("out "+i+" "+j+"= "+out[i][j]);
		for(int i=0; i<num; i++){
			out[0][i] = 1;
			//System.out.println("x "+0+" "+i+"= "+x[0][i]);
		for(int i=0; i<m; i++){
			x[0][i] = 1;
			//System.out.println("x "+0+" "+i+"= "+x[0][i]);
		for(int j=0; j<n+1; j++){
			t[j] = 0;                                  //theta value initializing
		for(int p = 0; p<500; p++){                   //no. of times
			for(int k=0; k<n+1; k++){
				float dum = 0;
				for(int j=0; j<m; j++){
					float ans = 0;
					for(int i=0; i<n+1; i++){
						ans+= t[i] * x[i][j];
					ans-= x[n+1][j];
					ans*= x[k][j];
					//System.out.println("x "+k+" "+j+" ="+x[k][j]);
				temp[k] = (float) (t[k]-(alpha * dum * (1.0/m)));
			for(int k=0; k<=n; k++){
				//System.out.print(t[k]+" ");
			//System.out.println(" ");
		for(int i = 0; i<num; i++){
			float foo = 0;
			for(int j=0; j<n+1; j++){
				foo+=out[j][i] * t[j];

Don’t judge me by this code coz, I don’t know much about algorithms and ML. And there are so many stdouts because I dunno how to debug in eclipse or any IDE for that mater. BTW, I got ten on ten for this problem.

Something Productive- CHECK!

Don’t forget to travel in time.





Reply and/or Suggestions? Right here!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s