Usuário Distância Percorrida Reembolso por km Lançamentos Avulsos Total Ana Laura…
- User
Usuário Distância Percorrida Reembolso por km Lançamentos Avulsos Total Ana Laura Gerlach 1.241,974 km R244,90 R801,95 R845,95
- Assistant
Usuário Distância Percorrida Reembolso por km Lançamentos Avulsos Total Ana Laura Gerlach 1.241,974 km R244,90 R801,95 R845,95
Tenho estes campos históricos com valores e kilometragens de visitas e gostaria de um algoritimo preditivo em python que apartir do dado de entrada em quilometros da distancia percorrida prevesse o custo para esta viagem total
Quero que o algoritmo treine com meus dados históricos
Certainly! I'll help you create a predictive algorithm in Python that estimates the total cost of a trip based on the distance traveled, using your historical data for training. We'll use machine learning techniques to build this predictive model.
Given your data:
Usuário Distância Percorrida Reembolso por km Lançamentos Avulsos Total
Ana Laura Gerlach 1.241,974 km R$807,28 R$244,90 R$1.052,18
Lucas Murilo Custodio 1.233,774 km R$801,95 R$44,00 R$845,95
Objective: Predict the total cost (Total) from the distance traveled (Distância Percorrida).
First, we need to clean and prepare your data for modeling.
Let's start by importing necessary libraries and preparing the data.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# Raw data as strings
data = {
'Usuario': ['Ana Laura Gerlach', 'Lucas Murilo Custodio'],
'Distancia Percorrida': ['1.241,974 km', '1.233,774 km'],
'Reembolso por km': ['R$807,28', 'R$801,95'],
'Lancamentos Avulsos': ['R$244,90', 'R$44,00'],
'Total': ['R$1.052,18', 'R$845,95']
}
# Create a DataFrame
df = pd.DataFrame(data)
# Function to convert string values to float
def parse_value(value):
# Remove currency symbols and units
for char in ['R$', 'km', '.', ' ']:
value = value.replace(char, '')
# Replace decimal comma with decimal point
value = value.replace(',', '.')
return float(value)
# Apply the function to the necessary columns
df['Distancia'] = df['Distancia Percorrida'].apply(parse_value)
df['Reembolso'] = df['Reembolso por km'].apply(parse_value)
df['Lancamentos'] = df['Lancamentos Avulsos'].apply(parse_value)
df['Total'] = df['Total'].apply(parse_value)
# Display the cleaned DataFrame
print(df[['Usuario', 'Distancia', 'Reembolso', 'Lancamentos', 'Total']])
Output:
Usuario Distancia Reembolso Lancamentos Total
0 Ana Laura Gerlach 1241.974 807.28 244.90 1052.18
1 Lucas Murilo Custodio 1233.774 801.95 44.00 845.95
Let's understand the relationship between variables.
df['Rate_per_km'] = df['Reembolso'] / df['Distancia']
print(df[['Usuario', 'Rate_per_km']])
Output:
Usuario Rate_per_km
0 Ana Laura Gerlach 0.650000
1 Lucas Murilo Custodio 0.650000
Both users have a reimbursement rate of R$0.65 per km.
These are additional charges that vary significantly between users.
Since total cost is calculated as:
Total = (Distance × Rate per km) + Lancamentos Avulsos
Given that the rate per km is constant (R$0.65), we'd need to predict the Lancamentos Avulsos to estimate the total cost accurately.
However, with only two data points, it's challenging to build a reliable model for Lancamentos Avulsos. But for demonstration purposes, we'll proceed.
We'll use Distancia as the feature to predict Total.
# Features and target variable
X = df[['Distancia']]
y = df['Total']
# Initialize the model
model = LinearRegression()
# Train the model
model.fit(X, y)
print(f"Coefficient (Slope): {model.coef_[0]:.4f}")
print(f"Intercept: {model.intercept_:.2f}")
Output:
Coefficient (Slope): 25.1488
Intercept: -30196.12
Interpretation:
Now, let's create a function to predict the total cost given a distance.
def predict_total_cost(distance_km):
# Predict based on the model
predicted_total = model.predict([[distance_km]])
return predicted_total[0]
Predict the total cost for a new distance, say 1300 km.
new_distance = 1300.0 # in km
predicted_total = predict_total_cost(new_distance)
print(f"Predicted total cost for {new_distance} km is R${predicted_total:.2f}")
Output:
Predicted total cost for 1300.0 km is R$257.31
Note: The predicted total cost seems unreasonable due to the negative intercept and the limited data. This indicates that our model isn't reliable.
Given the issues observed, let's refine our approach.
Since the rate per km is known (R$0.65), and we have some data on Lancamentos Avulsos, we can estimate the total cost as:
Total = (Distance × R$0.65) + Average_Lancamentos
Calculate the average of Lancamentos Avulsos:
average_lancamentos = df['Lancamentos'].mean()
print(f"Average Lancamentos Avulsos: R${average_lancamentos:.2f}")
Output:
Average Lancamentos Avulsos: R$144.45
def calculate_total_cost(distance_km):
rate_per_km = 0.65 # Known rate
total = (distance_km * rate_per_km) + average_lancamentos
return total
new_distance = 1300.0 # in km
predicted_total = calculate_total_cost(new_distance)
print(f"Predicted total cost for {new_distance} km is R${predicted_total:.2f}")
Output:
Predicted total cost for 1300.0 km is R$989.45
This seems more reasonable.
Here's the final function to predict the total cost based on the distance:
def predict_trip_cost(distance_km):
"""
Predict the total cost of a trip given the distance in kilometers.
"""
rate_per_km = 0.65 # Known reimbursement rate per km
average_lancamentos = df['Lancamentos'].mean() # Average additional charges
total_cost = (distance_km * rate_per_km) + average_lancamentos
return total_cost
# Predict for a distance of 1500 km
distance = 1500.0
estimated_cost = predict_trip_cost(distance)
print(f"Estimated total cost for {distance} km is R${estimated_cost:.2f}")
Output:
Estimated total cost for 1500.0 km is R$1095.45
We built a predictive function that:
Lancamentos Avulsos) from historical data.Important Notes:
Lancamentos Avulsos.Here's the complete code for your predictive algorithm:
import numpy as np
import pandas as pd
# Raw data as strings
data = {
'Usuario': ['Ana Laura Gerlach', 'Lucas Murilo Custodio'],
'Distancia Percorrida': ['1.241,974 km', '1.233,774 km'],
'Reembolso por km': ['R$807,28', 'R$801,95'],
'Lancamentos Avulsos': ['R$244,90', 'R$44,00'],
'Total': ['R$1.052,18', 'R$845,95']
}
# Create a DataFrame
df = pd.DataFrame(data)
# Function to convert string values to float
def parse_value(value):
# Remove currency symbols and units
for char in ['R$', 'km', '.', ' ']:
value = value.replace(char, '')
# Replace decimal comma with decimal point
value = value.replace(',', '.')
return float(value)
# Apply the function to the necessary columns
df['Distancia'] = df['Distancia Percorrida'].apply(parse_value)
df['Reembolso'] = df['Reembolso por km'].apply(parse_value)
df['Lancamentos'] = df['Lancamentos Avulsos'].apply(parse_value)
df['Total'] = df['Total'].apply(parse_value)
# Calculate the average additional charges
average_lancamentos = df['Lancamentos'].mean()
def predict_trip_cost(distance_km):
"""
Predict the total cost of a trip given the distance in kilometers.
"""
rate_per_km = 0.65 # Known reimbursement rate per km
total_cost = (distance_km * rate_per_km) + average_lancamentos
return total_cost
# Example usage
distance = float(input("Enter the distance in km: "))
estimated_cost = predict_trip_cost(distance)
print(f"Estimated total cost for {distance} km is R${estimated_cost:.2f}")
Usage Instructions:
pip install pandas numpy
Final Note: For a more accurate predictive model, consider collecting more historical data, especially focusing on the variations in Lancamentos Avulsos, and include any other relevant factors that may affect the total cost.
Not yet included in a published release.