JuanAcevedo/Find_clinet
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
Load the saved pipeline
pipeline = jb.load('/home/j/Machine-Learning-Solutions/segmentaciongrupoclustering/models/final_pipe.joblib')
Load the dataset for cluster visualization and summary
df = pd.readcsv('../data/cleandf.csv')
Function to predict the cluster for a new customer
def predictcluster(newcustomer): newcustomerdf = pd.DataFrame([newcustomer]) cluster = pipeline.predict(newcustomer_df)[0] return cluster
Function to create a scatter plot of clusters
def plotclusters(): # Transform the data using the PCA part of the pipeline Xtransformed = pipeline.namedsteps['pca'].transform(pipeline.namedsteps['scaler'].transform(df.drop(['ID', 'Education', 'Marital_Status'], axis=1)))
# Add cluster labels to the DataFrame df['Cluster'] = pipeline.predict(df.drop(['ID', 'Education', 'Marital_Status'], axis=1))
plt.figure(figsize=(10, 6)) sns.scatterplot(x=Xtransformed[:, 0], y=Xtransformed[:, 1], hue=df['Cluster'], palette='viridis', alpha=0.6) plt.title('2D Scatter Plot of Customer Clusters') plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.legend(title='Cluster') plt.grid() plt.tight_layout()
plt.savefig('clustersplot.png') plt.close() return 'clustersplot.png'
Function to summarize averages for the selected cluster
def summarizecluster(cluster): clusterdata = df[df['Cluster'] == cluster] summary = clusterdata.mean().toframe(name='Average').reset_index() summary.columns = ['Feature', 'Average'] return summary
Gradio interface
def main(): # Input fields for new customer newcustomerinput = { 'Year_Birth': gr.inputs.Slider(minimum=1900, maximum=2023, default=1985, label='Year of Birth'), 'Income': gr.inputs.Slider(minimum=0, maximum=200000, default=45000, label='Income'), 'Kidhome': gr.inputs.Slider(minimum=0, maximum=10, default=1, label='Number of Kids at Home'), 'Teenhome': gr.inputs.Slider(minimum=0, maximum=10, default=0, label='Number of Teens at Home'), 'Recency': gr.inputs.Slider(minimum=0, maximum=100, default=20, label='Recency'), 'MntWines': gr.inputs.Slider(minimum=0, maximum=1000, default=250, label='Wine Spending'), 'MntFruits': gr.inputs.Slider(minimum=0, maximum=1000, default=30, label='Fruit Spending'), 'MntMeatProducts': gr.inputs.Slider(minimum=0, maximum=1000, default=120, label='Meat Spending'), 'MntFishProducts': gr.inputs.Slider(minimum=0, maximum=1000, default=40, label='Fish Spending'), 'MntSweetProducts': gr.inputs.Slider(minimum=0, maximum=1000, default=15, label='Sweet Spending'), 'MntGoldProds': gr.inputs.Slider(minimum=0, maximum=1000, default=10, label='Gold Spending'), 'NumDealsPurchases': gr.inputs.Slider(minimum=0, maximum=10, default=2, label='Number of Deals Purchased'), 'NumWebPurchases': gr.inputs.Slider(minimum=0, maximum=10, default=3, label='Number of Web Purchases'), 'NumCatalogPurchases': gr.inputs.Slider(minimum=0, maximum=10, default=1, label='Number of Catalog Purchases'), 'NumStorePurchases': gr.inputs.Slider(minimum=0, maximum=10, default=5, label='Number of Store Purchases'), 'NumWebVisitsMonth': gr.inputs.Slider(minimum=0, maximum=10, default=4, label='Number of Web Visits per Month'), }
# Create Gradio interface with gr.Blocks() as demo: gr.Markdown("## Customer Personality Analysis Clustering") gr.Markdown("This application allows you to predict customer clusters based on their characteristics.")
# Display the scatter plot plotimage = gr.Image(plotclusters(), label="2D Scatter Plot of Clusters")
# Dropdown for cluster selection cluster_dropdown = gr.Dropdown(choices=[0, 1], label="Select Cluster", value=0)
# Summary table for selected cluster summary_table = gr.DataFrame(label="Cluster Summary")
# Button to update summary table def updatesummary(cluster): return summarizecluster(cluster)
clusterdropdown.change(updatesummary, inputs=clusterdropdown, outputs=summarytable)
# New customer input gr.Markdown("### Predict Cluster for a New Customer") newcustomer = gr.Interface(fn=predictcluster, inputs=newcustomerinput, outputs="text")
# Display assigned cluster assigned_cluster = gr.Textbox(label="Assigned Cluster")
# Button to predict cluster for new customer def predictanddisplay(newcustomerdata): cluster = predictcluster(newcustomerdata) assignedcluster.update(value=f"This new customer belongs to cluster {cluster}") return assigned_cluster
newcustomer.submit(predictanddisplay, inputs=newcustomerinput, outputs=assignedcluster)
demo.launch()
if _name == "main_": main()
### Explanation of the Code:
1. **Loading the Model**: The saved pipeline is loaded using `joblib`.
2. **Predicting Clusters**: The `predict_cluster` function takes a new customer's data and predicts the cluster using the loaded pipeline.
3. **Plotting Clusters**: The `plot_clusters` function generates a scatter plot of the clusters using PCA-transformed data.
4. **Summarizing Clusters**: The `summarize_cluster` function calculates the average values of features for the selected cluster.
5. **Gradio Interface**: The Gradio interface is created with:
- A markdown section for explanatory text.
- An image component to display the scatter plot.
- A dropdown to select a cluster and display the summary table.
- Input sliders for new customer data.
- A textbox to display the assigned cluster for the new customer.
### Running the Application:
To run the application, simply execute the `app.py` file. Make sure you have Gradio installed in your environment. You can install it using pip if you haven't done so:
pip install gradio
This application will allow users to visualize clusters, select a cluster to see its summary, and input new customer data to predict their cluster.