File size: 2,729 Bytes
8bb329c | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
np.random.seed(42)
n_samples = 500
year = np.random.randint(2005, 2024, n_samples)
mileage = np.random.randint(0, 250000, n_samples)
color = np.random.choice(['white', 'black', 'red', 'blue'], n_samples)
transmission = np.random.choice(['manual', 'auto'], n_samples)
fuel = np.random.choice(['petrol', 'gas', 'hybrid'], n_samples)
price = (
200 + (year - 2005) * 15
- mileage * 0.0005
+ (transmission == 'auto') * 50
+ (fuel == 'hybrid') * 80
+ np.random.normal(0, 20, n_samples)
)
data = pd.DataFrame({
"year": year,
"mileage": mileage,
"color": color,
"transmission": transmission,
"fuel": fuel,
"price": price
})
data = pd.get_dummies(data, drop_first=True)
X = data.drop("price", axis=1)
y = data["price"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=400, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
def predict_car_price(model, columns):
print("Mashina ma'lumotlarini kiriting:")
year = int(input("Yili: "))
mileage = int(input("Yurgan km: "))
color = input("Rangi (white/black/red/blue): ")
transmission = input("Uzatma (manual/auto): ")
fuel = input("Yoqilg'i (petrol/gas/hybrid): ")
data = {
"year": year,
"mileage": mileage,
"color": color,
"transmission": transmission,
"fuel": fuel
}
df = pd.DataFrame([data])
df = pd.get_dummies(df)
df = df.reindex(columns=columns, fill_value=0)
price = model.predict(df)[0]
print(f"\nTaxminiy narx: {price:.1f}")
predict_car_price(model, X.columns)
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print("=" * 50)
print("MODEL EVALUATION")
print("=" * 50)
print(f"MAE: {mae:.2f}")
print(f"RMSE: {rmse:.2f}")
print(f"R²: {r2:.3f}")
import matplotlib.pyplot as plt
plt.figure(figsize=(6,6))
plt.scatter(y_test, y_pred)
plt.xlabel("Haqiqiy narx")
plt.ylabel("Model aytgan narx")
plt.title("Haqiqiy vs Bashorat")
plt.plot([y_test.min(), y_test.max()],
[y_test.min(), y_test.max()])
plt.show()
# saqlash
# import pickle
# with open("car_price_model.pkl", "wb") as f:
# pickle.dump(model, f)
# with open("model_columns.pkl", "wb") as f:
# pickle.dump(X.columns, f)
|