lenawilli commited on
Commit
1eb2368
·
verified ·
1 Parent(s): bc450d3

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +54 -39
src/streamlit_app.py CHANGED
@@ -1,40 +1,55 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
- import streamlit as st
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import numpy as np
5
+ import tensorflow as tf
6
+ import joblib
7
+
8
+ @st.cache_resource
9
+ def load_model():
10
+ return tf.keras.models.load_model("recommender_model.keras")
11
+
12
+ @st.cache_data
13
+ def load_assets():
14
+ df_movies = pd.read_csv("movies.csv")
15
+ user_map, movie_map = joblib.load("encodings.pkl")
16
+ return df_movies, user_map, movie_map
17
+
18
+ model = load_model()
19
+ movies_df, user2idx, movie2idx = load_assets()
20
+ reverse_movie_map = {v: k for k, v in movie2idx.items()}
21
+
22
+ st.title("TensorFlow Movie Recommender")
23
+ st.write("Select some movies you've liked to get recommendations:")
24
+
25
+ movie_titles = movies_df.set_index("movieId")["title"].to_dict()
26
+ movie_choices = [movie_titles[mid] for mid in movie2idx.keys() if mid in movie_titles]
27
+ selected_titles = st.multiselect("Liked movies", sorted(movie_choices))
28
+
29
+ user_ratings = {}
30
+ for title in selected_titles:
31
+ movie_id = [k for k, v in movie_titles.items() if v == title][0]
32
+ user_ratings[movie_id] = 5.0
33
+
34
+ if st.button("Get Recommendations"):
35
+ if not user_ratings:
36
+ st.warning("Please select at least one movie.")
37
+ else:
38
+ liked_indices = [movie2idx[m] for m in user_ratings if m in movie2idx]
39
+ avg_embedding = tf.reduce_mean(model.layers[2](tf.constant(liked_indices)), axis=0, keepdims=True)
40
+ all_movie_indices = tf.range(len(movie2idx))
41
+ movie_embeddings = model.layers[3](all_movie_indices)
42
+ scores = tf.reduce_sum(avg_embedding * movie_embeddings, axis=1).numpy()
43
+ top_indices = np.argsort(scores)[::-1]
44
+
45
+ recommended = []
46
+ for idx in top_indices:
47
+ mid = reverse_movie_map[idx]
48
+ if mid not in user_ratings and mid in movie_titles:
49
+ recommended.append((movie_titles[mid], scores[idx]))
50
+ if len(recommended) >= 10:
51
+ break
52
+
53
+ st.subheader("Top Recommendations")
54
+ for title, score in recommended:
55
+ st.write(f"{title} — Score: {score:.3f}")