Write a program that performs the least mean squares optimization.
Given a large collection of data of the form (x0 x1 x2 x3 d), your task is to determine w0
w1 w2 w3. The LMS technique finds these weights by starting with some assumed
weights, such asw0=w1=w2=w3=0, and finding the result of the function using the first
grouping of data. For each weight wi, set wi=wi+ nxi(d−y). Assume n=0.05
I understood I was to have an update function which returns void and is pass by reference. Also another function to calculate y.
this is my code:
1 #include <iostream>
2 #include <fstream>
3 #include <cstdlib>
4 using namespace std;
5 double eval(double x0,double x1, double x2,double x3, double w0,
6 double w1, double w2,double w3)
7 {
8 w0=w1=w2=w3=0.0; //initializing weights
9 double y;
10 y=(w0*x0)+(w1*x1)+(w2*x2)+(w3*x3);//calculating y
11 return y;
12 }
13 void update(double &w0, double &w1, double &w2, double &w3,
14 double x0, double x1, double x2, double x3, double d)
15 //updating weights
16 {
17 double n=0.05;
18 double y;
19 w0=w0+(n*x0)*(d-y);
20 w1=w1+(n*x1)*(d-y);
21 w2=w2+(n*x2)*(d-y);
22 w3=w3+(n*x3)*(d-y);
23 }
24 int main()
25 {
26 double y=0.0, w0=0.0, w1=0.0, w2=0.0,w3=0.0;
27 ifstream fin;
28 string file_name;
29 cout<<"Enter input file name: "<<endl; //asking user for file name
30 cin>>file_name;
31 fin.open(file_name.c_str(),ios::in); //converting to c-string
32 if(!fin.is_open()) //condition on not being able to open file
33 {
34 cerr<<"Error opening file"<<endl;
35 exit(2);
36 }
37 double x0,x1,x2,x3,d; //declaring x0,x1,x2,x3,d
38 fin>>x0>>x1>>x2>>x3>>d;
39 for(int i=0; i<100; i++) //running loop 100times
40 {
41 //resetting file
42 fin.clear();
43 fin.seekg(0);
44 while(fin>>x0>>x1>>x2>>x3>>d)
45 {
46 update(w0,w1,w2,w3,x0,x1,x2,x3,d); //updating weights
47
48 }
49 }
50 y=eval(x0,x1,x2,x3,w0,w1,w2,w3); //calculating y
51 cout<<y<<endl; //printing y
52 fin.close(); //closing file
53 return 0; //exit
54 }
We were given a bunch of test inputs and their sample outputs, for example
=== Test 2
--- Input
pa-4-input-2.txt
--- Output
Enter input file name:
Function: y = 15*x0 + -4.28*x1 + 2.25*x2 + -10*x3
but my output is always zero can someone help please!