Dmbi 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Practical-5

Generate a linear regression based model and


demonstrate its working on the given dataset.

Code:
#include <conio.h>

#include <math.h>

#include <stdio.h>

#define s 100

void linear_reg(int x[], int y[], float x_m, float y_m, int n) {

float Xi[s], Yi[s];

int i;

float XiYi = 0, Xi_squ = 0, w_one, w_zero, c, reg;

for (i = 0; i < n; i++) {

Xi[i] = x[i] - x_m;

for (i = 0; i < n; i++) {

Yi[i] = y[i] - y_m;

for (i = 0; i < n; i++) {

XiYi += (Xi[i] * Yi[i]);

}
for (i = 0; i < n; i++) {

Xi_squ += pow(Xi[i], 2);

w_one = XiYi / Xi_squ;

printf("W1 is: %f", w_one);

w_zero = y_m - (w_one * x_m);

printf("\nW0 is: %f", w_zero);

printf("\nEquation is y= %f + %fx\n", w_zero, w_one);

printf("Enter the time period (for predicting future value): ");

scanf("%f", &c);

reg = w_zero + w_one * c;

printf("Value after the %.0f(time period) is : %f\n", c, reg);

float mean(int arr[], int n) {

float sum = 0;

int i;

for (i = 0; i < n; i++) {

sum += arr[i];

return (sum / n);

void main() {

int x[s], y[s];


int n, i;

float x_mean, y_mean;

printf("Enter length of the dataset: ");

scanf("%d", &n);

printf("Enter element in X(array):\n");

for (i = 0; i < n; i++) {

scanf("%d", &x[i]);

printf("Enter element in Y(array):\n");

for (i = 0; i < n; i++) {

scanf("%d", &y[i]);

x_mean = mean(x, n);

y_mean = mean(y, n);

printf("X Mean: %f\n", x_mean);

printf("Y Mean: %f\n", y_mean);

linear_reg(x, y, x_mean, y_mean, n);

You might also like