#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define M 100
#define N 3
#define Max_it 1500
int main(void)
{
int i, j, count, y[M];
double x[M][N-1], theta[N], alpha;
FILE *ifp;
void stochastic(double x[][N-1], int *y, int m, double *theta, int n, double alpha, int tt);
//read data from file
count = 0;
if((ifp = fopen("ex2data1.txt", "r")) == NULL)
{
printf("open error, check!\n");
exit(1);
}
else
{
for(i=0;!feof(ifp);i++)
{
fscanf(ifp,"%lf,%lf,%d\n", &x[i][0],&x[i][1], &y[i]);
count++;
}
}
fclose(ifp);
count;
theta[0] = -25.0; theta[1] = 0.3; theta[2] = 0.2;
alpha = 0.01;
stochastic(x, y, count,theta, N, alpha, Max_it);
printf("The regression parameters are:\n");
for(i=0; i<N; i++)
{
printf("%10.2f \n", theta[i]);
}
exit(0);
}
//============================================================================================
void stochastic(double x[][N-1], int *y, int m, double *theta, int n, double alpha, int max_it)
//m: sample numbers, n: the dimesion of theta, max_it: max interation number.
{
int i, j, k, l;
double sum1, err, loss;
loss = 1.0;
for(k=0; k<max_it && loss>0.001; k++)//for max iteration numbers
{
err = 0.0;
i = k%m;
{
sum1 = theta[0];
for(j=1; j<n; j++)
{
sum1 += theta[j]*x[i][j-1];
}
sum1 = 1.0/(1.0 + exp(-sum1));
err = y[i] - sum1;
for(l=0;l<n;l++)
{
if(l == 0)
theta[l] = theta[l] + alpha*err/m;
else
theta[l] = theta[l] + alpha*err*x[i][l-1]/m;
}
}
loss = 0.0;
for(l=0; l<m; l++)
{
sum1 = theta[0];
for(j=1; j<n; j++ )
sum1 += x[l][j-1]*theta[j];
loss += (sum1 - y[l])*(sum1 - y[l]);
}
}
}
83,1 Bot