Untitled

mail@pastecode.io avatar
unknown
python
a month ago
7.7 kB
1
Indexable
Never
import numpy as np
import random


def display_services(services):
    print("Dostępne usługi: ")
    for index, serv in enumerate(services.keys(), 1):
        print(f"{index}. {serv}")


def get_service_selection(services):
    selected_services = []

    while True:
        user_input = input("Wybierz numer usługi (lub wpisz 'q' aby zakończyć wybór): ")
        if user_input.lower() == 'q':
            break
        try:
            service_index = int(user_input) - 1
            if 0 <= service_index < len(services):
                selected_service = list(services.keys())[service_index]
                if selected_service not in selected_services:
                    selected_services.append(selected_service)
                    print(f"Usługa '{selected_service}' została dodana do wybranych.")
                else:
                    print(f"Usługa '{selected_service}' jest już wybrana.")
            else:
                print("Nieprawidłowy numer usługi, spróbuj ponownie.")
        except ValueError:
            print("Nieprawidłowe dane, wpisz numer usługi lub 'q' aby zakończyć.")

    return selected_services


def display_selected_services(selected_services, services):
    print("\nWybrane usługi:")
    for serv in selected_services:
        details = services[serv]
        print(f"Usługa: {serv}")
        print(f"  Stawka za m²: {details['price_per_sqm']} zł")
        print(f"  Czas na m²: {details['time_per_sqm']} godziny")
        print()


def generate_training_samples(selected_services, services, num_samples=100):
    training_data = {}

    for serv in selected_services:
        service_data = []
        price_per_sqm = services[serv]['price_per_sqm']
        time_per_sqm = services[serv]['time_per_sqm']

        for _ in range(num_samples):
            sqm = random.randint(1, 100)

            price_rate = random.uniform(sqm * price_per_sqm * 1.1, sqm * price_per_sqm * 2.0)
            price = int(price_rate)

            min_time = sqm * time_per_sqm
            max_time = min_time * 1.2
            time = random.uniform(min_time, max_time)
            time = int(time)

            service_data.append({'sqm': sqm, 'time': time, 'price': price})

        training_data[serv] = service_data

    return training_data


def prepare_test_samples(base_data, training_samples):
    testing_samples = {}

    for serv, details in training_samples.items():
        service_data = []
        price_per_sqm = base_data[serv]['price_per_sqm']
        time_per_sqm = base_data[serv]['time_per_sqm']

        for detail in details:
            sqm = detail['sqm']

            price = sqm * price_per_sqm
            time = sqm * time_per_sqm

            service_data.append({'sqm': sqm, 'time': time, 'price': price})

        testing_samples[serv] = service_data

    return testing_samples


def linear_regression(X, y):
    n = len(X)
    mean_x = sum(X) / n
    mean_y = sum(y) / n

    numer = sum((X[i] - mean_x) * (y[i] - mean_y) for i in range(n))
    denom = sum((X[i] - mean_x) ** 2 for i in range(n))

    b1 = numer / denom
    b0 = mean_y - b1 * mean_x

    return b0, b1


def predict(X, b0, b1):
    return [b0 + b1 * x for x in X]


def calculate_rmse(actual, predicted):
    n = len(actual)
    mse = sum((actual[i] - predicted[i]) ** 2 for i in range(n)) / n
    rmse = np.sqrt(mse)
    return rmse


def calculate_mae(actual, predicted):
    n = len(actual)
    mae = sum(abs(actual[i] - predicted[i]) for i in range(n)) / n
    return mae


if __name__ == "__main__":
    data = {
        "Murowanie": {"price_per_sqm": 55, "time_per_sqm": 3},
        "Malowanie": {"price_per_sqm": 25, "time_per_sqm": 3},
        "Sprzątanie": {"price_per_sqm": 35, "time_per_sqm": 1},
        "Układanie płytek": {"price_per_sqm": 120, "time_per_sqm": 4},
        "Tapetowanie": {"price_per_sqm": 50, "time_per_sqm": 3},
        "Układanie dachówek": {"price_per_sqm": 50, "time_per_sqm": 6},
        "Wylewanie betonu": {"price_per_sqm": 80, "time_per_sqm": 2},
        "Rozkładanie rusztowania": {"price_per_sqm": 30, "time_per_sqm": 2}
    }

    display_services(data)
    selected_data = get_service_selection(data)

    # Testowe wypisanie usług wybranych przez użytkownika.
    display_selected_services(selected_data, data)

    train_samples = generate_training_samples(selected_data, data, 100)

    # Kontrolne wypisanie danych treningowych.
    # for service, samples in train_samples.items():
    #     print(f"Usługa: {service}")
    #     for sample in samples:
    #         print(f"  Metry kwadratowe: {sample['sqm']}, Czas: {sample['time']} godzin, Cena: {sample['price']:.2f} zł")

    test_samples = prepare_test_samples(data, train_samples)

    # Kontrolne wypisanie danych testowych.
    # for service, samples in test_samples.items():
    #     print(f"Usługa: {service}")
    #     for sample in samples:
    #         print(f"  Metry kwadratowe: {sample['sqm']}, Czas: {sample['time']} godzin, Cena: {sample['price']:.2f} zł")

    # Przygotowanie danych do regresji
    for service, samples in train_samples.items():
        print(f"\nTrening danych dla usługi: {service}")
        sqm_values = [sample['sqm'] for sample in samples]
        time_values = [sample['time'] for sample in samples]
        price_values = [sample['price'] for sample in samples]

        b0_time, b1_time = linear_regression(sqm_values, time_values)
        b0_price, b1_price = linear_regression(sqm_values, price_values)

        print(f"Model regresji dla czasu: y = {b0_time:.2f} + {b1_time:.2f}x")
        print(f"Model regresji dla ceny: y = {b0_price:.2f} + {b1_price:.2f}x")

        test_samples = prepare_test_samples(data, {service: samples})

        sqm_test = [sample['sqm'] for sample in test_samples[service]]
        time_test = [sample['time'] for sample in test_samples[service]]
        price_test = [sample['price'] for sample in test_samples[service]]

        time_pred = predict(sqm_test, b0_time, b1_time)
        price_pred = predict(sqm_test, b0_price, b1_price)

        # print(f"\nPredykcje czasu dla usługi: {service}")
        # for i in range(len(sqm_test)):
        #     print(
        #         f"Metry kwadratowe: {sqm_test[i]}, "
        #         f"Rzeczywisty czas: {time_test[i]}, Przewidywany czas: {time_pred[i]:.2f} zł")
        #
        # print(f"\nPredykcje ceny dla usługi: {service}")
        # for i in range(len(sqm_test)):
        #     print(
        #         f"Metry kwadratowe: {sqm_test[i]}, Rzeczywista cena: {price_test[i]}, "
        #         f"Przewidywana cena: {price_pred[i]:.2f} zł")

        # Obliczanie RMSE i MAE dla czasu
        rmse_time = calculate_rmse(time_test, time_pred)
        mae_time = calculate_mae(time_test, time_pred)

        # Obliczanie RMSE i MAE dla ceny
        rmse_price = calculate_rmse(price_test, price_pred)
        mae_price = calculate_mae(price_test, price_pred)

        # Średnie wartości na metr kwadratowy
        avg_time_per_sqm = sum(time_test) / sum(sqm_test)
        avg_price_per_sqm = sum(price_test) / sum(sqm_test)

        print(f"\nWskaźniki dla usługi: {service}")
        print(f"RMSE czasu: {rmse_time:.2f}")
        print(f"MAE czasu: {mae_time:.2f}")
        print(f"RMSE ceny: {rmse_price:.2f}")
        print(f"MAE ceny: {mae_price:.2f}")
        print(f"Średni czas na m²: {avg_time_per_sqm:.2f} godziny")
        print(f"Średnia cena na m²: {avg_price_per_sqm:.2f} zł")
Leave a Comment