-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
154 lines (117 loc) · 4.2 KB
/
app.py
File metadata and controls
154 lines (117 loc) · 4.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# ==========================================
# Web Ad Optimization using UCB - Streamlit App
# ==========================================
import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
# ==========================================
# Page Config
# ==========================================
st.set_page_config(
page_title="Web Ad Optimization (UCB)",
page_icon="📊",
layout="wide"
)
# ==========================================
# Custom Styling
# ==========================================
st.markdown("""
<style>
.main {
background-color: #0e1117;
color: white;
}
h1, h2, h3 {
color: #FFA500;
}
.stButton>button {
background-color: #FFA500;
color: black;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
# ==========================================
# Title Section
# ==========================================
st.title("📊 Web Ad Optimization using UCB")
st.markdown("### Reinforcement Learning Project")
st.write("""
This app uses the **Upper Confidence Bound (UCB)** algorithm to optimize ad selection
and maximize user clicks (CTR).
""")
# ==========================================
# Sidebar Controls
# ==========================================
st.sidebar.header("⚙️ Settings")
observations = st.sidebar.slider("Number of Users (Rounds)", 1000, 10000, 10000, step=1000)
no_of_ads = st.sidebar.slider("Number of Ads", 5, 15, 10)
uploaded_file = st.sidebar.file_uploader("Upload Dataset (CSV)", type=["csv"])
# ==========================================
# Load Dataset
# ==========================================
if uploaded_file is not None:
dataset = pd.read_csv(uploaded_file)
st.subheader("📂 Dataset Preview")
st.dataframe(dataset.head())
# ==========================================
# Run UCB Button
# ==========================================
if st.button("🚀 Run UCB Algorithm"):
ads_selected = []
numbers_of_selections = [0] * no_of_ads
sums_of_rewards = [0] * no_of_ads
total_reward = 0
# UCB Algorithm
for n in range(0, observations):
ad = 0
max_upper_bound = 0
for i in range(0, no_of_ads):
if numbers_of_selections[i] > 0:
average_reward = sums_of_rewards[i] / numbers_of_selections[i]
delta_i = math.sqrt((3/2) * math.log(n + 1) / numbers_of_selections[i])
upper_bound = average_reward + delta_i
else:
upper_bound = 1e400
if upper_bound > max_upper_bound:
max_upper_bound = upper_bound
ad = i
ads_selected.append(ad)
numbers_of_selections[ad] += 1
reward = dataset.values[n, ad]
sums_of_rewards[ad] += reward
total_reward += reward
# ==========================================
# Results Section
# ==========================================
col1, col2 = st.columns(2)
with col1:
st.metric("🎯 Total Reward", total_reward)
with col2:
best_ad = np.argmax(sums_of_rewards)
st.metric("🏆 Best Performing Ad", best_ad)
st.subheader("📊 Rewards per Ad")
rewards_df = pd.DataFrame({
"Ad": list(range(no_of_ads)),
"Total Rewards": sums_of_rewards
})
st.dataframe(rewards_df)
# ==========================================
# Visualization
# ==========================================
st.subheader("📈 Ad Selection Distribution")
fig, ax = plt.subplots()
ax.hist(ads_selected, bins=no_of_ads)
ax.set_title("Histogram of Ad Selections")
ax.set_xlabel("Ads")
ax.set_ylabel("Number of Selections")
st.pyplot(fig)
else:
st.warning("⚠️ Please upload a dataset to proceed.")
# ==========================================
# Footer
# ==========================================
st.markdown("---")
st.markdown("💡 Built using Streamlit | Reinforcement Learning (UCB)")