Skip to content

primepvi/libreg

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

libreg

A minimalistic C library for linear regression using gradient descent.

Usage

This library provides functions to create, fit, predict, and free a linear regression model.

#include "linear.h"
#include <stdio.h>

int main(void) {
  // 1. Create a new Linear Model
  LinearModel *model = linear_model_create();

  // 2. Prepare your training data (array of Point structs)
  Point train_points[] = {
      {-5.0, -16.1}, {-4.0, -14.2}, {-3.0, -11.8}, {-2.0, -8.9}, {-1.0, -5.1},
      {0.0, -2.0},   {1.0, 1.2},    {2.0, 4.1},    {3.0, 7.9},   {4.0, 10.2},
      {5.0, 13.8}
  };
  size_t point_count = sizeof(train_points) / sizeof(Point);

  // 3. Configure Gradient Descent parameters
  GradientDescentConfig config = {
      .epochs = 1000,        // Number of training iterations
      .learning_rate = 0.01, // Step size for each iteration
      .tolerance = 1e-6,     // Stop if gradient norm is below this
      .verbose = true        // Print progress during training
  };

  // 4. Fit the model to the training data
  Metrics metrics = linear_model_fit(model, &config, train_points, point_count);
  printf("Model fitted: m=%.4f, b=%.4f, MSE=%.4f after %zu epochs\n",
         metrics.m, metrics.b, metrics.mse, metrics.epochs);

  // 5. Make predictions with the fitted model
  double x_value = 6.0;
  double prediction = linear_model_predict(model, x_value);
  printf("Prediction for x=%.1f: y=%.4f\n", x_value, prediction);

  // 6. Free the model's allocated memory
  linear_model_free(model);

  return 0;
}

Building and Testing

To compile and run a program that uses this library (e.g., main.c), you can use a C compiler like GCC:

# Compile the library and your main application
gcc main.c linear.c -o main -lm

# Run the compiled program
./main

The -lm flag is required to link the math library for functions like sqrt in linear.c.

About

linear regression from scratch in c

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages