Metadata-Version: 2.4
Name: ml-learnkit
Version: 0.1.1
Summary: Machine Learning and Statistical Analysis Toolkit
Author-email: Vincent Amonde <vinnyamonde@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/vinnyamonde/ml-learnkit
Project-URL: Bug Tracker, https://github.com/vinnyamonde/ml-learnkit/issues
Keywords: machine learning,statistics,regression,linear regression,anova,data science
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >3.10
Description-Content-Type: text/markdown
Requires-Dist: numpy>=2.0
Requires-Dist: pandas>=2.0
Requires-Dist: matplotlib>=3.8
Requires-Dist: scipy>=1.13
Requires-Dist: seaborn>=0.13
Requires-Dist: prettytable

# ml-learnkit

A lightweight Python toolkit for machine learning and statistical analysis, designed for transparency and education. It exposes every intermediate calculation so you can follow along with the maths, not just get an answer.

---

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [API Reference](#api-reference)
  - [Reader](#reader)
  - [Data](#data)
  - [SimpleLinearRegressor](#simplelinearregressor)
- [Full Worked Example](#full-worked-example)
- [Requirements](#requirements)
- [Project Structure](#project-structure)
- [Contributing](#contributing)
- [License](#license)



## Features

- Load raw Python lists into a structured `Data` object with tabular display
- `SimpleLinearRegressor` built from first principles — no black-box estimators
- Regression coefficients table with standard errors, t-statistics, and p-values
- ANOVA table (SSR, SSE, SST, MSR, MSE, F-statistic, p-value)
- Six diagnostic plots in one call (scatter + SE band, residuals vs fitted, Q-Q, scale-location, residuals vs leverage, residual histogram) via seaborn



## Installation

```bash
pip install ml-learnkit
```

Requires Python > 3.10.



## Quick Start

```python
from ml_learnkit import Reader, SimpleLinearRegressor

# 1. Load data
reader = Reader()
data = reader.read_lists(
    lists=[[1, 2, 3, 4, 5], [2.1, 4.0, 5.9, 8.2, 9.8]],
    columns=["X", "Y"]
)

# 2. Inspect
data.show()

# 3. Fit model
model = SimpleLinearRegressor()
model.fit(data.get("X"), data.get("Y"))

# 4. Results
print(model.equation())
model.regression_table()
model.anova()
model.plot()
```



## API Reference

### `Reader`

Utility class for loading raw Python lists into a `Data` object.

```python
from ml_learnkit import Reader
reader = Reader()
```

#### `read_lists(lists, columns) → Data`

| Parameter | Type | Description |
|-----------|------|-------------|
| `lists` | `list[list]` | One list per variable. All lists must be the same length. |
| `columns` | `list[str]` | Column names, one per list. |

**Returns** a `Data` instance.

**Raises** `ValueError` if the number of lists does not match the number of column names, or if lists have unequal lengths.

```python
data = reader.read_lists(
    lists=[[10, 20, 30], [1.1, 2.2, 3.3]],
    columns=["Hours", "Score"]
)
```


### `Data`

Structured tabular container built on top of a plain Python dictionary.

```python
from ml_learnkit import Reader
data = Reader().read_lists(...)
```

#### `data.show(n=5)`

Prints the first `n` rows as a formatted table. Default `n=5`.

#### `data.tail(n=5)`

Prints the last `n` rows as a formatted table. Default `n=5`.

#### `data.get(column) → list`

Returns the raw list for the given column name.

**Raises** `ValueError` if the column does not exist.

```python
x = data.get("Hours")
y = data.get("Score")
```

#### `data.rows → list[tuple]`

Property. Returns all rows as a list of tuples.


### `SimpleLinearRegressor`

Fits a simple (one predictor) ordinary least squares regression model.  
The model equation is: **Ŷ = b₀ + b₁X**

```python
from ml_learnkit import SimpleLinearRegressor
model = SimpleLinearRegressor()
```

#### `fit(X, y) → self`

Fits the model and computes all intermediate sums required by later methods.

| Parameter | Type | Description |
|-----------|------|-------------|
| `X` | `list[float]` | Predictor (independent variable) values. |
| `y` | `list[float]` | Response (dependent variable) values. |

Returns `self` to allow method chaining.

```python
model.fit(x, y)
```


#### `equation() → str`

Returns the fitted regression equation as a string.

```
'Y = 0.3452 + 1.9231x'
```


#### `table()`

Returns a `PrettyTable` showing the computation worksheet:  
X, X², Y, Y², XY, (X−X̄)², (Y−Ȳ)² — with column totals (Σ) in the final row.  
Long datasets are truncated to the first and last 5 rows.

```python
print(model.table())
```


#### `t_statistics() → dict`

Computes the standard error and t-statistic for the intercept (b₀) and slope (b₁).

```python
stats = model.t_statistics()
# stats["Intercept"]["coefficient"]
# stats["Intercept"]["standard_error"]
# stats["Intercept"]["t"]
# stats["Slope"]["coefficient"]
# stats["Slope"]["standard_error"]
# stats["Slope"]["t"]
```


#### `p_value() → dict`

Computes the two-tailed p-values for b₀ and b₁ from the t-distribution.

```python
pvals = model.p_value()
# pvals["Intercept"]["p_value"]
# pvals["Slope"]["p_value"]
```


#### `regression_table()`

Prints a formatted coefficients table (mirrors SPSS / statsmodels output):

```
=============================================================...
REGRESSION COEFFICIENTS
=============================================================...
Predictor                              B     Std. Error       Beta            t        P>|t|
---------------------------------------------------------------------------------------------
Constant                          0.3452         0.2814          -       1.2266     0.223456
Independent Variable (X)          1.9231         0.0891     0.7420      21.5870     0.000000
=============================================================...
```


#### `statistics()`

Prints a model summary block (sample size, R, R², Adjusted R², standard error of estimate).



#### `anova()`

Computes and prints the one-way ANOVA table for the regression.

| Column | Description |
|--------|-------------|
| SS | Sum of squares |
| df | Degrees of freedom |
| MS | Mean square (SS / df) |
| F | F-statistic (MSR / MSE) |
| P > F | p-value from the F-distribution |

```
==================================================================
ANOVA TABLE
==================================================================
Source                SS      df            MS           F        P > F
------------------------------------------------------------------
Regression       450.1234       1      450.1234    123.4567     0.000000
Residual          65.4321      48        1.3632
------------------------------------------------------------------
Total            515.5555      49
==================================================================
```



#### `plot()`

Renders **6 diagnostic plots** in a 2 × 3 grid using seaborn and matplotlib:

| Position | Plot | Purpose |
|----------|------|---------|
| Row 1, Col 1 | Scatter + Regression Line | Fitted line with 95 % SE shading |
| Row 1, Col 2 | Residuals vs Fitted | Check linearity and constant variance |
| Row 1, Col 3 | Normal Q-Q | Check normality of residuals |
| Row 2, Col 1 | Scale-Location | Check homoscedasticity |
| Row 2, Col 2 | Residuals vs Leverage | Identify influential observations (Cook's distance contours at 0.5 and 1.0) |
| Row 2, Col 3 | Residual Histogram | Distribution of residuals with KDE |

```python
model.plot()
```


## Full Worked Example

```python
from ml_learnkit import Reader, SimpleLinearRegressor

# Sample data: advertising spend vs. sales
spend  = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
sales  = [22, 28, 35, 40, 48, 55, 60, 68, 74, 80]

reader = Reader()
data = reader.read_lists(lists=[spend, sales], columns=["Spend", "Sales"])

# Inspect the data
data.show()
print(data.tail(3))

# Fit the model
model = SimpleLinearRegressor()
model.fit(data.get("Spend"), data.get("Sales"))

# Computation worksheet
print(model.table())

# Equation
print(model.equation())

# Coefficients table
model.regression_table()

# ANOVA table
model.anova()

# All six diagnostic plots
model.plot()
```



## Requirements

| Package | Minimum version |
|---------|-----------------|
| Python  | > 3.10 |
| numpy   | >= 2.0 |
| pandas  | >= 2.0 |
| matplotlib | >= 3.8 |
| scipy   | >= 1.13 |
| seaborn | >= 0.13 |
| prettytable | (any recent) |

Install all dependencies:

```bash
pip install ml-learnkit
```

---







## Author



*Author: Vincent Amonde — vinnyamonde@gmail.com*
