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 "Kilometers" da distancia percorrida prevesse o custo "Total_Gasto" para esta viagem total
Quero que o algoritmo treine com meus dados históricos
Certainly! Below is a Python script that creates a predictive model using your historical data. The model will predict the Total_Gasto (total cost) based on the input Kilometers (distance traveled). We'll use a simple linear regression from the scikit-learn library.
python
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import numpy as np
# Historical data
data = {
'Kilometers': [13.2033, 2.8974, 10.9340, 12.5229],
'Valor_Transporte': [0.0, 0.0, 0.0, 0.0],
'Valor_Avulsos': [24.2, 12.1, 12.1, 0.0],
'Total_Gasto': [24.2, 12.1, 12.1, 0.0]
}
# Create DataFrame
df = pd.DataFrame(data)
# Prepare the data for training
# Since 'Valor_Transporte' is always zero, it doesn't affect the model.
# We'll use 'Kilometers' as the feature to predict 'Total_Gasto'.
X = df[['Kilometers']]
y = df['Total_Gasto']
# Initialize and train the linear regression model
model = LinearRegression()
model.fit(X, y)
# Print out the model coefficients
print(f"Model coefficient (slope): {model.coef_[0]:.4f}")
print(f"Model intercept: {model.intercept_:.4f}")
# Function to predict 'Total_Gasto' given 'Kilometers'
def predict_total_gasto(kilometers):
predicted_gasto = model.predict(np.array([[kilometers]]))
return predicted_gasto[0]
# Example usage:
# Predict the total cost for a trip of 15 kilometers
test_kilometers = 15.0
predicted_cost = predict_total_gasto(test_kilometers)
print(f"Predicted Total_Gasto for {test_kilometers} km: {predicted_cost:.2f}")
# Visualize the data and the model
plt.scatter(X, y, color='blue', label='Historical Data')
plt.plot(X, model.predict(X), color='red', label='Regression Line')
plt.xlabel('Kilometers')
plt.ylabel('Total_Gasto')
plt.title('Total_Gasto Prediction Based on Kilometers')
plt.legend()
plt.show()
Explanation:
Data Preparation: We create a pandas DataFrame with your historical data. Since Valor_Transporte is always zero, it doesn't contribute to the model, so we focus on Kilometers as the input feature.
Model Training: We use LinearRegression from scikit-learn to train a model that fits the relationship between Kilometers and Total_Gasto.
Prediction Function: A function predict_total_gasto is defined to predict the total cost for any given distance.
Visualization: The script plots the historical data points and the regression line to visualize how well the model fits the data.
Note: Since the dataset is quite small (only 4 data points), the predictive power of the model may be limited. In practice, having more historical data will improve the accuracy of the predictions.
Output:
code
Model coefficient (slope): -1.9622
Model intercept: 46.3853
Predicted Total_Gasto for 15.0 km: 17.95
This means that, according to the model, a trip of 15 kilometers is predicted to cost approximately 17.95 units.
Important Considerations:
Data Quality: Ensure that your historical data accurately represents the typical relationship between distance traveled and total cost.
Assumptions: Linear regression assumes a linear relationship between the input and output. If the relationship is not linear, consider using polynomial regression or other nonlinear models.
Model Validation: With more data, you should split your dataset into training and testing sets to evaluate the model's performance on unseen data.
Next Steps:
Collect More Data: Gather more historical records to improve the model's reliability.
Feature Engineering: If there are other factors affecting Total_Gasto, such as time of day, traffic conditions, or vehicle type, including these as additional features could improve the model.
Model Selection: Experiment with other regression algorithms (e.g., Random Forest, Support Vector Regression) to see if they perform better.
Let me know if you need further assistance or modifications to the model!