Golyass commited on
Commit
afc1a2b
·
1 Parent(s): afb4152

Upload recomender_system_cluster_based.py

Browse files
Files changed (1) hide show
  1. recomender_system_cluster_based.py +301 -0
recomender_system_cluster_based.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """recomender2.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1WTIRumzmdqNSB2Z2dIv3r2LkSN5CdoU5
8
+ """
9
+
10
+ from google.colab import drive
11
+ drive.mount('/content/drive')
12
+
13
+ import os
14
+ os.environ['KAGGLE_CONFIG_DIR'] = "/content/drive/MyDrive/kaggle"
15
+
16
+ # Commented out IPython magic to ensure Python compatibility.
17
+ # %ls
18
+
19
+ import pandas as pd
20
+ import numpy as np
21
+ from matplotlib import pyplot as plt
22
+ from sklearn.cluster import KMeans
23
+ from sklearn.metrics import silhouette_score
24
+ from sklearn.preprocessing import scale, StandardScaler, normalize
25
+ from yellowbrick.cluster import KElbowVisualizer
26
+ from sklearn.manifold import TSNE
27
+ import seaborn as sns
28
+ import random
29
+
30
+ df1=pd.read_csv('/content/drive/MyDrive/kaggle/ratings.csv')
31
+ df2=pd.read_csv('/content/drive/MyDrive/kaggle/movies_metadata.csv')
32
+ df3=pd.read_csv('/content/drive/MyDrive/kaggle/ratings_small.csv')
33
+
34
+ df2
35
+
36
+ df2.shape
37
+
38
+ df2.columns
39
+
40
+ df2.info()
41
+
42
+ df2.isna().sum()
43
+
44
+ data=df2[['revenue','runtime','vote_average','vote_count','title']]
45
+
46
+ data
47
+
48
+ data=data.fillna(0)
49
+
50
+ #scale the data
51
+
52
+ scaler = StandardScaler()
53
+ data_scaled = scaler.fit_transform(data.iloc[:, :-1])
54
+ data_scaled
55
+
56
+ inertia = []
57
+ silhouette_scores = []
58
+ k_values = range(2, 10)
59
+ for k in k_values:
60
+ kmeans = KMeans(n_clusters=k, random_state=3,n_init=4)
61
+ kmeans.fit(data_scaled)
62
+ #center=kmeans.cluster_centers
63
+ inertia.append(kmeans.inertia_)
64
+ silhouette_scores.append(silhouette_score(data_scaled, kmeans.labels_))
65
+ print(silhouette_scores)
66
+
67
+ plt.figure(figsize=(12, 4))
68
+ plt.subplot(1, 2, 1)
69
+ plt.plot(k_values, inertia, marker='o')
70
+ plt.xlabel('Number of clusters (k)')
71
+ plt.ylabel('Inertia')
72
+ plt.title('Inertia vs. Number of Clusters')
73
+
74
+ plt.subplot(1, 2, 2)
75
+ plt.plot(k_values, silhouette_scores, marker='o')
76
+ plt.xlabel('Number of clusters (k)')
77
+ plt.ylabel('Silhouette Score')
78
+ plt.title('Silhouette Score vs. Number of Clusters')
79
+
80
+ plt.tight_layout()
81
+ plt.show()
82
+
83
+ model = KMeans(n_init=8)
84
+ visualiser = KElbowVisualizer(model, k=(2,12))
85
+ visualiser.fit(data_scaled)
86
+ visualiser.show()
87
+
88
+ kmeans_mod = KMeans(n_clusters=5, n_init=10)
89
+ kmeans_mod.fit(data_scaled)
90
+
91
+ labels =kmeans_mod.fit_predict(data_scaled)
92
+ data['cluster']=labels
93
+ data=data[['revenue','runtime','vote_average','vote_count','cluster','title']]
94
+ data
95
+
96
+ data['cluster'].value_counts()
97
+
98
+ tsne = TSNE(n_components=2, random_state=42)
99
+ X_tsne = tsne.fit_transform(data_scaled)
100
+
101
+ plt.figure(figsize=(8,6))
102
+ plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=kmeans.labels_, cmap='viridis')
103
+ plt.xlabel('t-SNE Dimension 1')
104
+ plt.ylabel('t-SNE Dimension 2')
105
+ plt.title('Clustering Results with K-Means (k=5)'.format(5))
106
+ plt.colorbar(label='Cluster')
107
+ plt.show()
108
+
109
+ cdata=data[['cluster','title']]
110
+ cdata
111
+
112
+ cluster0=[]
113
+ cluster1=[]
114
+ cluster2=[]
115
+ cluster3=[]
116
+ cluster4=[]
117
+
118
+ filmname=''
119
+ for i in cdata.iloc():
120
+ if i[0]==0:
121
+ filmname=''
122
+ filmname=i[1]
123
+ #print(filmname)
124
+ cluster0.append(filmname)
125
+ elif i[0]==1:
126
+ filmname=''
127
+ filmname=i[1]
128
+ cluster1.append(filmname)
129
+ elif i[0]==2:
130
+ filmname=''
131
+ filmname=i[1]
132
+ cluster2.append(filmname)
133
+ if i[0]==3:
134
+ filmname=''
135
+ filmname=i[1]
136
+ cluster3.append(filmname)
137
+ if i[0]==4:
138
+ filmname=''
139
+ filmname=i[1]
140
+ cluster4.append(filmname)
141
+ print(len(cluster0))
142
+ print(len(cluster1))
143
+ print(len(cluster2))
144
+ print(len(cluster3))
145
+ print(len(cluster4))
146
+
147
+
148
+ print((cluster0))
149
+ print((cluster1))
150
+ print((cluster2))
151
+ print((cluster3))
152
+ print((cluster4))
153
+
154
+ data=data.iloc[:, :-1]
155
+ data
156
+
157
+ from sklearn.decomposition import PCA
158
+ pca_mod = PCA(n_components=3)
159
+ # fit the PCA model to the (scaled) features
160
+ pca_mod.fit(data)
161
+
162
+ # plot the cumulative variance explained across all the components
163
+ # start the explained variance at 0
164
+ exp_variance = np.insert(pca_mod.explained_variance_ratio_, 0, 0)
165
+
166
+ # plot the explained variance
167
+ figure = plt.figure(figsize=(8, 5))
168
+
169
+ plt.plot(np.cumsum(exp_variance))
170
+ plt.xticks(range(0,6))
171
+ plt.xlabel("Number of principal components (PCs)", size=13)
172
+ plt.ylabel("% cumulative variance explained", size=13)
173
+ plt.title("Cumulative variance explained", size=15)
174
+
175
+ plt.show()
176
+ np.cumsum(exp_variance)
177
+
178
+ pca_mod = PCA(n_components=3)
179
+
180
+ data_pca = pd.DataFrame(data=pca_mod.fit_transform(data_scaled),
181
+ columns=['PC1', 'PC2', 'PC3'])
182
+
183
+ # view data frame of PCs
184
+ data_pca.head()
185
+
186
+ # combine data for plotting
187
+ data.reset_index(drop=True, inplace=True)
188
+ data_pca.reset_index(drop=True, inplace=True)
189
+ plot_data = pd.concat([data_pca, data['cluster']], axis=1)
190
+
191
+ # visualise the clusters by plotting the PCAs in a scatter/pair plot,
192
+ # with points colored by cluster membership
193
+ sns.pairplot(data=plot_data,
194
+ hue='cluster',
195
+ palette='Set1',
196
+ corner=True)
197
+
198
+ cluster=[cluster0,cluster1,cluster2,cluster3,cluster4]
199
+
200
+ def recomender(input1,input2,input3):
201
+
202
+ encod_input1=[]
203
+ encod_input2=[]
204
+ encod_input3=[]
205
+
206
+
207
+ encod_input1.append(cluster0.count(input1))
208
+ encod_input1.append(cluster1.count(input1))
209
+ encod_input1.append(cluster2.count(input1))
210
+ encod_input1.append(cluster3.count(input1))
211
+ encod_input1.append(cluster4.count(input1))
212
+
213
+
214
+
215
+ encod_input2.append(cluster0.count(input2))
216
+ encod_input2.append(cluster1.count(input2))
217
+ encod_input2.append(cluster2.count(input2))
218
+ encod_input2.append(cluster3.count(input2))
219
+ encod_input2.append(cluster4.count(input2))
220
+
221
+
222
+
223
+ encod_input3.append(cluster0.count(input3))
224
+ encod_input3.append(cluster1.count(input3))
225
+ encod_input3.append(cluster2.count(input3))
226
+ encod_input3.append(cluster3.count(input3))
227
+ encod_input3.append(cluster4.count(input3))
228
+
229
+
230
+ return encod_input1,encod_input2,encod_input3
231
+
232
+
233
+ def recomender2(a):
234
+ s1=0
235
+ s2=0
236
+ s3=0
237
+ for i in range(0,5):
238
+ if a[0][i]!=0:
239
+ s1=i
240
+ #print(f'The first film is in cluster {i+1}')
241
+ if a[1][i]!=0:
242
+ s2=i
243
+ #print(f'The second film is in cluster {i+1}')
244
+ if a[2][i]!=0:
245
+ s3=i
246
+ #print(f'The third film is in cluster {i+1}')
247
+ return s1, s2, s3
248
+
249
+
250
+
251
+ def recom(b):
252
+ if b[0]==b[1]==b[2]:
253
+ return random.choice(cluster[b[1]])
254
+ if b[0]==b[1]!=b[2]:
255
+ return random.choice(cluster[b[1]])
256
+ if b[0]!=b[1]==b[2]:
257
+ return random.choice(cluster[b[1]])
258
+ if b[0]==b[2]!=b[1]:
259
+ return random.choice(cluster[b[2]])
260
+ if b[0]!=b[2]!=b[1]:
261
+ return random.choice(cluster[b[0]])
262
+
263
+ def original_recom(input1,input2,input3):
264
+ return recom(recomender2(recomender(input1,input2,input3)))
265
+
266
+ a=recomender('The Ballroom','Scooby-Doo! and the Reluctant Werewolf','Last Summer')
267
+ a
268
+
269
+ b=recomender2(a)
270
+ print(b)
271
+
272
+ recom(b)
273
+
274
+ cluster4.count("Trial")
275
+
276
+ !pip install gradio
277
+
278
+ import numpy as np
279
+ import gradio as gr
280
+
281
+
282
+ def original_recom(input1,input2,input3):
283
+ return recom(recomender2(recomender(input1,input2,input3)))
284
+ with gr.Blocks() as demo:
285
+ gr.Markdown("Flip text or image files using this demo.")
286
+
287
+ input1 = gr.Textbox(placeholder='first film name...')
288
+
289
+ input2 = gr.Textbox(placeholder='second film name...')
290
+
291
+ input3 = gr.Textbox(placeholder='third film name...')
292
+
293
+ text_output=gr.Textbox( )
294
+
295
+
296
+ text_button = gr.Button("Submit")
297
+ text_button.click(original_recom, inputs=[input1,input2,input3], outputs=text_output)
298
+ demo.launch()
299
+
300
+ cluster4.count('The Sex of Angels')
301
+