diff options
| author | Thomas Vanbesien <tvanbesi@proton.me> | 2026-04-01 15:50:31 +0200 |
|---|---|---|
| committer | Thomas Vanbesien <tvanbesi@proton.me> | 2026-04-01 15:50:31 +0200 |
| commit | 9f5876dcaad0977e6ef4cb350d52b70236f55e76 (patch) | |
| tree | dda9f7c9b1210b7120671eb74a5331a6dfb6e666 | |
| parent | b998b2cdfe454c9d177e06304c2c01c63747335c (diff) | |
| download | ft_linear_regression-9f5876dcaad0977e6ef4cb350d52b70236f55e76.tar.gz ft_linear_regression-9f5876dcaad0977e6ef4cb350d52b70236f55e76.zip | |
| -rw-r--r-- | calculate_precision.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/calculate_precision.py b/calculate_precision.py new file mode 100644 index 0000000..acf1391 --- /dev/null +++ b/calculate_precision.py @@ -0,0 +1,45 @@ +import csv + +DATA_FILE = "data.csv" +THETAS_FILE = "thetas.csv" + + +def load_thetas(): + with open(THETAS_FILE) as f: + lines = f.readlines() + return float(lines[0]), float(lines[1]) + + +def load_data(): + km = [] + price = [] + with open(DATA_FILE) as f: + reader = csv.reader(f) + next(reader) + for row in reader: + km.append(float(row[0])) + price.append(float(row[1])) + return km, price + + +def mean(vals): + return sum(vals) / len(vals) + + +def estimate_price(mileage, theta0, theta1): + return theta0 + theta1 * mileage + + +def main(): + kms, prices = load_data() + theta0, theta1 = load_thetas() + predicted_prices = [estimate_price(x, theta0, theta1) for x in kms] + mean_price = mean(prices) + r2 = 1 - sum((p - pp) ** 2 for p, pp in zip(prices, predicted_prices)) / sum( + (p - mean_price) ** 2 for p in prices + ) + print(f"R-squared = {r2}") + + +if __name__ == "__main__": + main() |
