deeprust/sgd/
gradient.rs

1// Task :- Performing gradient descent operations
2// Author :- @digneshwer
3// Version :- 0.0.1
4// Date : - 28 Jan 2017
5
6// Modules used
7use std::{f64,i32};
8
9// Main function point of execution
10pub fn exec() {
11    println!("Gradient Descent Experiment");
12
13    let mut parameter_test = Params {
14    	sgd_alpha : 0.1,sample_size : 2.0,theta : (1.0, 1.0),data : (1.0,1.0),label: (1.0,1.0), update_int :(0.0,0.0)
15    };
16    parameter_test.cal_update();
17    parameter_test.theta_zero_update();
18    parameter_test.theta_one_update();
19    println!("Updated theta_zero : {:?}",parameter_test.theta.0);
20    println!("Updated theta_one : {:?}",parameter_test.theta.1);
21}
22
23// Defining an user defined data type params
24// check the ../../sgd_working.md file variable documentation
25#[derive(Debug)]
26struct Params {
27	sgd_alpha : f64,
28	sample_size : f64,
29	theta : (f64, f64),
30	data : (f64,f64),
31	label : (f64,f64),
32	update_int : (f64,f64),
33}
34
35// Parameter optimization functionality for the param datatype
36trait ParameterOptimization {
37	// fn theta_zero_update(&self) -> (f64,f64,i32,f64);
38	// fn theta_one_update(&self) -> (f64,f64,i32,f64);
39	fn theta_zero_update(&mut self) -> &Params;
40	fn theta_one_update(&mut self) -> &Params;
41	fn cal_update(&mut self) -> &Params;
42}
43
44// implement area for circle
45impl ParameterOptimization for Params {
46	fn theta_zero_update(&mut self) -> &Params {
47		self.theta.0 = self.theta.0 - self.update_int.0;
48		// (self.theta.0, self.sgd_alpha, self.sample_size, self.data.0)
49		self
50	}
51
52	fn theta_one_update(&mut self) -> &Params {
53		self.theta.1 = self.theta.1 - self.update_int.1;
54		// (self.theta.1, self.sgd_alpha, self.sample_size, self.data.1)
55		self
56	}
57
58	fn cal_update(&mut self) -> &Params{
59		let (mut int_0,mut int_1,mut int) = (0.0,0.0,0.0);
60		for index in 0..2{
61			int = self.theta.0 + self.theta.1 * self.data.0 - self.label.0;
62			int_0 += int;
63			int_1 += int*self.data.0;
64		}
65		self.update_int.0 = (self.sgd_alpha*(1/self.sample_size as i32)as f64)*int_0;
66		self.update_int.1 = (self.sgd_alpha*(1/self.sample_size as i32) as f64)*int_1;
67		self
68	}
69}