0% found this document useful (0 votes)
20 views

Python Code

Uploaded by

Monica H N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Code

Uploaded by

Monica H N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Code:

import pandas as pd

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression

from sklearn.metrics import accuracy_score

# Step 1: Create a sample dataset

np.random.seed(42)

num_customers = 1000

data = {

'customer_id': range(1, num_customers + 1),

'age': np.random.randint(18, 70, size=num_customers),

'tenure': np.random.randint(1, 25, size=num_customers), # in months

'churned': np.random.choice([0, 1], size=num_customers) # 0 = didn't churn, 1 = churned

df = pd.DataFrame(data)

# Step 2: Data aggregation to find average age and tenure based on churn status

agg_data = df.groupby('churned').agg({'age': 'mean', 'tenure': 'mean'}).reset_index()

agg_data.columns = ['Churned', 'Average Age', 'Average Tenure']

print("Aggregated Data:\n", agg_data)

# Step 3: Split the dataset into features and target variable

X = df[['age', 'tenure']] # Features

y = df['churned'] # Target variable

# Step 4: Split the data into training (80%) and testing (20%) sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)


print(f"Training set size: {X_train.shape[0]}")

print(f"Testing set size: {X_test.shape[0]}")

# Step 5: Initialize and train the Logistic Regression model

model = LogisticRegression()

model.fit(X_train, y_train)

# Step 6: Make predictions on the test set

y_pred = model.predict(X_test)

# Step 7: Evaluate the model's performance using accuracy

accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy of the model: {accuracy:.2f}")

You might also like