1. Perform competitor analysis of any two airlines using social media.
2. An analysis of Twitter posts on National Education Policy and visualization.
3. Social Network Data Analysis using NetworkX API:
   i) Create a random social network graph  ii) Find influencer node iii) Calculate different network measures such as degree centrality, betweenness centrality, etc.
4. Perform Amazon product review analytics.
5. Competitor analysis of any two educational institutes using social media.
6. Perform Google Trend analysis on popular healthcare / AI product related topics.
7. Competitor analysis of any two hospitals using social media.
8. Collect data from Twitter / Google Reviews and perform Exploratory Data Analysis (EDA) and visualization for any business / brand.
9. Perform Google Trend analysis on popular agricultural related topics.
10. Perform negative tweets analysis on any product or service.
11. An analysis of Twitter posts on Coronavirus and visualization.
12. Analyze and compare the popularity of coaching classes.
13. Airline negative tweet sentiment analysis and visualization using tweets dataset for any two airlines and perform competitor analysis.
14. Competitor analysis of any two mobile brands using social media.
15. An analysis of Twitter posts on any hospital / hotel / service industry and visualization.
16. Perform sentiment analysis on any product or service.
17. Competitor analysis of Patanjali and HUL using social media.
18. Hashtag popularity analysis and sentiment analysis using IPL 2021 dataset.
19. Analyze competitors using social media for famous jewellery brands.

CODE: https://colab.research.google.com/drive/19zIjXzkO_Y_S-o1vWyztvGIi36kDAQO7?usp=sharing

--------------SETUP----------------
!pip install vaderSentiment wordcloud textblob pytrends networkx requests -q

import requests, time, re, warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from wordcloud import WordCloud
from textblob import TextBlob
from collections import Counter
import networkx as nx
from pytrends.request import TrendReq
warnings.filterwarnings('ignore')

# ── SHARED HELPER FUNCTIONS ──
HEADERS = {'User-Agent': 'Mozilla/5.0'}
sia = SentimentIntensityAnalyzer()
STOP = {'the','a','is','in','and','of','to','for','this','was','i','it',
        'my','on','at','with','s','be','are','have','has','that','as','by'}

def scrape_reddit(query, label, pages=2):
    posts, after = [], ''
    for _ in range(pages):
        url = f'https://www.reddit.com/search.json?q={query}&sort=new&limit=100'
        if after: url += f'&after={after}'
        try:
            r = requests.get(url, headers=HEADERS, timeout=15).json()
            after = r['data'].get('after', '')
            for c in r['data']['children']:
                d = c['data']
                text = d.get('title','') + ' ' + d.get('selftext','')
                score = sia.polarity_scores(text)['compound']
                posts.append({
                    'label': label, 'text': text,
                    'upvotes': d.get('score', 0),
                    'comments': d.get('num_comments', 0),
                    'compound': score,
                    'sentiment': 'Positive' if score>=0.05 else ('Negative' if score<=-0.05 else 'Neutral'),
                    'date': pd.to_datetime(d.get('created_utc', 0), unit='s')
                })
            time.sleep(2)
        except Exception as e: print(f'Error: {e}')
    return posts

def wordcloud_plot(ax, texts, title, cmap='Blues'):
    corpus = ' '.join([re.sub(r'[^a-zA-Z\s]','',str(t).lower()) for t in texts])
    if corpus.strip():
        wc = WordCloud(width=400, height=250, background_color='white',
                       colormap=cmap, stopwords=STOP, max_words=50)
        wc.generate(corpus)
        ax.imshow(wc, interpolation='bilinear')
    ax.axis('off'); ax.set_title(title, fontweight='bold')

def sentiment_pie(ax, df, col='sentiment', title='Sentiment'):
    vc = df[col].value_counts()
    colors = [{'Positive':'#2ecc71','Neutral':'#f39c12','Negative':'#e74c3c'}.get(s,'gray') for s in vc.index]
    ax.pie(vc.values, labels=vc.index, autopct='%1.0f%%', colors=colors,
           wedgeprops={'edgecolor':'white','linewidth':1.5})
    ax.set_title(title, fontweight='bold')

print(' Setup complete! Now run any experiment below.')

--------------------------------------------------------------------------------------
1
---------------------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)
n = 100
months = pd.date_range('2024-01', periods=n, freq='W')

indigo = pd.DataFrame({
    'date': months,
    'airline': 'IndiGo',
    'likes': np.random.randint(200, 1500, n),
    'retweets': np.random.randint(50, 400, n),
    'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.55,0.25,0.20])
})

airindia = pd.DataFrame({
    'date': months,
    'airline': 'Air India',
    'likes': np.random.randint(100, 900, n),
    'retweets': np.random.randint(30, 250, n),
    'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.40,0.30,0.30])
})

df = pd.concat([indigo, airindia])

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Airlines Social Media: IndiGo vs Air India', fontsize=13, fontweight='bold')

# Avg Likes
avg = df.groupby('airline')['likes'].mean()
axes[0].bar(avg.index, avg.values, color=['#1877F2','#E4002B'])
axes[0].set_title('Avg Likes per Post'); axes[0].set_ylabel('Likes')

# Sentiment
for i, airline in enumerate(['IndiGo','Air India']):
    sub = df[df['airline']==airline]['sentiment'].value_counts()
    axes[1].bar([x + i*0.35 for x in range(3)], [sub.get(s,0) for s in ['Positive','Neutral','Negative']], 0.35, label=airline)
axes[1].set_xticks([0.175,1.175,2.175]); axes[1].set_xticklabels(['Positive','Neutral','Negative'])
axes[1].set_title('Sentiment Distribution'); axes[1].legend()

# Retweets
avg_rt = df.groupby('airline')['retweets'].mean()
axes[2].barh(avg_rt.index, avg_rt.values, color=['#1877F2','#E4002B'])
axes[2].set_title('Avg Retweets per Post')

plt.tight_layout(); plt.show()

print("\n--- Summary Stats ---")
print(df.groupby('airline')[['likes','retweets']].mean().round(1))

# Display first few rows of dataset
print(df.head())

# Display random sample rows
print(df.sample(10))

# Display full dataset in tabular form (Jupyter/Colab)
from IPython.display import display
display(df)

# Dataset info
print("\nShape of dataset:", df.shape)
print("\nColumns:", df.columns.tolist())

# Last few rows
print(df.tail())

# Download dataset as CSV file
df.to_csv("airlines_social_media_dataset.csv", index=False)
---------------------------
2
-----------------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter

np.random.seed(7)
n = 200
sentiments = np.random.choice(['Positive','Neutral','Negative'], n, p=[0.45,0.30,0.25])
hashtags_pool = ['#NEP2020','#EducationPolicy','#NewEducation','#NEPIndia','#DigitalLearning']
hashtags = [np.random.choice(hashtags_pool) for _ in range(n)]
dates = pd.date_range('2024-01', periods=n, freq='D')
likes = np.random.randint(10, 500, n)

df = pd.DataFrame({'date': dates, 'sentiment': sentiments, 'hashtag': hashtags, 'likes': likes})

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Twitter Analysis: National Education Policy (NEP)', fontsize=13, fontweight='bold')

# Sentiment pie
s = df['sentiment'].value_counts()
axes[0].pie(s.values, labels=s.index, autopct='%1.1f%%', colors=['#4CAF50','#FFC107','#F44336'])
axes[0].set_title('Sentiment Share')

# Hashtag frequency
h = Counter(df['hashtag'])
axes[1].barh(list(h.keys()), list(h.values()), color='#1877F2')
axes[1].set_title('Top Hashtags')

# Weekly tweet volume
df['week'] = df['date'].dt.to_period('W')
wv = df.groupby('week').size()
axes[2].plot(range(len(wv)), wv.values, marker='o', color='#9C27B0')
axes[2].set_title('Weekly Tweet Volume'); axes[2].set_xlabel('Week')

plt.tight_layout(); plt.show()

print("\n--- Sentiment Counts ---")
print(df['sentiment'].value_counts())
print("\n--- Avg Likes by Sentiment ---")
print(df.groupby('sentiment')['likes'].mean().round(1))
------------------------------------------------------------------
3
-------------------------------------------------------------------------
# Build random social network
G = nx.barabasi_albert_graph(n=100, m=2, seed=42)

deg  = nx.degree_centrality(G)
betw = nx.betweenness_centrality(G)
clos = nx.closeness_centrality(G)
pr   = nx.pagerank(G)

top_node = max(deg, key=deg.get)
print(f'Top Influencer Node: {top_node} | Degree Centrality: {deg[top_node]:.3f}')

fig, axes = plt.subplots(1, 3, figsize=(16, 5))
fig.suptitle('EXP 3: Social Network Analysis', fontsize=13, fontweight='bold')

# Network graph
pos = nx.spring_layout(G, seed=42)
sizes = [deg[n]*2000+30 for n in G.nodes()]
colors = [deg[n] for n in G.nodes()]
nx.draw_networkx_edges(G, pos, alpha=0.2, ax=axes[0])
nx.draw_networkx_nodes(G, pos, node_size=sizes, node_color=colors, cmap='YlOrRd', ax=axes[0])
nx.draw_networkx_labels(G, pos, {top_node: f'★{top_node}'}, font_size=9, ax=axes[0])
axes[0].set_title('Network Graph (node=influence)'); axes[0].axis('off')

# Degree distribution
degrees = [d for n,d in G.degree()]
axes[1].hist(degrees, bins=15, color='steelblue', edgecolor='white')
axes[1].set_title('Degree Distribution')
axes[1].set_xlabel('Degree'); axes[1].set_ylabel('Count')

# Top 10 by degree centrality
top10 = sorted(deg.items(), key=lambda x: x[1], reverse=True)[:10]
nodes, vals = zip(*top10)
axes[2].barh([f'Node {n}' for n in nodes][::-1], list(vals)[::-1], color='coral')
axes[2].set_title('Top 10 Influencer Nodes')

plt.tight_layout(); plt.savefig('exp3.png', dpi=120); plt.show()

print(f'Nodes: {G.number_of_nodes()} | Edges: {G.number_of_edges()}')
print(f'Density: {nx.density(G):.4f} | Avg Clustering: {nx.average_clustering(G):.4f}')
print(f'Avg Shortest Path: {nx.average_shortest_path_length(G):.4f}')
----------------------------------------------------------------------------------------------------
4
-----------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(42)
n = 300
products = ['Echo Dot','Fire TV','Kindle','Ring Doorbell','Alexa App']
df = pd.DataFrame({
    'product': np.random.choice(products, n),
    'rating': np.random.choice([1,2,3,4,5], n, p=[0.08,0.07,0.15,0.30,0.40]),
    'helpful_votes': np.random.randint(0, 200, n),
    'review_length': np.random.randint(20, 500, n),
    'verified': np.random.choice([True, False], n, p=[0.75,0.25])
})
df['sentiment'] = df['rating'].map({1:'Negative',2:'Negative',3:'Neutral',4:'Positive',5:'Positive'})

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Amazon Product Review Analytics', fontsize=13, fontweight='bold')

df['rating'].value_counts().sort_index().plot(kind='bar', ax=axes[0], color='#FF9900', edgecolor='white')
axes[0].set_title('Rating Distribution'); axes[0].set_xlabel('Stars'); axes[0].set_ylabel('Count')

df.groupby('product')['rating'].mean().sort_values().plot(kind='barh', ax=axes[1], color='#146EB4')
axes[1].set_title('Avg Rating by Product'); axes[1].set_xlabel('Avg Rating')

s = df['sentiment'].value_counts()
axes[2].pie(s.values, labels=s.index, autopct='%1.1f%%', colors=['#4CAF50','#FFC107','#F44336'])
axes[2].set_title('Overall Sentiment')

plt.tight_layout(); plt.show()
print("\n--- Rating Stats ---")
print(df.groupby('product')['rating'].describe().round(2))
print("\n--- Verified vs Avg Rating ---")
print(df.groupby('verified')['rating'].mean().round(2))
---------------------------------------------------------------------------
5
------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(3)
n = 80

def gen(name, like_hi, rt_hi):
    return pd.DataFrame({
        'institute': name,
        'likes': np.random.randint(50, like_hi, n),
        'retweets': np.random.randint(10, rt_hi, n),
        'replies': np.random.randint(5, 80, n),
        'content': np.random.choice(['Research','Admission','Event','Achievement','Alumni'], n),
        'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.65,0.25,0.10])
    })

iitd = gen('IIT Delhi', 1200, 300)
iitb = gen('IIT Bombay', 1000, 250)
df = pd.concat([iitd, iitb])

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Education Social Media: IIT Delhi vs IIT Bombay', fontsize=13, fontweight='bold')

# Avg metrics
metrics = ['likes','retweets','replies']
x = np.arange(len(metrics)); w = 0.35
axes[0].bar(x, iitd[metrics].mean(), w, label='IIT Delhi', color='#1565C0')
axes[0].bar(x+w, iitb[metrics].mean(), w, label='IIT Bombay', color='#6A1B9A')
axes[0].set_xticks(x+w/2); axes[0].set_xticklabels(metrics)
axes[0].set_title('Avg Engagement'); axes[0].legend()

# Content type
ct = df.groupby(['institute','content'])['likes'].mean().unstack()
ct.T.plot(kind='bar', ax=axes[1], color=['#1565C0','#6A1B9A'])
axes[1].set_title('Likes by Content Type'); axes[1].tick_params(axis='x', rotation=20)

# Engagement rate scatter
axes[2].scatter(iitd['likes'], iitd['retweets'], alpha=0.5, label='IIT Delhi', color='#1565C0')
axes[2].scatter(iitb['likes'], iitb['retweets'], alpha=0.5, label='IIT Bombay', color='#6A1B9A')
axes[2].set_xlabel('Likes'); axes[2].set_ylabel('Retweets')
axes[2].set_title('Likes vs Retweets'); axes[2].legend()

plt.tight_layout(); plt.show()
print("\n--- Avg Stats ---")
print(df.groupby('institute')[['likes','retweets','replies']].mean().round(1))
------------------------------------------------------------------------------------------------
6
------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(10)
weeks = pd.date_range('2023-01', periods=52, freq='W')
topics = ['ChatGPT','Telemedicine','AI Diagnosis','Mental Health','Wearable Health']
base = [80,45,30,60,40]

data = {}
for t, b in zip(topics, base):
    trend = b + np.cumsum(np.random.randn(52)*3)
    trend = np.clip(trend, 5, 100)
    data[t] = trend

df = pd.DataFrame(data, index=weeks)

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Google Trends: Healthcare & AI Topics (2023)', fontsize=13, fontweight='bold')

df.plot(ax=axes[0], linewidth=1.5)
axes[0].set_title('Weekly Trend Index'); axes[0].set_ylabel('Interest (0-100)')
axes[0].legend(fontsize=7); axes[0].tick_params(axis='x', rotation=20)

avg = df.mean().sort_values(ascending=False)
avg.plot(kind='bar', ax=axes[1], color='#0097A7', edgecolor='white')
axes[1].set_title('Avg Interest Score'); axes[1].set_ylabel('Avg Score')
axes[1].tick_params(axis='x', rotation=25)

df['month'] = df.index.month
monthly = df.drop(columns='month').groupby(df.index.month).mean()
monthly[['ChatGPT','Telemedicine','Mental Health']].plot(ax=axes[2], marker='o', linewidth=1.5)
axes[2].set_title('Monthly Trend (Key Topics)'); axes[2].set_xlabel('Month')

plt.tight_layout(); plt.show()
print("\n--- Avg Trend Scores ---")
print(df.drop(columns='month').mean().round(1).sort_values(ascending=False))

------------------------------------------------------------------------------------------
7
----------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)
n = 80

def gen(name, like_range, pos_p):
    return pd.DataFrame({
        'hospital': name,
        'likes': np.random.randint(*like_range, n),
        'comments': np.random.randint(10, 200, n),
        'shares': np.random.randint(5, 100, n),
        'post_type': np.random.choice(['Health Tip','Patient Story','Event','Awareness'], n),
        'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[pos_p, 0.25, 1-pos_p-0.25])
    })

apollo = gen('Apollo', (300,2000), 0.60)
fortis = gen('Fortis', (200,1500), 0.50)
df = pd.concat([apollo, fortis])

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Hospital Social Media: Apollo vs Fortis', fontsize=13, fontweight='bold')

# Engagement
metrics = ['likes','comments','shares']
x = np.arange(len(metrics)); w = 0.35
a_mean = apollo[metrics].mean()
f_mean = fortis[metrics].mean()
axes[0].bar(x, a_mean, w, label='Apollo', color='#0D47A1')
axes[0].bar(x+w, f_mean, w, label='Fortis', color='#B71C1C')
axes[0].set_xticks(x+w/2); axes[0].set_xticklabels(metrics)
axes[0].set_title('Avg Engagement'); axes[0].legend()

# Post types
pt = df.groupby(['hospital','post_type'])['likes'].mean().unstack()
pt.T.plot(kind='bar', ax=axes[1], color=['#0D47A1','#B71C1C'])
axes[1].set_title('Likes by Post Type'); axes[1].tick_params(axis='x', rotation=20)

# Sentiment
for i, (hosp, color) in enumerate([('Apollo','#0D47A1'),('Fortis','#B71C1C')]):
    s = df[df['hospital']==hosp]['sentiment'].value_counts()
    axes[2].bar([x+i*0.35 for x in range(3)], [s.get(k,0) for k in ['Positive','Neutral','Negative']], 0.35, label=hosp, color=color)
axes[2].set_xticks([0.175,1.175,2.175]); axes[2].set_xticklabels(['Pos','Neu','Neg'])
axes[2].set_title('Sentiment'); axes[2].legend()

plt.tight_layout(); plt.show()
print("\n--- Mean Engagement ---")
print(df.groupby('hospital')[['likes','comments','shares']].mean().round(1))
--------------------------------------------------------------------------------------------
8
------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(21)
n = 250
df = pd.DataFrame({
    'rating': np.random.choice([1,2,3,4,5], n, p=[0.07,0.08,0.15,0.35,0.35]),
    'likes': np.random.randint(0, 500, n),
    'retweets': np.random.randint(0, 150, n),
    'review_len': np.random.randint(15, 400, n),
    'source': np.random.choice(['Twitter','Google Reviews'], n, p=[0.55,0.45]),
    'category': np.random.choice(['Coffee','Service','Ambience','Price','App'], n)
})
df['sentiment'] = df['rating'].map({1:'Neg',2:'Neg',3:'Neu',4:'Pos',5:'Pos'})

fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle('EDA: Starbucks Reviews & Tweets', fontsize=13, fontweight='bold')

df['rating'].value_counts().sort_index().plot(kind='bar', ax=axes[0,0], color='#00704A')
axes[0,0].set_title('Rating Distribution')

df.groupby('category')['likes'].mean().sort_values().plot(kind='barh', ax=axes[0,1], color='#1DA1F2')
axes[0,1].set_title('Avg Likes by Category')

axes[1,0].hist(df['review_len'], bins=20, color='#CBA258', edgecolor='white')
axes[1,0].set_title('Review Length Distribution'); axes[1,0].set_xlabel('Characters')

s = df.groupby(['source','sentiment']).size().unstack(fill_value=0)
s.plot(kind='bar', ax=axes[1,1], color=['#4CAF50','#FFC107','#F44336'])
axes[1,1].set_title('Sentiment by Source'); axes[1,1].tick_params(axis='x', rotation=0)

plt.tight_layout(); plt.show()
print("\n--- Correlation ---")
print(df[['rating','likes','retweets','review_len']].corr().round(2))
------------------------------------------------------------------------------------
9
--------------
# Google Trends Alternative (No 429 Error)
# Simulated dataset for Agricultural Topics

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)

dates = pd.date_range("2024-01-01", periods=12, freq="M")

df = pd.DataFrame({
    'Date': dates,
    'Organic Farming': np.random.randint(45, 100, 12),
    'Drip Irrigation': np.random.randint(40, 95, 12),
    'Hydroponics': np.random.randint(30, 85, 12),
    'Fertilizers': np.random.randint(55, 100, 12),
    'Crop Insurance': np.random.randint(35, 90, 12)
})

df.set_index('Date', inplace=True)

fig, axes = plt.subplots(1,2, figsize=(14,5))
fig.suptitle("Google Trend Analysis: Agriculture Topics", fontsize=14, fontweight='bold')

# Trend Over Time
df.plot(ax=axes[0], linewidth=2)
axes[0].set_title("Trend Over Time")
axes[0].set_ylabel("Popularity Score")

# Average Trend Score
avg = df.mean().sort_values()

axes[1].barh(avg.index, avg.values, color='green')
axes[1].set_title("Average Popularity")

plt.tight_layout()
plt.show()

print("\n--- Average Scores ---")
print(avg.round(2))

print("\nMost Popular Topic:", avg.idxmax())
-----------------------------------------------------------------
10
--------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(33)
n = 200
issues = ['Buffering','Price Hike','Content Removed','App Crash','Bad Subtitles','No Offline','Ads']
df = pd.DataFrame({
    'issue': np.random.choice(issues, n, p=[0.22,0.20,0.18,0.15,0.10,0.08,0.07]),
    'retweets': np.random.randint(0, 300, n),
    'likes': np.random.randint(0, 200, n),
    'date': pd.date_range('2024-01', periods=n, freq='D')
})
df['week'] = df['date'].dt.isocalendar().week

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Negative Tweets Analysis: Netflix', fontsize=13, fontweight='bold')

ic = df['issue'].value_counts()
axes[0].barh(ic.index, ic.values, color='#E50914')
axes[0].set_title('Top Complaint Categories'); axes[0].set_xlabel('Tweet Count')

df.groupby('issue')['retweets'].mean().sort_values().plot(kind='barh', ax=axes[1], color='#831010')
axes[1].set_title('Avg Retweets per Issue')

weekly = df.groupby('week').size()
axes[2].plot(weekly.index, weekly.values, color='#E50914', marker='o', linewidth=2)
axes[2].set_title('Negative Tweets per Week'); axes[2].set_xlabel('Week No.')

plt.tight_layout(); plt.show()
print("\n--- Issue Frequency ---")
print(df['issue'].value_counts())
print("\n--- Avg Engagement per Issue ---")
print(df.groupby('issue')[['likes','retweets']].mean().round(1))
-----------------------------------------------------------------------------------------
11 G20
-------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(7)
n = 300
tags = ['#G20India','#G20Summit','#G20Delhi','#ClimateG20','#G20Economy']
countries = ['India','USA','UK','China','Germany','Brazil','Japan']
df = pd.DataFrame({
    'hashtag': np.random.choice(tags, n, p=[0.30,0.25,0.20,0.15,0.10]),
    'country': np.random.choice(countries, n),
    'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.50,0.30,0.20]),
    'likes': np.random.randint(10, 1000, n),
    'date': pd.date_range('2023-09-01', periods=n, freq='H')
})

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Twitter Analysis: G20 Summit', fontsize=13, fontweight='bold')

df['hashtag'].value_counts().plot(kind='bar', ax=axes[0], color='#FF6B35', edgecolor='white')
axes[0].set_title('Hashtag Frequency'); axes[0].tick_params(axis='x', rotation=25)

s = df['sentiment'].value_counts()
axes[1].pie(s.values, labels=s.index, autopct='%1.1f%%', colors=['#4CAF50','#FFC107','#F44336'])
axes[1].set_title('Sentiment Share')

df.groupby('country')['likes'].mean().sort_values().plot(kind='barh', ax=axes[2], color='#1565C0')
axes[2].set_title('Avg Likes by Country')

plt.tight_layout(); plt.show()
print("\n--- Tweet Counts ---")
print(df['hashtag'].value_counts())
print("\n--- Sentiment by Country ---")
print(pd.crosstab(df['country'], df['sentiment']))
-------------------------------------------------------------------------------
11 corona
---------------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(7)
n = 300
tags = ['#COVID19','#Coronavirus','#StaySafe','#Vaccination','#Pandemic']
countries = ['India','USA','UK','China','Germany','Brazil','Japan']

df = pd.DataFrame({
    'hashtag': np.random.choice(tags, n, p=[0.30,0.25,0.20,0.15,0.10]),
    'country': np.random.choice(countries, n),
    'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.45,0.30,0.25]),
    'likes': np.random.randint(10, 1000, n),
    'date': pd.date_range('2021-01-01', periods=n, freq='H')
})

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Twitter Analysis: Coronavirus Posts', fontsize=13, fontweight='bold')

# Hashtag Frequency
df['hashtag'].value_counts().plot(kind='bar', ax=axes[0], color='#FF5722', edgecolor='white')
axes[0].set_title('Hashtag Frequency')
axes[0].tick_params(axis='x', rotation=25)

# Sentiment Share
s = df['sentiment'].value_counts()
axes[1].pie(s.values, labels=s.index, autopct='%1.1f%%',
            colors=['#4CAF50','#FFC107','#F44336'])
axes[1].set_title('Sentiment Share')

# Avg Likes by Country
df.groupby('country')['likes'].mean().sort_values().plot(kind='barh', ax=axes[2], color='#1976D2')
axes[2].set_title('Avg Likes by Country')

plt.tight_layout()
plt.show()

print("\n--- Tweet Counts ---")
print(df['hashtag'].value_counts())

print("\n--- Sentiment by Country ---")
print(pd.crosstab(df['country'], df['sentiment']))

----------------------------------------------------------------------
12 local business
---------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(55)
n = 200
businesses = ['Cafe Mocha','Spice Garden','Burger Hub','Pizza Palace','Sushi Corner']
hours = list(range(8, 22))
df = pd.DataFrame({
    'business': np.random.choice(businesses, n),
    'rating': np.round(np.random.uniform(2.5, 5.0, n), 1),
    'reviews': np.random.randint(10, 500, n),
    'hour': np.random.choice(hours, n, p=[0.02,0.03,0.05,0.10,0.12,0.12,0.12,0.10,0.08,0.08,0.07,0.05,0.04,0.02]),
    'category': np.random.choice(['Dine-in','Takeaway','Delivery'], n)
})

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Local Business Popularity Analysis', fontsize=13, fontweight='bold')

df.groupby('business')[['rating','reviews']].mean().plot(kind='bar', ax=axes[0], color=['#FF7043','#42A5F5'], edgecolor='white')
axes[0].set_title('Avg Rating & Reviews'); axes[0].tick_params(axis='x', rotation=25)

peak = df['hour'].value_counts().sort_index()
axes[1].bar(peak.index, peak.values, color='#66BB6A')
axes[1].set_title('Peak Review Hours'); axes[1].set_xlabel('Hour of Day')

cat = df.groupby(['business','category']).size().unstack(fill_value=0)
cat.plot(kind='bar', stacked=True, ax=axes[2], colormap='Set2')
axes[2].set_title('Order Type by Business'); axes[2].tick_params(axis='x', rotation=25)

plt.tight_layout(); plt.show()
print("\n--- Business Summary ---")
print(df.groupby('business')[['rating','reviews']].mean().round(2))

--------------------------------------------------------------------------------------
12 classes
---------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(55)
n = 200

classes = ['Aakash Institute','Allen Career','FIITJEE','Resonance','Career Point']
hours = list(range(8, 22))

df = pd.DataFrame({
    'coaching_class': np.random.choice(classes, n),
    'rating': np.round(np.random.uniform(2.5, 5.0, n), 1),
    'reviews': np.random.randint(10, 500, n),
    'hour': np.random.choice(hours, n, 
                             p=[0.02,0.03,0.05,0.10,0.12,0.12,0.12,0.10,0.08,0.08,0.07,0.05,0.04,0.02]),
    'course': np.random.choice(['JEE','NEET','Boards'], n)
})

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Coaching Classes Popularity Analysis', fontsize=13, fontweight='bold')

# Avg Rating & Reviews
df.groupby('coaching_class')[['rating','reviews']].mean().plot(
    kind='bar', ax=axes[0], color=['#FF7043','#42A5F5'], edgecolor='white'
)
axes[0].set_title('Avg Rating & Reviews')
axes[0].tick_params(axis='x', rotation=25)

# Peak Inquiry Hours
peak = df['hour'].value_counts().sort_index()
axes[1].bar(peak.index, peak.values, color='#66BB6A')
axes[1].set_title('Peak Inquiry Hours')
axes[1].set_xlabel('Hour of Day')

# Course Preference
cat = df.groupby(['coaching_class','course']).size().unstack(fill_value=0)
cat.plot(kind='bar', stacked=True, ax=axes[2], colormap='Set2')
axes[2].set_title('Course Popularity by Class')
axes[2].tick_params(axis='x', rotation=25)

plt.tight_layout()
plt.show()

print("\n--- Coaching Classes Summary ---")
print(df.groupby('coaching_class')[['rating','reviews']].mean().round(2))
------------------------------------------------------------------------------------------
13
-------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt
np.random.seed(42)
n = 250

dates = pd.date_range('2024-01-01', periods=n, freq='D')

indigo = pd.DataFrame({
    'date': dates,
    'airline': 'IndiGo',
    'tweet_id': range(1, n+1),
    'negative_score': np.random.randint(20, 95, n),
    'issue': np.random.choice(
        ['Delay','Baggage','Refund','Staff Behavior','Cancellation'],
        n, p=[0.35,0.20,0.20,0.15,0.10]
    ),
    'likes': np.random.randint(5, 400, n)
})

airindia = pd.DataFrame({
    'date': dates,
    'airline': 'Air India',
    'tweet_id': range(n+1, 2*n+1),
    'negative_score': np.random.randint(25, 100, n),
    'issue': np.random.choice(
        ['Delay','Baggage','Refund','Staff Behavior','Cancellation'],
        n, p=[0.30,0.25,0.20,0.15,0.10]
    ),
    'likes': np.random.randint(5, 400, n)
})

df = pd.concat([indigo, airindia])
fig, axes = plt.subplots(1, 3, figsize=(14,4))
fig.suptitle('Negative Tweet Sentiment Analysis: IndiGo vs Air India',
             fontsize=13, fontweight='bold')

# Avg Negative Score
avg = df.groupby('airline')['negative_score'].mean()
axes[0].bar(avg.index, avg.values, color=['#1976D2','#E53935'])
axes[0].set_title('Avg Negative Sentiment Score')
axes[0].set_ylabel('Score')

# Common Complaint Issues
issues = pd.crosstab(df['issue'], df['airline'])
issues.plot(kind='bar', ax=axes[1], colormap='Set2')
axes[1].set_title('Complaint Categories')
axes[1].tick_params(axis='x', rotation=25)

# Negative Trend Over Time
trend = df.groupby(['date','airline'])['negative_score'].mean().unstack()
trend.plot(ax=axes[2], linewidth=2)
axes[2].set_title('Negative Sentiment Trend')
axes[2].set_ylabel('Score')

plt.tight_layout()
plt.show()

print("\n--- Competitor Summary ---")
print(df.groupby('airline')[['negative_score','likes']].mean().round(2))

print("\n--- Complaint Distribution ---")
print(pd.crosstab(df['airline'], df['issue']))

------------------------------------------------------------------------------------------
14
-------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
n = 100

def gen(brand, like_range, pos_p):
    return pd.DataFrame({
        'brand': brand,
        'likes': np.random.randint(*like_range, n),
        'retweets': np.random.randint(20, 500, n),
        'impressions': np.random.randint(1000, 20000, n),
        'topic': np.random.choice(['Launch','Feature','Price','Support','Offer'], n),
        'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[pos_p, 0.25, round(1-pos_p-0.25,2)])
    })

samsung = gen('Samsung', (500,3000), 0.55)
oneplus = gen('OnePlus', (300,2000), 0.62)
df = pd.concat([samsung, oneplus])
df['eng_rate'] = (df['likes'] + df['retweets']) / df['impressions'] * 100

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Mobile Brands Social Media: Samsung vs OnePlus', fontsize=13, fontweight='bold')

# Sentiment
colors_map = {'Positive':'#4CAF50','Neutral':'#FFC107','Negative':'#F44336'}
for i, brand in enumerate(['Samsung','OnePlus']):
    s = df[df['brand']==brand]['sentiment'].value_counts()
    axes[0].bar([x+i*0.35 for x in range(3)], [s.get(k,0) for k in ['Positive','Neutral','Negative']], 0.35, label=brand)
axes[0].set_xticks([0.175,1.175,2.175]); axes[0].set_xticklabels(['Pos','Neu','Neg'])
axes[0].set_title('Sentiment'); axes[0].legend()

# Topic avg likes
tp = df.groupby(['brand','topic'])['likes'].mean().unstack()
tp.T.plot(kind='bar', ax=axes[1], color=['#1565C0','#C62828'])
axes[1].set_title('Avg Likes by Topic'); axes[1].tick_params(axis='x', rotation=20)

# Engagement rate
axes[2].boxplot([df[df['brand']=='Samsung']['eng_rate'], df[df['brand']=='OnePlus']['eng_rate']],
                labels=['Samsung','OnePlus'], patch_artist=True,
                boxprops=dict(facecolor='#BBDEFB'), medianprops=dict(color='red'))
axes[2].set_title('Engagement Rate (%)'); axes[2].set_ylabel('%')

plt.tight_layout(); plt.show()
print("\n--- Engagement Rate ---")
print(df.groupby('brand')['eng_rate'].describe().round(2))

------------------------------------------------------------------------------
15
-----------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(17)
n = 250
topics = ['Patient Care','Appointment','Emergency','Staff','Research','Facilities','OPD Wait']
df = pd.DataFrame({
    'topic': np.random.choice(topics, n, p=[0.20,0.18,0.15,0.12,0.12,0.12,0.11]),
    'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[0.40,0.30,0.30]),
    'likes': np.random.randint(0, 400, n),
    'retweets': np.random.randint(0, 120, n),
    'date': pd.date_range('2024-01', periods=n, freq='D')
})
df['week'] = df['date'].dt.isocalendar().week

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Twitter Analysis: AIIMS Hospital', fontsize=13, fontweight='bold')

df['topic'].value_counts().plot(kind='bar', ax=axes[0], color='#1565C0', edgecolor='white')
axes[0].set_title('Tweet Topics'); axes[0].tick_params(axis='x', rotation=30)

sent = df.groupby(['topic','sentiment']).size().unstack(fill_value=0)
sent.plot(kind='bar', ax=axes[1], color=['#F44336','#FFC107','#4CAF50'])
axes[1].set_title('Sentiment by Topic'); axes[1].tick_params(axis='x', rotation=30)
axes[1].legend(fontsize=7)

wk = df.groupby(['week','sentiment']).size().unstack(fill_value=0)
wk.plot(ax=axes[2], linewidth=1.5, marker='o')
axes[2].set_title('Weekly Sentiment Trend'); axes[2].set_xlabel('Week')

plt.tight_layout(); plt.show()
print("\n--- Avg Engagement by Topic ---")
print(df.groupby('topic')[['likes','retweets']].mean().round(1))

-----------------------------------------------------------------------------------
16
---------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt

np.random.seed(99)
n = 300
df = pd.DataFrame({
    'rating': np.random.choice([1,2,3,4,5], n, p=[0.10,0.10,0.15,0.30,0.35]),
    'likes': np.random.randint(0, 300, n),
    'city': np.random.choice(['Mumbai','Delhi','Bangalore','Hyderabad','Chennai'], n),
    'cuisine': np.random.choice(['Indian','Chinese','Italian','Fast Food','Continental'], n),
    'date': pd.date_range('2024-01', periods=n, freq='D')
})
df['sentiment'] = df['rating'].map({1:'Very Negative',2:'Negative',3:'Neutral',4:'Positive',5:'Very Positive'})
df['month'] = df['date'].dt.month

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
fig.suptitle('Sentiment Analysis: Zomato Reviews', fontsize=13, fontweight='bold')

s = df['sentiment'].value_counts()
colors = ['#B71C1C','#E53935','#FFC107','#66BB6A','#2E7D32']
axes[0].bar(s.index, s.values, color=colors[:len(s)])
axes[0].set_title('Sentiment Distribution'); axes[0].tick_params(axis='x', rotation=20)

city_sent = df.groupby('city')['rating'].mean().sort_values()
city_sent.plot(kind='barh', ax=axes[1], color='#E53935')
axes[1].set_title('Avg Rating by City'); axes[1].set_xlabel('Avg Rating')

monthly = df.groupby(['month','sentiment']).size().unstack(fill_value=0)
if 'Positive' in monthly.columns and 'Negative' in monthly.columns:
    monthly[['Very Positive','Positive','Negative','Very Negative']].plot(ax=axes[2], linewidth=1.5)
axes[2].set_title('Monthly Sentiment Trend'); axes[2].set_xlabel('Month')
axes[2].legend(fontsize=7)

plt.tight_layout(); plt.show()
print("\n--- Sentiment Counts ---")
print(df['sentiment'].value_counts())
print("\n--- Avg Rating by Cuisine ---")
print(df.groupby('cuisine')['rating'].mean().round(2).sort_values(ascending=False))

----------------------------------------------------------------------------------------------
17
--------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(9)
n = 100

def gen(brand, like_range, pos_p, products):
    return pd.DataFrame({
        'brand': brand,
        'likes': np.random.randint(*like_range, n),
        'shares': np.random.randint(10, 300, n),
        'comments': np.random.randint(5, 150, n),
        'product': np.random.choice(products, n),
        'sentiment': np.random.choice(['Positive','Neutral','Negative'], n, p=[pos_p, 0.25, round(1-pos_p-0.25,2)])
    })

pat = gen('Patanjali', (100,800), 0.50, ['Dant Kanti','Chyawanprash','Ghee','Atta','Hair Oil'])
hul = gen('HUL', (400,3000), 0.60, ['Dove','Surf Excel','Lux','Knorr','Pond\'s'])
df = pd.concat([pat, hul])
df['total_eng'] = df['likes'] + df['shares'] + df['comments']

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle('Brand Social Media: Patanjali vs HUL', fontsize=13, fontweight='bold')

# Total engagement
avg = df.groupby('brand')['total_eng'].mean()
axes[0].bar(avg.index, avg.values, color=['#FF6F00','#1565C0'])
axes[0].set_title('Avg Total Engagement'); axes[0].set_ylabel('Likes+Shares+Comments')

# Sentiment
for i, (brand, color) in enumerate([('Patanjali','#FF6F00'),('HUL','#1565C0')]):
    s = df[df['brand']==brand]['sentiment'].value_counts()
    axes[1].bar([x+i*0.35 for x in range(3)], [s.get(k,0) for k in ['Positive','Neutral','Negative']], 0.35, label=brand, color=color)
axes[1].set_xticks([0.175,1.175,2.175]); axes[1].set_xticklabels(['Pos','Neu','Neg'])
axes[1].set_title('Sentiment'); axes[1].legend()

# Top product likes
pp = df.groupby(['brand','product'])['likes'].mean().reset_index()
for brand, color in [('Patanjali','#FF6F00'),('HUL','#1565C0')]:
    sub = pp[pp['brand']==brand].sort_values('likes', ascending=False)
    axes[2].barh(sub['product'], sub['likes'], color=color, alpha=0.8, label=brand)
axes[2].set_title('Avg Likes by Product'); axes[2].legend()

plt.tight_layout(); plt.show()
print("\n--- Brand Summary ---")
print(df.groupby('brand')[['likes','shares','comments','total_eng']].mean().round(1))

----------------------------------------------------------------------------------------------------
18(download and upload dataset)
https://drive.google.com/file/d/1pTfK6lI1rn5pi18kmYQg1vvDXW6eCJG7/view?usp=sharing
---------------------------------------------------------------------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
from textblob import TextBlob
import ast
import csv

df = pd.read_csv(
    "/content/IPL_2021_tweets.csv",
    engine='python',          # safer parser
    on_bad_lines='skip',      # skip corrupted rows
    quoting=csv.QUOTE_MINIMAL,
    encoding='utf-8'
)

print("Dataset Loaded Successfully")
print("Rows:", df.shape[0], " Columns:", df.shape[1])
df = df[['date','text','hashtags','user_followers']].dropna()

# Convert hashtag string list into actual list
df['hashtags'] = df['hashtags'].apply(lambda x: ast.literal_eval(x) if str(x).startswith('[') else [])
hash_df = df.explode('hashtags')
def get_sentiment(text):
    score = TextBlob(str(text)).sentiment.polarity
    if score > 0:
        return 'Positive'
    elif score < 0:
        return 'Negative'
    else:
        return 'Neutral'

df['sentiment'] = df['text'].apply(get_sentiment)

fig, axes = plt.subplots(1,3, figsize=(15,4))
fig.suptitle("IPL 2021 Twitter Analysis", fontsize=14, fontweight='bold')

# Top hashtags
top_tags = hash_df['hashtags'].value_counts().head(10)
axes[0].bar(top_tags.index, top_tags.values, color='orange')
axes[0].set_title("Top Hashtags")
axes[0].tick_params(axis='x', rotation=45)

# Sentiment Pie
sent = df['sentiment'].value_counts()
axes[1].pie(sent.values, labels=sent.index, autopct='%1.1f%%')
axes[1].set_title("Sentiment Analysis")

# Avg followers by hashtag
popular = hash_df.groupby('hashtags')['user_followers'].mean().sort_values(ascending=False).head(10)
axes[2].barh(popular.index, popular.values, color='green')
axes[2].set_title("Influential Hashtags")

plt.tight_layout()
plt.show()

print("\nTop Hashtags:\n", top_tags)
print("\nSentiment:\n", sent)
----------------------------------------------------------------------------------
19
---------------
import pandas as pd, numpy as np, matplotlib.pyplot as plt
np.random.seed(101)
n = 250

brands = ['Tanishq', 'Kalyan Jewellers', 'Malabar Gold']

df = pd.DataFrame({
    'brand': np.random.choice(brands, n),
    'likes': np.random.randint(500, 8000, n),
    'comments': np.random.randint(50, 1200, n),
    'shares': np.random.randint(20, 900, n),
    'sentiment': np.random.choice(
        ['Positive', 'Neutral', 'Negative'],
        n,
        p=[0.60, 0.25, 0.15]
    ),
    'platform': np.random.choice(
        ['Instagram', 'Facebook', 'Twitter'],
        n
    )
})

fig, axes = plt.subplots(1, 3, figsize=(14,4))
fig.suptitle('Social Media Competitor Analysis: Jewellery Brands',
             fontsize=13, fontweight='bold')

# Avg Likes
avg_likes = df.groupby('brand')['likes'].mean()
axes[0].bar(avg_likes.index, avg_likes.values,
            color=['#D4AF37','#C0C0C0','#CD7F32'])
axes[0].set_title('Average Likes')
axes[0].set_ylabel('Likes')

# Sentiment Distribution
sent = pd.crosstab(df['brand'], df['sentiment'])
sent.plot(kind='bar', stacked=True, ax=axes[1], colormap='Set2')
axes[1].set_title('Brand Sentiment')
axes[1].tick_params(axis='x', rotation=20)

# Avg Shares
avg_share = df.groupby('brand')['shares'].mean()
axes[2].barh(avg_share.index, avg_share.values, color='#8E44AD')
axes[2].set_title('Average Shares')

plt.tight_layout()
plt.show()
print("\n--- Brand Engagement Summary ---")
print(df.groupby('brand')[['likes','comments','shares']].mean().round(1))

print("\n--- Sentiment Analysis ---")
print(pd.crosstab(df['brand'], df['sentiment']))


SUCCESSFULLY INSTALLED Seaborn 1.1.2 v2.53.5
||||||||||||||||||||||||||||||||||||||||||||||

ADS


||||||||||||||||||||||||||||||||||||||||||||||
#EDA
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")

print("mean", df['Fare'].mean(numeric_only= True))

print("med", df['Fare'].median(numeric_only= True))

print("mode", df['PassengerId'].mode().iloc[0])

print("skew", df['Fare'].skew(numeric_only= True))

print("variance:", df['Fare'].var(numeric_only=True))
print("std:", df['Fare'].std(numeric_only=True))

print("range", df['Fare'].max(numeric_only=True)-df['Fare'].min(numeric_only=True))

print("Q1", df['Fare'].quantile(0.25))
print("Q2", df['Fare'].quantile(0.50))
print("Q3", df['Fare'].quantile(0.75))

print('IQR',df['Fare'].quantile(0.75)-df['Fare'].quantile(0.25))

print("kurtosis", df['Fare'].kurt(numeric_only=True))

#----------------------------------------------------
#HANDLING OUTLIERS
Q1 = df['Fare'].quantile(0.25)
Q3 = df['Fare'].quantile(0.75)
IQR = Q3 - Q1

df = df[(df['Fare'] >= Q1 - 1.5*IQR) & (df['Fare'] <= Q3 + 1.5*IQR)]

#----------------------------------------------------
#MISSING VALUES
# see missing values
df.isnull().sum()
df = df.fillna(df.mean(numeric_only=True))    #  sabse best shortcut
# Drop rows with missing values
ndf=df.dropna() #stored the new dataset after drop in ndf variable
df['Embarked'].fillna(df['Fare'].mean(numeric_only=True), inplace=True)   #to fill nan values with some value(not needed coz apan drop kar rhe sab nan rows ko)
# shape of graph
df.shape   # df (original) use kiya h yaha
ndf.shape  # ndf ko use kiya h yaha so rows are dropped (final output ndf ka hai )

#----------------------------------------------------
#CORRELATION
# Identify correlation between total_bill and tip
df[['Fare','Pclass']].corr()

#----------------------------------------------------
#PLOTS
import seaborn as sns

sns.histplot(df['Age'])
sns.histplot(x=df["Sex"],y=df["Fare"])
sns.boxplot(df["Fare"])
sns.heatmap(df.corr(numeric_only=True), annot=True)
sns.scatterplot(x=df['Age'], y=df['Fare'])
sns.violinplot(x=df['Sex'],y=df['Fare'])

#----------------------------------------------------
#LOGISTIC REG MODEL
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

X = df[['Pclass','Age','SibSp','Parch','Fare']]  # isme humesha x me normal numerical values daalo
y = df['Survived']   # y me 0, 1 wale daal    if incase nai hoga 0,1 then apply as  ---->
# from sklearn.preprocessing import LabelEncoder -----> le = LabelEncoder() ---->  y = le.fit_transform(df['species'])

X = X.fillna(X.mean())

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2)

# Model
model = LogisticRegression()
model.fit(X_train, y_train)

# Prediction
y_pred = model.predict(X_test)

# Metrics
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:\n", cm)

# Heatmap
sns.heatmap(cm, annot=True)
plt.show()

#----------------------------------------------------
#LINEAR REG MODEL
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Features (X) and target (y)
X = df[['Pclass','Age','SibSp','Parch']]
y= df['Fare']  

X = X.fillna(X.mean())

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Model
model = LinearRegression()
model.fit(X_train, y_train)

# Prediction
y_pred = model.predict(X_test)

# Evaluation
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)

print("MSE:", mse)
print("RMSE:", rmse)

#----------------------------------------------------
#KMEANS
from sklearn.cluster import KMeans
import pandas as pd

df = pd.read_csv('Name.csv')

# Use only features (NO Class column)
X = df.drop('Class', axis=1).fillna(0)

# Create model
model = KMeans(n_clusters=3)

# Predict clusters
df['cluster'] = model.fit_predict(X)

# See cluster distribution
print(df['cluster'].value_counts())

#------------------------------------------------------
#TIME SERIES
df = pd.read_csv('Name.csv')

df['Month']= pd.to_datetime(df['Month'])      #converts into yyyy-mm-dd

plt.plot(df['Month'],df['Passengers'])
plt.xlabel('Month')
plt.show()

df['MA'] = df['Passengers'].rolling(3).mean()     #normal moving avg
print(df)

# Forecast next 5 values
forecast = [round(df['Passengers'].mean(),2)] * 5
print(forecast)

#------------------------------------------------------
#ARIMA
from statsmodels.tsa.arima.model import ARIMA

model = ARIMA(df['Passengers'], order=(1,1,1))
model_fit = model.fit()
forecast = model_fit.forecast(5)
print(forecast)

#------------------------------------------------------
#SMOTE
import pandas as pd
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load data
df = pd.read_csv('creditcard.csv')
# Identify class imbalance
df['Class'].value_counts()

from imblearn.over_sampling import SMOTE


X = df.drop('Class', axis=1).fillna(0)
y = df['Class'].fillna(0)

X_res, y_res = SMOTE().fit_resample(X, y)

#Logistic code write here
#---------------------------------------------------
Installing collected packages: seaborn
SUCCESSFULLY INSTALLED Seaborn 1.1.2 v2.53.5
||||||||||||||||||||||||||||||||||||||||||||||
Note: you may need to restart the kernel to use updated packages.