zhq0 commited on
Commit
e80ea63
Β·
verified Β·
1 Parent(s): b68636d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -51
app.py CHANGED
@@ -1,69 +1,99 @@
1
  import gradio as gr
 
2
  import numpy as np
3
- import matplotlib.pyplot as plt
4
- import seaborn as sns
5
 
6
- def simulate_scoring(total_qs, known_qs, guess_qs, marks_correct, marks_negative, num_options, trials=10000):
7
- # 1. Calculate fixed score from known questions
8
- base_score = known_qs * marks_correct
9
-
10
- # 2. Simulate guesses
11
- # Probability of getting a guess right
12
- p_correct = 1 / num_options
13
-
14
- # Each trial: number of correct guesses follows a Binomial Distribution
15
- correct_guesses = np.random.binomial(guess_qs, p_correct, trials)
16
- wrong_guesses = guess_qs - correct_guesses
17
-
18
- # 3. Calculate total scores for all trials
19
- guess_scores = (correct_guesses * marks_correct) - (wrong_guesses * marks_negative)
20
- total_scores = base_score + guess_scores
21
 
22
- # 4. Statistical Analysis
23
- mean_score = np.mean(total_scores)
24
- prob_negative_gain = np.mean(total_scores < base_score) * 100
25
- prob_total_negative = np.mean(total_scores < 0) * 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # 5. Plotting
28
- plt.figure(figsize=(10, 6))
29
- sns.histplot(total_scores, kde=True, color="skyblue", bins=30)
30
- plt.axvline(base_score, color='red', linestyle='--', label=f'Score without guessing ({base_score})')
31
- plt.axvline(mean_score, color='green', linestyle='-', label=f'Expected Mean Score ({mean_score:.2f})')
32
 
33
- plt.title(f"Score Distribution across {trials:,} Simulations")
34
- plt.xlabel("Total Score")
35
- plt.ylabel("Frequency")
36
- plt.legend()
37
 
38
- return plt.gcf(), f"Expected Average Score: {mean_score:.2f}\nProbability that guessing HURTS your score: {prob_negative_gain:.2f}%\nProbability of an overall negative score: {prob_total_negative:.2f}%"
 
 
 
 
 
 
39
 
40
- # Gradio UI Setup
41
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
42
- gr.Markdown("# 🎯 Negative Marking Probability Simulator")
43
- gr.Markdown("Visualize how guessing affects your final score using Monte Carlo simulations.")
44
 
45
  with gr.Row():
46
- with gr.Column():
47
- t_qs = gr.Number(label="Total Questions", value=100)
48
- k_qs = gr.Slider(0, 100, label="Questions You Know (100% Correct)", value=50)
49
- g_qs = gr.Slider(0, 100, label="Questions to Guess", value=20)
50
-
 
 
 
 
 
51
  with gr.Row():
52
- m_pos = gr.Number(label="Marks for Correct", value=4)
53
- m_neg = gr.Number(label="Marks for Wrong (as positive value)", value=1)
54
 
55
- opts = gr.Radio([2, 3, 4, 5], label="Number of Options per Question", value=4)
56
- btn = gr.Button("Simulate Results", variant="primary")
57
 
58
- with gr.Column():
59
- plot_output = gr.Plot(label="Score Distribution")
60
- stats_output = gr.Textbox(label="Statistical Summary")
 
61
 
62
- btn.click(
63
- fn=simulate_scoring,
64
- inputs=[t_qs, k_qs, g_qs, m_pos, m_neg, opts],
65
- outputs=[plot_output, stats_output]
66
- )
67
 
68
  if __name__ == "__main__":
69
  demo.launch()
 
1
  import gradio as gr
2
+ import pandas as pd
3
  import numpy as np
 
 
4
 
5
+ # Probability mapping based on student's elimination strategy
6
+ PROB_MAP = {
7
+ "Known (100%)": 1.0,
8
+ "2 Options Left (50/50)": 0.5,
9
+ "3 Options Left (33%)": 0.33,
10
+ "Blind Guess (25%)": 0.25,
11
+ "Skip (0%)": 0.0
12
+ }
13
+
14
+ def run_simulation(df, marks_pos, marks_neg):
15
+ results = []
16
+ total_score = 0
17
+ correct_count = 0
18
+ wrong_count = 0
19
+ skipped_count = 0
20
 
21
+ # Logic for a single simulation run (One "Trial")
22
+ for _, row in df.iterrows():
23
+ status = row["Confidence / Strategy"]
24
+ prob = PROB_MAP[status]
25
+
26
+ if prob == 0:
27
+ outcome = "skipped"
28
+ skipped_count += 1
29
+ else:
30
+ # Roll the dice based on probability
31
+ is_correct = np.random.random() < prob
32
+ if is_correct:
33
+ outcome = "correct"
34
+ total_score += marks_pos
35
+ correct_count += 1
36
+ else:
37
+ outcome = "wrong"
38
+ total_score -= marks_neg
39
+ wrong_count += 1
40
+ results.append(outcome)
41
+
42
+ # Generate the Grid Visualization (HTML/CSS)
43
+ grid_html = '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(30px, 1fr)); gap: 5px;">'
44
+ for i, res in enumerate(results):
45
+ color = "#28a745" if res == "correct" else "#dc3545" if res == "wrong" else "#6c757d"
46
+ grid_html += f'<div style="width:30px; height:30px; background-color:{color}; border-radius:4px; display:flex; align-items:center; justify-content:center; color:white; font-size:10px; font-weight:bold;" title="Q{i+1}: {res.upper()}">{i+1}</div>'
47
+ grid_html += "</div>"
48
+
49
+ # Statistical Summary
50
+ expected_score = sum([PROB_MAP[s] * marks_pos - (1 - PROB_MAP[s]) * marks_neg if PROB_MAP[s] > 0 else 0 for s in df["Confidence / Strategy"]])
51
 
52
+ summary = f"""
53
+ ### πŸ“Š Trial Result
54
+ - **Total Score:** {total_score}
55
+ - **Correct βœ…:** {correct_count} | **Wrong ❌:** {wrong_count} | **Skipped βšͺ:** {skipped_count}
 
56
 
57
+ ### πŸ“ˆ Strategy Analysis (Probability)
58
+ - **Mathematically Expected Score:** {expected_score:.2f}
59
+ - **Risk Factor:** This specific trial's deviation from mean is {total_score - expected_score:.2f}
60
+ """
61
 
62
+ return grid_html, summary
63
+
64
+ # Initial Data
65
+ init_data = pd.DataFrame({
66
+ "Question #": range(1, 11),
67
+ "Confidence / Strategy": ["Known (100%)"] * 5 + ["2 Options Left (50/50)"] * 3 + ["Blind Guess (25%)"] * 2
68
+ })
69
 
 
70
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
71
+ gr.Markdown("# 🧩 Granular Negative Marking Simulator")
72
+ gr.Markdown("Define your strategy for each question to see a visual simulation of your test paper.")
73
 
74
  with gr.Row():
75
+ with gr.Column(scale=2):
76
+ gr.Markdown("### πŸ“ Define Your Test Paper")
77
+ input_df = gr.Dataframe(
78
+ headers=["Question #", "Confidence / Strategy"],
79
+ datatype=["number", "str"],
80
+ value=init_data,
81
+ interactive=True,
82
+ row_count=10,
83
+ col_count=(2, "fixed")
84
+ )
85
  with gr.Row():
86
+ pos = gr.Number(label="Marks per Correct", value=4)
87
+ neg = gr.Number(label="Marks per Wrong", value=1)
88
 
89
+ btn = gr.Button("πŸ”₯ Run Simulation Trial", variant="primary")
 
90
 
91
+ with gr.Column(scale=3):
92
+ gr.Markdown("### 🎯 Simulation Visual (Green=Right, Red=Wrong, Grey=Skip)")
93
+ grid_output = gr.HTML()
94
+ stats_output = gr.Markdown()
95
 
96
+ btn.click(fn=run_simulation, inputs=[input_df, pos, neg], outputs=[grid_output, stats_output])
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
  demo.launch()