<jupyter_start><jupyter_text>**Mouting My google Drive to this notebook**<jupyter_code>from google.colab import drive
drive.mount('/content/drive')
import pandas as pd<jupyter_output><empty_output><jupyter_text>To get anime.csv and rating.csv data click on link :- [Anime Recommendation Dataset](https://www.kaggle.com/CooperUnion/anime-recommendations-database)<jupyter_code>anime_data=pd.read_csv('/content/drive/MyDrive/anime.csv')
rating_data=pd.read_csv('/content/drive/MyDrive/rating.csv')<jupyter_output><empty_output><jupyter_text>**Checking Data**<jupyter_code>anime_data.shape
anime_data.head()
rating_data.shape

rating_data.tail()
anime_data.info()
rating_data.info()
rating_data.describe
anime_data.describe
anime_fulldata=pd.merge(anime_data,rating_data,on='anime_id',suffixes= ['', '_user'])
anime_fulldata = anime_fulldata.rename(columns={'name': 'anime_title', 'rating_user': 'user_rating'})

anime_fulldata.head()
anime_fulldata.shape
anime_fulldata.describe<jupyter_output><empty_output><jupyter_text>**Visualising data to Understand the data better** Drpping na values<jupyter_code>combine_anime_rating = anime_fulldata.dropna(axis = 0, subset = ['anime_title'])
combine_anime_rating.head()
anime_ratingCount = (combine_anime_rating.
     groupby(by = ['anime_title'])['user_rating'].
     count().
     reset_index().rename(columns = {'rating': 'totalRatingCount'})
    [['anime_title', 'user_rating']]
    )
import seaborn as sns<jupyter_output><empty_output><jupyter_text>**Seeing top 10 anime based on user rating**<jupyter_code>top10_animerating=anime_ratingCount[['anime_title', 'user_rating']].sort_values(by = 'user_rating',ascending = False).head(10)
ax=sns.barplot(x="anime_title", y="user_rating", data=top10_animerating, palette="Dark2")
ax.set_xticklabels(ax.get_xticklabels(), fontsize=11, rotation=40, ha="right")
ax.set_title('Top 10 Anime based on rating counts',fontsize = 22)
ax.set_xlabel('Anime',fontsize = 20) 
ax.set_ylabel('User Rating count', fontsize = 20)<jupyter_output><empty_output><jupyter_text>**Top anime accoridng to member count**<jupyter_code>top10_animerating=anime_data[['name', 'members']].sort_values(by = 'members',ascending = False).head(10)
ax=sns.barplot(x="name", y="members", data=top10_animerating, palette="Dark2")
ax.set_xticklabels(ax.get_xticklabels(), fontsize=11, rotation=40, ha="right")
ax.set_title('Top 10 Anime based on members counts',fontsize = 22)
ax.set_xlabel('Anime',fontsize = 20) 
ax.set_ylabel('Members', fontsize = 20)
import matplotlib.pyplot as plt

plt.figure(figsize = (15, 7))
plt.subplot(1,2,1)
anime_fulldata['rating'].hist(bins=70)
plt.title("Rating of websites")
plt.subplot(1,2,2)
anime_fulldata['user_rating'].hist(bins=70)
plt.title("Rating of users")<jupyter_output><empty_output><jupyter_text>Plotting a pie graph to see From where these anime came<jupyter_code>import plotly.graph_objects as go
labels = anime_fulldata['type'].value_counts().index
print(labels)
values = anime_fulldata['type'].value_counts().values
colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']
fig = go.Figure(data=[go.Pie(labels=labels,
                             values=values)])
fig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,
                  marker=dict(colors=colors, line=dict(color='#000000', width=2)))

fig.update_layout(
    title={
        'text': "Medium of Streaming",
        'y':0.9,
        'x':0.5,
        'xanchor': 'center',
        'yanchor': 'top'})

fig.show()<jupyter_output>Index(['TV', 'Movie', 'OVA', 'Special', 'ONA', 'Music'], dtype='object')<jupyter_text>**Word cloud Graph more the size more the occurence**<jupyter_code>nonull_anime=anime_fulldata.copy()
nonull_anime.dropna(inplace=True)
from collections import defaultdict

all_genres = defaultdict(int)

for genres in nonull_anime['genre']:
    for genre in genres.split(','):
        all_genres[genre.strip()] += 1
        
from wordcloud import WordCloud

genres_cloud = WordCloud(width=800, height=400, background_color='white', colormap='gnuplot').generate_from_frequencies(all_genres)
plt.imshow(genres_cloud, interpolation='bilinear')
plt.axis('off')<jupyter_output><empty_output><jupyter_text>**Assigning the data to another variable so that our data won't be lost**<jupyter_code>anime_feature=anime_fulldata.copy()<jupyter_output><empty_output><jupyter_text>**as the user who haven't given any rating is defined as -1 so replacing it with a Nan value and then dropping that as it doesn't add anything to our model**<jupyter_code>import numpy as np
anime_feature["user_rating"].replace({-1: np.nan}, inplace=True)
anime_feature.head()<jupyter_output><empty_output><jupyter_text>how= takes two parameter (any and all)


*   By defualt it's any which means if any value of row or column contain Nan then drop that column and row
*   ‘all’ : If all values are NA, drop that row or column.<jupyter_code>anime_feature = anime_feature.dropna(axis = 0, how ='any') 
anime_feature.isnull().sum()
anime_feature['user_id'].value_counts()
counts = anime_feature['user_id'].value_counts()
anime_feature = anime_feature[anime_feature['user_id'].isin(counts[counts >= 200].index)]<jupyter_output><empty_output><jupyter_text>**Creating a pivod table which will help us to easily calcualte cosine similarity**<jupyter_code>anime_pivot=anime_feature.pivot_table(index='anime_title',columns='user_id',values='user_rating').fillna(0)
anime_pivot.head()
anime_fulldata.columns

from sklearn.feature_extraction.text import TfidfVectorizer


genres_str = anime_data['genre'].str.split(',').astype(str)

tfidf = TfidfVectorizer(analyzer='word', ngram_range=(1, 4), min_df=0)
tfidf_matrix = tfidf.fit_transform(genres_str)

tfidf_matrix.shape
from sklearn.metrics.pairwise import linear_kernel

cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
indices = pd.Series(anime_data.index, index=anime_data['name'])

def genre_recommendations(title, highest_rating=False, similarity=False):
    
    if highest_rating == False:
        if similarity == False:
        
            idx = indices[title]
            sim_scores = list(enumerate(cosine_sim[idx]))
            sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
            sim_scores = sim_scores[1:11]
        
            anime_indices = [i[0] for i in sim_scores]
        
            return pd.DataFrame({'Anime name': anime_data['name'].iloc[anime_indices].values,
                                 'Type': anime_data['type'].iloc[anime_indices].values})
    
        elif similarity == True:
        
            idx = indices[title]
            sim_scores = list(enumerate(cosine_sim[idx]))
            sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
            sim_scores = sim_scores[1:11]
        
            anime_indices = [i[0] for i in sim_scores]
            similarity_ = [i[1] for i in sim_scores]
        
            return pd.DataFrame({'Anime name': anime_data['name'].iloc[anime_indices].values,
                                 'Similarity': similarity_,
                                 'Type': anime_data['type'].iloc[anime_indices].values})
        
    elif highest_rating == True:
        if similarity == False:
        
            idx = indices[title]
            sim_scores = list(enumerate(cosine_sim[idx]))
            sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
            sim_scores = sim_scores[1:11]
        
            anime_indices = [i[0] for i in sim_scores]
        
            result_df = pd.DataFrame({'Anime name': anime_data['name'].iloc[anime_indices].values,
                                 'Type': anime_data['type'].iloc[anime_indices].values,
                                 'Rating': anime_data['rating'].iloc[anime_indices].values})
            
            return result_df.sort_values('Rating', ascending=False)
    
        elif similarity == True:
        
            idx = indices[title]
            sim_scores = list(enumerate(cosine_sim[idx]))
            sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
            sim_scores = sim_scores[1:11]
        
            anime_indices = [i[0] for i in sim_scores]
            similarity_ = [i[1] for i in sim_scores]
        
            result_df = pd.DataFrame({'Anime name': anime_data['name'].iloc[anime_indices].values,
                                 'Similarity': similarity_,
                                 'Type': anime_data['type'].iloc[anime_indices].values,
                                 'Rating': anime_data['rating'].iloc[anime_indices].values})
            
            return result_df.sort_values('Rating', ascending=False)<jupyter_output><empty_output><jupyter_text>This model it not deployed yet but you can name the an<jupyter_code>genre_recommendations('One Piece', highest_rating=True, similarity=False)<jupyter_output><empty_output>