-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
57 lines (46 loc) · 1.58 KB
/
Copy pathpredict.py
File metadata and controls
57 lines (46 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
"""Prediction program: estimate a car's price from its mileage.
Prompts for a mileage (or takes it as an argument) and prints
``estimatePrice(mileage) = theta0 + theta1 * mileage``. Before training,
theta0 and theta1 are 0, so the estimate is 0.
Usage:
python3 predict.py # interactive prompt
python3 predict.py 50000 # one-shot
"""
from __future__ import annotations
import math
import sys
from linear_regression import THETA_FILE, estimate_price, load_model
def read_mileage(argv: list[str]) -> float | None:
"""Return a valid non-negative mileage, or None on bad/absent input."""
if len(argv) > 1:
raw = argv[1]
else:
try:
raw = input("Enter the mileage (km): ").strip()
except EOFError:
print()
return None
try:
km = float(raw)
except ValueError:
print(f"predict: '{raw}' is not a valid number", file=sys.stderr)
return None
if not math.isfinite(km):
print("predict: mileage must be a finite number", file=sys.stderr)
return None
if km < 0:
print("predict: mileage cannot be negative", file=sys.stderr)
return None
return km
def main(argv: list[str] | None = None) -> int:
argv = sys.argv if argv is None else argv
model = load_model(THETA_FILE)
km = read_mileage(argv)
if km is None:
return 1
price = estimate_price(km, model.theta0, model.theta1)
print(f"Estimated price for {km:.0f} km: {price:.2f}")
return 0
if __name__ == "__main__":
raise SystemExit(main())