diff --git a/Practical_AI_exam_grades.csv b/Practical_AI_exam_grades.csv new file mode 100644 index 0000000000000000000000000000000000000000..e0b276828bb52f4d344b16fcc84c9fbce4cab10a --- /dev/null +++ b/Practical_AI_exam_grades.csv @@ -0,0 +1,1039 @@ +Number,TA_1_ID,TA_2_ID,TA 1 - Q1 Grade,TA 1 - Q2 Grade,TA 1 - Q3 Grade,TA 1 - Total Grade,TA 2 - Q1 Grade,TA 2 - Q2 Grade,TA 2 - Q3 Grade,TA 2 - Total Grade,Average Grade +1,TA_1,TA_2,3.0,0.0,2.0,5.0,7.0,0.0,2.0,9.0,7.0 +2,TA_1,TA_2,1.0,0.0,0.0,1.0,1.5,0.0,0.0,1.5,1.25 +3,TA_1,TA_2,2.0,0.0,2.0,4.0,2.5,0.0,2.0,4.5,4.25 +4,TA_1,TA_2,6.0,9.0,5.0,20.0,4.5,5.5,5.5,15.5,17.75 +5,TA_1,TA_2,8.0,0.0,0.0,8.0,9.0,0.0,0.0,9.0,8.5 +6,TA_1,TA_2,14.0,0.0,2.0,16.0,15.0,0.0,2.0,17.0,16.5 +7,TA_1,TA_2,1.5,0.0,0.0,1.5,5.0,0.0,0.0,5.0,3.25 +8,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +9,TA_1,TA_2,4.5,1.0,2.5,8.0,2.5,6.0,3.5,12.0,10.0 +10,TA_1,TA_2,15.0,16.0,21.0,52.0,21.0,17.0,22.0,60.0,56.0 +11,TA_1,TA_2,3.0,9.0,0.0,12.0,4.0,8.0,0.0,12.0,12.0 +12,TA_1,TA_2,1.5,3.5,1.5,6.5,-0.5,2.5,3.0,5.0,5.75 +13,TA_1,TA_2,8.0,2.25,3.0,13.25,7.5,3.5,3.5,14.5,13.875 +14,TA_1,TA_2,6.0,10.0,13.0,29.0,5.0,7.0,12.0,24.0,26.5 +15,TA_1,TA_2,8.5,9.0,4.0,21.5,9.5,7.5,3.5,20.5,21.0 +16,TA_1,TA_2,2.5,0.0,0.0,2.5,1.0,1.0,0.0,2.0,2.25 +17,TA_1,TA_2,4.75,0.0,2.5,7.25,5.5,0.0,2.5,8.0,7.625 +18,TA_1,TA_2,1.5,0.0,0.0,1.5,2.0,0.0,0.0,2.0,1.75 +19,TA_1,TA_2,11.0,0.0,0.0,11.0,11.5,0.0,0.0,11.5,11.25 +20,TA_1,TA_2,1.5,3.5,1.5,6.5,3.0,7.5,3.0,13.5,10.0 +21,TA_1,TA_2,2.0,0.0,0.0,2.0,2.0,0.0,0.0,2.0,2.0 +22,TA_1,TA_2,0.0,2.0,0.0,2.0,0.0,0.0,0.0,0.0,1.0 +23,TA_1,TA_2,6.5,3.0,0.0,9.5,4.0,4.0,0.0,8.0,8.75 +24,TA_1,TA_2,15.0,4.0,2.0,21.0,17.5,4.0,2.0,23.5,22.25 +25,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +26,TA_1,TA_2,6.0,2.0,0.0,8.0,8.0,3.0,0.0,11.0,9.5 +27,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +28,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +29,TA_1,TA_2,6.0,6.5,14.0,26.5,0.0,0.0,0.0,0.0,13.25 +30,TA_1,TA_2,4.0,0.0,0.0,4.0,3.5,0.0,0.0,3.5,3.75 +31,TA_1,TA_2,1.25,0.0,2.0,3.25,2.0,0.0,2.0,4.0,3.625 +32,TA_1,TA_2,8.5,0.0,4.0,12.5,13.5,2.0,5.5,21.0,16.75 +33,TA_1,TA_2,10.5,0.0,0.0,10.5,13.5,0.0,0.0,13.5,12.0 +34,TA_1,TA_2,3.0,0.0,0.0,3.0,3.0,0.0,0.0,3.0,3.0 +35,TA_1,TA_2,1.5,0.0,0.0,1.5,2.0,0.0,0.0,2.0,1.75 +36,TA_1,TA_2,1.0,0.0,0.0,1.0,-1.5,0.0,0.0,-1.5,-0.25 +37,TA_1,TA_2,0.0,2.0,0.0,2.0,-1.0,1.5,0.0,0.5,1.25 +38,TA_1,TA_2,12.0,0.0,6.0,18.0,13.5,0.0,5.5,19.0,18.5 +39,TA_1,TA_2,5.0,0.0,0.0,5.0,11.0,0.0,0.0,11.0,8.0 +40,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +41,TA_1,TA_2,1.5,4.0,3.5,9.0,5.5,4.5,4.5,14.5,11.75 +42,TA_1,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +43,TA_1,TA_2,1.0,0.0,0.0,1.0,0.5,0.0,0.0,0.5,0.75 +44,TA_3,TA_4,7.0,8.25,3.0,18.25,9.0,8.0,2.0,19.0,18.625 +45,TA_3,TA_4,4.0,2.5,5.0,11.5,6.0,2.75,4.5,13.25,12.375 +46,TA_3,TA_4,2.0,8.75,2.0,12.75,3.0,7.75,2.0,12.75,12.75 +47,TA_3,TA_4,2.0,8.75,4.25,15.0,2.2,7.5,4.0,13.7,14.35 +48,TA_3,TA_4,10.0,6.75,4.5,21.25,9.5,6.5,5.0,21.0,21.125 +49,TA_3,TA_4,6.0,9.75,5.5,21.25,5.5,9.0,7.0,21.5,21.375 +50,TA_3,TA_4,7.5,2.75,0.0,10.25,11.2,3.5,0.0,14.7,12.475 +51,TA_3,TA_4,11.0,0.75,0.0,11.75,10.5,3.0,0.0,13.5,12.625 +52,TA_3,TA_4,9.0,0.0,4.25,13.25,7.0,0.0,3.0,10.0,11.625 +53,TA_3,TA_4,3.0,2.75,2.0,7.75,4.0,4.0,2.0,10.0,8.875 +54,TA_3,TA_4,10.5,0.0,0.0,10.5,10.5,0.0,0.0,10.5,10.5 +55,TA_3,TA_4,10.0,7.75,10.0,27.75,14.0,7.25,7.0,28.25,28.0 +56,TA_3,TA_4,21.0,17.0,20.0,58.0,20.5,17.0,19.25,56.75,57.375 +57,TA_3,TA_4,11.0,8.5,8.5,28.0,6.5,9.5,6.25,22.25,25.125 +58,TA_3,TA_4,9.5,9.5,4.5,23.5,10.0,9.5,5.0,24.5,24.0 +59,TA_3,TA_4,4.0,9.0,8.25,21.25,4.5,11.0,9.0,24.5,22.875 +60,TA_3,TA_4,20.0,16.25,21.5,57.75,20.0,15.0,19.75,54.75,56.25 +61,TA_3,TA_4,22.0,15.0,22.0,59.0,20.0,16.0,19.5,55.5,57.25 +62,TA_3,TA_4,7.0,9.5,7.5,24.0,14.25,9.5,8.0,31.75,27.875 +63,TA_3,TA_4,6.5,9.25,7.5,23.25,7.15,9.25,5.0,21.4,22.325 +64,TA_3,TA_4,10.5,11.5,5.0,27.0,12.5,10.5,2.0,25.0,26.0 +65,TA_3,TA_4,8.5,13.0,2.0,23.5,12.0,12.5,2.0,26.5,25.0 +66,TA_3,TA_4,25.0,0.0,0.0,25.0,20.0,0.0,0.0,20.0,22.5 +67,TA_3,TA_4,8.5,0.0,8.5,17.0,10.0,0.0,6.5,16.5,16.75 +68,TA_3,TA_4,5.5,6.5,4.5,16.5,4.9,6.5,4.5,15.9,16.2 +69,TA_3,TA_4,8.5,0.0,2.0,10.5,10.0,0.0,2.0,12.0,11.25 +70,TA_3,TA_4,20.0,17.0,18.0,55.0,20.0,17.0,15.0,52.0,53.5 +71,TA_3,TA_4,0.0,4.25,0.0,4.25,2.5,4.5,0.0,7.0,5.625 +72,TA_3,TA_4,16.5,0.0,5.0,21.5,19.35,0.0,5.5,24.85,23.175 +73,TA_3,TA_4,1.5,3.0,1.0,5.5,1.5,3.5,2.5,7.5,6.5 +74,TA_3,TA_4,4.0,10.5,3.75,18.25,6.3,10.5,3.0,19.8,19.025 +75,TA_3,TA_4,11.0,0.0,4.0,15.0,10.4,0.0,4.0,14.4,14.7 +76,TA_3,TA_4,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +77,TA_3,TA_4,6.0,0.0,0.0,6.0,5.5,0.0,0.0,5.5,5.75 +78,TA_3,TA_4,6.0,6.5,0.0,12.5,6.5,5.5,2.0,14.0,13.25 +79,TA_3,TA_4,9.5,3.5,8.0,21.0,10.5,3.0,7.25,20.75,20.875 +80,TA_3,TA_4,5.0,4.25,4.5,13.75,5.3,5.5,4.0,14.8,14.275 +81,TA_3,TA_4,22.0,17.0,16.25,55.25,22.0,17.0,15.75,54.75,55.0 +82,TA_3,TA_4,14.0,15.0,17.25,46.25,15.15,15.9,15.55,46.6,46.425 +83,TA_3,TA_4,4.0,0.5,6.0,10.5,5.3,1.0,5.5,11.8,11.15 +84,TA_3,TA_4,6.0,0.0,0.0,6.0,3.75,0.0,0.0,3.75,4.875 +85,TA_3,TA_4,9.5,10.5,3.75,23.75,6.2,10.5,3.0,19.7,21.725 +86,TA_3,TA_4,10.0,11.0,6.75,27.75,12.0,10.75,7.5,30.25,29.0 +87,TA_3,TA_4,0.5,0.0,2.0,2.5,1.2,0.0,2.0,3.2,2.85 +88,TA_3,TA_4,20.0,10.5,5.75,36.25,21.0,8.75,5.5,35.25,35.75 +89,TA_5,TA_6,4.0,10.5,9.5,24.0,2.5,10.0,8.75,21.25,22.625 +90,TA_5,TA_6,0.5,0.0,0.0,0.5,2.75,0.0,3.5,6.25,3.375 +91,TA_5,TA_6,13.0,3.0,2.0,18.0,15.0,3.5,2.0,20.5,19.25 +92,TA_5,TA_6,1.0,5.0,1.25,7.25,5.75,6.0,2.5,14.25,10.75 +93,TA_5,TA_6,7.0,2.0,2.0,11.0,9.0,2.0,2.0,13.0,12.0 +94,TA_5,TA_6,13.5,9.0,0.0,22.5,16.0,7.5,0.0,23.5,23.0 +95,TA_5,TA_6,11.0,2.0,5.25,18.25,11.0,2.0,5.5,18.5,18.375 +96,TA_5,TA_6,3.0,0.0,3.0,6.0,6.0,0.5,3.0,9.5,7.75 +97,TA_5,TA_6,3.25,0.0,0.0,3.25,3.0,0.0,0.0,3.0,3.125 +98,TA_5,TA_6,3.0,8.5,4.0,15.5,5.5,9.0,4.25,18.75,17.125 +99,TA_5,TA_6,20.0,16.0,17.5,53.5,20.5,16.75,19.25,56.5,55.0 +100,TA_5,TA_6,6.0,7.0,5.5,18.5,5.5,6.5,5.5,17.5,18.0 +101,TA_5,TA_6,10.0,10.0,16.5,36.5,9.5,10.5,16.5,36.5,36.5 +102,TA_5,TA_6,11.0,0.0,15.0,26.0,11.5,0.0,13.75,25.25,25.625 +103,TA_5,TA_6,6.0,0.0,4.0,10.0,9.0,0.0,4.75,13.75,11.875 +104,TA_5,TA_6,5.0,11.0,8.25,24.25,6.5,10.5,7.25,24.25,24.25 +105,TA_5,TA_6,5.0,10.5,2.0,17.5,5.5,9.0,2.25,16.75,17.125 +106,TA_5,TA_6,17.0,11.75,10.5,39.25,17.0,11.0,9.5,37.5,38.375 +107,TA_5,TA_6,20.5,10.5,0.0,31.0,20.5,8.5,0.0,29.0,30.0 +108,TA_5,TA_6,-1.0,5.0,0.0,4.0,1.0,3.5,0.0,4.5,4.25 +109,TA_5,TA_6,11.5,11.0,5.0,27.5,6.0,11.0,5.0,22.0,24.75 +110,TA_5,TA_6,5.5,10.0,14.0,29.5,6.5,8.5,14.0,29.0,29.25 +111,TA_5,TA_6,11.5,11.5,3.75,26.75,14.5,10.0,4.0,28.5,27.625 +112,TA_5,TA_6,16.0,11.0,3.75,30.75,16.5,10.0,4.0,30.5,30.625 +113,TA_5,TA_6,22.0,17.0,18.5,57.5,22.0,17.0,16.5,55.5,56.5 +114,TA_5,TA_6,5.0,12.0,9.0,26.0,7.5,9.5,8.5,25.5,25.75 +115,TA_5,TA_6,3.25,7.75,4.0,15.0,3.0,7.0,3.0,13.0,14.0 +116,TA_5,TA_6,0.0,0.0,1.5,1.5,0.0,0.0,1.5,1.5,1.5 +117,TA_5,TA_6,-0.5,4.25,0.0,3.75,2.5,3.5,1.0,7.0,5.375 +118,TA_5,TA_6,2.0,6.75,3.25,12.0,3.5,8.0,4.0,15.5,13.75 +119,TA_5,TA_6,26.0,15.0,22.0,63.0,26.0,15.5,22.5,64.0,63.5 +120,TA_5,TA_6,0.5,3.5,2.0,6.0,2.0,4.0,2.0,8.0,7.0 +121,TA_5,TA_6,3.5,0.0,4.0,7.5,6.5,0.0,5.25,11.75,9.625 +122,TA_5,TA_6,7.0,10.75,0.0,17.75,6.0,9.0,0.0,15.0,16.375 +123,TA_5,TA_6,0.5,2.0,2.5,5.0,0.0,1.75,2.75,4.5,4.75 +124,TA_5,TA_6,10.0,11.0,5.75,26.75,9.0,8.75,5.25,23.0,24.875 +125,TA_5,TA_6,8.5,0.0,0.0,8.5,9.0,0.0,0.0,9.0,8.75 +126,TA_5,TA_6,5.0,12.0,0.0,17.0,6.0,11.5,0.0,17.5,17.25 +127,TA_5,TA_6,12.5,10.5,3.5,26.5,14.0,10.0,4.25,28.25,27.375 +128,TA_5,TA_6,8.5,9.5,3.0,21.0,10.0,8.5,3.0,21.5,21.25 +129,TA_5,TA_6,21.0,14.0,22.0,57.0,19.5,14.0,21.0,54.5,55.75 +130,TA_5,TA_6,9.0,10.5,8.0,27.5,10.0,9.0,2.0,21.0,24.25 +131,TA_5,TA_6,6.5,11.0,4.5,22.0,7.0,9.0,4.5,20.5,21.25 +132,TA_5,TA_6,9.5,8.0,9.25,26.75,9.0,7.0,10.25,26.25,26.5 +133,TA_5,TA_6,8.0,10.5,10.5,29.0,6.0,12.5,12.0,30.5,29.75 +134,TA_7,TA_8,13.0,11.75,2.25,27.0,10.5,10.55,2.0,23.05,25.025 +135,TA_7,TA_8,25.0,16.0,17.5,58.5,23.0,13.0,16.0,52.0,55.25 +136,TA_7,TA_8,7.5,10.0,6.0,23.5,4.75,10.5,5.5,20.75,22.125 +137,TA_7,TA_8,12.0,7.25,6.0,25.25,7.5,9.55,5.5,22.55,23.9 +138,TA_7,TA_8,18.5,12.5,2.25,33.25,17.75,12.5,2.0,32.25,32.75 +139,TA_7,TA_8,6.0,10.5,6.5,23.0,6.65,11.1,11.5,29.25,26.125 +140,TA_7,TA_8,22.0,12.5,19.0,53.5,20.25,13.0,19.0,52.25,52.875 +141,TA_7,TA_8,17.5,11.0,19.0,47.5,13.5,12.5,19.0,45.0,46.25 +142,TA_7,TA_8,16.5,11.5,3.0,31.0,19.0,12.25,4.0,35.25,33.125 +143,TA_7,TA_8,17.5,11.5,13.0,42.0,16.0,12.1,16.5,44.6,43.3 +144,TA_7,TA_8,9.0,0.0,3.5,12.5,9.5,0.0,3.25,12.75,12.625 +145,TA_7,TA_8,5.5,0.0,9.0,14.5,3.5,0.0,7.5,11.0,12.75 +146,TA_7,TA_8,3.5,0.0,3.5,7.0,3.0,0.0,4.0,7.0,7.0 +147,TA_7,TA_8,9.0,10.0,9.0,28.0,9.25,11.65,10.0,30.9,29.45 +148,TA_7,TA_8,11.0,8.5,12.5,32.0,4.8,7.5,13.0,25.3,28.65 +149,TA_7,TA_8,8.5,7.25,9.5,25.25,7.75,8.5,11.0,27.25,26.25 +150,TA_7,TA_8,10.0,6.5,11.0,27.5,8.5,8.75,13.5,30.75,29.125 +151,TA_7,TA_8,4.5,10.5,4.0,19.0,4.75,11.75,3.5,20.0,19.5 +152,TA_7,TA_8,12.0,6.5,8.5,27.0,13.5,10.25,8.5,32.25,29.625 +153,TA_7,TA_8,19.5,6.5,6.0,32.0,16.5,9.55,6.5,32.55,32.275 +154,TA_7,TA_8,26.0,16.0,22.0,64.0,21.0,15.0,21.0,57.0,60.5 +155,TA_7,TA_8,0.0,2.0,0.0,2.0,0.0,3.75,0.0,3.75,2.875 +156,TA_7,TA_8,5.5,7.75,3.5,16.75,4.5,12.5,4.5,21.5,19.125 +157,TA_7,TA_8,19.5,2.5,3.0,25.0,15.0,4.0,3.0,22.0,23.5 +158,TA_7,TA_8,0.5,0.5,0.0,1.0,0.0,0.0,4.0,4.0,2.5 +159,TA_7,TA_8,8.5,8.5,7.5,24.5,7.5,10.35,12.0,29.85,27.175 +160,TA_7,TA_8,10.5,4.5,10.0,25.0,13.5,10.85,10.2,34.55,29.775 +161,TA_7,TA_8,2.5,9.0,4.5,16.0,6.75,10.6,5.0,22.35,19.175 +162,TA_7,TA_8,14.0,16.0,20.0,50.0,19.75,16.0,22.0,57.75,53.875 +163,TA_7,TA_8,13.0,9.5,6.5,29.0,12.4,10.6,7.0,30.0,29.5 +164,TA_7,TA_8,14.0,9.5,5.5,29.0,6.75,10.75,7.5,25.0,27.0 +165,TA_7,TA_8,19.0,11.0,13.0,43.0,9.5,13.4,14.5,37.4,40.2 +166,TA_7,TA_8,8.0,10.0,6.5,24.5,4.15,10.65,5.25,20.05,22.275 +167,TA_7,TA_8,5.0,7.5,5.5,18.0,7.0,10.75,6.5,24.25,21.125 +168,TA_7,TA_8,26.0,16.0,22.0,64.0,23.0,16.0,20.5,59.5,61.75 +169,TA_7,TA_8,2.5,0.0,0.0,2.5,2.0,0.0,0.0,2.0,2.25 +170,TA_7,TA_8,10.5,0.0,11.0,21.5,10.5,0.0,12.5,23.0,22.25 +171,TA_7,TA_8,6.5,1.5,2.0,10.0,4.5,2.0,1.0,7.5,8.75 +172,TA_7,TA_8,8.5,8.5,5.0,22.0,13.5,9.55,5.5,28.55,25.275 +173,TA_7,TA_8,5.0,8.5,8.5,22.0,5.5,12.5,8.25,26.25,24.125 +174,TA_7,TA_8,9.0,0.0,3.0,12.0,10.0,0.0,2.5,12.5,12.25 +175,TA_7,TA_8,16.0,7.5,6.0,29.5,13.0,7.55,7.5,28.05,28.775 +176,TA_7,TA_8,20.0,10.5,11.0,41.5,15.5,10.75,13.5,39.75,40.625 +177,TA_9,TA_10,14.5,10.0,0.0,24.5,15.0,8.0,0.0,23.0,23.75 +178,TA_9,TA_10,11.5,3.0,2.0,16.5,11.5,3.0,3.0,17.5,17.0 +179,TA_9,TA_10,1.5,0.0,0.5,2.0,0.0,0.0,0.0,0.0,1.0 +180,TA_9,TA_10,9.5,0.0,5.5,15.0,10.0,0.0,4.0,14.0,14.5 +181,TA_9,TA_10,8.5,11.0,6.0,25.5,6.0,11.0,4.0,21.0,23.25 +182,TA_9,TA_10,21.0,12.5,20.5,54.0,18.5,14.0,17.0,49.5,51.75 +183,TA_9,TA_10,18.0,10.5,13.0,41.5,14.0,13.0,12.0,39.0,40.25 +184,TA_9,TA_10,21.0,17.0,21.0,59.0,18.0,12.0,18.0,48.0,53.5 +185,TA_9,TA_10,23.0,10.5,11.0,44.5,22.0,11.0,8.0,41.0,42.75 +186,TA_9,TA_10,11.0,8.0,4.5,23.5,13.0,5.0,8.0,26.0,24.75 +187,TA_9,TA_10,20.0,17.0,22.0,59.0,19.0,14.0,19.0,52.0,55.5 +188,TA_9,TA_10,2.0,8.0,0.0,10.0,3.0,7.0,0.0,10.0,10.0 +189,TA_9,TA_10,19.5,15.5,20.5,55.5,17.0,14.0,17.0,48.0,51.75 +190,TA_9,TA_10,19.25,15.5,18.25,53.0,12.0,14.0,6.0,32.0,42.5 +191,TA_9,TA_10,10.0,10.5,14.0,34.5,6.0,6.0,7.0,19.0,26.75 +192,TA_9,TA_10,13.0,10.5,9.0,32.5,4.0,6.0,4.0,14.0,23.25 +193,TA_9,TA_10,7.5,6.5,8.0,22.0,10.0,5.0,6.0,21.0,21.5 +194,TA_9,TA_10,7.0,12.0,8.5,27.5,3.0,4.0,4.0,11.0,19.25 +195,TA_9,TA_10,5.5,6.0,6.5,18.0,3.5,0.5,4.0,8.0,13.0 +196,TA_9,TA_10,25.0,17.0,19.0,61.0,25.0,16.0,19.0,60.0,60.5 +197,TA_9,TA_10,6.5,9.5,10.5,26.5,11.0,10.5,6.5,28.0,27.25 +198,TA_9,TA_10,10.5,9.5,13.0,33.0,9.0,10.5,9.5,29.0,31.0 +199,TA_9,TA_10,8.0,2.5,5.5,16.0,7.5,0.5,4.5,12.5,14.25 +200,TA_9,TA_10,9.0,5.5,12.5,27.0,6.0,3.0,11.0,20.0,23.5 +201,TA_9,TA_10,12.5,5.5,9.0,27.0,10.0,5.0,8.0,23.0,25.0 +202,TA_9,TA_10,12.5,0.0,0.0,12.5,11.0,0.0,0.0,11.0,11.75 +203,TA_9,TA_10,11.5,11.0,5.5,28.0,10.0,14.0,5.0,29.0,28.5 +204,TA_9,TA_10,10.5,12.5,6.0,29.0,7.5,16.0,5.0,28.5,28.75 +205,TA_9,TA_10,13.5,10.0,9.5,33.0,8.0,9.0,6.0,23.0,28.0 +206,TA_9,TA_10,15.0,11.5,19.0,45.5,12.5,13.0,18.5,44.0,44.75 +207,TA_9,TA_10,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +208,TA_9,TA_10,11.5,12.5,12.5,36.5,8.5,9.0,14.0,31.5,34.0 +209,TA_9,TA_10,20.5,17.0,17.5,55.0,20.0,15.0,15.0,50.0,52.5 +210,TA_9,TA_10,17.5,13.5,19.5,50.5,16.0,11.0,17.0,44.0,47.25 +211,TA_9,TA_10,14.0,11.0,15.0,40.0,9.0,5.0,13.0,27.0,33.5 +212,TA_9,TA_10,5.0,3.0,5.0,13.0,4.0,3.0,4.0,11.0,12.0 +213,TA_9,TA_10,17.0,11.5,2.0,30.5,16.0,14.0,2.0,32.0,31.25 +214,TA_9,TA_10,17.0,0.0,0.0,17.0,17.0,0.0,0.0,17.0,17.0 +215,TA_9,TA_10,19.5,14.0,18.5,52.0,17.0,14.0,18.0,49.0,50.5 +216,TA_9,TA_10,15.5,12.5,18.5,46.5,16.0,13.0,19.0,48.0,47.25 +217,TA_9,TA_10,19.5,10.0,4.5,34.0,16.0,11.0,2.5,29.5,31.75 +218,TA_9,TA_10,12.5,7.0,6.0,25.5,12.0,7.0,4.0,23.0,24.25 +219,TA_9,TA_10,23.5,15.0,16.0,54.5,21.0,14.0,17.0,52.0,53.25 +220,TA_9,TA_10,23.0,11.0,20.0,54.0,22.0,12.0,18.0,52.0,53.0 +221,TA_11,TA_12,10.5,13.5,11.5,35.5,10.0,11.0,7.0,28.0,31.75 +222,TA_11,TA_12,12.5,11.75,12.5,36.75,16.0,10.0,12.0,38.0,37.375 +223,TA_11,TA_12,13.0,11.75,11.0,35.75,13.0,8.0,10.0,31.0,33.375 +224,TA_11,TA_12,13.5,0.0,10.0,23.5,6.0,0.0,10.0,16.0,19.75 +225,TA_11,TA_12,10.5,5.0,8.75,24.25,3.0,4.0,8.0,15.0,19.625 +226,TA_11,TA_12,8.75,10.25,9.5,28.5,3.0,8.0,9.0,20.0,24.25 +227,TA_11,TA_12,10.0,9.25,0.0,19.25,10.0,10.0,0.0,20.0,19.625 +228,TA_11,TA_12,11.5,7.5,9.75,28.75,11.0,8.0,12.0,31.0,29.875 +229,TA_11,TA_12,13.5,9.5,11.5,34.5,7.0,0.0,6.0,13.0,23.75 +230,TA_11,TA_12,13.0,12.5,9.0,34.5,8.0,0.0,4.0,12.0,23.25 +231,TA_11,TA_12,16.0,10.25,12.5,38.75,16.0,11.0,13.5,40.5,39.625 +232,TA_11,TA_12,11.0,10.5,9.0,30.5,11.0,11.0,6.0,28.0,29.25 +233,TA_11,TA_12,12.0,0.0,10.0,22.0,9.0,0.0,9.0,18.0,20.0 +234,TA_11,TA_12,9.5,9.0,5.5,24.0,4.0,0.0,5.0,9.0,16.5 +235,TA_11,TA_12,24.5,12.0,18.5,55.0,22.0,8.0,20.0,50.0,52.5 +236,TA_11,TA_12,10.5,11.25,15.0,36.75,9.5,10.0,16.0,35.5,36.125 +237,TA_11,TA_12,6.25,10.0,0.0,16.25,6.0,8.0,0.0,14.0,15.125 +238,TA_11,TA_12,18.0,16.0,14.5,48.5,9.5,17.0,8.0,34.5,41.5 +239,TA_11,TA_12,4.0,12.5,9.0,25.5,3.0,8.0,7.0,18.0,21.75 +240,TA_11,TA_12,15.5,8.75,18.5,42.75,15.0,0.0,15.0,30.0,36.375 +241,TA_11,TA_12,16.5,8.5,10.0,35.0,7.0,2.0,5.0,14.0,24.5 +242,TA_11,TA_12,15.0,12.5,16.0,43.5,13.0,11.0,17.5,41.5,42.5 +243,TA_11,TA_12,7.0,11.25,11.5,29.75,7.0,10.0,9.0,26.0,27.875 +244,TA_11,TA_12,19.0,13.0,14.0,46.0,19.0,13.0,12.0,44.0,45.0 +245,TA_11,TA_12,11.0,11.25,12.5,34.75,6.5,8.0,7.0,21.5,28.125 +246,TA_11,TA_12,9.0,11.25,9.0,29.25,7.0,10.0,9.0,26.0,27.625 +247,TA_11,TA_12,13.0,10.0,10.0,33.0,10.0,10.0,6.0,26.0,29.5 +248,TA_11,TA_12,6.0,0.0,3.5,9.5,5.0,0.0,3.0,8.0,8.75 +249,TA_11,TA_12,8.25,0.0,6.0,14.25,8.0,0.0,5.0,13.0,13.625 +250,TA_11,TA_12,2.0,5.75,7.0,14.75,2.0,0.0,4.0,6.0,10.375 +251,TA_11,TA_12,8.0,9.5,7.0,24.5,0.0,0.0,2.0,2.0,13.25 +252,TA_11,TA_12,6.25,0.0,2.5,8.75,9.0,0.0,2.0,11.0,9.875 +253,TA_11,TA_12,8.0,6.0,6.0,20.0,2.0,0.0,5.0,7.0,13.5 +254,TA_11,TA_12,6.0,8.5,8.0,22.5,3.0,0.0,10.0,13.0,17.75 +255,TA_11,TA_12,9.0,9.25,9.0,27.25,9.0,9.0,9.0,27.0,27.125 +256,TA_11,TA_12,2.5,4.0,4.5,11.0,3.0,0.0,2.0,5.0,8.0 +257,TA_11,TA_12,0.0,0.5,0.0,0.5,0.0,0.0,0.0,0.0,0.25 +258,TA_11,TA_12,10.5,12.0,0.0,22.5,3.0,4.0,0.0,7.0,14.75 +259,TA_11,TA_12,8.5,8.75,8.0,25.25,4.0,0.0,5.0,9.0,17.125 +260,TA_11,TA_12,12.0,0.0,10.0,22.0,9.0,0.0,8.0,17.0,19.5 +261,TA_11,TA_12,12.0,9.75,10.0,31.75,7.0,9.0,8.0,24.0,27.875 +262,TA_11,TA_12,9.0,11.0,7.0,27.0,7.0,14.0,3.0,24.0,25.5 +263,TA_11,TA_12,11.5,4.0,6.5,22.0,6.0,4.0,5.0,15.0,18.5 +264,TA_11,TA_12,20.0,17.0,22.0,59.0,19.0,17.0,21.0,57.0,58.0 +265,TA_11,TA_12,11.0,11.0,14.0,36.0,9.0,8.0,15.0,32.0,34.0 +266,TA_11,TA_12,22.0,17.0,21.0,60.0,26.0,17.0,21.0,64.0,62.0 +267,TA_11,TA_12,21.0,11.25,18.0,50.25,21.0,12.0,14.0,47.0,48.625 +268,TA_11,TA_12,17.0,13.5,20.0,50.5,16.0,13.0,17.0,46.0,48.25 +269,TA_13,TA_14,10.0,0.0,0.0,10.0,28.0,0.0,0.0,28.0,19.0 +270,TA_13,TA_14,10.0,7.0,5.0,22.0,21.0,13.0,5.0,39.0,30.5 +271,TA_13,TA_14,10.0,7.0,0.0,17.0,11.5,11.5,2.5,25.5,21.25 +272,TA_13,TA_14,23.0,8.0,23.0,54.0,22.0,14.5,22.0,58.5,56.25 +273,TA_13,TA_14,20.0,16.0,0.0,36.0,12.5,17.0,10.5,40.0,38.0 +274,TA_13,TA_14,17.0,14.0,23.0,54.0,18.5,17.0,22.0,57.5,55.75 +275,TA_13,TA_14,15.0,9.0,20.0,44.0,14.0,13.0,19.5,46.5,45.25 +276,TA_13,TA_14,23.0,16.0,0.0,39.0,24.5,16.0,0.0,40.5,39.75 +277,TA_13,TA_14,23.0,10.0,8.0,41.0,21.0,10.5,10.0,41.5,41.25 +278,TA_13,TA_14,25.0,14.0,22.0,61.0,24.0,17.0,19.0,60.0,60.5 +279,TA_13,TA_14,12.0,0.0,12.0,24.0,10.5,7.5,5.0,23.0,23.5 +280,TA_13,TA_14,15.0,7.0,5.0,27.0,14.5,8.5,3.0,26.0,26.5 +281,TA_13,TA_14,10.0,5.0,10.0,25.0,11.5,7.0,5.0,23.5,24.25 +282,TA_13,TA_14,13.0,7.0,15.0,35.0,12.5,4.0,17.0,33.5,34.25 +283,TA_13,TA_14,25.0,16.0,23.0,64.0,23.0,17.0,22.0,62.0,63.0 +284,TA_13,TA_14,22.0,13.0,8.0,43.0,16.5,17.0,7.0,40.5,41.75 +285,TA_13,TA_14,20.0,0.0,0.0,20.0,10.5,0.0,6.5,17.0,18.5 +286,TA_13,TA_14,8.0,5.0,10.0,23.0,8.5,8.5,2.0,19.0,21.0 +287,TA_13,TA_14,23.0,16.0,16.0,55.0,15.0,17.0,19.0,51.0,53.0 +288,TA_13,TA_14,20.0,10.0,7.0,37.0,15.0,11.5,5.5,32.0,34.5 +289,TA_13,TA_14,12.0,0.0,0.0,12.0,5.0,1.0,1.0,7.0,9.5 +290,TA_13,TA_14,22.0,16.0,23.0,61.0,19.5,17.0,19.0,55.5,58.25 +291,TA_13,TA_14,23.0,8.0,0.0,31.0,18.0,7.5,0.0,25.5,28.25 +292,TA_13,TA_14,14.0,12.0,23.0,49.0,14.5,13.0,15.5,43.0,46.0 +293,TA_13,TA_14,15.0,5.0,7.0,27.0,9.5,7.0,4.0,20.5,23.75 +294,TA_13,TA_14,15.0,0.0,20.0,35.0,7.0,7.0,14.0,28.0,31.5 +295,TA_13,TA_14,20.0,8.0,23.0,51.0,16.0,9.5,18.5,44.0,47.5 +296,TA_13,TA_14,25.0,16.0,22.0,63.0,20.0,14.0,22.0,56.0,59.5 +297,TA_13,TA_14,22.0,16.0,15.0,53.0,21.0,14.0,10.5,45.5,49.25 +298,TA_13,TA_14,15.0,12.0,17.0,44.0,17.0,11.0,6.5,34.5,39.25 +299,TA_13,TA_14,20.0,10.0,8.0,38.0,10.0,9.0,9.5,28.5,33.25 +300,TA_13,TA_14,10.0,0.0,10.0,20.0,3.0,5.0,2.0,10.0,15.0 +301,TA_13,TA_14,10.0,8.0,15.0,33.0,15.0,2.0,4.5,21.5,27.25 +302,TA_13,TA_14,7.0,8.0,12.0,27.0,4.5,5.0,5.5,15.0,21.0 +303,TA_13,TA_14,23.0,16.0,15.0,54.0,21.0,5.5,12.0,38.5,46.25 +304,TA_13,TA_14,15.0,8.0,12.0,35.0,10.0,0.0,8.0,18.0,26.5 +305,TA_13,TA_14,16.0,5.0,8.0,29.0,7.5,0.0,4.0,11.5,20.25 +306,TA_13,TA_14,15.0,10.0,10.0,35.0,7.5,9.0,0.0,16.5,25.75 +307,TA_13,TA_14,7.0,12.0,8.0,27.0,3.0,0.0,0.0,3.0,15.0 +308,TA_13,TA_14,19.0,6.0,16.0,41.0,6.0,0.0,5.0,11.0,26.0 +309,TA_13,TA_14,15.0,16.0,16.0,47.0,8.0,3.0,4.0,15.0,31.0 +310,TA_13,TA_14,23.0,12.0,10.0,45.0,4.0,0.0,0.0,4.0,24.5 +311,TA_15,TA_16,18.0,9.5,5.0,32.5,14.0,6.25,4.0,24.25,28.375 +312,TA_15,TA_16,10.5,13.5,7.0,31.0,0.0,6.5,6.25,12.75,21.875 +313,TA_15,TA_16,17.5,13.0,13.5,44.0,15.5,14.0,16.5,46.0,45.0 +314,TA_15,TA_16,17.5,13.0,6.0,36.5,12.0,9.5,7.0,28.5,32.5 +315,TA_15,TA_16,19.5,10.5,17.0,47.0,13.5,7.0,18.5,39.0,43.0 +316,TA_15,TA_16,17.5,13.0,7.0,37.5,16.0,12.5,6.0,34.5,36.0 +317,TA_15,TA_16,14.0,5.0,10.0,29.0,9.0,0.0,18.0,27.0,28.0 +318,TA_15,TA_16,22.0,11.0,18.5,51.5,21.5,8.75,18.0,48.25,49.875 +319,TA_15,TA_16,6.5,0.0,9.0,15.5,12.0,3.0,12.5,27.5,21.5 +320,TA_15,TA_16,11.5,12.0,9.5,33.0,20.5,0.0,13.0,33.5,33.25 +321,TA_15,TA_16,19.5,11.0,9.5,40.0,16.5,9.0,11.5,37.0,38.5 +322,TA_15,TA_16,19.0,13.0,11.0,43.0,15.0,14.0,13.25,42.25,42.625 +323,TA_15,TA_16,22.5,17.0,21.5,61.0,23.0,15.5,21.0,59.5,60.25 +324,TA_15,TA_16,15.0,12.0,11.5,38.5,12.0,9.0,12.5,33.5,36.0 +325,TA_15,TA_16,13.5,17.0,19.5,50.0,22.5,16.0,21.5,60.0,55.0 +326,TA_15,TA_16,6.5,1.0,3.0,10.5,15.5,3.0,4.0,22.5,16.5 +327,TA_15,TA_16,8.0,9.5,7.5,25.0,7.0,2.0,16.5,25.5,25.25 +328,TA_15,TA_16,11.0,8.0,9.5,28.5,9.75,8.5,5.0,23.25,25.875 +329,TA_15,TA_16,8.5,10.5,0.0,19.0,8.0,8.0,0.0,16.0,17.5 +330,TA_15,TA_16,19.0,11.5,6.5,37.0,21.5,4.0,6.0,31.5,34.25 +331,TA_15,TA_16,23.0,12.0,13.0,48.0,22.0,6.0,0.0,28.0,38.0 +332,TA_15,TA_16,13.5,11.5,7.5,32.5,11.0,8.5,17.0,36.5,34.5 +333,TA_15,TA_16,14.0,10.5,2.0,26.5,21.0,9.0,2.0,32.0,29.25 +334,TA_15,TA_16,15.5,12.5,6.0,34.0,19.0,10.0,4.0,33.0,33.5 +335,TA_15,TA_16,7.5,0.0,3.0,10.5,12.5,1.0,4.0,17.5,14.0 +336,TA_15,TA_16,18.5,12.5,13.0,44.0,22.75,10.5,11.25,44.5,44.25 +337,TA_15,TA_16,12.5,0.0,11.0,23.5,14.0,1.0,7.0,22.0,22.75 +338,TA_15,TA_16,17.5,12.0,8.5,38.0,12.5,9.0,3.0,24.5,31.25 +339,TA_15,TA_16,9.0,9.0,0.0,18.0,12.25,4.5,0.0,16.75,17.375 +340,TA_15,TA_16,10.0,0.5,6.0,16.5,15.5,4.0,7.0,26.5,21.5 +341,TA_15,TA_16,14.5,11.5,4.5,30.5,15.0,8.0,5.0,28.0,29.25 +342,TA_15,TA_16,10.0,10.5,4.5,25.0,12.0,6.5,6.0,24.5,24.75 +343,TA_15,TA_16,17.0,9.5,11.5,38.0,20.5,9.0,0.0,29.5,33.75 +344,TA_15,TA_16,12.0,7.5,5.0,24.5,11.0,5.0,4.5,20.5,22.5 +345,TA_15,TA_16,12.0,5.5,5.0,22.5,10.0,5.0,5.0,20.0,21.25 +346,TA_15,TA_16,7.0,6.0,7.5,20.5,16.0,10.0,13.5,39.5,30.0 +347,TA_15,TA_16,16.0,10.5,4.5,31.0,14.0,9.5,5.0,28.5,29.75 +348,TA_15,TA_16,24.0,12.0,19.0,55.0,18.0,9.0,18.0,45.0,50.0 +349,TA_15,TA_16,13.0,11.0,7.5,31.5,14.5,7.25,12.5,34.25,32.875 +350,TA_15,TA_16,13.5,7.0,6.5,27.0,18.5,9.5,9.0,37.0,32.0 +351,TA_15,TA_16,20.0,17.0,17.5,54.5,17.0,16.5,17.5,51.0,52.75 +352,TA_15,TA_16,14.5,10.0,2.0,26.5,13.0,4.0,6.0,23.0,24.75 +353,TA_15,TA_16,21.5,15.5,15.0,52.0,19.5,16.0,13.5,49.0,50.5 +354,TA_15,TA_16,18.5,11.5,9.0,39.0,10.5,11.5,10.5,32.5,35.75 +355,TA_15,TA_16,12.5,11.5,0.0,24.0,9.0,9.0,0.0,18.0,21.0 +356,TA_15,TA_16,8.0,9.5,7.5,25.0,10.5,9.5,0.0,20.0,22.5 +357,TA_17,TA_18,19.0,10.5,12.0,41.5,21.3,11.3,11.0,43.6,42.55 +358,TA_17,TA_18,6.0,11.5,2.0,19.5,14.3,11.8,2.0,28.1,23.8 +359,TA_17,TA_18,11.5,13.0,11.0,35.5,12.7,13.3,12.5,38.5,37.0 +360,TA_17,TA_18,10.0,7.5,4.25,21.75,12.9,9.2,5.0,27.1,24.425 +361,TA_17,TA_18,3.0,11.0,5.5,19.5,4.2,12.3,5.1,21.6,20.55 +362,TA_17,TA_18,12.0,11.0,0.0,23.0,11.5,10.5,0.0,22.0,22.5 +363,TA_17,TA_18,5.0,10.0,0.0,15.0,12.0,10.3,0.0,22.3,18.65 +364,TA_17,TA_18,1.0,7.0,4.0,12.0,3.2,5.3,5.4,13.9,12.95 +365,TA_17,TA_18,13.0,12.25,6.25,31.5,19.0,10.8,5.6,35.4,33.45 +366,TA_17,TA_18,8.0,9.0,3.0,20.0,10.0,9.6,2.3,21.900000000000002,20.950000000000003 +367,TA_17,TA_18,13.5,12.5,18.0,44.0,15.0,12.0,12.5,39.5,41.75 +368,TA_17,TA_18,10.0,12.0,11.5,33.5,8.5,13.3,4.3,26.1,29.8 +369,TA_17,TA_18,3.0,5.5,10.0,18.5,5.0,7.5,10.0,22.5,20.5 +370,TA_17,TA_18,8.0,10.5,10.0,28.5,8.6,9.9,6.8,25.3,26.9 +371,TA_17,TA_18,15.0,0.0,14.0,29.0,15.5,0.0,16.0,31.5,30.25 +372,TA_17,TA_18,9.5,0.0,9.0,18.5,10.0,0.0,8.0,18.0,18.25 +373,TA_17,TA_18,13.5,0.0,10.5,24.0,11.5,0.0,9.8,21.3,22.65 +374,TA_17,TA_18,11.0,9.5,9.0,29.5,13.5,10.5,10.0,34.0,31.75 +375,TA_17,TA_18,10.0,10.0,9.0,29.0,13.0,11.3,10.0,34.3,31.65 +376,TA_17,TA_18,1.5,7.0,6.0,14.5,5.2,8.1,6.0,19.3,16.9 +377,TA_17,TA_18,16.0,10.0,0.0,26.0,17.0,7.3,0.0,24.3,25.15 +378,TA_17,TA_18,0.0,6.5,2.0,8.5,4.0,9.1,2.0,15.1,11.8 +379,TA_17,TA_18,14.0,0.0,0.0,14.0,14.0,0.0,0.0,14.0,14.0 +380,TA_17,TA_18,4.0,0.0,1.5,5.5,4.0,0.0,2.0,6.0,5.75 +381,TA_17,TA_18,7.0,6.0,3.5,16.5,7.0,8.3,3.4,18.7,17.6 +382,TA_17,TA_18,5.5,8.5,8.0,22.0,6.0,11.8,5.5,23.3,22.65 +383,TA_17,TA_18,18.0,13.5,11.5,43.0,19.0,16.0,0.0,35.0,39.0 +384,TA_17,TA_18,11.5,12.5,7.0,31.0,12.6,13.5,8.0,34.1,32.55 +385,TA_17,TA_18,11.0,14.0,14.5,39.5,12.0,14.0,10.8,36.8,38.15 +386,TA_17,TA_18,11.0,2.5,10.0,23.5,14.0,3.0,5.8,22.8,23.15 +387,TA_17,TA_18,13.0,14.5,10.0,37.5,14.2,15.0,7.5,36.7,37.1 +388,TA_17,TA_18,4.5,4.5,5.0,14.0,7.8,4.8,3.3,15.899999999999999,14.95 +389,TA_17,TA_18,4.0,8.0,9.0,21.0,6.5,0.0,7.5,14.0,17.5 +390,TA_17,TA_18,11.5,10.0,2.0,23.5,10.5,9.7,2.0,22.2,22.85 +391,TA_17,TA_18,11.0,9.5,4.5,25.0,14.0,11.8,5.5,31.3,28.15 +392,TA_17,TA_18,10.5,12.0,9.5,32.0,12.7,13.0,6.3,32.0,32.0 +393,TA_17,TA_18,6.5,0.0,8.5,15.0,7.0,0.0,5.5,12.5,13.75 +394,TA_17,TA_18,10.0,7.0,2.0,19.0,10.5,8.8,2.0,21.3,20.15 +395,TA_17,TA_18,8.0,11.0,4.0,23.0,7.5,11.5,4.5,23.5,23.25 +396,TA_17,TA_18,8.5,9.0,2.0,19.5,11.7,12.0,2.2,25.9,22.7 +397,TA_17,TA_18,9.0,8.0,10.0,27.0,9.3,7.6,8.2,25.099999999999998,26.049999999999997 +398,TA_17,TA_18,8.0,7.5,4.0,19.5,9.4,7.0,5.0,21.4,20.45 +399,TA_17,TA_18,13.0,6.0,5.0,24.0,9.0,9.0,5.0,23.0,23.5 +400,TA_17,TA_18,16.0,14.5,10.5,41.0,17.0,13.0,8.5,38.5,39.75 +401,TA_17,TA_18,2.5,0.0,0.0,2.5,4.0,0.0,0.0,4.0,3.25 +402,TA_19,TA_20,15.0,14.0,17.0,46.0,11.0,13.5,15.5,40.0,43.0 +403,TA_19,TA_20,9.5,9.0,4.0,22.5,11.5,8.5,5.0,25.0,23.75 +404,TA_19,TA_20,10.5,13.5,18.0,42.0,14.0,14.0,19.0,47.0,44.5 +405,TA_19,TA_20,13.0,11.5,14.5,39.0,17.0,11.5,14.0,42.5,40.75 +406,TA_19,TA_20,15.0,13.0,20.5,48.5,18.0,13.5,19.0,50.5,49.5 +407,TA_19,TA_20,23.5,16.0,19.0,58.5,25.0,12.5,16.0,53.5,56.0 +408,TA_19,TA_20,7.5,12.5,18.0,38.0,12.0,13.0,15.5,40.5,39.25 +409,TA_19,TA_20,11.5,10.0,5.5,27.0,11.5,10.5,5.0,27.0,27.0 +410,TA_19,TA_20,5.5,11.0,2.5,19.0,8.0,13.0,3.5,24.5,21.75 +411,TA_19,TA_20,15.5,14.5,15.0,45.0,21.0,15.0,15.5,51.5,48.25 +412,TA_19,TA_20,16.0,0.0,16.0,32.0,16.0,0.0,13.5,29.5,30.75 +413,TA_19,TA_20,21.0,11.5,17.0,49.5,21.5,13.0,13.0,47.5,48.5 +414,TA_19,TA_20,13.0,8.0,7.0,28.0,10.0,9.0,6.0,25.0,26.5 +415,TA_19,TA_20,21.0,17.0,15.5,53.5,25.0,17.0,15.5,57.5,55.5 +416,TA_19,TA_20,13.0,6.5,5.0,24.5,9.0,9.0,11.0,29.0,26.75 +417,TA_19,TA_20,19.0,17.0,15.5,51.5,23.0,17.0,17.0,57.0,54.25 +418,TA_19,TA_20,13.0,8.0,13.0,34.0,14.0,9.0,13.0,36.0,35.0 +419,TA_19,TA_20,19.0,12.0,9.5,40.5,18.5,12.0,11.0,41.5,41.0 +420,TA_19,TA_20,22.5,8.0,18.0,48.5,21.5,9.5,18.0,49.0,48.75 +421,TA_19,TA_20,16.5,9.5,3.0,29.0,16.5,10.0,2.5,29.0,29.0 +422,TA_19,TA_20,10.0,9.5,0.0,19.5,14.0,9.0,0.0,23.0,21.25 +423,TA_19,TA_20,13.5,11.5,5.0,30.0,12.0,11.0,1.0,24.0,27.0 +424,TA_19,TA_20,10.5,6.5,15.0,32.0,10.0,7.5,14.0,31.5,31.75 +425,TA_19,TA_20,10.0,10.0,6.5,26.5,13.5,9.5,9.5,32.5,29.5 +426,TA_19,TA_20,7.0,9.0,8.5,24.5,9.0,9.0,7.5,25.5,25.0 +427,TA_19,TA_20,3.5,8.0,3.0,14.5,1.0,10.0,4.0,15.0,14.75 +428,TA_19,TA_20,1.0,1.0,0.0,2.0,2.0,4.0,0.0,6.0,4.0 +429,TA_19,TA_20,10.0,4.0,5.0,19.0,12.5,4.5,6.5,23.5,21.25 +430,TA_19,TA_20,3.0,4.0,3.0,10.0,3.5,5.5,5.0,14.0,12.0 +431,TA_19,TA_20,12.5,13.0,17.5,43.0,15.0,13.5,14.5,43.0,43.0 +432,TA_19,TA_20,3.0,0.5,2.0,5.5,-1.0,1.0,2.0,2.0,3.75 +433,TA_19,TA_20,10.0,12.5,15.0,37.5,14.0,12.5,13.5,40.0,38.75 +434,TA_19,TA_20,18.0,16.0,5.5,39.5,21.0,16.5,6.5,44.0,41.75 +435,TA_19,TA_20,4.0,7.0,1.0,12.0,1.0,4.0,1.0,6.0,9.0 +436,TA_19,TA_20,20.0,17.0,21.0,58.0,26.0,16.5,22.0,64.5,61.25 +437,TA_19,TA_20,18.5,12.0,18.0,48.5,19.0,11.5,16.5,47.0,47.75 +438,TA_19,TA_20,15.0,11.5,19.0,45.5,18.5,12.5,20.0,51.0,48.25 +439,TA_19,TA_20,20.0,16.5,22.0,58.5,24.0,17.0,22.0,63.0,60.75 +440,TA_19,TA_20,18.0,0.0,5.5,23.5,19.0,0.0,7.5,26.5,25.0 +441,TA_19,TA_20,14.0,4.0,14.0,32.0,13.5,4.0,12.5,30.0,31.0 +442,TA_19,TA_20,17.5,9.5,17.0,44.0,14.0,10.0,15.0,39.0,41.5 +443,TA_19,TA_20,15.5,9.5,5.0,30.0,12.5,9.0,5.0,26.5,28.25 +444,TA_19,TA_20,11.0,14.0,9.5,34.5,14.5,14.0,8.5,37.0,35.75 +445,TA_19,TA_20,15.0,11.0,9.0,35.0,12.0,10.0,10.5,32.5,33.75 +446,TA_19,TA_20,14.5,11.0,15.5,41.0,18.0,11.5,16.0,45.5,43.25 +447,TA_19,TA_20,14.5,10.0,3.0,27.5,15.5,11.0,3.5,30.0,28.75 +448,TA_19,TA_20,7.0,8.5,8.0,23.5,4.0,9.5,7.5,21.0,22.25 +449,TA_46,TA_22,10.5,0.0,10.0,20.5,10.0,0.0,10.0,20.0,20.25 +450,TA_49+TA_50,TA_22,14.0,6.5,0.0,20.5,15.0,5.0,0.0,20.0,20.25 +451,TA_51,TA_22,0.0,6.0,9.0,15.0,1.0,7.0,4.0,12.0,13.5 +452,TA_47,TA_22,10.5,12.0,3.0,25.5,11.0,13.0,3.0,27.0,26.25 +453,TA_46,TA_22,16.0,13.0,12.0,41.0,13.0,13.0,10.0,36.0,38.5 +454,TA_49+TA_50,TA_22,15.0,11.5,8.0,34.5,16.0,12.0,12.0,40.0,37.25 +455,TA_51,TA_22,14.0,12.0,10.75,36.75,13.0,10.0,12.0,35.0,35.875 +456,TA_47,TA_22,3.0,10.0,2.0,15.0,2.0,5.0,2.0,9.0,12.0 +457,TA_46,TA_22,10.0,13.0,4.0,27.0,10.0,11.0,4.0,25.0,26.0 +458,TA_49+TA_50,TA_22,8.5,6.5,0.0,15.0,8.0,5.0,0.0,13.0,14.0 +459,TA_51,TA_22,18.0,11.0,15.75,44.75,14.0,7.0,17.0,38.0,41.375 +460,TA_47,TA_22,11.0,11.0,10.0,32.0,8.0,14.0,11.0,33.0,32.5 +461,TA_46,TA_22,4.0,2.0,0.0,6.0,9.0,1.0,0.0,10.0,8.0 +462,TA_49+TA_50,TA_22,21.0,17.0,18.0,56.0,16.0,17.0,19.0,52.0,54.0 +463,TA_51,TA_22,4.0,12.0,8.75,24.75,6.0,7.0,9.0,22.0,23.375 +464,TA_47,TA_22,16.0,11.0,18.5,45.5,16.0,13.0,17.0,46.0,45.75 +465,TA_46,TA_22,13.0,11.5,11.0,35.5,14.0,9.0,11.0,34.0,34.75 +466,TA_49+TA_50,TA_22,14.0,13.0,9.0,36.0,16.0,11.0,10.0,37.0,36.5 +467,TA_51,TA_22,16.0,17.0,17.75,50.75,19.0,17.0,16.0,52.0,51.375 +468,TA_47,TA_22,16.0,7.0,7.0,30.0,16.0,9.0,14.0,39.0,34.5 +469,TA_46,TA_22,20.0,13.0,11.0,44.0,20.0,14.0,10.0,44.0,44.0 +470,TA_49+TA_50,TA_22,19.0,17.0,15.0,51.0,19.0,17.0,18.0,54.0,52.5 +471,TA_51,TA_22,17.0,13.0,14.75,44.75,18.0,8.0,18.0,44.0,44.375 +472,TA_47,TA_22,2.0,0.0,2.0,4.0,5.0,4.0,6.0,15.0,9.5 +473,TA_46,TA_22,16.5,14.0,14.0,44.5,17.0,14.0,17.0,48.0,46.25 +474,TA_49+TA_50,TA_22,14.0,14.0,1.0,29.0,14.0,10.0,4.0,28.0,28.5 +475,TA_51,TA_22,12.0,9.0,9.5,30.5,18.0,8.0,12.0,38.0,34.25 +476,TA_47,TA_22,0.0,7.0,4.0,11.0,3.0,5.0,5.0,13.0,12.0 +477,TA_46,TA_22,7.0,11.5,10.0,28.5,5.0,6.0,13.0,24.0,26.25 +478,TA_49+TA_50,TA_22,24.0,17.0,17.0,58.0,21.0,16.0,20.0,57.0,57.5 +479,TA_51,TA_22,9.0,0.0,5.5,14.5,7.0,0.0,8.0,15.0,14.75 +480,TA_47,TA_22,0.0,0.0,11.0,11.0,0.0,0.0,13.0,13.0,12.0 +481,TA_46,TA_22,7.0,1.0,3.0,11.0,10.0,0.0,4.0,14.0,12.5 +482,TA_49+TA_50,TA_22,5.0,4.75,2.0,11.75,7.0,2.0,4.0,13.0,12.375 +483,TA_51,TA_22,12.0,11.0,6.75,29.75,10.0,11.0,7.0,28.0,28.875 +484,TA_47,TA_22,16.0,17.0,12.0,45.0,18.0,17.0,17.0,52.0,48.5 +485,TA_46,TA_22,5.0,10.5,0.0,15.5,4.0,5.0,0.0,9.0,12.25 +486,TA_49+TA_50,TA_22,9.0,17.0,7.0,33.0,7.0,17.0,10.0,34.0,33.5 +487,TA_51,TA_22,5.0,14.0,2.5,21.5,11.0,12.0,2.0,25.0,23.25 +488,TA_47,TA_22,16.0,10.0,13.5,39.5,18.0,10.0,15.0,43.0,41.25 +489,TA_46,TA_22,4.0,3.0,5.0,12.0,8.0,3.0,5.0,16.0,14.0 +490,TA_49+TA_50,TA_22,14.0,13.0,8.5,35.5,12.0,12.0,11.0,35.0,35.25 +491,TA_51,TA_22,14.0,13.0,12.75,39.75,12.0,12.0,14.0,38.0,38.875 +492,TA_47,TA_22,10.0,9.0,9.5,28.5,11.0,10.0,13.0,34.0,31.25 +493,TA_46,TA_22,16.0,14.0,10.0,40.0,15.0,11.0,12.0,38.0,39.0 +494,TA_49+TA_50,TA_22,5.0,0.25,3.0,8.25,5.0,2.0,5.0,12.0,10.125 +495,TA_51,TA_22,10.0,0.0,8.75,18.75,12.0,0.0,10.0,22.0,20.375 +496,TA_47,TA_22,16.0,13.0,18.5,47.5,13.0,14.0,20.0,47.0,47.25 +497,TA_23,TA_24,12.0,11.0,4.0,27.0,8.0,11.0,4.0,23.0,25.0 +498,TA_23,TA_24,5.0,11.0,6.0,22.0,6.0,9.0,5.0,20.0,21.0 +499,TA_23,TA_24,4.5,11.0,11.0,26.5,14.0,13.0,11.0,38.0,32.25 +500,TA_23,TA_24,10.0,10.0,5.0,25.0,12.0,13.0,11.0,36.0,30.5 +501,TA_23,TA_24,15.0,10.0,3.0,28.0,2.0,11.0,3.0,16.0,22.0 +502,TA_23,TA_24,12.0,10.0,13.0,35.0,12.0,10.0,13.0,35.0,35.0 +503,TA_23,TA_24,12.0,10.0,8.0,30.0,8.0,11.0,6.0,25.0,27.5 +504,TA_23,TA_24,7.0,7.0,3.0,17.0,2.0,8.0,3.0,13.0,15.0 +505,TA_23,TA_24,5.0,12.0,10.0,27.0,5.0,13.0,10.0,28.0,27.5 +506,TA_23,TA_24,13.0,14.0,13.0,40.0,15.0,15.0,14.0,44.0,42.0 +507,TA_23,TA_24,18.0,14.0,9.0,41.0,15.0,14.0,9.0,38.0,39.5 +508,TA_23,TA_24,2.0,2.0,6.0,10.0,3.0,2.0,5.0,10.0,10.0 +509,TA_23,TA_24,11.0,12.0,7.0,30.0,11.0,6.0,6.0,23.0,26.5 +510,TA_23,TA_24,10.0,10.0,11.0,31.0,9.0,13.0,11.0,33.0,32.0 +511,TA_23,TA_24,4.0,11.0,6.0,21.0,10.0,10.0,9.0,29.0,25.0 +512,TA_23,TA_24,14.0,14.0,8.0,36.0,9.0,14.0,13.0,36.0,36.0 +513,TA_23,TA_24,22.0,17.0,18.0,57.0,23.0,16.0,24.0,63.0,60.0 +514,TA_23,TA_24,7.0,8.0,9.0,24.0,10.0,0.0,8.0,18.0,21.0 +515,TA_23,TA_24,19.0,17.0,25.0,61.0,17.0,13.0,22.0,52.0,56.5 +516,TA_23,TA_24,18.0,17.0,17.0,52.0,18.0,16.0,18.0,52.0,52.0 +517,TA_23,TA_24,13.5,12.0,12.0,37.5,16.0,8.0,18.0,42.0,39.75 +518,TA_23,TA_24,9.0,10.0,12.0,31.0,8.0,14.0,17.0,39.0,35.0 +519,TA_23,TA_24,18.0,7.0,0.0,25.0,1.0,3.0,4.0,8.0,16.5 +520,TA_23,TA_24,16.0,17.0,12.0,45.0,17.5,16.0,14.0,47.5,46.25 +521,TA_23,TA_24,18.0,12.0,2.0,32.0,14.0,11.0,10.0,35.0,33.5 +522,TA_23,TA_24,15.0,17.0,15.0,47.0,14.0,12.0,10.0,36.0,41.5 +523,TA_23,TA_24,7.0,10.0,7.0,24.0,8.0,11.0,14.0,33.0,28.5 +524,TA_23,TA_24,7.0,11.0,11.0,29.0,4.0,9.0,11.0,24.0,26.5 +525,TA_23,TA_24,7.0,8.0,5.0,20.0,2.5,3.0,2.0,7.5,13.75 +526,TA_23,TA_24,13.0,12.0,9.0,34.0,14.0,12.0,8.0,34.0,34.0 +527,TA_23,TA_24,11.0,10.0,7.0,28.0,11.0,14.0,12.0,37.0,32.5 +528,TA_23,TA_24,8.0,8.0,10.0,26.0,9.0,6.0,6.0,21.0,23.5 +529,TA_23,TA_24,21.0,17.0,22.0,60.0,18.0,15.0,23.0,56.0,58.0 +530,TA_23,TA_24,20.0,13.0,19.0,52.0,18.0,15.0,19.0,52.0,52.0 +531,TA_23,TA_24,7.0,13.0,10.0,30.0,4.0,14.0,10.0,28.0,29.0 +532,TA_23,TA_24,11.0,12.0,0.0,23.0,14.0,12.0,0.0,26.0,24.5 +533,TA_23,TA_24,13.0,5.0,3.0,21.0,9.0,7.0,3.0,19.0,20.0 +534,TA_23,TA_24,9.0,11.0,8.0,28.0,7.0,11.0,9.0,27.0,27.5 +535,TA_23,TA_24,7.0,9.0,8.0,24.0,5.0,9.0,9.0,23.0,23.5 +536,TA_23,TA_24,14.0,11.0,3.0,28.0,8.0,11.0,2.0,21.0,24.5 +537,TA_23,TA_24,7.0,6.0,11.0,24.0,5.0,8.0,5.0,18.0,21.0 +538,TA_23,TA_24,15.0,11.0,16.0,42.0,11.0,11.0,17.0,39.0,40.5 +539,TA_23,TA_24,13.0,14.0,8.0,35.0,0.0,0.0,6.0,6.0,20.5 +540,TA_23,TA_24,11.0,9.0,8.0,28.0,10.0,10.0,9.0,29.0,28.5 +541,TA_23,TA_24,6.0,11.0,6.0,23.0,3.0,9.0,7.0,19.0,21.0 +542,TA_23,TA_24,10.0,8.0,6.0,24.0,12.0,0.0,4.0,16.0,20.0 +543,TA_23,TA_24,7.0,3.0,0.0,10.0,8.5,13.0,7.0,28.5,19.25 +544,TA_23,TA_24,12.0,13.0,4.0,29.0,5.0,9.0,8.0,22.0,25.5 +545,TA_25,TA_26,23.0,13.5,3.5,40.0,20.0,11.5,6.25,37.75,38.875 +546,TA_25,TA_26,19.0,14.0,9.5,42.5,18.0,13.0,11.0,42.0,42.25 +547,TA_25,TA_26,0.0,1.0,2.5,3.5,0.0,0.0,2.5,2.5,3.0 +548,TA_25,TA_26,9.0,1.0,2.0,12.0,4.0,1.0,2.0,7.0,9.5 +549,TA_25,TA_26,3.0,0.0,4.0,7.0,4.5,0.0,6.0,10.5,8.75 +550,TA_25,TA_26,5.0,10.0,13.0,28.0,14.0,9.5,11.0,34.5,31.25 +551,TA_25,TA_26,1.0,8.0,2.5,11.5,0.0,3.0,0.0,3.0,7.25 +552,TA_25,TA_26,13.5,13.0,14.0,40.5,13.5,14.0,13.5,41.0,40.75 +553,TA_25,TA_26,12.5,11.0,5.0,28.5,3.25,8.0,5.5,16.75,22.625 +554,TA_25,TA_26,8.0,2.0,0.0,10.0,9.0,2.5,0.0,11.5,10.75 +555,TA_25,TA_26,13.0,8.0,13.5,34.5,10.5,4.0,15.0,29.5,32.0 +556,TA_25,TA_26,16.0,9.0,2.0,27.0,16.5,5.5,2.0,24.0,25.5 +557,TA_25,TA_26,17.5,17.0,6.0,40.5,18.5,17.0,6.0,41.5,41.0 +558,TA_25,TA_26,19.0,10.0,17.0,46.0,17.5,11.0,16.0,44.5,45.25 +559,TA_25,TA_26,13.0,12.5,6.0,31.5,11.0,11.5,6.0,28.5,30.0 +560,TA_25,TA_26,20.0,0.0,20.0,40.0,18.0,0.0,21.5,39.5,39.75 +561,TA_25,TA_26,18.0,14.0,11.0,43.0,18.0,14.0,9.0,41.0,42.0 +562,TA_25,TA_26,19.5,12.5,19.0,51.0,19.0,12.5,18.5,50.0,50.5 +563,TA_25,TA_26,20.0,17.0,20.0,57.0,17.5,17.0,22.0,56.5,56.75 +564,TA_25,TA_26,14.0,9.0,8.0,31.0,6.0,8.5,6.5,21.0,26.0 +565,TA_25,TA_26,17.0,14.0,18.0,49.0,19.0,17.0,19.0,55.0,52.0 +566,TA_25,TA_26,12.5,9.0,3.5,25.0,7.0,6.0,3.75,16.75,20.875 +567,TA_25,TA_26,14.0,14.0,15.5,43.5,12.5,15.0,16.0,43.5,43.5 +568,TA_25,TA_26,11.5,11.0,8.0,30.5,10.5,11.0,6.0,27.5,29.0 +569,TA_25,TA_26,17.0,14.5,17.5,49.0,18.0,13.5,17.0,48.5,48.75 +570,TA_25,TA_26,15.0,15.0,12.0,42.0,16.0,15.5,11.5,43.0,42.5 +571,TA_25,TA_26,7.5,1.0,8.0,16.5,8.25,1.5,5.0,14.75,15.625 +572,TA_25,TA_26,18.0,15.0,0.0,33.0,23.0,17.0,0.0,40.0,36.5 +573,TA_25,TA_26,11.0,15.0,0.0,26.0,14.0,13.0,0.0,27.0,26.5 +574,TA_25,TA_26,16.5,17.0,20.0,53.5,16.5,17.0,20.5,54.0,53.75 +575,TA_25,TA_26,19.0,13.0,11.0,43.0,18.5,14.0,12.5,45.0,44.0 +576,TA_25,TA_26,18.0,11.0,8.0,37.0,20.5,12.25,12.0,44.75,40.875 +577,TA_25,TA_26,18.5,14.0,21.0,53.5,22.5,17.0,22.0,61.5,57.5 +578,TA_25,TA_26,13.5,13.0,10.0,36.5,17.0,13.0,10.0,40.0,38.25 +579,TA_25,TA_26,16.0,11.5,4.0,31.5,18.5,12.0,2.0,32.5,32.0 +580,TA_25,TA_26,18.0,14.0,11.5,43.5,18.0,15.0,14.0,47.0,45.25 +581,TA_25,TA_26,7.1,1.0,5.0,13.1,6.0,0.0,3.0,9.0,11.05 +582,TA_25,TA_26,24.0,14.0,20.0,58.0,22.5,14.0,20.0,56.5,57.25 +583,TA_25,TA_26,10.5,3.5,7.0,21.0,5.0,7.5,6.5,19.0,20.0 +584,TA_25,TA_26,14.5,12.5,17.0,44.0,17.0,13.0,19.5,49.5,46.75 +585,TA_25,TA_26,8.0,4.0,18.0,30.0,6.5,4.0,12.0,22.5,26.25 +586,TA_25,TA_26,12.5,11.0,7.0,30.5,16.5,10.0,8.5,35.0,32.75 +587,TA_25,TA_26,16.0,12.0,17.0,45.0,16.5,12.5,15.0,44.0,44.5 +588,TA_25,TA_26,5.5,11.0,7.0,23.5,4.75,9.5,7.5,21.75,22.625 +589,TA_25,TA_26,21.0,14.0,19.0,54.0,26.0,15.5,19.0,60.5,57.25 +590,TA_25,TA_26,11.0,12.0,5.0,28.0,10.5,9.0,4.0,23.5,25.75 +591,TA_25,TA_26,17.0,16.0,21.0,54.0,15.5,16.25,22.0,53.75,53.875 +592,TA_25,TA_26,17.0,14.0,19.5,50.5,17.5,17.0,19.5,54.0,52.25 +593,TA_25,TA_26,13.0,14.0,17.0,44.0,17.0,14.0,18.5,49.5,46.75 +594,TA_25,TA_26,16.5,10.5,15.0,42.0,14.0,10.5,16.0,40.5,41.25 +595,TA_25,TA_26,17.0,12.0,13.5,42.5,16.0,14.0,14.5,44.5,43.5 +596,TA_27,TA_28,6.0,0.0,4.0,10.0,9.0,0.0,6.0,15.0,12.5 +597,TA_27,TA_28,2.0,0.0,0.0,2.0,5.0,0.0,0.0,5.0,3.5 +598,TA_27,TA_28,6.5,11.0,9.5,27.0,10.0,11.0,12.0,33.0,30.0 +599,TA_27,TA_28,23.0,13.0,9.5,45.5,23.0,13.0,9.0,45.0,45.25 +600,TA_27,TA_28,13.0,8.5,12.0,33.5,14.5,11.5,13.5,39.5,36.5 +601,TA_27,TA_28,13.5,0.0,0.0,13.5,17.0,1.5,0.0,18.5,16.0 +602,TA_27,TA_28,7.5,6.5,5.0,19.0,9.5,9.5,4.0,23.0,21.0 +603,TA_27,TA_28,20.0,11.5,6.5,38.0,21.0,13.0,14.0,48.0,43.0 +604,TA_27,TA_28,13.0,10.0,0.0,23.0,13.5,12.0,0.0,25.5,24.25 +605,TA_27,TA_28,12.0,11.5,0.0,23.5,12.5,16.0,0.0,28.5,26.0 +606,TA_27,TA_28,3.5,2.5,2.0,8.0,7.5,7.0,6.5,21.0,14.5 +607,TA_27,TA_28,15.0,11.0,11.0,37.0,20.0,13.5,15.0,48.5,42.75 +608,TA_27,TA_28,10.0,0.0,8.0,18.0,10.0,2.5,10.0,22.5,20.25 +609,TA_27,TA_28,14.0,7.5,8.0,29.5,14.0,11.5,10.0,35.5,32.5 +610,TA_27,TA_28,8.0,9.5,3.0,20.5,14.0,11.0,4.5,29.5,25.0 +611,TA_27,TA_28,8.0,7.5,5.0,20.5,12.5,11.0,5.5,29.0,24.75 +612,TA_27,TA_28,8.5,10.0,14.0,32.5,9.0,12.5,16.5,38.0,35.25 +613,TA_27,TA_28,17.5,15.0,22.0,54.5,17.5,15.0,22.0,54.5,54.5 +614,TA_27,TA_28,13.0,10.0,17.5,40.5,17.5,13.5,18.5,49.5,45.0 +615,TA_27,TA_28,14.0,0.0,3.0,17.0,16.5,0.0,3.0,19.5,18.25 +616,TA_27,TA_28,13.5,17.0,0.0,30.5,15.0,17.0,0.0,32.0,31.25 +617,TA_27,TA_28,8.0,14.0,8.0,30.0,11.5,14.0,9.0,34.5,32.25 +618,TA_27,TA_28,15.0,10.5,9.0,34.5,16.0,13.0,17.0,46.0,40.25 +619,TA_27,TA_28,19.0,17.0,19.0,55.0,19.5,17.0,20.0,56.5,55.75 +620,TA_27,TA_28,7.5,8.0,8.0,23.5,15.0,11.0,9.0,35.0,29.25 +621,TA_27,TA_28,8.5,10.5,18.0,37.0,11.5,12.5,15.0,39.0,38.0 +622,TA_27,TA_28,18.5,14.5,16.0,49.0,19.0,17.0,20.0,56.0,52.5 +623,TA_27,TA_28,9.0,8.0,5.5,22.5,9.5,11.0,10.0,30.5,26.5 +624,TA_27,TA_28,11.5,10.0,4.0,25.5,12.5,11.5,9.5,33.5,29.5 +625,TA_27,TA_28,14.0,7.5,15.5,37.0,22.0,11.5,17.0,50.5,43.75 +626,TA_27,TA_28,17.5,3.0,0.0,20.5,20.0,3.0,0.0,23.0,21.75 +627,TA_27,TA_28,10.0,11.5,6.0,27.5,14.5,12.5,7.5,34.5,31.0 +628,TA_27,TA_28,10.0,8.5,3.0,21.5,14.0,11.5,4.5,30.0,25.75 +629,TA_27,TA_28,7.5,6.0,8.0,21.5,13.5,9.0,13.5,36.0,28.75 +630,TA_27,TA_28,1.5,0.0,0.0,1.5,1.5,0.0,0.0,1.5,1.5 +631,TA_27,TA_28,13.5,6.5,0.0,20.0,17.0,11.0,0.0,28.0,24.0 +632,TA_27,TA_28,9.0,10.5,10.5,30.0,10.0,12.0,12.0,34.0,32.0 +633,TA_27,TA_28,17.5,10.0,15.0,42.5,18.0,11.0,15.0,44.0,43.25 +634,TA_27,TA_28,0.0,0.0,0.0,0.0,14.5,16.0,20.5,51.0,25.5 +635,TA_27,TA_28,8.0,4.5,4.5,17.0,11.0,10.0,7.0,28.0,22.5 +636,TA_27,TA_28,18.5,17.0,18.0,53.5,22.5,17.0,20.0,59.5,56.5 +637,TA_27,TA_28,20.5,10.5,18.0,49.0,21.5,10.5,18.0,50.0,49.5 +638,TA_27,TA_28,20.0,12.0,17.0,49.0,20.5,12.5,17.5,50.5,49.75 +639,TA_27,TA_28,13.5,12.5,18.5,44.5,14.0,12.5,20.0,46.5,45.5 +640,TA_27,TA_28,15.5,7.0,13.5,36.0,17.0,11.5,16.5,45.0,40.5 +641,TA_27,TA_28,12.0,16.0,18.5,46.5,13.5,16.5,19.0,49.0,47.75 +642,TA_27,TA_28,10.0,8.5,15.5,34.0,18.0,13.5,18.0,49.5,41.75 +643,TA_27,TA_28,21.5,14.0,17.0,52.5,22.0,14.0,18.0,54.0,53.25 +644,TA_46,TA_30,9.0,7.5,4.0,20.5,8.5,9.5,4.5,22.5,21.5 +645,TA_49+TA_50,TA_30,18.0,0.0,0.0,18.0,18.0,0.0,2.5,20.5,19.25 +646,TA_51,TA_30,15.0,13.0,7.75,35.75,15.0,10.5,7.5,33.0,34.375 +647,TA_47,TA_30,17.5,12.0,3.0,32.5,18.0,14.0,3.0,35.0,33.75 +648,TA_46,TA_30,17.5,12.5,13.0,43.0,18.5,8.5,17.5,44.5,43.75 +649,TA_49+TA_50,TA_30,3.6,4.0,0.0,7.6,2.5,8.5,0.0,11.0,9.3 +650,TA_51,TA_30,12.0,9.0,9.5,30.5,12.0,10.0,9.5,31.5,31.0 +651,TA_47,TA_30,24.0,17.0,21.5,62.5,24.0,16.0,21.5,61.5,62.0 +652,TA_46,TA_30,20.0,17.0,16.0,53.0,18.5,16.5,16.5,51.5,52.25 +653,TA_49+TA_50,TA_30,15.0,13.5,1.0,29.5,19.0,12.0,4.5,35.5,32.5 +654,TA_51,TA_30,15.0,10.0,0.0,25.0,14.5,7.5,0.0,22.0,23.5 +655,TA_47,TA_30,17.5,13.0,3.0,33.5,17.0,11.5,12.0,40.5,37.0 +656,TA_46,TA_30,11.0,14.0,5.0,30.0,16.0,14.0,4.5,34.5,32.25 +657,TA_49+TA_50,TA_30,15.0,11.0,2.0,28.0,15.0,8.75,6.0,29.75,28.875 +658,TA_51,TA_30,6.0,8.0,6.75,20.75,6.5,11.0,8.5,26.0,23.375 +659,TA_47,TA_30,9.0,8.0,9.0,26.0,13.0,15.5,10.5,39.0,32.5 +660,TA_46,TA_30,16.5,13.0,5.0,34.5,16.5,12.5,6.0,35.0,34.75 +661,TA_49+TA_50,TA_30,5.5,9.0,8.0,22.5,11.5,9.5,12.0,33.0,27.75 +662,TA_51,TA_30,16.0,8.0,13.0,37.0,17.0,10.5,12.5,40.0,38.5 +663,TA_47,TA_30,15.0,11.0,19.0,45.0,17.0,14.5,19.75,51.25,48.125 +664,TA_46,TA_30,19.0,9.0,12.0,40.0,18.5,10.0,13.0,41.5,40.75 +665,TA_49+TA_50,TA_30,13.0,11.0,3.0,27.0,11.5,11.5,7.0,30.0,28.5 +666,TA_51,TA_30,12.0,14.0,9.5,35.5,16.5,13.5,13.0,43.0,39.25 +667,TA_47,TA_30,2.0,0.0,3.0,5.0,2.5,0.5,4.0,7.0,6.0 +668,TA_46,TA_30,10.0,0.0,0.0,10.0,8.0,0.0,0.0,8.0,9.0 +669,TA_48,TA_30,17.0,10.0,8.0,35.0,15.5,10.5,10.0,36.0,35.5 +670,TA_51,TA_30,19.5,11.0,13.0,43.5,22.0,16.0,12.0,50.0,46.75 +671,TA_47,TA_30,12.0,14.0,18.5,44.5,13.0,14.0,20.5,47.5,46.0 +672,TA_46,TA_30,21.0,14.0,9.0,44.0,21.0,13.0,12.0,46.0,45.0 +673,TA_48,TA_30,6.0,9.0,4.0,19.0,10.0,11.5,4.0,25.5,22.25 +674,TA_51,TA_30,5.0,13.0,12.0,30.0,15.5,11.5,13.0,40.0,35.0 +675,TA_47,TA_30,12.5,17.0,16.5,46.0,13.75,16.5,18.25,48.5,47.25 +676,TA_46,TA_30,14.0,14.0,15.0,43.0,18.0,13.5,15.5,47.0,45.0 +677,TA_48,TA_30,4.0,9.0,0.0,13.0,9.0,12.0,0.0,21.0,17.0 +678,TA_51,TA_30,7.0,0.0,0.0,7.0,9.0,0.0,0.0,9.0,8.0 +679,TA_47,TA_30,10.0,11.0,0.0,21.0,9.5,14.0,0.0,23.5,22.25 +680,TA_46,TA_30,8.0,12.5,6.0,26.5,9.0,13.5,9.0,31.5,29.0 +681,TA_48,TA_30,9.5,7.0,2.0,18.5,13.5,12.0,2.0,27.5,23.0 +682,TA_51,TA_30,2.0,10.0,7.5,19.5,7.5,14.5,11.5,33.5,26.5 +683,TA_47,TA_30,15.0,15.0,15.0,45.0,15.0,15.0,17.3,47.3,46.15 +684,TA_46,TA_30,7.0,13.0,14.0,34.0,10.0,11.5,13.0,34.5,34.25 +685,TA_48,TA_30,3.5,0.0,4.0,7.5,5.75,0.5,4.75,11.0,9.25 +686,TA_51,TA_30,22.5,12.0,20.5,55.0,25.0,12.5,21.0,58.5,56.75 +687,TA_47,TA_30,6.0,14.0,6.0,26.0,7.0,13.0,6.0,26.0,26.0 +688,TA_46,TA_30,12.0,14.0,6.0,32.0,18.5,13.5,6.0,38.0,35.0 +689,TA_48,TA_30,16.0,10.0,18.0,44.0,17.5,12.0,16.5,46.0,45.0 +690,TA_51,TA_30,20.0,12.0,22.0,54.0,18.0,11.5,22.0,51.5,52.75 +691,TA_47,TA_30,13.0,8.0,13.5,34.5,11.0,10.0,13.0,34.0,34.25 +692,TA_46,TA_30,19.0,14.0,15.0,48.0,22.5,11.0,12.5,46.0,47.0 +693,TA_48,TA_30,4.0,4.0,4.0,12.0,5.0,12.5,8.0,25.5,18.75 +694,TA_31,TA_32,20.0,13.5,12.0,45.5,19.5,14.0,14.0,47.5,46.5 +695,TA_31,TA_32,3.0,0.0,6.0,9.0,10.0,0.5,7.0,17.5,13.25 +696,TA_31,TA_32,9.5,7.0,5.0,21.5,10.5,10.5,6.5,27.5,24.5 +697,TA_31,TA_32,5.5,0.0,7.0,12.5,9.0,0.0,11.0,20.0,16.25 +698,TA_31,TA_32,12.0,12.5,14.0,38.5,13.5,13.0,16.0,42.5,40.5 +699,TA_31,TA_32,15.0,8.0,15.5,38.5,13.0,11.5,16.0,40.5,39.5 +700,TA_31,TA_32,4.0,8.5,8.0,20.5,8.0,12.5,13.5,34.0,27.25 +701,TA_31,TA_32,8.0,16.0,14.0,38.0,8.0,17.0,17.0,42.0,40.0 +702,TA_31,TA_32,13.0,9.0,14.5,36.5,14.0,12.0,15.0,41.0,38.75 +703,TA_31,TA_32,14.0,9.5,7.5,31.0,16.5,13.0,11.5,41.0,36.0 +704,TA_31,TA_32,11.0,8.0,2.0,21.0,15.0,10.5,2.0,27.5,24.25 +705,TA_31,TA_32,0.5,0.0,0.0,0.5,1.0,0.0,0.0,1.0,0.75 +706,TA_31,TA_32,22.0,17.0,18.0,57.0,22.5,17.0,18.5,58.0,57.5 +707,TA_31,TA_32,7.0,6.0,10.5,23.5,14.0,12.5,15.5,42.0,32.75 +708,TA_31,TA_32,16.0,14.0,9.0,39.0,16.0,14.0,10.5,40.5,39.75 +709,TA_31,TA_32,8.5,6.0,2.0,16.5,13.5,9.5,3.0,26.0,21.25 +710,TA_31,TA_32,14.5,9.5,7.5,31.5,18.0,11.5,13.5,43.0,37.25 +711,TA_31,TA_32,12.0,7.5,0.5,20.0,13.0,12.0,0.0,25.0,22.5 +712,TA_31,TA_32,9.0,1.0,5.0,15.0,12.0,2.0,10.0,24.0,19.5 +713,TA_31,TA_32,5.5,6.0,3.0,14.5,8.0,8.0,6.0,22.0,18.25 +714,TA_31,TA_32,13.0,7.5,12.0,32.5,13.0,10.0,15.0,38.0,35.25 +715,TA_31,TA_33,3.0,4.0,5.0,12.0,2.0,6.0,5.0,13.0,12.5 +716,TA_31,TA_32,8.0,1.0,7.5,16.5,13.5,1.5,13.5,28.5,22.5 +717,TA_31,TA_32,11.0,8.0,13.0,32.0,12.0,13.0,16.5,41.5,36.75 +718,TA_31,TA_32,13.0,8.5,10.0,31.5,15.0,10.5,14.0,39.5,35.5 +719,TA_31,TA_33,16.5,9.0,12.0,37.5,17.5,16.0,11.0,44.5,41.0 +720,TA_31,TA_32,8.0,10.0,11.5,29.5,12.0,13.0,13.0,38.0,33.75 +721,TA_31,TA_32,5.0,5.0,5.0,15.0,8.0,7.5,5.5,21.0,18.0 +722,TA_31,TA_32,8.5,0.0,4.0,12.5,10.5,0.0,6.0,16.5,14.5 +723,TA_31,TA_32,9.5,13.0,8.0,30.5,10.0,13.5,12.0,35.5,33.0 +724,TA_31,TA_32,6.0,2.0,5.0,13.0,9.0,1.5,9.0,19.5,16.25 +725,TA_31,TA_32,10.0,0.0,6.5,16.5,11.5,0.0,11.0,22.5,19.5 +726,TA_31,TA_32,12.0,9.0,9.5,30.5,12.0,11.0,12.5,35.5,33.0 +727,TA_31,TA_32,11.0,11.5,7.5,30.0,15.0,13.5,11.0,39.5,34.75 +728,TA_31,TA_32,5.0,7.5,2.0,14.5,7.0,10.5,4.5,22.0,18.25 +729,TA_31,TA_32,6.0,10.0,10.0,26.0,8.0,13.0,13.0,34.0,30.0 +730,TA_31,TA_32,20.0,10.0,11.0,41.0,20.0,12.0,13.5,45.5,43.25 +731,TA_31,TA_32,19.0,11.5,13.0,43.5,17.0,15.0,15.0,47.0,45.25 +732,TA_31,TA_32,8.0,5.0,3.0,16.0,9.5,7.5,5.0,22.0,19.0 +733,TA_31,TA_32,15.5,14.0,11.0,40.5,14.5,14.0,15.0,43.5,42.0 +734,TA_31,TA_32,13.0,10.0,8.5,31.5,15.0,15.0,11.5,41.5,36.5 +735,TA_31,TA_32,18.0,12.0,15.0,45.0,17.5,14.0,17.0,48.5,46.75 +736,TA_31,TA_32,5.0,10.0,7.0,22.0,8.0,12.5,8.0,28.5,25.25 +737,TA_31,TA_32,3.5,3.0,1.5,8.0,1.5,7.5,3.0,12.0,10.0 +738,TA_31,TA_32,19.0,10.0,15.0,44.0,19.5,11.5,14.0,45.0,44.5 +739,TA_31,TA_32,4.0,5.0,4.5,13.5,6.5,10.5,5.5,22.5,18.0 +740,TA_31,TA_32,4.0,8.0,5.0,17.0,5.5,12.0,9.0,26.5,21.75 +741,TA_34,TA_35,0.0,0.0,8.5,8.5,0.0,0.0,10.0,10.0,9.25 +742,TA_34,TA_35,17.0,13.0,18.0,48.0,7.0,8.5,13.5,29.0,38.5 +743,TA_34,TA_35,26.0,16.0,14.5,56.5,21.0,14.0,3.0,38.0,47.25 +744,TA_34,TA_33,4.0,3.0,4.0,11.0,6.0,5.0,5.0,16.0,13.5 +745,TA_34,TA_35,10.0,10.0,12.0,32.0,9.75,11.5,10.0,31.25,31.625 +746,TA_34,TA_35,10.5,7.5,6.5,24.5,12.0,10.0,15.0,37.0,30.75 +747,TA_34,TA_35,16.5,9.5,11.5,37.5,17.0,11.5,9.5,38.0,37.75 +748,TA_34,TA_35,22.5,9.5,13.5,45.5,15.5,13.5,11.5,40.5,43.0 +749,TA_34,TA_35,12.5,7.5,9.5,29.5,5.0,9.5,3.5,18.0,23.75 +750,TA_34,TA_35,28.0,16.0,20.0,64.0,15.0,12.5,13.5,41.0,52.5 +751,TA_34,TA_35,14.5,7.5,13.5,35.5,20.0,14.0,18.0,52.0,43.75 +752,TA_34,TA_35,21.0,16.0,14.5,51.5,15.0,14.0,7.0,36.0,43.75 +753,TA_34,TA_35,27.0,16.0,22.0,65.0,20.0,13.0,18.0,51.0,58.0 +754,TA_34,TA_35,14.0,0.0,10.0,24.0,7.0,0.0,11.0,18.0,21.0 +755,TA_34,TA_35,20.0,8.0,10.0,38.0,19.0,13.0,8.0,40.0,39.0 +756,TA_34,TA_35,20.0,5.5,11.5,37.0,14.0,9.0,13.0,36.0,36.5 +757,TA_34,TA_33,12.5,6.0,9.5,28.0,12.0,12.0,9.5,33.5,30.75 +758,TA_34,TA_35,15.0,7.5,12.5,35.0,5.5,3.5,8.5,17.5,26.25 +759,TA_34,TA_35,28.0,15.0,20.0,63.0,17.5,12.5,7.0,37.0,50.0 +760,TA_34,TA_35,13.5,16.0,6.5,36.0,12.0,14.0,4.5,30.5,33.25 +761,TA_34,TA_33,16.0,3.0,5.0,24.0,13.0,9.0,14.0,36.0,30.0 +762,TA_34,TA_35,7.5,10.0,13.5,31.0,6.0,8.0,15.0,29.0,30.0 +763,TA_34,TA_35,12.5,6.5,9.5,28.5,3.5,0.0,3.0,6.5,17.5 +764,TA_34,TA_35,8.5,6.5,4.0,19.0,16.0,8.0,3.5,27.5,23.25 +765,TA_34,TA_35,25.0,8.0,13.0,46.0,21.0,10.0,10.0,41.0,43.5 +766,TA_34,TA_35,11.0,5.5,6.5,23.0,5.5,11.0,3.5,20.0,21.5 +767,TA_34,TA_35,24.0,10.0,17.0,51.0,20.0,16.0,19.0,55.0,53.0 +768,TA_34,TA_35,12.0,12.5,10.0,34.5,5.0,8.0,7.5,20.5,27.5 +769,TA_34,TA_33,17.5,9.0,19.0,45.5,10.0,13.0,17.0,40.0,42.75 +770,TA_34,TA_35,21.5,12.5,16.5,50.5,18.0,14.0,17.0,49.0,49.75 +771,TA_34,TA_35,15.0,13.0,11.5,39.5,15.0,16.0,20.0,51.0,45.25 +772,TA_34,TA_35,17.0,8.0,15.0,40.0,10.5,11.0,12.0,33.5,36.75 +773,TA_34,TA_35,11.5,7.0,9.5,28.0,13.0,12.0,10.0,35.0,31.5 +774,TA_34,TA_35,17.0,13.0,17.0,47.0,18.0,15.0,20.0,53.0,50.0 +775,TA_34,TA_35,21.0,13.0,20.0,54.0,8.0,12.0,14.0,34.0,44.0 +776,TA_34,TA_35,15.0,9.0,14.0,38.0,4.0,5.5,5.5,15.0,26.5 +777,TA_34,TA_35,18.5,10.0,2.5,31.0,13.5,12.0,3.0,28.5,29.75 +778,TA_34,TA_35,20.0,14.0,14.0,48.0,20.5,14.0,18.0,52.5,50.25 +779,TA_34,TA_35,12.5,14.0,22.0,48.5,18.5,13.5,19.0,51.0,49.75 +780,TA_34,TA_35,13.5,7.5,10.5,31.5,5.5,14.0,4.0,23.5,27.5 +781,TA_34,TA_35,14.5,8.0,11.0,33.5,13.0,11.5,13.0,37.5,35.5 +782,TA_34,TA_35,22.5,9.5,10.5,42.5,14.0,8.5,7.5,30.0,36.25 +783,TA_34,TA_35,21.0,16.0,13.0,50.0,16.0,14.0,2.0,32.0,41.0 +784,TA_34,TA_35,23.5,14.5,18.5,56.5,17.0,14.0,14.0,45.0,50.75 +785,TA_34,TA_35,16.0,12.0,16.0,44.0,6.0,13.0,6.0,25.0,34.5 +786,TA_34,TA_35,23.5,16.0,21.0,60.5,20.5,14.0,19.0,53.5,57.0 +787,TA_34,TA_35,25.0,5.0,17.0,47.0,18.0,2.0,13.0,33.0,40.0 +788,TA_34,TA_35,24.0,13.0,19.0,56.0,17.0,0.0,1.0,18.0,37.0 +789,TA_34,TA_35,13.5,12.5,14.5,40.5,7.0,13.0,15.5,35.5,38.0 +790,TA_34,TA_35,26.0,15.5,19.5,61.0,23.0,16.0,22.0,61.0,61.0 +791,TA_36,TA_37,12.0,9.5,3.5,25.0,14.0,10.0,8.0,32.0,28.5 +792,TA_36,TA_37,5.0,6.0,5.0,16.0,11.0,5.0,7.5,23.5,19.75 +793,TA_36,TA_37,8.5,8.0,8.0,24.5,14.5,9.5,13.0,37.0,30.75 +794,TA_36,TA_37,13.0,8.5,8.5,30.0,14.0,12.5,10.0,36.5,33.25 +795,TA_36,TA_37,7.5,9.0,14.5,31.0,9.0,10.0,12.0,31.0,31.0 +796,TA_36,TA_37,10.0,0.0,0.0,10.0,8.0,0.0,0.0,8.0,9.0 +797,TA_36,TA_37,9.0,8.0,9.5,26.5,10.0,9.0,11.0,30.0,28.25 +798,TA_36,TA_37,8.0,1.5,5.5,15.0,11.0,1.0,4.0,16.0,15.5 +799,TA_36,TA_37,11.0,11.5,13.0,35.5,11.0,12.0,13.0,36.0,35.75 +800,TA_36,TA_37,15.0,9.0,3.5,27.5,20.0,10.0,6.0,36.0,31.75 +801,TA_36,TA_37,17.5,11.0,18.75,47.25,18.0,12.0,18.0,48.0,47.625 +802,TA_36,TA_37,15.5,12.0,17.0,44.5,20.5,14.0,15.5,50.0,47.25 +803,TA_36,TA_37,1.5,2.5,0.5,4.5,2.0,5.0,0.5,7.5,6.0 +804,TA_36,TA_37,13.0,14.0,4.5,31.5,12.0,14.0,5.5,31.5,31.5 +805,TA_36,TA_37,14.0,10.5,8.5,33.0,16.0,11.5,10.5,38.0,35.5 +806,TA_36,TA_37,17.5,8.0,18.0,43.5,18.0,7.5,17.0,42.5,43.0 +807,TA_36,TA_37,18.0,17.0,4.5,39.5,18.0,17.0,7.0,42.0,40.75 +808,TA_36,TA_37,9.0,7.0,7.0,23.0,13.0,9.5,13.0,35.5,29.25 +809,TA_36,TA_37,8.0,8.5,5.0,21.5,10.5,10.0,8.0,28.5,25.0 +810,TA_36,TA_37,11.5,10.0,4.0,25.5,13.0,10.5,5.0,28.5,27.0 +811,TA_36,TA_37,9.0,9.0,0.0,18.0,10.5,10.0,0.0,20.5,19.25 +812,TA_36,TA_37,10.5,5.0,0.0,15.5,14.0,6.0,0.0,20.0,17.75 +813,TA_36,TA_37,8.5,0.0,0.0,8.5,10.0,0.0,0.0,10.0,9.25 +814,TA_36,TA_33,7.5,6.0,8.0,21.5,10.0,4.0,12.0,26.0,23.75 +815,TA_36,TA_37,24.0,17.0,21.0,62.0,23.5,17.0,19.0,59.5,60.75 +816,TA_36,TA_37,16.0,9.5,10.0,35.5,18.0,10.5,17.0,45.5,40.5 +817,TA_36,TA_37,15.0,1.0,2.0,18.0,13.5,1.0,2.0,16.5,17.25 +818,TA_36,TA_37,6.5,14.0,7.0,27.5,6.5,14.0,7.5,28.0,27.75 +819,TA_36,TA_37,17.0,4.0,15.5,36.5,19.0,4.0,18.0,41.0,38.75 +820,TA_36,TA_37,8.0,9.5,6.0,23.5,10.0,9.5,8.0,27.5,25.5 +821,TA_36,TA_37,11.5,11.0,2.5,25.0,14.0,9.5,3.0,26.5,25.75 +822,TA_36,TA_37,7.0,9.0,6.0,22.0,7.5,10.5,7.0,25.0,23.5 +823,TA_36,TA_37,13.5,10.5,7.5,31.5,18.0,11.5,14.0,43.5,37.5 +824,TA_36,TA_37,16.0,0.0,16.0,32.0,16.0,1.0,16.0,33.0,32.5 +825,TA_36,TA_37,14.5,13.0,9.5,37.0,15.0,14.0,12.5,41.5,39.25 +826,TA_36,TA_37,13.0,12.0,12.0,37.0,13.0,12.5,12.0,37.5,37.25 +827,TA_36,TA_37,17.0,12.0,4.0,33.0,17.0,12.0,5.0,34.0,33.5 +828,TA_36,TA_37,11.0,16.0,10.0,37.0,15.0,17.0,11.5,43.5,40.25 +829,TA_36,TA_33,19.0,9.0,18.0,46.0,21.0,9.0,17.0,47.0,46.5 +830,TA_36,TA_37,9.5,8.0,2.0,19.5,6.0,10.0,2.0,18.0,18.75 +831,TA_36,TA_37,6.5,13.0,6.0,25.5,9.5,14.0,7.0,30.5,28.0 +832,TA_36,TA_37,11.0,3.5,3.0,17.5,11.5,6.0,4.0,21.5,19.5 +833,TA_36,TA_37,12.0,9.0,2.0,23.0,13.0,11.5,2.0,26.5,24.75 +834,TA_36,TA_37,5.5,9.0,6.5,21.0,6.0,9.5,13.0,28.5,24.75 +835,TA_36,TA_37,16.0,11.0,6.0,33.0,21.0,12.5,7.0,40.5,36.75 +836,TA_36,TA_37,21.5,0.0,0.0,21.5,16.0,0.0,0.0,16.0,18.75 +837,TA_36,TA_37,4.5,6.5,5.0,16.0,8.0,5.0,6.0,19.0,17.5 +838,TA_36,TA_37,20.5,12.5,17.5,50.5,23.5,12.0,20.0,55.5,53.0 +839,TA_36,TA_37,18.0,12.5,9.0,39.5,17.0,14.0,12.5,43.5,41.5 +840,TA_36,TA_37,16.0,7.5,9.5,33.0,15.5,9.5,10.0,35.0,34.0 +841,TA_38,TA_51,12.5,13.5,11.0,37.0,8.0,11.0,4.75,23.75,30.375 +842,TA_38,TA_47,6.0,0.0,3.0,9.0,5.0,0.0,4.0,9.0,9.0 +843,TA_38,TA_46,6.5,8.5,6.0,21.0,3.0,7.5,5.0,15.5,18.25 +844,TA_38,TA_48,19.5,13.5,13.0,46.0,17.5,11.0,12.0,40.5,43.25 +845,TA_38,TA_51,10.5,12.5,3.0,26.0,10.0,13.0,4.5,27.5,26.75 +846,TA_38,TA_48,13.5,0.0,4.0,17.5,12.0,0.0,3.0,15.0,16.25 +847,TA_38,TA_33,8.0,9.5,9.5,27.0,6.0,9.0,5.0,20.0,23.5 +848,TA_38,TA_46,13.5,10.5,7.5,31.5,13.0,11.5,7.0,31.5,31.5 +849,TA_38,TA_48,18.0,11.5,2.5,32.0,17.0,9.0,2.0,28.0,30.0 +850,TA_38,TA_51,15.0,10.0,6.5,31.5,13.5,10.0,7.0,30.5,31.0 +851,TA_38,TA_48,20.0,0.0,18.5,38.5,16.0,0.0,16.0,32.0,35.25 +852,TA_38,TA_46,7.5,11.5,8.5,27.5,8.0,12.5,4.0,24.5,26.0 +853,TA_38,TA_48,9.0,12.5,5.5,27.0,4.0,11.0,2.0,17.0,22.0 +854,TA_38,TA_51,20.0,12.5,19.0,51.5,19.5,15.0,19.75,54.25,52.875 +855,TA_38,TA_48,0.0,11.0,9.5,20.5,0.0,6.0,9.0,15.0,17.75 +856,TA_38,TA_46,14.0,0.0,4.0,18.0,12.0,0.0,3.0,15.0,16.5 +857,TA_38,TA_33,15.0,12.0,7.0,34.0,13.0,13.0,6.0,32.0,33.0 +858,TA_38,TA_48,11.5,13.0,6.5,31.0,10.0,12.0,10.0,32.0,31.5 +859,TA_38,TA_51,12.5,13.5,8.0,34.0,10.0,12.0,8.75,30.75,32.375 +860,TA_38,TA_48,16.5,15.0,10.0,41.5,13.0,14.0,10.0,37.0,39.25 +861,TA_38,TA_46,21.0,9.0,21.0,51.0,19.0,9.5,17.0,45.5,48.25 +862,TA_38,TA_48,19.0,14.0,15.0,48.0,18.0,14.0,16.0,48.0,48.0 +863,TA_38,TA_51,9.5,13.0,2.0,24.5,5.5,12.0,2.0,19.5,22.0 +864,TA_38,TA_48,19.0,11.5,14.0,44.5,13.0,9.0,10.0,32.0,38.25 +865,TA_38,TA_46,20.0,10.5,5.0,35.5,17.0,10.0,5.0,32.0,33.75 +866,TA_38,TA_48,13.0,10.5,9.5,33.0,11.0,8.0,5.0,24.0,28.5 +867,TA_38,TA_51,16.5,1.0,2.0,19.5,16.0,1.0,2.0,19.0,19.25 +868,TA_38,TA_33,20.0,11.0,10.0,41.0,19.5,12.0,9.0,40.5,40.75 +869,TA_38,TA_48,13.5,13.0,5.5,32.0,13.0,13.5,4.0,30.5,31.25 +870,TA_38,TA_46,15.0,14.0,20.5,49.5,13.0,12.5,15.0,40.5,45.0 +871,TA_38,TA_48,16.5,11.5,6.0,34.0,11.0,12.0,6.0,29.0,31.5 +872,TA_38,TA_51,12.0,12.5,17.0,41.5,12.0,14.0,10.75,36.75,39.125 +873,TA_38,TA_48,11.5,9.5,0.0,21.0,7.0,7.0,0.0,14.0,17.5 +874,TA_38,TA_46,11.5,13.0,18.0,42.5,10.0,13.0,14.0,37.0,39.75 +875,TA_38,TA_48,8.5,8.5,7.5,24.5,8.0,8.0,6.0,22.0,23.25 +876,TA_38,TA_51,16.0,12.5,11.5,40.0,15.0,14.0,5.0,34.0,37.0 +877,TA_38,TA_48,18.0,12.5,19.5,50.0,16.0,12.0,16.0,44.0,47.0 +878,TA_38,TA_46,12.0,11.5,7.5,31.0,16.0,12.5,7.0,35.5,33.25 +879,TA_38,TA_48,12.5,15.5,15.0,43.0,10.0,13.0,16.0,39.0,41.0 +880,TA_38,TA_51,14.0,10.5,21.0,45.5,13.0,14.0,21.25,48.25,46.875 +881,TA_38,TA_48,9.0,7.5,10.0,26.5,2.0,0.0,12.0,14.0,20.25 +882,TA_38,TA_46,20.0,14.0,19.0,53.0,14.0,14.0,15.0,43.0,48.0 +883,TA_38,TA_33,19.0,14.0,14.0,47.0,18.0,13.0,15.0,46.0,46.5 +884,TA_38,TA_48,16.5,14.0,18.0,48.5,18.0,14.0,16.0,48.0,48.25 +885,TA_40,TA_41,14.0,12.0,5.0,31.0,17.0,13.5,6.5,37.0,34.0 +886,TA_40,TA_41,9.0,8.75,0.0,17.75,9.0,8.5,0.5,18.0,17.875 +887,TA_40,TA_41,25.0,17.0,8.5,50.5,25.5,17.0,7.5,50.0,50.25 +888,TA_40,TA_41,5.0,0.0,4.0,9.0,9.0,0.0,6.5,15.5,12.25 +889,TA_40,TA_41,15.0,0.0,15.0,30.0,18.5,0.0,15.5,34.0,32.0 +890,TA_40,TA_41,14.0,9.0,3.0,26.0,16.5,10.0,3.5,30.0,28.0 +891,TA_40,TA_41,9.0,7.0,0.0,16.0,13.5,5.5,0.5,19.5,17.75 +892,TA_40,TA_41,25.5,17.0,12.0,54.5,23.5,17.0,13.0,53.5,54.0 +893,TA_40,TA_41,10.0,6.75,0.0,16.75,10.5,5.5,0.0,16.0,16.375 +894,TA_40,TA_41,22.0,17.0,17.5,56.5,23.0,17.0,16.5,56.5,56.5 +895,TA_40,TA_41,11.5,12.5,18.0,42.0,14.5,10.5,19.0,44.0,43.0 +896,TA_40,TA_41,20.0,14.0,17.0,51.0,19.0,14.0,17.5,50.5,50.75 +897,TA_40,TA_33,11.0,10.75,5.5,27.25,12.0,12.0,9.0,33.0,30.125 +898,TA_40,TA_41,8.5,13.0,4.0,25.5,11.0,11.5,4.5,27.0,26.25 +899,TA_40,TA_41,13.0,13.0,12.5,38.5,18.0,6.0,13.5,37.5,38.0 +900,TA_40,TA_41,9.0,8.25,6.0,23.25,11.0,6.5,11.5,29.0,26.125 +901,TA_40,TA_41,14.5,0.0,10.5,25.0,15.0,0.0,15.0,30.0,27.5 +902,TA_40,TA_41,13.5,11.0,10.0,34.5,15.5,13.5,13.0,42.0,38.25 +903,TA_40,TA_33,4.5,3.0,5.5,13.0,8.5,1.0,8.0,17.5,15.25 +904,TA_40,TA_41,16.5,8.5,3.0,28.0,19.5,9.0,6.5,35.0,31.5 +905,TA_40,TA_41,12.5,8.5,7.0,28.0,11.0,8.5,10.0,29.5,28.75 +906,TA_40,TA_41,17.0,8.0,11.0,36.0,17.0,7.5,12.0,36.5,36.25 +907,TA_40,TA_41,15.5,13.0,16.0,44.5,19.0,13.0,16.0,48.0,46.25 +908,TA_40,TA_41,6.5,11.25,5.5,23.25,11.5,11.5,10.5,33.5,28.375 +909,TA_40,TA_41,17.0,17.0,6.0,40.0,16.5,16.0,7.5,40.0,40.0 +910,TA_40,TA_41,10.0,12.25,2.0,24.25,15.0,13.0,2.0,30.0,27.125 +911,TA_40,TA_41,11.5,12.5,14.0,38.0,16.0,12.0,12.0,40.0,39.0 +912,TA_40,TA_41,11.0,6.75,5.5,23.25,16.0,6.5,7.0,29.5,26.375 +913,TA_40,TA_41,9.0,9.5,2.0,20.5,11.0,7.5,2.5,21.0,20.75 +914,TA_40,TA_41,3.0,4.0,10.0,17.0,9.0,4.0,12.5,25.5,21.25 +915,TA_40,TA_41,12.5,12.0,11.0,35.5,17.5,10.5,10.5,38.5,37.0 +916,TA_40,TA_41,3.0,5.5,2.5,11.0,3.0,5.5,4.5,13.0,12.0 +917,TA_40,TA_41,4.5,11.0,12.0,27.5,9.0,11.0,14.0,34.0,30.75 +918,TA_40,TA_41,14.0,13.5,10.5,38.0,16.5,14.0,14.5,45.0,41.5 +919,TA_40,TA_41,12.5,14.0,8.0,34.5,15.5,14.0,8.0,37.5,36.0 +920,TA_40,TA_41,20.0,11.75,10.0,41.75,20.0,11.5,10.0,41.5,41.625 +921,TA_40,TA_41,24.0,16.25,20.5,60.75,25.5,15.5,21.5,62.5,61.625 +922,TA_40,TA_41,13.0,17.0,19.0,49.0,15.0,17.0,20.0,52.0,50.5 +923,TA_40,TA_41,4.0,5.5,4.0,13.5,7.0,10.5,8.0,25.5,19.5 +924,TA_40,TA_41,2.5,0.0,2.0,4.5,4.25,2.0,1.5,7.75,6.125 +925,TA_40,TA_41,7.0,6.25,10.5,23.75,9.0,7.0,15.0,31.0,27.375 +926,TA_40,TA_41,8.0,10.0,12.5,30.5,10.0,14.0,12.5,36.5,33.5 +927,TA_40,TA_41,11.5,8.75,6.0,26.25,9.5,9.0,7.0,25.5,25.875 +928,TA_40,TA_41,19.0,12.75,18.0,49.75,17.0,13.5,14.5,45.0,47.375 +929,TA_40,TA_41,12.5,0.0,0.0,12.5,10.5,0.0,0.0,10.5,11.5 +930,TA_40,TA_41,20.0,13.0,18.0,51.0,20.5,11.5,18.0,50.0,50.5 +931,TA_42,TA_43,20.0,14.0,6.0,40.0,20.0,12.5,12.0,44.5,42.25 +932,TA_42,TA_43,11.5,9.0,2.0,22.5,14.5,9.5,3.0,27.0,24.75 +933,TA_42,TA_43,0.0,1.0,0.0,1.0,1.5,4.0,0.0,5.5,3.25 +934,TA_42,TA_43,2.0,4.0,0.5,6.5,6.0,6.5,1.0,13.5,10.0 +935,TA_42,TA_43,3.0,5.0,2.0,10.0,9.0,5.0,2.0,16.0,13.0 +936,TA_42,TA_43,3.0,0.0,4.0,7.0,5.5,6.5,7.0,19.0,13.0 +937,TA_42,TA_43,9.0,0.0,5.0,14.0,13.5,0.0,7.0,20.5,17.25 +938,TA_42,TA_43,9.0,13.0,16.0,38.0,10.5,12.0,17.5,40.0,39.0 +939,TA_42,TA_43,5.0,9.0,6.0,20.0,8.0,11.0,5.0,24.0,22.0 +940,TA_42,TA_43,8.0,5.0,0.0,13.0,15.5,4.5,0.0,20.0,16.5 +941,TA_42,TA_43,6.0,17.0,10.0,33.0,9.5,17.0,21.5,48.0,40.5 +942,TA_42,TA_43,7.0,12.0,6.0,25.0,6.0,12.0,5.0,23.0,24.0 +943,TA_42,TA_43,3.5,1.5,2.0,7.0,2.5,1.0,2.0,5.5,6.25 +944,TA_42,TA_43,4.0,4.0,0.0,8.0,5.0,8.5,0.0,13.5,10.75 +945,TA_42,TA_43,0.0,0.0,0.0,0.0,0.0,5.0,0.0,5.0,2.5 +946,TA_42,TA_43,6.0,5.0,0.0,11.0,4.0,6.5,0.0,10.5,10.75 +947,TA_42,TA_43,6.0,12.0,8.0,26.0,5.5,11.5,8.5,25.5,25.75 +948,TA_42,TA_43,5.0,4.0,0.0,9.0,11.0,8.0,17.5,36.5,22.75 +949,TA_42,TA_43,9.0,7.0,5.0,21.0,16.0,7.0,7.0,30.0,25.5 +950,TA_42,TA_43,13.0,9.0,5.0,27.0,16.5,8.5,5.0,30.0,28.5 +951,TA_42,TA_43,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.5 +952,TA_42,TA_43,2.0,5.0,0.0,7.0,2.0,6.0,0.0,8.0,7.5 +953,TA_42,TA_43,21.0,12.0,15.0,48.0,16.0,12.0,18.0,46.0,47.0 +954,TA_42,TA_43,15.0,4.0,4.0,23.0,15.0,3.5,4.0,22.5,22.75 +955,TA_42,TA_43,8.0,7.0,0.0,15.0,13.0,7.0,0.0,20.0,17.5 +956,TA_42,TA_43,15.0,12.0,5.0,32.0,12.5,10.0,10.0,32.5,32.25 +957,TA_42,TA_43,7.0,5.0,4.0,16.0,13.0,13.0,17.0,43.0,29.5 +958,TA_42,TA_43,6.0,6.0,11.0,23.0,5.5,3.5,14.0,23.0,23.0 +959,TA_42,TA_43,9.0,11.5,16.0,36.5,11.0,14.0,19.0,44.0,40.25 +960,TA_42,TA_43,9.0,0.0,2.5,11.5,10.0,8.5,2.0,20.5,16.0 +961,TA_42,TA_43,0.0,17.0,20.0,37.0,2.0,17.0,20.5,39.5,38.25 +962,TA_42,TA_43,4.0,2.0,2.0,8.0,13.0,5.0,18.0,36.0,22.0 +963,TA_42,TA_43,20.0,11.5,19.0,50.5,17.5,13.5,16.0,47.0,48.75 +964,TA_42,TA_43,18.0,12.0,3.0,33.0,17.0,12.0,3.0,32.0,32.5 +965,TA_42,TA_43,2.0,8.0,2.0,12.0,1.0,5.0,3.0,9.0,10.5 +966,TA_42,TA_43,6.0,8.0,7.0,21.0,10.0,10.0,8.0,28.0,24.5 +967,TA_42,TA_43,24.0,17.0,9.0,50.0,25.0,17.0,10.0,52.0,51.0 +968,TA_42,TA_43,9.0,0.0,0.0,9.0,11.5,0.0,2.0,13.5,11.25 +969,TA_44,TA_33,21.0,0.0,8.5,29.5,21.0,17.0,12.0,50.0,39.75 +970,TA_44,TA_41,20.0,13.5,11.0,44.5,16.0,14.0,12.5,42.5,43.5 +971,TA_44,TA_43,0.0,0.0,0.0,0.0,1.0,0.0,1.0,2.0,1.0 +972,TA_44,TA_33,6.0,0.0,3.5,9.5,3.0,0.0,4.0,7.0,8.25 +973,TA_44,TA_33,18.5,17.0,20.0,55.5,21.0,17.0,17.0,55.0,55.25 +974,TA_44,TA_33,12.5,9.0,4.5,26.0,13.0,9.0,4.0,26.0,26.0 +975,TA_44,TA_33,9.5,8.5,7.5,25.5,18.0,9.5,11.0,38.5,32.0 +976,TA_44,TA_41,5.5,0.0,0.0,5.5,4.0,0.0,0.0,4.0,4.75 +977,TA_44,TA_33,8.5,1.0,11.0,20.5,7.0,0.0,9.0,16.0,18.25 +978,TA_44,TA_43,10.5,6.0,10.5,27.0,9.0,8.5,8.0,25.5,26.25 +979,TA_44,TA_33,9.5,8.5,6.5,24.5,8.0,11.0,6.0,25.0,24.75 +980,TA_44,TA_33,14.0,0.0,0.0,14.0,11.0,0.0,0.0,11.0,12.5 +981,TA_44,TA_33,17.5,13.0,19.0,49.5,18.0,17.0,17.0,52.0,50.75 +982,TA_44,TA_33,5.5,4.0,0.5,10.0,2.5,4.0,1.5,8.0,9.0 +983,TA_44,TA_51,15.0,12.5,11.5,39.0,12.5,12.0,11.75,36.25,37.625 +984,TA_44,TA_41,8.5,10.0,11.5,30.0,7.5,10.0,12.0,29.5,29.75 +985,TA_44,TA_33,10.0,9.0,12.5,31.5,11.5,13.0,11.0,35.5,33.5 +986,TA_44,TA_33,16.0,9.0,13.5,38.5,10.0,11.5,9.0,30.5,34.5 +987,TA_44,TA_33,15.5,10.5,8.5,34.5,16.0,12.5,9.0,37.5,36.0 +988,TA_44,TA_33,19.0,14.0,0.0,33.0,23.5,14.0,0.0,37.5,35.25 +989,TA_44,TA_33,16.0,9.5,0.0,25.5,20.0,11.5,0.0,31.5,28.5 +990,TA_44,TA_33,7.5,8.5,10.0,26.0,5.0,8.5,11.0,24.5,25.25 +991,TA_44,TA_33,9.0,7.5,3.5,20.0,13.0,10.0,3.0,26.0,23.0 +992,TA_44,TA_33,19.5,15.0,19.0,53.5,19.0,16.0,17.0,52.0,52.75 +993,TA_44,TA_33,8.0,6.0,11.0,25.0,5.0,8.5,11.0,24.5,24.75 +994,TA_44,TA_33,23.0,13.5,17.5,54.0,23.0,17.0,19.0,59.0,56.5 +995,TA_44,TA_48,15.5,12.5,25.0,53.0,19.0,13.0,19.0,51.0,52.0 +996,TA_44,TA_46,11.5,12.0,12.0,35.5,15.5,14.0,8.0,37.5,36.5 +997,TA_44,TA_33,13.0,10.0,17.0,40.0,20.0,10.0,10.5,40.5,40.25 +998,TA_45,TA_16,21.588,12.736,13.846,48.17,6.5,8.0,13.0,27.5,37.835 +999,TA_45,TA_2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 +1000,TA_45,TA_8,20.72,8.896,15.87,45.486,14.0,12.45,12.75,39.2,42.343 +1001,TA_45,TA_8,11.48,4.48,0.0,15.96,3.0,0.0,0.0,3.0,9.48 +1002,TA_45,TA_14,17.304,11.2,15.295,43.799,8.0,0.0,8.5,16.5,30.1495 +1003,TA_45,TA_6,20.02,0.0,0.0,20.02,10.0,0.0,0.0,10.0,15.01 +1004,TA_45,TA_4,29.4,16.0,23.046,68.446,22.0,17.0,17.75,56.75,62.598 +1005,TA_45,TA_20,17.864,9.856,0.0,27.72,15.0,11.5,0.0,26.5,27.11 +1006,TA_45,TA_8,28.0,4.48,15.272,47.752,8.25,1.0,7.5,16.75,32.251000000000005 +1007,TA_45,TA_10,25.48,11.776,21.712,58.968,14.0,12.0,16.0,42.0,50.484 +1008,TA_45,TA_4,29.4,0.0,10.12,39.519999999999996,16.0,0.0,5.5,21.5,30.509999999999998 +1009,TA_45,TA_6,14.84,0.0,0.0,14.84,7.0,0.0,0.0,7.0,10.92 +1010,TA_45,TA_10,15.68,16.0,16.79,48.47,10.5,14.0,5.0,29.5,38.985 +1011,TA_45,TA_14,25.2,11.2,16.1,52.5,18.0,0.0,2.0,20.0,36.25 +1012,TA_45,TA_14,26.6,8.896,12.282,47.778000000000006,16.0,9.5,11.0,36.5,42.139 +1013,TA_45,TA_14,10.976,6.24,0.0,17.216,11.0,7.0,0.0,18.0,17.608 +1014,TA_45,TA_4,22.4,13.12,22.77,58.28999999999999,17.0,16.0,16.5,49.5,53.894999999999996 +1015,TA_45,TA_16,17.668,12.736,12.88,43.284,14.5,8.5,7.0,30.0,36.641999999999996 +1016,TA_45,TA_6,24.64,15.04,20.7,60.379999999999995,21.0,13.5,15.75,50.25,55.315 +1017,TA_45,TA_8,28.0,11.2,24.15,63.35,20.0,16.0,20.5,56.5,59.925 +1018,TA_45,TA_4,25.48,16.0,22.54,64.02000000000001,24.0,17.0,21.0,62.0,63.010000000000005 +1019,TA_45,TA_14,24.976,12.736,12.558,50.27,14.5,12.0,6.0,32.5,41.385000000000005 +1020,TA_45,TA_14,17.192,11.2,0.0,28.392,14.0,12.5,0.0,26.5,27.445999999999998 +1021,TA_45,TA_2,0.0,2.944,0.0,2.944,0.0,0.0,0.0,0.0,1.472 +1022,TA_45,TA_14,26.32,12.736,8.74,47.796,10.0,11.0,6.0,27.0,37.397999999999996 +1023,TA_45,TA_16,16.184,11.776,16.744,44.704,16.5,9.5,13.5,39.5,42.102000000000004 +1024,TA_45,TA_10,20.02,8.576,4.6,33.196,5.0,1.0,2.0,8.0,20.598 +1025,TA_45,TA_8,29.4,9.856,5.98,45.236000000000004,22.5,10.9,4.0,37.4,41.318 +1026,TA_45,TA_8,17.64,11.2,7.084,35.924,5.0,11.75,4.5,21.25,28.587 +1027,TA_45,TA_6,15.68,12.64,17.02,45.34,8.5,6.75,13.25,28.5,36.92 +1028,TA_45,TA_10,19.712,10.368,12.328,42.408,5.0,5.0,4.0,14.0,28.204 +1029,TA_45,TA_20,28.0,10.24,15.939,54.179,14.5,10.0,9.0,33.5,43.8395 +1030,TA_45,TA_16,23.52,3.136,15.18,41.836,0.0,8.5,12.0,20.5,31.168 +1031,TA_45,TA_20,24.92,9.856,13.846,48.622,14.5,12.0,8.0,34.5,41.561 +1032,TA_45,TA_8,24.92,0.0,8.05,32.97,10.25,0.0,3.0,13.25,23.11 +1033,TA_45,TA_10,28.0,14.4,19.32,61.72,22.0,14.0,16.0,52.0,56.86 +1034,TA_45,TA_10,26.32,11.2,19.412,56.931999999999995,21.0,14.0,18.0,53.0,54.965999999999994 +1035,TA_39,TA_2,14.5,14.0,13.0,41.5,13.5,10.0,10.5,34.0,37.75 +1036,TA_39,TA_2,13.0,10.0,6.5,29.5,14.5,6.5,6.0,27.0,28.25 +1037,TA_39,TA_2,18.0,11.25,14.5,43.75,14.5,10.0,11.5,36.0,39.875 +1038,TA_39,TA_2,4.0,12.0,4.0,20.0,5.5,11.0,5.5,22.0,21.0 diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cafeec77e5e6c11a8cb9689b48322229153a1220 --- /dev/null +++ b/README.md @@ -0,0 +1,159 @@ +# Introduction to AI — Practical Exam Grading Dataset (Stage 2) + +1,038 anonymized student submissions to a university-level practical AI exam, +each independently graded by **two** teaching assistants, plus the rubric and +the instructor reference solutions. + +The 18 LLM grading runs measured on this data, the graders that produced them, +and the analysis code all live in the project repository alongside the +equivalent Computer Vision dataset; this folder is the data itself. + +The dataset was built to test how sensitive LLM graders are to the *prompt* they +are given — specifically, what happens when an instructor adds a plausible +"be strict" instruction to an otherwise well-behaved grading prompt. + +## What is here + +| path | contents | +|---|---| +| `Practical_AI_exam_grades.csv` | ground truth: two TA grades per student, per question and total | +| `submissions_extracted//Q{1,2,3}.ipynb` | the anonymized student notebooks | +| `Solutions/` | instructor reference solution per question | +| `stage_2_rubrics_ta.md` | the marking scheme the TAs graded against | + +Students are identified only by a number (1–1038) that is stable across every +file. Notebook `submissions_extracted/7/Q2.ipynb` belongs to the student in row +`Number == 7` of the grades CSV. + +## The exam and its scale + +Three questions: **Q1** tabular regression (predict food delivery time), +**Q2** PyTorch (predict age from face images), **Q3** classification (find the +most predictive feature in an anonymized dataset). + +Marks come from the rubric's task tables, not its header totals — the two +disagree in the distributed PDF, which is preserved here as `stage_2_rubrics_ta.md`: + +| question | base | bonus | +|---|---|---| +| Q1 Regression | 23 | 3 | +| Q2 PyTorch | 14 | 3 | +| Q3 Classification | 19 | 3 | + +Two instructor corrections were issued by email *during* grading, both affecting +Q3 only (Part 1 dropped a task and became 2 marks; Part 4 dropped a task and +became 5). Both are folded into the rubric file and marked ⚠. + +## Ground truth quality + +Every student is graded by two TAs, so the dataset carries its own noise floor: + +| statistic | value | +|---|---| +| TA-vs-TA mean absolute difference (totals) | 5.13 | +| **floor: \|TA − TA mean\|**, the quantity an AI grader is scored against | **2.57** (95% CI 2.41–2.74) | +| inter-TA correlation (totals) | 0.871 | + +The floor is ~4% of the ~65-point scale. Any AI grader should be read against +2.57, not against zero. + +## Anonymization + +Student names, ID numbers, emails, and submission links are absent. Notebooks +were rebuilt from scratch keeping only code cells: markdown cells, outputs, +execution counts, and all per-cell metadata were dropped, so Colab +`executionInfo` blocks (which embed a Google account name and user id) do not +survive. Remaining identifiers inside code — names in variable names or +comments, emails, ID numbers, phone numbers, filesystem usernames — were +replaced with `ANON` (identifier-safe) or `[REDACTED]`. + +Scrubbing was verified two ways: an exhaustive scan against the full roster +(every student and TA name, email and ID, plus generic email/ID/phone patterns +and notebook-format regressions), and an LLM review of all ~25k comment and +string literals looking for identifiers the roster could not know about. The +second pass is what caught a reference to an instructor by first name and one +student who had loaded the exam data from a personal account. + +TAs appear only as pseudonyms (`TA_1`, `TA_2`, …). One slot carries the +composite id `TA_49+TA_50`: those 18 students had Q1 and Q2 graded by one TA and +Q3 by another. The pseudonym-to-person mapping is **not** published, so grading +behaviour cannot be attributed to any individual. + +One deliberate difference between the released grader and the script that +produced `results/`: the prompt's opening sentence named the institution and +programme running the course, and reads *"an introductory AI practical exam"* +here instead. That phrase is the only difference, and it changes no grading +rule — but a run reproduced from this bundle sends a prompt one phrase +different from the published one. + +## Known gaps, stated plainly + +- 24 students from the original cohort are absent: they uploaded nothing, an + unreadable archive, or files that were not the exam. The remaining 1,038 are + numbered contiguously. +- Roughly 96 students are missing a notebook for at least one question — they + did not submit that question. An absent `Q.ipynb` means exactly that, and + the grading code scores it 0. +- The rubric's header totals contradict its own task tables in all three + questions. This is preserved rather than corrected; it is part of what a real + grading prompt has to cope with. +- A handful of TA grades exceed the rubric maximum for a question. +- Two TA grades awarded credit for a question the student never submitted + (8.0 and 10.0, each contradicted by the paired TA's 0). Both were set to 0 + and the totals recomputed: ground truth that credits work no grader can see + would penalise every grader, human or machine. + +## The LLM runs in `results/` + +Nine open-weights models, each run twice over the full cohort with an identical +prompt except for one leading persona sentence: + +- **neutral** — "You are a strict but fair teaching assistant." +- **strict** — "You are a HARSH teaching assistant. Award the MINIMUM defensible + score for any task that is incomplete, buggy, or deviates from the rubric. + Never give partial credit if the task does not run correctly." + +Everything else is held fixed: reference solution included, per-task breakdown +requested, no chain-of-thought, temperature 0, one sample per question. Each +workbook holds the AI score, bonus, and reasoning per question alongside the TA +columns. `runs_summary.csv` carries MAE against the TA average with a +2,000-resample bootstrap CI. + +`behaviour` classes: `refusal` (≥90% of students zeroed, awarded-total std +< 0.5), `near-refusal` (≥90% zeroed but still varying), `collapse` (MAE ≥ 8, +i.e. ≥3× the human floor, while still discriminating between students), +`graded` otherwise. + +## Reproducing + +The grading and analysis code lives in the project repository, which expects +this folder at `introduction_to_ai_dataset/`: + +```bash +# serve a model with vLLM, then: +python introduction_to_ai_grade_with_local.py --all \ + --model --api-base http://localhost:8000/v1 \ + --with-solution --no-reasoning --with-breakdown \ + --strictness strict --temperature 0.0 --runs 1 \ + --tag IA02_m-_sol1_gd0_rs0_bd1_str-strict_t00_n1 + +python introduction_to_ai_analyze_run.py # MAE, CI, behaviour class +``` + +`introduction_to_ai_submit_persona_sweep.sbatch` is the SLURM launcher: an +array job, one task per persona (`--array=0,1` gives the published +neutral+strict pair). `STUDENTS=1-5` turns it into a smoke run that writes +outside the results tree. It also supports splitting one persona across +`SHARDS=K` concurrent jobs, reassembled with +`introduction_to_ai_merge_shards.py`. +Shards must never share an output workbook — the grader holds the whole workbook +in memory and rewrites it after every question, so two writers silently destroy +each other's grades. + +The published runs used vLLM 0.19.1. Grading is not bitwise reproducible: +generation is unconstrained, and JSON is parsed leniently. + +## Licence and intended use + +The student work belongs to its authors and is released for research on +automated grading. Do not attempt to re-identify students or TAs. diff --git a/Solutions/Q1_Regression_Solution.ipynb b/Solutions/Q1_Regression_Solution.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..303bcb62acefc1a3fb4c3ef2b46b5e2dff3d58fe --- /dev/null +++ b/Solutions/Q1_Regression_Solution.ipynb @@ -0,0 +1,331 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Question 1 SOLUTION: Predict Food Delivery Time\n", + "\n", + "You are provided with a food delivery dataset that includes features such as delivery distance, restaurant preparation time, traffic conditions, and order details. Your objective is to develop a regression model that accurately predicts the delivery time in minutes.\n", + "\n", + "Your target is the column: \"delivery_time\".\n", + "\n", + "You are provided with the code to download and load the csv file.\n", + "\n", + "Your work will be evaluated based on the completion of the following tasks:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 1: Read Data\n", + "\n", + "**Tasks:**\n", + "\n", + "1. Read the dataset using `read_csv()`\n", + "2. Inspect the first few rows using `head()`\n", + "3. Display dataset information using `info()`\n", + "4. Show statistical description using `describe()`\n", + "5. Plot the target distribution (delivery_time)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "df = pd.read_csv(os.path.join(path, 'Q1_data.csv'))\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'].hist(bins=30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 2: Data Cleaning\n", + "\n", + "**Tasks:**\n", + "\n", + "Inspect and fix the following when needed:\n", + "\n", + "1. **Drop the 'Order_ID' column from the data** \n", + "2. **Handle missing values appropriately** (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "3. **Check and remove duplicates** if any exist\n", + "4. **Encode categorical variables** if needed\n", + "5. **Apply feature scaling** to numerical features (Use StandardScaler)\n", + "6. **Check for target imbalance and state if it is imbalanced or not** (keep this cell empty if not needed)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "# Drop rows with missing target\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "# Fill missing values\n", + "df = df.fillna(df.median(numeric_only=True))\n", + "df = df.fillna(df.mode().iloc[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(\"object\").columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "X_cols = [col for col in df.columns if col != 'Delivery_Time']\n", + "df[X_cols] = scaler.fit_transform(df[X_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6\n", + "# Not applicable for regression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 3: Modeling\n", + "\n", + "**Tasks:**\n", + "\n", + "1. Split the dataset into features (X) and target (y)\n", + "2. Use the correct split: **KFold** OR **StratifiedKFold**\n", + "3. Train a **RandomForest** model\n", + "4. Evaluate using **MAE (Mean Absolute Error) ONLY**\n", + "5. Print the averaged score across all folds" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(random_state=42)\n", + "scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + " scores.append(mean_absolute_error(y_val, y_pred))\n", + "\n", + "print(f'Average MAE: {np.mean(scores):.2f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 4: Plots\n", + "\n", + "**Tasks:**\n", + "\n", + "1. Plot feature importance from your trained model\n", + "2. Plot predicted delivery time histogram" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "plt.barh(X.columns, model.feature_importances_)\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = model.predict(X)\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel('Predicted Delivery Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 5: Bonus - Ensemble\n", + "\n", + "**Task:**\n", + "\n", + "Why use one model? Let's use 2 then merge!\n", + "\n", + "Rewrite the KFold loop such that you:\n", + "1. Train **2 different models** inside the loop at the same time in each iteration\n", + "2. Average their predictions\n", + "3. Calculate the MAE metric on the averaged predictions\n", + "\n", + "Use RandomForestRegressor and CatBoostRegressor." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model1 = RandomForestRegressor(random_state=42)\n", + "model2 = CatBoostRegressor(verbose=0, random_state=42)\n", + "scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + " \n", + " model1.fit(X_train, y_train)\n", + " model2.fit(X_train, y_train)\n", + " \n", + " y_pred1 = model1.predict(X_val)\n", + " y_pred2 = model2.predict(X_val)\n", + " y_pred_avg = (y_pred1 + y_pred2) / 2\n", + " \n", + " scores.append(mean_absolute_error(y_val, y_pred_avg))\n", + "\n", + "print(f'Average MAE (Ensemble): {np.mean(scores):.2f}')" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/Solutions/Q2_Pytorch_Solution.ipynb b/Solutions/Q2_Pytorch_Solution.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..be5c90dd43013ff5adc59afdf548bd463a492de3 --- /dev/null +++ b/Solutions/Q2_Pytorch_Solution.ipynb @@ -0,0 +1,396 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Question 2: Predict Age from Face Images\n", + "\n", + "You are provided with a face image dataset containing 2000 images of human faces. Your objective is to develop a regression model using PyTorch that accurately predicts the age of a person based on their face image.\n", + "\n", + "You are provided with the code to download and load the dataset.\n", + "\n", + "Your work will be evaluated based on the completion of the following tasks:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Load and Process Data (Provided)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### **1. Load and Process Data (Provided)**\n", + "\n", + "The code below is provided for you. It:\n", + "1. Loads images from the `images` folder.\n", + "2. Loads labels from `labels.csv`.\n", + "3. Splits the data into training and testing sets (`X_train`, `X_test`, `y_train`, `y_test`).\n", + "\n", + "**Just run these cell to load the data.**" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + " \n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## **Part 1: Prepare Data for PyTorch**\n", + "\n", + "**Tasks:**\n", + "1. **Convert to Tensors:** Convert the numpy arrays (`X_train`, `X_test`, `y_train`, `y_test`) into PyTorch tensors.\n", + "2. **Create Datasets:** Use `TensorDataset` to create `train_dataset` and `test_dataset` from the tensors.\n", + "3. **Create DataLoaders:** Create `train_loader` and `test_loader` with a batch size of 32. \n", + "4. **Inspect Data:** Print the shape of one batch from the train loader and \n", + "5. **Display a few images:** Use matplotlib to display a few images." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "images, labels = next(iter(train_loader))\n", + "print(f\"Batch images shape: {images.shape}\")\n", + "print(f\"Batch labels shape: {labels.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(4):\n", + " plt.subplot(1, 4, i+1)\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {labels[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 2: Model\n", + "\n", + "**Tasks:**\n", + "\n", + "1. Create a model class with **4 linear layers**\n", + "2. Create a training loop function\n", + "3. Create a validation loop function\n", + "4. Define the device, model, loss function, and optimizer\n", + "5. Start training for **20 epochs** and track training and validation losses" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn\n", + "\n", + "class AgeModel(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(AgeModel, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.relu(self.layer1(x))\n", + " x = self.relu(self.layer2(x))\n", + " x = self.relu(self.layer3(x))\n", + " x = self.layer4(x)\n", + " return x.squeeze()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 36 * 36 * 3\n", + "hidden_dim = 128\n", + "output_dim = 1\n", + "\n", + "model = AgeModel(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 3: Plots\n", + "\n", + "**Tasks:**\n", + "\n", + "1. Plot the training and validation loss over epochs\n", + "2. **Bonus:** Plot some predictions with their actual images (show predicted age vs actual age)" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "images, labels = next(iter(test_loader))\n", + "images = images.to(device)\n", + "with torch.no_grad():\n", + " preds = model(images.view(images.size(0), -1))\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(4):\n", + " plt.subplot(1, 4, i+1)\n", + " img = images[i].cpu().permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Real: {labels[i].item():.0f}\\nPred: {preds[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/Solutions/Q3_Classification_Solution.ipynb b/Solutions/Q3_Classification_Solution.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c9363082e51b049437bdfa7b79a31f21652259bb --- /dev/null +++ b/Solutions/Q3_Classification_Solution.ipynb @@ -0,0 +1,397 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Question 3: Exploring Anonymized Data - Can You Find the Golden Feature?\n", + "\n", + "\n", + "\n", + "**What is Anonymized Data?**\n", + "\n", + "\n", + "\n", + "Anonymized data is information that has been processed to remove or obscure personally identifiable details, making it impossible to trace back to specific individuals. In credit risk modeling, features are often anonymized (e.g., `P_2`, `D_39`, `B_1`) to protect customer privacy while still enabling powerful predictive analytics.\n", + "\n", + "\n", + "\n", + "**The Challenge:**\n", + "\n", + "\n", + "\n", + "Credit default prediction is central to managing risk in consumer lending. American Express, the world's largest payment card issuer, uses machine learning to predict whether cardholders will default on their payments. This helps optimize lending decisions and creates a better customer experience.\n", + "\n", + "\n", + "\n", + "You are provided with an anonymized dataset containing behavioral and profile features. Your objective is to build a classification model that predicts credit default (0 = No Default, 1 = Default).\n", + "\n", + "\n", + "\n", + "**Your Mission:** Can you discover the 'golden feature' - the most powerful predictor hidden in this anonymized data?\n", + "\n", + "\n", + "\n", + "Your work will be evaluated based on the completion of the following tasks:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 1: Read Data\n", + "\n", + "\n", + "\n", + "**Tasks:**\n", + "\n", + "\n", + "\n", + "1. Read the dataset `Q3_data.csv` using `read_csv()`\n", + "\n", + "2. Inspect the first few rows using `head()`\n", + "\n", + "3. Display dataset information using `info()`\n", + "\n", + "4. Show statistical description using `describe()`\n", + "\n", + "5. Plot the target distribution (target column)\"\n" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# The 'path' variable is defined in the download cell\n", + "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Target'].value_counts().plot(kind='bar')\n", + "plt.title('Target Distribution (0: No Default, 1: Default)')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Count')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 2: Data Cleaning\n", + "\n", + "\n", + "\n", + "**Tasks:**\n", + "\n", + "\n", + "\n", + "Inspect and fix the following when needed:\n", + "\n", + "\n", + "\n", + "1. **Handle missing values appropriately**\n", + "\n", + "2. **Check and remove duplicates** if any exist\n", + "\n", + "3. **Encode categorical variables** if needed\n", + "\n", + "4. **Apply feature scaling** to numerical features (Use StandardScaler)\n", + "\n", + "5. **Check for target imbalance and state if it is imbalanced or not**" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.isnull().sum())\n", + "df = df.fillna(df.median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f'Duplicates: {df.duplicated().sum()}')\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "if len(categorical_cols) > 0:\n", + " le = LabelEncoder()\n", + " for col in categorical_cols:\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + " print(f'Encoded columns: {list(categorical_cols)}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "X_cols = df.drop(columns=['Target']).columns\n", + "df[X_cols] = scaler.fit_transform(df[X_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Target'].value_counts()\n", + "# there is imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 3: Modeling\n", + "\n", + "\n", + "\n", + "**Tasks:**\n", + "\n", + "\n", + "\n", + "1. Split the dataset into features (X) and target (y)\n", + "\n", + "2. Use the correct split: **KFold** OR **StratifiedKFold**\n", + "\n", + "3. Train a **CatBoostClassifier** model\n", + "\n", + "4. Evaluate using the appropriate metric only (Accuracy vs. F1 Score).\n", + "\n", + "5. Print the averaged score across all folds" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=['Target'])\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(n_estimators=100, random_state=42)\n", + "\n", + "f1 = []\n", + "\n", + "for train_idx, val_idx in skf.split(X, y):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + " \n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_val)\n", + " f1.append(f1_score(y_val, preds))\n", + "\n", + "print(f'F1: {np.mean(f1):.4f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 4: Find the Golden Feature!\n", + "\n", + "\n", + "\n", + "**Tasks:**\n", + "\n", + "\n", + "\n", + "1. Plot feature importance from your trained model\n", + "\n", + "2. Identify and print the name of the most important feature (the 'golden feature')\n", + "\n", + "3. Plot the distribution of predictions" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "importances = model.feature_importances_\n", + "feat_importances = pd.Series(importances, index=X.columns).sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "feat_importances[:10].plot(kind='barh')\n", + "plt.gca().invert_yaxis()\n", + "plt.title('Top 10 Feature Importances')\n", + "plt.xlabel('Importance')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "golden_feature = feat_importances.index[0]\n", + "print(f'The Golden Feature is: {golden_feature}')\n", + "print(f'Importance: {feat_importances.iloc[0]:.4f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Part 5: Bonus - Retrain with Golden Feature Only\n", + "\n", + "\n", + "\n", + "**Task:**\n", + "\n", + "\n", + "\n", + "Now that you've found the golden feature, let's see how powerful it really is!\n", + "\n", + "\n", + "\n", + "Retrain your CatBoostClassifier using **ONLY the golden feature** and compare its performance to the full model:\n", + "\n", + "\n", + "\n", + "1. Create new X with only the golden feature\n", + "\n", + "2. Run the same KFold loop with this single feature\n", + "\n", + "3. Print and compare the accuracy with the full model" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(n_estimators=100, random_state=42)\n", + "\n", + "# Retrain with only the golden feature\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "golden_accuracies = []\n", + "for train_idx, val_idx in skf.split(X_golden, y):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + " \n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_val)\n", + " golden_accuracies.append(f1_score(y_val, preds))\n", + "\n", + "print(f'Accuracy with ONLY {golden_feature}: {np.mean(golden_accuracies):.4f}')\n", + "print(f'Full Model Accuracy: {np.mean(f1):.4f}')\n", + "print(f'Difference: {np.mean(f1) - np.mean(golden_accuracies):.4f}')\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/stage_2_rubrics_ta.md b/stage_2_rubrics_ta.md new file mode 100644 index 0000000000000000000000000000000000000000..84deb0b128c9881e4d5f25266c83628601c8eeaa --- /dev/null +++ b/stage_2_rubrics_ta.md @@ -0,0 +1,156 @@ +# Stage 2 Practical Exam — Marking Scheme + +The rubric the TAs graded against, transcribed from the distributed +`Marking_Scheme.pdf` with the two instructor corrections issued by email +during grading folded in (both affect Q3 only; they are marked ⚠ below). +Each student was graded independently by two TAs. Where the PDF's header +totals disagree with the sum of its own task tables, both numbers are noted. + +--- + +## Q1: Regression — Predict Food Delivery Time + +Header total: ~25 marks + 3 bonus. Task tables sum to a maximum of 23 + 3 bonus +(Part 2 is variable, 6–10 nominal). + +### Part 1: Read Data (3 marks) + +| Task | Marks | +|---|---| +| 1. Read the dataset using `read_csv()` | 0.5 | +| 2. Inspect the first few rows using `head()` | 0.5 | +| 3. Display dataset information using `info()` | 0.5 | +| 4. Show statistical description using `describe()` | 0.5 | +| 5. Plot the target distribution (`delivery_time`) | 1.0 | + +### Part 2: Data Cleaning (6–10 marks, variable) + +| Task | Marks | Notes | +|---|---|---| +| 1. Drop the `Order_ID` column | 1 | | +| 2. Handle missing values appropriately | max 4, min −2 | breakdown below | +| 3. Check and remove duplicates | 1 | | +| 4. Encode categorical variables | 1–3 | 1 if label encoding, 3 if one-hot | +| 5. Apply feature scaling (StandardScaler) | 1 | | +| 6. Check for target imbalance | +1 or −1 | +1 if kept empty / wrote a comment (regression target — imbalance does not apply); −1 if plotted anything | + +Task 2 breakdown: + +- Numerical features: filling with mean/median/constant/custom rule **+1**; dropping rows/features with numeric missings **+0.5** +- Categorical features: filling with mode/constant/custom rule **+1**; dropping rows/features with categorical missings **+0.5** +- Target: dropping rows with missing target **+2**; not dropping them **−2** + +### Part 3: Modeling (6 marks) + +| Task | Marks | +|---|---| +| 1. Split into features (X) and target (y) | 1 | +| 2. Use the correct split: KFold or StratifiedKFold | 2 | +| 3. Train a RandomForest model | 1 | +| 4. Evaluate using MAE only | 1 | +| 5. Print the averaged score across all folds | 1 | + +### Part 4: Plots (3 marks) + +| Task | Marks | +|---|---| +| 1. Plot feature importance from the trained model | 1 | +| 2. Plot predicted delivery time histogram | 2 | + +### Part 5: Bonus — Ensemble (3 marks) + +Rewrite the KFold loop to train two different models per iteration +(RandomForestRegressor and CatBoostRegressor), average their predictions, +and compute MAE on the averaged predictions. **3 marks.** + +--- + +## Q2: PyTorch — Predict Age from Face Images + +Header total: 16 marks. Task tables sum to 14 + 3 bonus (maximum achievable 17). +Data loading and preprocessing were provided to students. + +### Part 1: Prepare Data for PyTorch (5 marks) + +| Task | Marks | +|---|---| +| 1. Convert the numpy arrays to PyTorch tensors | 1 | +| 2. Create `train_dataset` / `test_dataset` with `TensorDataset` | 1 | +| 3. Create DataLoaders with batch size 32 | 1 | +| 4. Print the shape of one batch from the train loader | 1 | +| 5. Display a few images with matplotlib | 1 | + +### Part 2: Model (8 marks) + +| Task | Marks | +|---|---| +| 1. Create a model class with 4 linear layers | 2 | +| 2. Create a training loop function | 1 | +| 3. Create a validation loop function | 2 | +| 4. Define the device, model, loss function, and optimizer | 2 | +| 5. Train for 20 epochs, tracking training and validation losses | 1 | + +### Part 3: Plots (1 mark + 3 bonus) + +| Task | Marks | +|---|---| +| 1. Plot training and validation loss over epochs | 1 | +| 2. Bonus: plot predictions with their actual images (predicted vs actual age) | 3 | + +--- + +## Q3: Classification — Find the Golden Feature (anonymized data) + +Corrected total: 19 marks + 3 bonus (maximum 22). The distributed PDF said +22 + 3 bonus with task tables summing to 21 + 3; the two ⚠ corrections below +were issued by email during grading after inconsistencies were found in the +student version. + +### Part 1: Read Data (2 marks) ⚠ + +| Task | Marks | +|---|---| +| 1. Read `Q3_data.csv` using `read_csv()` | 0.5 | +| 2. Inspect the first few rows using `head()` | 0.5 | +| 3. Display dataset information using `info()` | 0.5 | +| 4. Show statistical description using `describe()` | 0.5 | + +⚠ Task 5 ("plot the target distribution", 1 mark) was removed by instructor +correction: inconsistent in the student version; TAs were told to treat +Part 1 as 4 tasks worth 2 marks. + +### Part 2: Data Cleaning (5 marks) + +| Task | Marks | Notes | +|---|---|---| +| 1. Handle missing values appropriately | 1 | any method accepted | +| 2. Check and remove duplicates | 1 | | +| 3. Encode categorical variables | 1 | | +| 4. Apply feature scaling (StandardScaler) | 1 | | +| 5. Check for target imbalance and state whether it is imbalanced | 1 | | + +### Part 3: Modeling (7 marks) + +| Task | Marks | +|---|---| +| 1. Split into features (X) and target (y) | 1 | +| 2. Use the correct split: KFold or StratifiedKFold | 2 | +| 3. Train a CatBoostClassifier model | 1 | +| 4. Evaluate using the appropriate metric only (Accuracy vs. F1) | 2 | +| 5. Print the averaged score across all folds | 1 | + +### Part 4: Find the Golden Feature (5 marks) ⚠ + +| Task | Marks | +|---|---| +| 1. Plot feature importance from the trained model | 2 | +| 2. Identify and print the most important feature (the "golden feature") | 3 | + +⚠ Task 3 ("plot the distribution of predictions", 1 mark) was removed by +instructor correction; TAs were told to grade Part 4 out of 5 marks. + +### Part 5: Bonus — Retrain with the Golden Feature Only (3 marks) + +Retrain the CatBoostClassifier using only the golden feature: build the +single-feature X, run the same KFold loop, and print and compare accuracy +with the full model. **3 marks.** diff --git a/submissions_extracted/1/Q1.ipynb b/submissions_extracted/1/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fa4958eedc4c25a75543f5c8075f016feac83d1f --- /dev/null +++ b/submissions_extracted/1/Q1.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from tqdm import tqdm\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "\n", + "%matplotlib inline\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "delev_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delev_path)\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('time taken')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "col = ['Distance_km','Weather','Traffic_Level', 'Time_of_Day','Vehicle_Type' , 'Preparation_Time_min','Courier_Experience_yrs']\n", + "target_column = \"Delivery_Time\"\n", + "X = df.drop(target_column , axis =1).copy()\n", + "y = df[target_column].copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df[col].copy()\n", + "f_clean = df.dropna(subset=['Distance_km','Weather','Traffic_Level', 'Time_of_Day','Vehicle_Type' , 'Preparation_Time_min','Courier_Experience_yrs'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "label_encoder = LabelEncoder()\n", + "for col in df_clean.select_dtypes(include=[\"object\"]).columns:\n", + " X[col] = label_encoder.fit_transform(X[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.datasets import make_regression\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "\n", + "X, y = make_regression(n_samples=1000, n_features=10, noise=10, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "# 1. Decision Tree\n", + "dt = DecisionTreeRegressor(max_depth=5, random_state=42)\n", + "dt.fit(X_train, y_train)\n", + "print(\"Decision Tree R²:\", dt.score(X_test, y_test))\n", + "\n", + "# 2. Random Forest\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + "# 3. Gradient Boosting\n", + "gb = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1,\n", + " max_depth=3, random_state=42)\n", + "gb.fit(X_train, y_train)\n", + "print(\"Gradient Boosting R²:\", gb.score(X_test, y_test))\n", + "\n", + "# Feature importance\n", + "print(\"\\nTop 3 important features (Random Forest):\")\n", + "importances = rf.feature_importances_\n", + "for i in np.argsort(importances)[-3:][::-1]:\n", + " print(f\" Feature {i}: {importances[i]:.3f}\")\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "col\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': col,\n", + " 'importance': dt.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1/Q3.ipynb b/submissions_extracted/1/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a8adf946b731d40c04d70242d242bc0afdc0201b --- /dev/null +++ b/submissions_extracted/1/Q3.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from tqdm import tqdm\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path1= os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(path1)\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/10/Q1.ipynb b/submissions_extracted/10/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c6603fcbb66f288c6e4232ec716b5125275043c5 --- /dev/null +++ b/submissions_extracted/10/Q1.ipynb @@ -0,0 +1,280 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Read the dataset\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import numpy as np\n", + "\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Inspect the first few rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Plot the target distribution\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Drop the 'Order_ID' column\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values\n", + "print(df.isnull().sum())\n", + "\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Check and remove duplicates\n", + "print(f\"Duplicates before: {df.duplicated().sum()}\")\n", + "df = df.drop_duplicates()\n", + "print(f\"Duplicates after: {df.duplicated().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Encode categorical variables (One Hot Encoding)\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Apply feature scaling (StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2, 3, 4, 5: KFold, RandomForest, MAE, Print averaged score\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "model = None\n", + "\n", + "for train_idx, val_idx in kfold.split(X_scaled):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "print(f\"MAE Scores per fold: {mae_scores}\")\n", + "print(f\"Average MAE: {np.mean(mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot feature importance\n", + "feature_importance = model.feature_importances_\n", + "feature_names = X_scaled.columns\n", + "\n", + "sorted_idx = np.argsort(feature_importance)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(range(len(sorted_idx)), feature_importance[sorted_idx])\n", + "plt.yticks(range(len(sorted_idx)), feature_names[sorted_idx])\n", + "plt.xlabel('Feature Importance')\n", + "plt.title('Random Forest Feature Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Plot predicted delivery time histogram\n", + "model_final = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "model_final.fit(X_scaled, y)\n", + "y_pred_all = model_final.predict(X_scaled)\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred_all, bins=30, edgecolor='black', alpha=0.7)\n", + "plt.title('Predicted Delivery Time Distribution')\n", + "plt.xlabel('Predicted Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "ensemble_mae_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_scaled):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # Model 1: RandomForest\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_val)\n", + "\n", + " # Model 2: CatBoost\n", + " cb_model = CatBoostRegressor(iterations=100, random_state=42, verbose=0)\n", + " cb_model.fit(X_train, y_train)\n", + " cb_pred = cb_model.predict(X_val)\n", + "\n", + " # Average predictions\n", + " ensemble_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " mae = mean_absolute_error(y_val, ensemble_pred)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + "print(f\"Ensemble MAE Scores per fold: {ensemble_mae_scores}\")\n", + "print(f\"Ensemble Average MAE: {np.mean(ensemble_mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/10/Q2.ipynb b/submissions_extracted/10/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3905c35fc55a4a631ae722dabe7248e3ec1a4a0b --- /dev/null +++ b/submissions_extracted/10/Q2.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "batch_size = 32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "for images, labels in train_loader:\n", + " print(f\"Batch images shape: {images.shape}\")\n", + " print(f\"Batch labels shape: {labels.shape}\")\n", + " break" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " img = X_train[i].transpose(1, 2, 0) # Convert from (C, H, W) to (H, W, C)\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {y_train[i]}\")\n", + " axes[i].axis('off')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Model class with 4 linear layers\n", + "import torch.nn as nn\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgePredictor, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.layer1 = nn.Linear(input_size, 512)\n", + " self.layer2 = nn.Linear(512, 256)\n", + " self.layer3 = nn.Linear(256, 64)\n", + " self.layer4 = nn.Linear(64, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.layer1(x))\n", + " x = self.relu(self.layer2(x))\n", + " x = self.relu(self.layer3(x))\n", + " x = self.layer4(x)\n", + " return x.squeeze()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Training loop function\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Validation loop function\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# Calculate input size: C * H * W\n", + "input_size = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "print(f\"Input size: {input_size}\")\n", + "\n", + "model = AgePredictor(input_size).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n", + "\n", + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"Starting Training...\")\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"Training Complete!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot training and validation loss over epochs\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Plot predictions with actual images\n", + "model.eval()\n", + "fig, axes = plt.subplots(2, 5, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "\n", + "with torch.no_grad():\n", + " # Get a batch of test data\n", + " test_images, test_labels = next(iter(test_loader))\n", + " test_images = test_images.to(device)\n", + " predictions = model(test_images).cpu().numpy()\n", + "\n", + " for i in range(10):\n", + " img = test_images[i].cpu().numpy().transpose(1, 2, 0) # (C, H, W) -> (H, W, C)\n", + " actual_age = test_labels[i].item()\n", + " predicted_age = predictions[i]\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Actual: {actual_age:.0f}\\nPred: {predicted_age:.1f}\")\n", + " axes[i].axis('off')\n", + "\n", + "plt.suptitle(\"Predicted vs Actual Age\", fontsize=14)\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/10/Q3.ipynb b/submissions_extracted/10/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5129bc3e8bcea206217c24cd0e545ced082d5db7 --- /dev/null +++ b/submissions_extracted/10/Q3.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Read the dataset\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Inspect the first few rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Handle missing values\n", + "print(\"Missing values before:\")\n", + "print(df.isnull().sum())\n", + "\n", + "# Fill missing values\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "print(\"\\nMissing values after:\")\n", + "print(df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Check and remove duplicates\n", + "print(f\"Duplicates before: {df.duplicated().sum()}\")\n", + "df = df.drop_duplicates()\n", + "print(f\"Duplicates after: {df.duplicated().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Encode categorical variables\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "print(f\"Categorical columns: {categorical_cols}\")\n", + "\n", + "if len(categorical_cols) > 0:\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Apply feature scaling (StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "target_col = 'Target' # Correct column name\n", + "\n", + "X = df.drop(target_col, axis=1)\n", + "y = df[target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Check for target imbalance\n", + "print(\"Target distribution:\")\n", + "print(y.value_counts())\n", + "print(f\"\\nPercentage:\\n{y.value_counts(normalize=True) * 100}\")\n", + "\n", + "# Plot target distribution\n", + "plt.figure(figsize=(6, 4))\n", + "y.value_counts().plot(kind='bar', edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Class')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=0)\n", + "plt.show()\n", + "\n", + "# Check imbalance ratio\n", + "imbalance_ratio = y.value_counts().min() / y.value_counts().max()\n", + "print(f\"\\nImbalance ratio: {imbalance_ratio:.2f}\")\n", + "\n", + "if imbalance_ratio < 0.8:\n", + " print(\"The dataset IS IMBALANCED - Use F1 Score and StratifiedKFold\")\n", + "else:\n", + " print(\"The dataset is balanced - Can use Accuracy\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2, 3, 4, 5: StratifiedKFold, CatBoost, F1 Score, Print averaged score\n", + "!pip install catboost -q\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "\n", + "# Use StratifiedKFold for classification (maintains class distribution)\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "accuracy_scores = []\n", + "model = None\n", + "\n", + "for train_idx, val_idx in skfold.split(X_scaled, y):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # Train CatBoostClassifier\n", + " model = CatBoostClassifier(iterations=100, random_state=42, verbose=0)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_val)\n", + "\n", + " # Calculate F1 Score (use for imbalanced data)\n", + " f1 = f1_score(y_val, y_pred)\n", + " acc = accuracy_score(y_val, y_pred)\n", + "\n", + " f1_scores.append(f1)\n", + " accuracy_scores.append(acc)\n", + "\n", + "# Print averaged scores\n", + "print(f\"F1 Scores per fold: {f1_scores}\")\n", + "print(f\"Average F1 Score: {np.mean(f1_scores):.4f}\")\n", + "print(f\"\\nAccuracy Scores per fold: {accuracy_scores}\")\n", + "print(f\"Average Accuracy: {np.mean(accuracy_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot feature importance\n", + "feature_importance = model.feature_importances_\n", + "feature_names = X_scaled.columns\n", + "\n", + "# Sort by importance\n", + "sorted_idx = np.argsort(feature_importance)\n", + "\n", + "plt.figure(figsize=(10, 20))\n", + "plt.barh(range(len(sorted_idx)), feature_importance[sorted_idx])\n", + "plt.yticks(range(len(sorted_idx)), feature_names[sorted_idx], fontsize=6)\n", + "plt.xlabel('Feature Importance')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Identify the golden feature (most important)\n", + "golden_feature_idx = np.argmax(feature_importance)\n", + "golden_feature = feature_names[golden_feature_idx]\n", + "\n", + "print(f\"The GOLDEN FEATURE is: {golden_feature}\")\n", + "print(f\"Importance score: {feature_importance[golden_feature_idx]:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Bonus: Retrain using ONLY the golden feature\n", + "\n", + "# 1. Create new X with only the golden feature\n", + "X_golden = X_scaled[[golden_feature]]\n", + "\n", + "# 2. Run StratifiedKFold with single feature\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "golden_f1_scores = []\n", + "golden_accuracy_scores = []\n", + "\n", + "for train_idx, val_idx in skfold.split(X_golden, y):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model_golden = CatBoostClassifier(iterations=100, random_state=42, verbose=0)\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " y_pred = model_golden.predict(X_val)\n", + "\n", + " f1 = f1_score(y_val, y_pred)\n", + " acc = accuracy_score(y_val, y_pred)\n", + "\n", + " golden_f1_scores.append(f1)\n", + " golden_accuracy_scores.append(acc)\n", + "\n", + "# 3. Print and compare\n", + "print(\"=\" * 50)\n", + "print(\"COMPARISON: Full Model vs Golden Feature Only\")\n", + "print(\"=\" * 50)\n", + "print(f\"\\nFull Model Average F1 Score: {np.mean(f1_scores):.4f}\")\n", + "print(f\"Golden Feature Average F1 Score: {np.mean(golden_f1_scores):.4f}\")\n", + "print(f\"\\nFull Model Average Accuracy: {np.mean(accuracy_scores):.4f}\")\n", + "print(f\"Golden Feature Average Accuracy: {np.mean(golden_accuracy_scores):.4f}\")\n", + "print(\"=\" * 50)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/100/Q1.ipynb b/submissions_extracted/100/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a1ed0dd4345b527948f38f68c9bb3cf69cc8f52d --- /dev/null +++ b/submissions_extracted/100/Q1.ipynb @@ -0,0 +1,311 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Load the dataset\n", + "Dli_path = os.path.join(path,'Q1_data.csv')\n", + "df_dli = pd.read_csv(Dli_path)\n", + "\n", + "print(f\"Dataset shape: {df_dli.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_dli.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_dli.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_dli.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# delivery_time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_dli['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('time Distribution')\n", + "plt.xlabel('time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_dli.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values\n", + "missing_percentage = (df_dli.isnull().sum() / len(df_dli)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "df_dli['Delivery_Time'].fillna(df_dli['Delivery_Time'].mean())\n", + "#df_dli.dropna(subset=['Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_dli)\n", + "df_dli.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Do we have categorical columns?\n", + "categorical_cols = df_dli.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "categorical_cols = df_dli.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_dli[col] = le.fit_transform(df_dli[col])\n", + "df_dli\n", + "\n", + "\n", + "#from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "#data_onehot_encoded = onehot_encoder.fit_transform(categories) # Apply fit_transform to the copied\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Standardize features using StandardScaler\n", + "numerical_cols = df_dli.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df_dli[numerical_cols] = scaler.fit_transform(df_dli[numerical_cols])\n", + "df_dli" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df['Delivery_Time'].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_dli, \"time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define features (X) and target (y)\n", + "feature_cols = ['Distance_km' ,'Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_dli[feature_cols]\n", + "y = df_dli['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "# Train Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/100/Q2.ipynb b/submissions_extracted/100/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5dc31397088a6526ca36ce64ed42d7b5bdafeeb6 --- /dev/null +++ b/submissions_extracted/100/Q2.ipynb @@ -0,0 +1,365 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Create a float32 tensor\n", + "x = torch.tensor([1.2, 2.3, 3.4], dtype=torch.float32)\n", + "print(x.dtype) # Output: torch.float32\n", + "\n", + "# Convert to float16\n", + "x_half = x.to(torch.float16)\n", + "print(x_half.dtype) # Output: torch.float16\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#class NN2Layer(nn.Module):\n", + "#use softMax instead\n", + "#!!!!!!!!!!! I have no time);\n", + "\n", + "#1\n", + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 4 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "#2\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " return a2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here: #I am Great in another story maybe):" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/100/Q3.ipynb b/submissions_extracted/100/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3931dccaf9de3a2963dd8381cf59f68ef8e910be --- /dev/null +++ b/submissions_extracted/100/Q3.ipynb @@ -0,0 +1,219 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "c_path = os.path.join(path, 'Q3_data.csv')\n", + "df_c = pd.read_csv(c_path)\n", + "\n", + "print(f\"Dataset shape: {df_c.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_c.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_c.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_c.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_c.isnull().sum() / len(df_c)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_c)\n", + "df_c.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_c.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "categorical_cols = df_c.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_c[col] = le.fit_transform(df_c[col])\n", + "df_c" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Standardize features using StandardScaler\n", + "numerical_cols = df_c.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"target\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df_c[numerical_cols] = scaler.fit_transform(df_c[numerical_cols])\n", + "df_c" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df['Delivery_Time'].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_c, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1000/Q1.ipynb b/submissions_extracted/1000/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..af34cdcbbb9868e814a34c638cd5243494be12ab --- /dev/null +++ b/submissions_extracted/1000/Q1.ipynb @@ -0,0 +1,293 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas\n", + "import os\n", + "q1_path = os.path.join(path, 'Q1_data.csv')\n", + "q1_dataset = pandas.read_csv(q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "q1_dataset.head(7)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "q1_dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "q1_dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "q1_dataset[\"Delivery_Time\"].plot()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "q1_dataset = q1_dataset.drop([\"Order_ID\"], axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "q1_dataset.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q1_dataset.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# i have 1600 + rows and thus droping wont hurt + my target is also missing\n", + "q1_dataset = q1_dataset.dropna()\n", + "q1_dataset.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q1_dataset.sample(20)\n", + "# Still there is NaN, i will drop it and the check for other issues" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q1_dataset = q1_dataset.dropna(subset = q1_dataset.columns)\n", + "q1_dataset.value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q1_dataset = q1_dataset.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n", + "\n", + "# Label encode (ordinal) = [\"Traffic_Level\", ]\n", + "# onehot (independante values) = [\"Vehicle_Type\", \"Weather\", \"Time_of_Day\"]\n", + "ordinalEncList = [\"Traffic_Level\"]\n", + "EncList = [\"Vehicle_Type\", \"Weather\", \"Time_of_Day\", \"Traffic_Level\"]\n", + "\n", + "le = LabelEncoder()\n", + "for item in EncList:\n", + " q1_dataset[item] = le.fit_transform(q1_dataset[item])\n", + "\n", + "\"\"\"\n", + "oneHot = OneHotEncoder(sparse_output = False)\n", + "for col in one_hot_EncList:\n", + " q1_dataset = oneHot.fit_transform(q1_dataset[col])\n", + "q1 = oneHot.fit_transform(q1_dataset[[\"Weather\", \"Time_of_Day\", \"Vehicle_Type\"]])\n", + "\"\"\"\n", + "\n", + "q1_dataset.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "\n", + "dataset = scaler.fit_transform(q1_dataset.drop([\"Delivery_Time\"], axis=1))\n", + "\n", + "dataset\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "q1_dataset[\"Delivery_Time\"].plot(kind = \"hist\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "Xtrain, Xtest, Ytrain, Ytest = train_test_split(dataset, q1_dataset[\"Delivery_Time\"], test_size=0.2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Xtrain.shape, Ytrain.shape, Xtest.shape, Ytest.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import numpy as np\n", + "\n", + "rfr = RandomForestRegressor(n_estimators= 50)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=30)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(Xtrain):\n", + " X_fold_train, X_fold_val = Xtrain[train_idx], Xtrain[val_idx]\n", + " y_fold_train, y_fold_val = Ytrain.iloc[train_idx], Ytrain.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " rfr.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = rfr.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "rfr.feature_importances_" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1000/Q2.ipynb b/submissions_extracted/1000/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2dcf669a9a2a9ea0db025ef3193edbbb64f5a479 --- /dev/null +++ b/submissions_extracted/1000/Q2.ipynb @@ -0,0 +1,400 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader, dataset, TensorDataset\n", + "import torch.nn.functional as F\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "image = images.squeeze()\n", + "image = image[32,3, :]\n", + "plt.imshow(images.squeeze())\n", + "plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # 3rd linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + " #self.linear = nn.Linear()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.linear(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 # MNIST images flattened\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 1 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1000/Q3.ipynb b/submissions_extracted/1000/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..60857e29f542e9d40320b34e4ac504f163356ac2 --- /dev/null +++ b/submissions_extracted/1000/Q3.ipynb @@ -0,0 +1,257 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas\n", + "import os\n", + "q3_path = os.path.join(path, 'Q3_data.csv')\n", + "q3_dataset = pandas.read_csv(q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "q3_dataset.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "q3_dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "q3_dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q3_dataset.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "q3_dataset.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q3_dataset = q3_dataset.dropna(axis = 1)\n", + "q3_dataset.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "q3_dataset.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "q3_dataset = q3_dataset.drop_duplicates(keep=\"first\")\n", + "q3_dataset.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Encode categorical variables if needed\n", + "# No need its all not categorical variables to my knowledge nor endoded categorica that got labeled using lebel encoder to one hot (how do i know?)\n", + "q3_dataset.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\n", + "\n", + "# Answer: Based on the describe table above most values looks to be already transformed!!\n", + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "\n", + "dataset = scaler.fit_transform(q3_dataset.drop([\"Target\"], axis=1))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Check for target imbalance and state if it is imbalanced or not\n", + "q3_dataset[\"Target\"].plot(kind=\"hist\")\n", + "\n", + "# Its Unbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_features = dataset\n", + "Y_target = q3_dataset[\"Target\"]\n", + "\n", + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, Y_train, Y_test = train_test_split(dataset, Y_target, test_size=0.2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#%pip install catboost\n", + "from catboost import CatBoostClassifier\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "import numpy as np\n", + "\n", + "cat = CatBoostClassifier(iterations= 100, learning_rate= 0.001)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=30)\n", + "\n", + "acc_scores = []\n", + "f1_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = Y_train.iloc[train_idx], Y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " cat.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = cat.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " acc_scores.append(accuracy_score(y_fold_val, y_fold_pred))\n", + " f1_scores.append(np.sqrt(accuracy_score(y_fold_val, y_fold_pred)))\n", + "\n", + "acc_scores = np.array(acc_scores)\n", + "f1_scores = np.array(f1_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"Mean F1 across folds (Primary Metric Due to unbalance): %{(f1_scores.mean()*100):,.2f}\")\n", + "print(f\"Mean Accuracy Score: %{(acc_scores.mean()*100):,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cat.feature_importances_" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1001/Q1.ipynb b/submissions_extracted/1001/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8979251992943b5588b685ba5dc8576265d5e940 --- /dev/null +++ b/submissions_extracted/1001/Q1.ipynb @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Delivery_Time\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Duplicates\n", + "print(\"Duplicates:\")\n", + "print(df.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Remove duplicates\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df\n", + "y = df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1001/Q2.ipynb b/submissions_extracted/1001/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80bee3071be38d2195fe5991f44d37ede7abc319 --- /dev/null +++ b/submissions_extracted/1001/Q2.ipynb @@ -0,0 +1,198 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# Create tensors\n", + "X_train = torch.tensor([1.0, 2.0, 3.0])\n", + "y_train = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1001/Q3.ipynb b/submissions_extracted/1001/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/1001/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1002/Q1.ipynb b/submissions_extracted/1002/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f35a10e702cc49e3ca7600f1ad008863e221dfe2 --- /dev/null +++ b/submissions_extracted/1002/Q1.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import seaborn as sns\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "data_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[data_cols] = scaler.fit_transform(df[data_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, data_cols):\n", + " print(\"Target Distribution:\")\n", + " print(df[data_cols].value_counts(normalize=True))\n", + " sns.countplot(x=df[data_cols])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "\n", + "scores_accuracy = []\n", + "scores_f1 = []\n", + "\n", + "# Stratified 5-Fold Cross-Validation initiation\n", + "skf = StratifiedKFold(n_splits=5, shuffle=False)\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets using the indices defined by the KFold\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train the model on the training data\n", + " model = RandomForestClassifier(n_estimators=100, random_state=42)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Metric from the sklearn.metrics package\n", + " scores_accuracy.append(accuracy_score(y_Test, y_pred))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Retrieve our model's coefficients and sort by absolute importance\n", + "l_importance = list(zip(X.columns, model.coef_[0]))\n", + "mportance = sorted(logistic_importance, key=lambda x: abs(x[1]), reverse=True)\n", + "\n", + "importance = importance[:10] # Choosing the highest 10 features\n", + "\n", + "\n", + "# Extract sorted features and their coefficients\n", + "features, coefficients = zip(*importance)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, np.abs(coefficients), color='darkblue')\n", + "plt.xlabel('delivery time ')\n", + "plt.ylabel('Features')\n", + "plt.title(' Regression Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1002/Q2.ipynb b/submissions_extracted/1002/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..41c10ba2db3deee7b67ba249f460407910df95d7 --- /dev/null +++ b/submissions_extracted/1002/Q2.ipynb @@ -0,0 +1,406 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "in_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " in_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + "\n", + " # Output layer TODO\n", + " z4 = self.layer5(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 50\n", + "learning_rate = 0.001\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1002/Q3.ipynb b/submissions_extracted/1002/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0996c91e6d6fe9dd09ee5f523cd252224cf1314d --- /dev/null +++ b/submissions_extracted/1002/Q3.ipynb @@ -0,0 +1,275 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import seaborn as sns\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df = scaler.fit_transform(df[data])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_col):\n", + " print(\"Target Distribution:\")\n", + " print(target_col.value_counts(normalize=True))\n", + " sns.countplot(x=df[data])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df,target_col)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from xgboost import XGBClassifier\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "or fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + "\n", + "\n", + "model = XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Retrieve our model's coefficients and sort by absolute importance\n", + "l_importance = list(zip(X.columns, model.coef_[0]))\n", + "mportance = sorted(logistic_importance, key=lambda x: abs(x[1]), reverse=True)\n", + "\n", + "importance = importance[:10] # Choosing the highest 10 features\n", + "\n", + "\n", + "# Extract sorted features and their coefficients\n", + "features, coefficients = zip(*importance)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, np.abs(coefficients), color='darkblue')\n", + "plt.xlabel('Golden Feature ')\n", + "plt.ylabel('Features')\n", + "plt.title(' Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1003/Q1.ipynb b/submissions_extracted/1003/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ba66da01170222f7f3fd30c9b152455a68d9e7c6 --- /dev/null +++ b/submissions_extracted/1003/Q1.ipynb @@ -0,0 +1,259 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(Q1_path)\n", + "\n", + "print(f\"Shape: {df_delivery.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_delivery\n", + "df_clean= df_clean.drop('Order_ID',axis=1)\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n", + "df_clean.isnull().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean.duplicated()\n", + "df_clean = df_clean.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(df_clean)\n", + "print(\"before:\", df_clean)\n", + "print(\"after:\\n\", encoded)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(encoded)\n", + "print(scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "counts = df_clean['Delivery_Time'].value_counts()\n", + "print(counts)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "X= df_clean.drop('Delivery_Time', axis=1)\n", + "y=df_clean['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import accuracy_score\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + "rf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "rf_pred = rf.predict(X_test)\n", + "print(\"Random Forest Accuracy:\", accuracy_score(y_test, rf_pred))\n", + "\n", + "mae = mean_absolute_error(y_true, y_pred)\n", + "print(f\"MAE: {mae:.2f}\")\n", + "\n", + "\n", + "scores = cross_val_score(model, X, y, cv=kfold, scoring='accuracy')\n", + "print(\"KFold scores:\", scores)\n", + "print(f\"Mean accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1004/Q1.ipynb b/submissions_extracted/1004/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5f1e3aea53c6a98983f740a70f5a47da52ca6b50 --- /dev/null +++ b/submissions_extracted/1004/Q1.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.hist(df[\"Delivery_Time\"], bins=30)\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in df.columns:\n", + " if df[col].dtype == \"object\":\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(\n", + " n_estimators=300,\n", + " random_state=42,\n", + " n_jobs=-1\n", + ")\n", + "\n", + "mae_scores = -cross_val_score(model, X, y, cv=kf, scoring=\"neg_mean_absolute_error\")\n", + "\n", + "print(\"MAE per fold:\", mae_scores)\n", + "print(\"Average MAE:\", mae_scores.mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\n", + "\n", + "model = RandomForestRegressor(n_estimators=300, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "\n", + "importances = model.feature_importances_\n", + "idx = np.argsort(importances)[-15:] # top 15\n", + "\n", + "plt.barh(X.columns[idx], importances[idx])\n", + "plt.xlabel(\"Importance\")\n", + "plt.title(\"Top Feature Importances (RandomForest)\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred = model.predict(X_test)\n", + "\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Histogram of Predicted Delivery Time\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip -q install catboost\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor\n", + "X = df.drop(columns=[\"Delivery_Time\"]).values\n", + "y = df[\"Delivery_Time\"].values\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X[train_idx], X[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + " rf = RandomForestRegressor(n_estimators=300, random_state=42, n_jobs=-1)\n", + " cb = CatBoostRegressor(iterations=500, learning_rate=0.05, depth=8, verbose=0, random_state=42)\n", + "\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + " pred_rf = rf.predict(X_val)\n", + " pred_cb = cb.predict(X_val)\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2.0\n", + "\n", + " mae_scores.append(mean_absolute_error(y_val, pred_avg))\n", + "\n", + "print(\"MAE per fold:\", mae_scores)\n", + "print(\"Average MAE:\", np.mean(mae_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1004/Q2.ipynb b/submissions_extracted/1004/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e1afda4539f062780da4f119a8b80fc70bea1c70 --- /dev/null +++ b/submissions_extracted/1004/Q2.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "xb, yb = next(iter(train_loader))\n", + "print(\"X batch:\", xb.shape)\n", + "print(\"y batch:\", yb.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "xb, yb = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(8, 3))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i+1)\n", + " img = xb[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"age={yb[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " self.net = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(3*36*36, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.net(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " n = 0\n", + "\n", + " for xb, yb in loader:\n", + " xb = xb.to(device)\n", + " yb = yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(xb)\n", + " loss = criterion(preds, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " bs = xb.size(0)\n", + " running_loss += loss.item() * bs\n", + " n += bs\n", + "\n", + " return running_loss / n\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " n = 0\n", + "\n", + " with torch.no_grad():\n", + " for xb, yb in loader:\n", + " xb = xb.to(device)\n", + " yb = yb.to(device)\n", + "\n", + " preds = model(xb)\n", + " loss = criterion(preds, yb)\n", + "\n", + " bs = xb.size(0)\n", + " running_loss += loss.item() * bs\n", + " n += bs\n", + "\n", + " return running_loss / n\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "model = AgeRegressor().to(device)\n", + "criterion = nn.L1Loss() # MAE loss\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " tr_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " va_loss = validate(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(tr_loss)\n", + " val_losses.append(va_loss)\n", + "\n", + " print(f\"Epoch {epoch+1:02d} | Train MAE: {tr_loss:.4f} | Val MAE: {va_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.plot(train_losses, label=\"train\")\n", + "plt.plot(val_losses, label=\"val\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"MAE Loss\")\n", + "plt.title(\"Training vs Validation Loss\")\n", + "plt.legend()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "\n", + "xb, yb = next(iter(test_loader))\n", + "xb = xb.to(device)\n", + "yb = yb.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(xb)\n", + "\n", + "xb = xb.cpu()\n", + "yb = yb.cpu()\n", + "preds = preds.cpu()\n", + "\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i+1)\n", + " img = xb[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred={preds[i].item():.1f} | True={yb[i].item():.1f}\")\n", + " plt.axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1004/Q3.ipynb b/submissions_extracted/1004/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d76cb596bad9a41ea3893d85401f93c46e0bafd6 --- /dev/null +++ b/submissions_extracted/1004/Q3.ipynb @@ -0,0 +1,250 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.columns = df.columns.str.strip().str.lower()\n", + "for col in df.columns:\n", + " if df[col].dtype == \"object\":\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# حدد عمود الهدف الصحيح\n", + "target_col = \"Target\" if \"Target\" in df.columns else \"target\"\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_col = \"Target\" if \"Target\" in df.columns else \"target\"\n", + "\n", + "df[target_col].value_counts(normalize=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_col = \"Target\" if \"Target\" in df.columns else \"target\"\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestClassifier(\n", + " n_estimators=100,\n", + " max_depth=12,\n", + " random_state=42,\n", + " n_jobs=1\n", + ")\n", + "\n", + "score_name = \"f1\" if y.value_counts(normalize=True).max() > 0.7 else \"accuracy\"\n", + "scores = cross_val_score(model, X, y, cv=skf, scoring=score_name)\n", + "\n", + "print(\"Metric:\", score_name)\n", + "print(\"Scores:\", scores)\n", + "print(\"Average:\", scores.mean())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "model = RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=1)\n", + "model.fit(X, y)\n", + "\n", + "importances = model.feature_importances_\n", + "idx = np.argsort(importances)[::-1]\n", + "\n", + "top = 15\n", + "plt.barh(X.columns[idx[:top]][::-1], importances[idx[:top]][::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.title(\"Top Feature Importances\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = X.columns[idx[0]]\n", + "print(\"Golden Feature:\", golden_feature)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model_full = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=1)\n", + "acc_full = cross_val_score(model_full, X, y, cv=skf, scoring=\"accuracy\").mean()\n", + "\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "model_golden = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=1)\n", + "acc_golden = cross_val_score(model_golden, X_golden, y, cv=skf, scoring=\"accuracy\").mean()\n", + "\n", + "print(\"Full model accuracy:\", acc_full)\n", + "print(\"Golden-only accuracy:\", acc_golden)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1005/Q1.ipynb b/submissions_extracted/1005/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f92893832eb3ded49f60b510431e72c127a44baf --- /dev/null +++ b/submissions_extracted/1005/Q1.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Plot the target distribution (delivery_time)\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(df['Delivery_Time'].dropna(),bins=30,edgecolor='black')\n", + "plt.title('delivery time')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Drop the 'Order_ID' column from the data\n", + "y = df['Order_ID']\n", + "df= df.drop(\"Order_ID\",axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "cols =['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df.copy()\n", + "# Drop rows where target (price) or key features a\n", + "print(f\"Before:{df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n", + "print(f\"After dropping missing:{df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from numpy import diff\n", + "# Task 3: Write your code here:\n", + "# Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.model_selection import train_test_split,KFold\n", + "from sklearn.preprocessing import StandardScaler,LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\",list(categorical_cols))\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "# scale the `numerical_cols`\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean[\"Delivery_Time\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score,mean_squared_error as sklearn_mse\n", + "\n", + "\n", + "X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)\n", + "print(f\"Train:{X_train.shape}, Test:{X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "model = RandomForestClassifier(n_estimators=100,max_depth=15,class_weight='balanced',\n", + "random_state=42)\n", + "model.fit(X_train,y_train)\n", + "print(\"Model trained!\")\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mse = sklearn_mse(y_test,y_pred)\n", + "# Evaluate the baseline\n", + "print(np.sqrt(mse))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(df['Traffic_Leve'].dropna(),bins=30,edgecolor='black')\n", + "plt.title('Traffic_Level')\n", + "plt.xlabel('Traffic Level')\n", + "plt.ylabel('time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(df_clean['Delivery_Time'].dropna(),bins=30,edgecolor='black')\n", + "plt.title('delivery time')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1005/Q2.ipynb b/submissions_extracted/1005/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..07105587219747e6726441682fab468ce76cfa6a --- /dev/null +++ b/submissions_extracted/1005/Q2.ipynb @@ -0,0 +1,410 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "from torchvision.datasets import MNIST\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# Create TensorDatasets for training and testing\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " img=images[i].permute(1,2,0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " # 3 linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " # Second hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device ,view(batch.size(0),-1) يخليها ليست\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions، هنا ياخد البروبرتي ويختار الاكبر ويضيفها في دمونشين ١\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3*32 * 32 # MNIST images flattened\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 10\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(\n", + "figsize=(7,5))\n", + "plt.plot(train_losses,label='Train Loss')\n", + "plt.plot(val_losses,label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel(\n", + "'Epoch')\n", + "plt.ylabel\n", + "('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1006/Q1.ipynb b/submissions_extracted/1006/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..21d65883df0e6676cc579da6a6c756a4c985cbab --- /dev/null +++ b/submissions_extracted/1006/Q1.ipynb @@ -0,0 +1,434 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Import Required Libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "\n", + "# Download dataset from Kaggle\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "# Load CSV file\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "####df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df\n", + "\n", + "###### THE ONE-HOTENCODER USED DOWN ######" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n", + "\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Task Bonus: Write your code here:\n", + "# Import models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "# TODO: Define models with hyperparameters of your choice\n", + "models = {\n", + " \"LR\": LogisticRegression(\n", + " max_iter=1000\n", + " ),\n", + " \"KNN\": KNeighborsClassifier(\n", + " n_neighbors=3,\n", + " ),\n", + " \"SVM\": SVC(\n", + " kernel='rbf',\n", + " C=1.0\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=16\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=280,\n", + " max_depth=10,\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "\n", + "\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + " for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + "\n", + " for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1006/Q2.ipynb b/submissions_extracted/1006/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..55cce0cbc6a7c2804c86eebc38c23601ce173444 --- /dev/null +++ b/submissions_extracted/1006/Q2.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# split features from targets\n", + "X = df.drop(\"Weather Type\",axis=1) ## يعتمد هلى الراتا حقتي وش الليبل وش التارقيت\n", + "y = df['Weather Type']\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# transform to tensorsA\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1006/Q3.ipynb b/submissions_extracted/1006/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..07d9dbdb22ccc62a289c008a88f01785a89fd21a --- /dev/null +++ b/submissions_extracted/1006/Q3.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Import Required Libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "\n", + "# Download dataset from Kaggle\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "# Load CSV file\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "####df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"])\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"D_1\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "X = df.drop(\"\", axis=1).astype(float)\n", + "y = df[''].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "# Train Random Forest Regressor\n", + "model = CatBoostClassifier()\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "print(\"Evaluating models on the test set...\")\n", + "\n", + "# Dictionary to store performance metrics\n", + "model_performance = {}\n", + "\n", + "# Iterate through each trained model\n", + "for model_name, model in models.items():\n", + " print(f\"\\nEvaluating {model_name}...\")\n", + "\n", + " # Make predictions on the test set (hard labels)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n", + "\n", + " # Store metrics\n", + " model_performance[model_name] = {\n", + " 'Accuracy': accuracy,\n", + " 'Precision': precision,\n", + " 'Recall': recall,\n", + " 'F1-Score': f1\n", + " }\n", + "\n", + " # Print metrics\n", + " print(f\" Accuracy: {accuracy:.4f}\")\n", + " print(f\" Precision: {precision:.4f}\")\n", + " print(f\" Recall: {recall:.4f}\")\n", + " print(f\" F1-Score: {f1:.4f}\")\n", + "\n", + " # Generate and visualize Confusion Matrix\n", + " cm = confusion_matrix(y_test, y_pred)\n", + " plt.figure(figsize=(6, 5))\n", + " sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,\n", + " xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)\n", + " plt.title(f'Confusion Matrix for {model_name}')\n", + " plt.xlabel('Predicted Label')\n", + " plt.ylabel('True Label')\n", + " plt.show()\n", + "\n", + "print(\"\\nAll models evaluated.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1007/Q1.ipynb b/submissions_extracted/1007/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b186d5cbd628bdbf5533a3482df35ac53a3d8a2 --- /dev/null +++ b/submissions_extracted/1007/Q1.ipynb @@ -0,0 +1,399 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "ppath = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(ppath)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop('Order_ID',axis = 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#see the na and at this moment drop but we will see\n", + "df.isna().sum()\n", + "df.shape\n", + "dff = df.copy()\n", + "#df['Wether'].fillna(df['col'].mode()[0])\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#check dups function\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#df.info()\n", + "#here for the string features\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + "\n", + " #i wanted to do onehot encoding but the time isnt in my hand\n", + "'''wv = df['Weather'].value_counts()\n", + "tv = df['Traffic_Level'].value_counts()\n", + "TIMv = df['Time_of_Day'].value_counts()\n", + "vv = df['Vehicle_Type'].value_counts()\n", + "print(wv,tv,TIMv,vv)\n", + "one_hot_encode(y, num_classes)\n", + "one_hot_encode(y, num_classes)\n", + "one_hot_encode(y, num_classes)\n", + "one_hot_encode(y, num_classes)'''\n", + "#for num in categorical_cols:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "for cat in categorical_cols:\n", + " df[cat] = le.fit_transform(df[cat])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#for linear reggression the balance isnt a factor of it but outlier is see if its skewed apply a log transform" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df[\"Delivery_Time\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mae_e=[]\n", + "lr_losses=[]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error\n", + "n_splits = 5 # K=5 Folds\n", + "model = RandomForestRegressor()\n", + "# 5-Fold shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + " loss = y_test-y_pred # it uses the resiual loss true - pred\n", + " mae = mean_absolute_error(y_test,y_pred)\n", + " mae_e.append(mae)\n", + " lr_losses.append(loss)\n", + "#lr_losses = lr_losses.value()\n", + "#average_losses = np.mean(lr_losses, axis=0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "importance_model= list(zip(X.columns, model.feature_importances_))\n", + "sorted_importance = sorted(importance_model, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('reandomforest importance Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "models = {\n", + "\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': [],'mae':[],}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro')\n", + " mae = mean_absolute_error(y_test,y_pred)\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + " results[model_name]['mae'].append(mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")\n", + " #print(f\" mae: {np.mean(results[model_name]['mae']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1007/Q2.ipynb b/submissions_extracted/1007/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..58ce41fb3b842d341cf427864a03d7b2d7848e8b --- /dev/null +++ b/submissions_extracted/1007/Q2.ipynb @@ -0,0 +1,419 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "#import torch\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "images.view(32,-1)\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + "\n", + " print(images.shape)\n", + " plt.subplot(2, 3, i + 1)\n", + " #here the problem is how to remove the channel from the image so its h*w\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim=1):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> 1 aka prediction for age\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(32,-1)\n", + " X_batch =torch.tensor(X_batch, dtype=torch.float32).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(X_train.shape)\n", + "#x_view = X_train.view(1600, -1)\n", + "# Model parameters\n", + "input_dim = 3*36*36 # Number of features WxHxC\n", + "hidden_dim = 14 # Design choice\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n", + "\n", + "\n", + "#####the erorr here is there is a problem the train epoch use 32*3*36 instade of 3*36*36 and i couldnt find the right way to change the shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1007/Q3.ipynb b/submissions_extracted/1007/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a1314bee24f9104f0a64921c21053df1fd227c21 --- /dev/null +++ b/submissions_extracted/1007/Q3.ipynb @@ -0,0 +1,335 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "ppath = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(ppath)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df['Target'].isna().sum()\n", + "numerical_cols = df.columns.drop(\"Target\")\n", + "print(numerical_cols)\n", + "for num in numerical_cols:\n", + " print(num)\n", + " df[num].fillna(df[num].mode()[0])\n", + "\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + "\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#no string or categorical clmn so no encode needed\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df[\"Target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "model = CatBoostClassifier()\n", + "# 5-Fold , shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred)\n", + " losses = y_test-y_pred\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance_model= list(zip(X.columns, model.feature_importances_))\n", + "sorted_importance = sorted(importance_model, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('catboost importance Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(features[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = df['P_2']\n", + "n_splits = 5 # K=5 Folds\n", + "model = CatBoostClassifier()\n", + "# 5-Fold , shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X_golden, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred)\n", + " losses = y_test-y_pred\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1008/Q1.ipynb b/submissions_extracted/1008/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df3d937efd83f74b7548f8c7288ad3c12b94264a --- /dev/null +++ b/submissions_extracted/1008/Q1.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "main_path = os.path.join(path, 'Q1_data.csv')\n", + "main_df = pd.read_csv(main_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Inspect the first few rows using head()\n", + "main_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Display dataset information using info()\n", + "main_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Show statistical description using describe()\n", + "main_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(main_df['Delivery_Time'].dropna(), bins=50)\n", + "plt.title('delivery_time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Drop the 'Order_ID' column from the data\n", + "df_clean = main_df.drop(columns=['Order_ID'])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "df_clean = df_clean.dropna()\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "print(\"duplicate\", df_clean.duplicated().sum())\n", + "df_clean = df_clean.drop_duplicates()\n", + "print(\"duplicate - after\", df_clean.duplicated().sum())\n", + "\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "categorical_cols = ['Vehicle_Type', 'Time_of_Day', 'Traffic_Level', 'Weather']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(df_clean)\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Distance_km',\t'Weather'\t,'Traffic_Level'\t,'Time_of_Day'\t,'Vehicle_Type'\t,'Preparation_Time_min'\t,'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import numpy as np" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Use the correct split: KFold OR StratifiedKFold\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")\n", + "# Evaluate using MAE (Mean Absolute Error) ONLY\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "# Print the averaged score across all folds" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:2. Plot predicted delivery time histogram\n", + "\n", + "# Plot Predictions vs Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")\n", + "plt.grid(True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1008/Q3.ipynb b/submissions_extracted/1008/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..89f1d8cf2626a3d7ce190569f6ce48c3c105c0e8 --- /dev/null +++ b/submissions_extracted/1008/Q3.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import os\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_data.dropna()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "print(\"duplicate\", df_data.duplicated().sum())\n", + "df_clean = df_clean.drop_duplicates()\n", + "print(\"duplicate\", df_clean.duplicated().sum())\n", + "\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Encode categorical variables if needed\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(df_clean)\n", + "df_clean.dropna()\n", + "df_clean\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1009/Q1.ipynb b/submissions_extracted/1009/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfa3c3ff7edbc2f5d59bdbb65fedf7ce395a9ed7 --- /dev/null +++ b/submissions_extracted/1009/Q1.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type','Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "df_clean = df_clean.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time'])\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "ccategorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in ccategorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")\n", + "#Data is balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted')\n", + "print(f\"Baseline F1-Score (majority class): {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n", + "}\n", + "\n", + "models[\"Ensemble\"] = VotingClassifier(estimators=[\n", + " ('rf', models[\"Logistic Regression\"]), ('gnb', models[\"Random Forest Classifier\"])], voting=\"soft\")\n", + "\n", + "for model_name, model in models.items():\n", + " scores_accuracy = []\n", + " scores_precision = []\n", + " scores_recall = []\n", + " scores_f1 = []\n", + "\n", + " # Stratified 5-Fold Cross-Validation\n", + " skf = KFold(n_splits=5)\n", + " for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + " # Print the results\n", + " print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print(\"\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/101/Q1.ipynb b/submissions_extracted/101/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf05dfb4997d04562e7ebb4bbf7618a3c8176f0a --- /dev/null +++ b/submissions_extracted/101/Q1.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#task2 cont. handeling the missing values\n", + "#missing categ\n", + "df['Weather'] = df['Weather'].fillna('none')\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna('none')\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna('none')\n", + "#fill numerical missing\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna('none')\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#we dont need it cause its not classification but regression but i will do it to make sure\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[\"Delivery_Time\"].value_counts(normalize=True))\n", + " sns.countplot(x=df[\"Delivery_Time\"])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " RF = RandomForestRegressor(n_estimators=200)\n", + "\n", + " # Train\n", + " RF.fit(X_train, y_train)\n", + "\n", + " # Validate\n", + " y_pred = RF.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': RF.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/101/Q2.ipynb b/submissions_extracted/101/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b01f6a936cf75e8186c4a685fb7e2fe3b319b8e6 --- /dev/null +++ b/submissions_extracted/101/Q2.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36\n", + "hidden_dim = 15\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/101/Q3.ipynb b/submissions_extracted/101/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cde488c608137b69c0fd507d9f6766f4a5ab5a8c --- /dev/null +++ b/submissions_extracted/101/Q3.ipynb @@ -0,0 +1,318 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, Target):\n", + " print(\"Target Distribution:\")\n", + " print(df[\"Target\"].value_counts(normalize=True))\n", + " sns.countplot(x=df[\"Target\"])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\",axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "sklearn_model = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in sklearn_model:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_model.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_model['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 12))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"the most important feature is: P_2 \")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1010/Q1.ipynb b/submissions_extracted/1010/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..77aa8a0fbdb6ee4649b0ce199204e1c3b9992d14 --- /dev/null +++ b/submissions_extracted/1010/Q1.ipynb @@ -0,0 +1,289 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n--- Task 3: Dataset Information ---\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\n--- Task 4: Statistical Description ---\")\n", + "print(df.describe())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\n--- Task 4: Statistical Description ---\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "df.columns = df.columns.str.strip().str.lower()\n", + "\n", + "if target_col not in df.columns:\n", + " print(\"Columns found in dataset:\", df.columns.tolist())\n", + "\n", + " potential_cols = [c for c in df.columns if 'time' in c]\n", + " if potential_cols:\n", + " target_col = potential_cols[0]\n", + "\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(df[target_col], kde=True, color='blue')\n", + "plt.title(f'Distribution of {target_col} (2026)')\n", + "plt.xlabel('Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "df.columns = df.columns.str.strip().str.lower()\n", + "target_col = 'delivery_time'\n", + "\n", + "df.drop(columns=['Order_ID'], inplace=True, errors='ignore')\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values per column before cleaning:\\n\", df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "for col in df.columns:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "for col in df.columns:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "features = df.drop(columns=['delivery_time'])\n", + "target = df['delivery_time']\n", + "\n", + "scaled_features = scaler.fit_transform(features)\n", + "df_scaled = pd.DataFrame(scaled_features, columns=features.columns)\n", + "df_scaled['delivery_time'] = target.values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "skewness = df['delivery_time'].skew()\n", + "if abs(skewness) > 1:\n", + " print(f\"\\nTarget 'delivery_time' is imbalanced (Skewness: {skewness:.2f})\")\n", + "else:\n", + " print(f\"\\nTarget 'delivery_time' is relatively balanced (Skewness: {skewness:.2f})\")\n", + "\n", + "print(\"\\nData Cleaning Complete.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "target_col = 'delivery_time'\n", + "\n", + "if target_col not in df.columns:\n", + "\n", + " potential_cols = [c for c in df.columns if 'time' in c]\n", + " target_col = potential_cols[0]\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2: Use KFold split (Standard for 2026 Regression tasks)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Task 3: Train a RandomForest model\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "mae_scores = cross_val_score(model, X, y, cv=kf, scoring='neg_mean_absolute_error')\n", + "average_mae = -np.mean(mae_scores)\n", + "\n", + "print(f\"Scores for each fold: {-mae_scores}\")\n", + "print(f\"Average MAE across all folds: {average_mae:.2f} minutes\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "\n", + "# Get importances and sort them\n", + "importances = model.feature_importances\n", + "indices = np.argsort(importances)[::-1]\n", + "feature_names = X.columns\n", + "\n", + "sns.barplot(x=importances[indices], y=feature_names[indices], palette='viridis')\n", + "\n", + "plt.title('Feature Importance for Delivery Time Prediction (2026)')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1010/Q2.ipynb b/submissions_extracted/1010/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..86743c3b94a1b75a9cad3095eb772a8371a25c3d --- /dev/null +++ b/submissions_extracted/1010/Q2.ipynb @@ -0,0 +1,353 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "import torch\n", + "import numpy as np\n", + "\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Extract the first batch\n", + "train_features, train_labels = next(iter(train_loader))\n", + "\n", + "print(f\"Feature batch shape: {train_features.shape}\") # Expected: [32, Channels, H, W]\n", + "print(f\"Labels batch shape: {train_labels.shape}\") # Expected: [32, 1]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Display first 4 images from the batch\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(4):\n", + " plt.subplot(1, 4, i + 1)\n", + " # Permute from (C, H, W) to (H, W, C) for plotting\n", + " img = train_features[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img.astype(np.uint8) if img.max() > 1 else img)\n", + " plt.title(f\"Age: {train_labels[i].item():.0f}\")\n", + " plt.axis('off')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "class AgePredictionModel(nn.Module):\n", + " def __init__(self, input_shape):\n", + " super(AgePredictionModel, self).__init__()\n", + " # input_shape should be: Channels * Height * Width\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(input_shape, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 64)\n", + " self.fc4 = nn.Linear(64, 1) # Output layer: 1 neuron for regression (age)\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x) # No activation for the last layer in regression\n", + " return x\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_step(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)\n", + "\n", + "def validate_step(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_step(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "sample_batch, _ = next(iter(train_loader))\n", + "input_size = sample_batch.shape[1] * sample_batch.shape[2] * sample_batch.shape[3]\n", + "\n", + "\n", + "model = AgePredictionModel(input_size).to(device)\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "epochs = 20\n", + "history = {\"train_loss\": [], \"val_loss\": []}\n", + "\n", + "print(f\"Starting training on {device}...\")\n", + "\n", + "for epoch in range(epochs):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer, device)\n", + " val_loss = validate_step(model, test_loader, criterion, device)\n", + "\n", + " history[\"train_loss\"].append(train_loss)\n", + " history[\"val_loss\"].append(val_loss)\n", + "\n", + " print(f\"Epoch [{epoch+1}/{epochs}] - Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"Training Complete.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(range(1, epochs + 1), history[\"train_loss\"], label='Training Loss', marker='o')\n", + "plt.plot(range(1, epochs + 1), history[\"val_loss\"], label='Validation Loss', marker='o')\n", + "\n", + "plt.title('Age Prediction Model: Loss Over Epochs (2026)')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Mean Squared Error (Loss)')\n", + "plt.legend()\n", + "plt.grid(True, linestyle='--', alpha=0.6)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval()\n", + "images, labels = next(iter(test_loader))\n", + "images, labels = images.to(device), labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(images)\n", + "\n", + "plt.figure(figsize=(15, 10))\n", + "for i in range(8):\n", + " plt.subplot(2, 4, i + 1)\n", + "\n", + "\n", + " img = images[i].cpu().permute(1, 2, 0).numpy()\n", + "\n", + "\n", + "\n", + " plt.imshow(img.clip(0, 1)) # Clip to ensure valid RGB range\n", + "\n", + " actual_age = labels[i].item()\n", + " predicted_age = preds[i].item()\n", + "\n", + "\n", + " color = 'green' if abs(actual_age - predicted_age) <= 5 else 'red'\n", + "\n", + " plt.title(f\"Actual: {actual_age:.0f}\\nPred: {predicted_age:.1f}\", color=color)\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1010/Q3.ipynb b/submissions_extracted/1010/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..677f9f0f7c301d120aa1afa4b4d9c3199082940b --- /dev/null +++ b/submissions_extracted/1010/Q3.ipynb @@ -0,0 +1,274 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df_credit = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"--- Task 2: First 5 Rows of Credit Data ---\")\n", + "print(df_credit.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\n--- Task 3: Dataset Information ---\")\n", + "df_credit.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:rint(\"\\n--- Task 4: Statistical Description ---\")\n", + "print(df_credit.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for col in df_credit.columns:\n", + " if df_credit[col].dtype == 'object':\n", + " df_credit[col] = df_credit[col].fillna(df_credit[col].mode()[0])\n", + " else:\n", + " df_credit[col] = df_credit[col].fillna(df_credit[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicate_count = df_credit.duplicated().sum()\n", + "print(f\"Duplicates found: {duplicate_count}\")\n", + "if duplicate_count > 0:\n", + " df_credit.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_credit = pd.get_dummies(df_credit, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "caler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "\n", + "df_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n", + "df_scaled[target_col] = y.values\n", + "\n", + "\n", + "imbalance_ratio = y.value_counts(normalize=True)\n", + "print(\"\\nTarget Distribution:\\n\", imbalance_ratio)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "imbalance_ratio = y.value_counts(normalize=True)\n", + "print(\"\\nTarget Distribution:\")\n", + "print(imbalance_ratio)\n", + "\n", + "# Identify if imbalanced (usually if one class is < 20%)\n", + "if imbalance_ratio.min() < 0.20:\n", + " print(\"State: The target is IMBALANCED.\")\n", + "else:\n", + " print(\"State: The target is relatively BALANCED.\")\n", + "sns.countplot(x=y)\n", + "plt.title('Target Distribution (0: No Default, 1: Default)')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_scaled.drop(columns=[target_col])\n", + "y = df_scaled[target_col]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(iterations=500, depth=6, learning_rate=0.05, verbose=0)\n", + "\n", + "f1_scores = []\n", + "print(\"Starting Stratified Cross-Validation...\")\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y)):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Fit model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " score = f1_score(y_test, y_pred)\n", + " f1_scores.append(score)\n", + " print(f\"Fold {fold+1} F1 Score: {score:.4f}\")\n", + "\n", + "\n", + "print(f\"\\nAverage F1 Score across all folds: {np.mean(f1_scores):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import pandas as pd\n", + "model.fit(X, y)\n", + "\n", + "\n", + "# Get feature importance from CatBoost\n", + "feature_importance = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "# Create a DataFrame for visualization\n", + "fi_df = pd.DataFrame({'Feature': feature_names, 'Importance': feature_importance})\n", + "fi_df = fi_df.sort_values(by='Importance', ascending=False).head(15) # Top 15 features\n", + "\n", + "# Plotting\n", + "plt.figure(figsize=(12, 8))\n", + "sns.barplot(x='Importance', y='Feature', data=fi_df, palette='magma')\n", + "plt.title('Top Feature Importances - Identifying the Golden Feature (2026)')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Anonymized Features')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = fi_df.iloc[0]['Feature']\n", + "importance_score = fi_df.iloc[0]['Importance']\n", + "\n", + "print(\"=\"*50)\n", + "print(f\"MISSION ACCOMPLISHED!\")\n", + "print(f\"The Golden Feature is: {golden_feature}\")\n", + "print(f\"Importance Score: {importance_score:.2f}\")\n", + "print(\"=\"*50)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1011/Q1.ipynb b/submissions_extracted/1011/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2c10db10a4314fa9e5ca75cb053f074a7d6789d7 --- /dev/null +++ b/submissions_extracted/1011/Q1.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import os\n", + "import kagglehub\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('df_food')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "#cols = df_food.drop(columns=['Order_ID'])\n", + "\n", + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping : {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "\n", + "\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(train_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: (OneHotEncoder)\n", + "print('data before encoding:\\n', categories)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6:\n", + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('df_food')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1011/Q2.ipynb b/submissions_extracted/1011/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a35e11df089b160add1c0647ac42c4a0e3bba1ba --- /dev/null +++ b/submissions_extracted/1011/Q2.ipynb @@ -0,0 +1,488 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train[41][0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1011/Q3.ipynb b/submissions_extracted/1011/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..07f9b3b135839fb675eb472565459adace763c47 --- /dev/null +++ b/submissions_extracted/1011/Q3.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "golden_path = os.path.join(path, 'Q3_data.csv')\n", + "df_golden = pd.read_csv(golden_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "print(f\"Dataset shape: {df_golden.shape}\")\n", + "df_golden.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df_golden.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_golden.count()\n", + "\n", + "\n", + "#the data is huge so i assue any value >20001 has a missing. and solve the entire Q with this problem :( i ask 2 TAs" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df_golden.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df_clean = df_golden[df_golden.count()].copy()\n", + "\n", + "df_clean['P_2'] = df_clean['P_2'].fillna(df_clean['P_2'].mean())\n", + "df_clean['B_2'] = df_clean['B_2'].fillna(df_clean['B_2'].mean())\n", + "df_clean['D_142'] = df_clean['D_142'].fillna(df_clean['D_142'].mean())\n", + "df_clean['D_143'] = df_clean['D_143'].fillna(df_clean['D_143'].mean())\n", + "df_clean['D_144'] = df_clean['D_144'].fillna(df_clean['D_144'].mean())\n", + "df_clean['D_145'] = df_clean['D_145'].fillna(df_clean['D_145'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(train_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "categorical_cols = [df_golden.count()]\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_cols = ['P_2', 'D_39', 'B_1', 'B_2','R_1']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['R_1']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + "sr_results['acc'].append(accuracy)\n", + "sr_results['f1'].append(f1)\n", + "\n", + "print(f\" Accuracy: {np.mean(sr_results['acc']):.4f}\")\n", + "print(f\" F1-Score: {np.mean(sr_results['f1']):.4f}\")\n", + "\n", + "#kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "#for train_idx, val_idx in kfold.split(X_train_scaled):\n", + "# X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + "# y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " # model.fit(X_fold_train, y_fold_train)\n", + " # y_fold_pred = model.predict(X_fold_val)\n", + "\n", + "#print(f\"5-Fold CV Results:\")\n", + "\n", + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train using gradient descent with learning rate = 0.5\n", + " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n", + "\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)\n", + "\n", + " avg_loss = np.mean(sr_results['loss'], axis=0)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_golden['R_1'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('R_1 Distribution')\n", + "plt.xlabel('R_1')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1012/Q1.ipynb b/submissions_extracted/1012/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fd65d52a4c916b71328a6b4e19f4152d9ed25724 --- /dev/null +++ b/submissions_extracted/1012/Q1.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Read the dataset Q1_data.csv using read_csv()\n", + "import os\n", + "import pandas as pd\n", + "\n", + "foodDeliv_path = os.path.join(path, 'Q1_data.csv')\n", + "df_foodDeliv = pd.read_csv(foodDeliv_path)\n", + "print(f\"Dataset shape: {df_foodDeliv.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Inspect the first few rows using head()\n", + "df_foodDeliv.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Display dataset information using info()\n", + "df_foodDeliv.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Show statistical description using describe()\n", + "df_foodDeliv.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Plot the target distribution (delivery_time)\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_foodDeliv['Delivery_Time'].dropna(), bins=50, edgecolor='black') # dropna drop null values\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Drop the 'Order_ID' column from the data\n", + "df_clean = df_foodDeliv.drop(columns=['Order_ID']).copy()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "missing_columns = [\"Weather\", \"Traffic_Level\", \"Delivery_Time\", \"Courier_Experience_yrs\", \"Time_of_Day\"]\n", + "categorize_Data = df_clean[missing_columns].select_dtypes(include=[\"object\"]).columns\n", + "numbers_Data = df_clean[missing_columns].select_dtypes(include=[\"float64\"]).columns\n", + "for column in categorize_Data:\n", + " df_clean[column] = df_clean[column].fillna('unknown')\n", + "\n", + "\n", + "for column in numbers_Data:\n", + " df_clean[column] = df_clean[column].fillna(df_clean[column].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "print(\"Duplicated:\", df_clean.duplicated().sum())\n", + "check_duplicates(df_clean)\n", + "print(\"Duplicated:\", df_clean.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoder = LabelEncoder()\n", + "categorize_Data = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for column in categorize_Data:\n", + " df_clean[column] = label_encoder.fit_transform(df_clean[column])\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean_scaled = scaler.fit_transform(df_clean) #####################3\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "\n", + "# we are talking about continue numbers, so not needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Split the dataset into features (X) and target (y)\n", + "\n", + "X = df_clean.drop(columns=['Delivery_Time'])\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "print(f\"Train: {X.shape}, Test: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Use the correct split: KFold OR StratifiedKFold\n", + "# Train a RandomForest model\n", + "# Evaluate using MAE (Mean Absolute Error) ONLY\n", + "# Print the averaged score across all folds\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "maeresult = 0\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + " model = RandomForestRegressor(n_estimators=200)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " maeresult += mae\n", + "print(\"mae result:\", maeresult / n_splits)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot feature importance from your trained model\n", + "# Create a 1x3 plot\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot predicted delivery time histogram\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black') # dropna drop null values\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1012/Q2.ipynb b/submissions_extracted/1012/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..148c8363caf6dbbb62f7204bacc3194ae32db11c --- /dev/null +++ b/submissions_extracted/1012/Q2.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# Convert to Tensors: Convert the numpy arrays (X_train, X_test, y_train, y_test) into PyTorch tensors.\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create Datasets: Use TensorDataset to create train_dataset and test_dataset from the tensors.\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create DataLoaders: Create train_loader and test_loader with a batch size of 32.\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Inspect Data: Print the shape of one batch from the train loader\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Display a few images: Use matplotlib to display a few images.\n", + "import matplotlib.pyplot as plt\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "# it supposed to show it\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze())\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "# Create a model class with 4 linear layers\n", + "import torch.nn as nn\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # output layer\n", + " output = self.layer3(a2)\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "# Create a training loop function\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # (batch size, remaining features)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # multi class\n", + " predicted = torch.argmax(probabilities, dim=1) # تاخذ البردكشن\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 # MNIST images flattened\n", + "hidden_dim = 6 # Design choice\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "################################ it supposed to be trained but I got an error in the train_one_epoch function\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1012/Q3.ipynb b/submissions_extracted/1012/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..245e551c234847d55d227d37446a0237ee7d6468 --- /dev/null +++ b/submissions_extracted/1012/Q3.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "print(\"Duplicated:\", df.duplicated().sum())\n", + "check_duplicates(df)\n", + "print(\"Duplicated:\", df.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "\n", + "# it suppose to run but I got an erro and I think because of the way hanlding missing values\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Apply feature scaling to numerical features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True)) # normilize means finding the means\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + " # Validate\n", + " y_pred_proba = model.predict(X_test)\n", + "\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1013/Q1.ipynb b/submissions_extracted/1013/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bf3e7e44b5b4e981a289a1a970524b9315ab980d --- /dev/null +++ b/submissions_extracted/1013/Q1.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "print(f\"Dataset shape: {df_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title(' Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_data[cols].copy()\n", + "\n", + "\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing Order ID: {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df_data):\n", + " missing_values = df_data.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_data):\n", + " duplicates = df_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categories = pd.DataFrame({\"categorical variables\": [' Weather ', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']})\n", + "\n", + "print('data before encoding:\\n', categories)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "data_for_scale = pd.DataFrame(df_data)\n", + "\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "\n", + "\n", + "X = np.array(df_data)\n", + "y = np.array(df_data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1013/Q2.ipynb b/submissions_extracted/1013/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bcde1316758c97c256546de583b470796ba55f7d --- /dev/null +++ b/submissions_extracted/1013/Q2.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import torch.nn as nn\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1014/Q1.ipynb b/submissions_extracted/1014/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..489ec31a4edfbf77c30cc6958e487f9a61ca91e9 --- /dev/null +++ b/submissions_extracted/1014/Q1.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "my_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(my_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\",axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna(subset=[\"Delivery_Time\"]).copy()\n", + "df['Weather'] = df['Weather'].fillna('none')\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna('none')\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna('none')\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df['Weather'] = le.fit_transform(df['Weather'])\n", + "df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n", + "df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n", + "df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])\n", + "\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n", + "\n", + "#Not really imbalanced its okay to not do anything" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Storage for linear regression results for each fold\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train and predict\n", + " model.fit(X_train, y_train)\n", + " y_fold_pred = model.predict(X_test)\n", + " y_actual = y_test.copy()\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_actual.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_fold_pred.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plotting results\n", + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_actual, y_fold_pred, alpha=0.7)\n", + "plt.plot([min(y_actual), max(y_actual)], [min(y_actual), max(y_actual)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (random forest)\")\n", + "plt.title(\"random forest: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_actual, y_fold_pred, alpha=0.7)\n", + "plt.plot([min(y_actual), max(y_actual)], [min(y_actual), max(y_actual)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (random forest)\")\n", + "plt.title(\"random forest: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1014/Q2.ipynb b/submissions_extracted/1014/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8833480ee54cac2916e1c24f3b5563dc5dd7a55e --- /dev/null +++ b/submissions_extracted/1014/Q2.ipynb @@ -0,0 +1,435 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3888\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss= validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1014/Q3.ipynb b/submissions_extracted/1014/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4a2964fbea4e40cbd5cc214e3291b6aa26ce2d93 --- /dev/null +++ b/submissions_extracted/1014/Q3.ipynb @@ -0,0 +1,375 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "my_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(my_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df = df.fillna(0) # just make it not there" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#no categorical" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "\n", + "#Not really imbalanced its okay to not do anything" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)\n", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Storage for logistic regression results for each fold\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "# 4. For each model:\n", + "X_train = X\n", + "y_train = y\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(skf.split(X_train,y)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + " y_pred = model.predict(X_val_fold)\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " y_test = y_val_fold\n", + " #print(X_val_fold.shape, y_test.shape)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['catboost'] = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "j=10\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "imp" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(features[0]) # this is the golden feature" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1015/Q1.ipynb b/submissions_extracted/1015/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fcf93ae60ebbeff83a5455488e85ffd956a2c6a5 --- /dev/null +++ b/submissions_extracted/1015/Q1.ipynb @@ -0,0 +1,298 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "#we dont need to log transform, its normally distributed." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food = df_food.drop('Order_ID', axis=1)\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#print(\"Missing values:\")\n", + "#print(df_food.isnull().sum())\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "#categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n", + "#print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "#for col in categorical_cols:\n", + " # print(f\"Encoding column: {col}\")\n", + " # le = LabelEncoder()\n", + " # df_food[col] = le.fit_transform(df_food[col])\n", + "#df_food\n", + "\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in df_food.select_dtypes(include=[\"object\"]).columns:\n", + " df_food[col] = label_encoder.fit_transform(df_food[col])\n", + "\n", + "df_food\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "#float64(3), int64(2), object(4)\n", + "features_cols = df_food.select_dtypes(include=[\"int64\", \"float64\",\"object\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "scaler = StandardScaler() # the average #??? # work best with nn #minmax better with bounded features\n", + "df_food[features_cols] = scaler.fit_transform(df_food[features_cols])\n", + "df_food" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food, \"Delivery_Time\")\n", + "#its normally ditributed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "#Distance_km\tWeather\tTraffic_Level\tTime_of_Day\tVehicle_Type\tPreparation_Time_min\tCourier_Experience_yrs\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_food[feature_cols]\n", + "y = df_food['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_squared_error(y_test, y_pred)\n", + "\n", + "print(f\"MSE: ${mse:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1015/Q2.ipynb b/submissions_extracted/1015/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..836dbd8606b06c19e8983b54f2e3b7217b1fef2e --- /dev/null +++ b/submissions_extracted/1015/Q2.ipynb @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "#X_train, X_test, y_train, y_test\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "#first batch from the training and test DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim) # This is the intended output layer for a 4-layer network.\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Fourth/Output layer\n", + " output = self.layer4(a3) # Direct output from layer4.\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam, AdamW\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 30\n", + "output_dim = 120 # age classes ending at 120 for logical reasons assuming no person older than 120\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "learning_rate = 0.001\n", + "\n", + "#(loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1015/Q3.ipynb b/submissions_extracted/1015/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..410ac2dc18f5b6025c28ef3d6ef40c613020441b --- /dev/null +++ b/submissions_extracted/1015/Q3.ipynb @@ -0,0 +1,219 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "data= pd.read_csv(data_path)\n", + "\n", + "print(f\"Dataset shape: {data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(data)\n", + "\n", + "data = data.fillna(data.mean())\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in data.select_dtypes(include=['float64', 'int64']).columns:\n", + " data[col] = label_encoder.fit_transform(data[col])\n", + "\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "#float64, int64\n", + "features_cols = data.select_dtypes(include=[\"int64\", \"float64\",\"object\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "data[features_cols] = scaler.fit_transform(data[features_cols])\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(data, \"Target\")\n", + "#theres very few no credit default" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1016/Q1.ipynb b/submissions_extracted/1016/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4b59c6b04622caad477bdd197e763ce3881aad0e --- /dev/null +++ b/submissions_extracted/1016/Q1.ipynb @@ -0,0 +1,318 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "data = pd.read_csv(csv_path)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 rows of the dataset:\")\n", + "print(data.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\nDataset info:\")\n", + "print(data.info())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nStatistical description:\")\n", + "print(data.describe())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "target_col = [col for col in data.columns if 'delivery' in col.lower() and 'time' in col.lower()]\n", + "if len(target_col) == 0:\n", + " raise ValueError(\"No column matching 'delivery_time' found.\")\n", + "target_col = target_col[0]\n", + "print(f\"\\nDetected target column: {target_col}\")\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.hist(data[target_col], bins=30, color='skyblue', edgecolor='black')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "if 'Order_ID' in data.columns:\n", + " data = data.drop(columns=['Order_ID'])\n", + " print(\"Dropped 'Order_ID' column.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (data.isnull().sum() / len(data)) * 100\n", + "missing_data = missing_percentage[missing_percentage > 0].sort_values(ascending=False)\n", + "print(\"\\nColumns with missing values (%):\")\n", + "print(missing_data)\n", + "\n", + "numeric_cols = data.select_dtypes(include=['int64', 'float64']).columns\n", + "data[numeric_cols] = data[numeric_cols].fillna(data[numeric_cols].mean())\n", + "\n", + "\n", + "categorical_cols = data.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " data[col] = data[col].fillna(data[col].mode()[0])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = data.duplicated().sum()\n", + "print(f\"\\nNumber of duplicate rows: {duplicates}\")\n", + "if duplicates > 0:\n", + " data = data.drop_duplicates()\n", + " print(\"Duplicates removed.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = data.select_dtypes(include=['object']).columns\n", + "if len(categorical_cols) > 0:\n", + " data = pd.get_dummies(data, columns=categorical_cols, drop_first=True)\n", + " print(f\"Applied One Hot Encoding to columns: {list(categorical_cols)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_col = [col for col in data.columns if 'delivery' in col.lower() and 'time' in col.lower()][0]\n", + "features = data.drop(columns=[target_col])\n", + "scaler = StandardScaler()\n", + "features_scaled = scaler.fit_transform(features)\n", + "data_scaled = pd.DataFrame(features_scaled, columns=features.columns)\n", + "data_scaled[target_col] = data[target_col].values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(\"\\nData cleaning and preprocessing complete.\")\n", + "print(\"Scaled data shape:\", data_scaled.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "target_col = [col for col in data_scaled.columns if 'delivery' in col.lower() and 'time' in col.lower()][0]\n", + "X = data_scaled.drop(columns=[target_col])\n", + "y = data_scaled[target_col]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42) # Use shuffle=True for better distribution\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold, (train_index, valid_index) in enumerate(kf.split(X), 1):\n", + " X_train, X_valid = X.iloc[train_index], X.iloc[valid_index]\n", + " y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n", + "\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + "\n", + " y_pred = rf_model.predict(X_valid)\n", + " mae = mean_absolute_error(y_valid, y_pred)\n", + " mae_scores.append(mae)\n", + " print(f\"Fold {fold} MAE: {mae:.3f}\")\n", + "\n", + "print(f\"\\nAverage MAE across all folds: {np.mean(mae_scores):.3f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importances = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': rf_model.feature_importances_\n", + "}).sort_values(by='importance', ascending=False)\n", + "\n", + "\n", + "top_features = feature_importances.head(20).sort_values(by='importance')\n", + "\n", + "plt.figure(figsize=(10,8))\n", + "plt.barh(top_features['feature'], top_features['importance'], color='skyblue')\n", + "plt.xlabel('Importance')\n", + "plt.title('Top 20 Feature Importances from RandomForest')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred_full = rf_model.predict(X)\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.hist(y_pred_full, bins=30, color='lightcoral', edgecolor='black')\n", + "plt.title('Histogram of Predicted Delivery Time')\n", + "plt.xlabel('Predicted Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "target_col = [col for col in data_scaled.columns if 'delivery' in col.lower() and 'time' in col.lower()][0]\n", + "X = data_scaled.drop(columns=[target_col])\n", + "y = data_scaled[target_col]\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "for fold, (train_index, valid_index) in enumerate(kf.split(X), 1):\n", + " X_train, X_valid = X.iloc[train_index], X.iloc[valid_index]\n", + " y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " cb_model.fit(X_train, y_train)\n", + "\n", + " y_pred_rf = rf_model.predict(X_valid)\n", + " y_pred_cb = cb_model.predict(X_valid)\n", + "\n", + " y_pred_ensemble = (y_pred_rf + y_pred_cb) / 2\n", + "\n", + " mae = mean_absolute_error(y_valid, y_pred_ensemble)\n", + " mae_scores.append(mae)\n", + " print(f\"Fold {fold} Ensemble MAE: {mae:.3f}\")\n", + "\n", + "print(f\"\\nAverage Ensemble MAE across all folds: {np.mean(mae_scores):.3f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1016/Q2.ipynb b/submissions_extracted/1016/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d4a51d9d2a1900bce0a9b047e13d3fabcdd08f6d --- /dev/null +++ b/submissions_extracted/1016/Q2.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1) # Make it (N,1)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "batch_size = 32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "sample_batch = next(iter(train_loader))\n", + "X_sample, y_sample = sample_batch\n", + "print(f\"Batch X shape: {X_sample.shape}\")\n", + "print(f\"Batch y shape: {y_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "fig, axes = plt.subplots(1, 5, figsize=(15,3))\n", + "for i in range(5):\n", + " img = X_sample[i].permute(1,2,0).numpy() # Convert to HWC for plotting\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {y_sample[i].item():.0f}\")\n", + " axes[i].axis('off')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "class AgeRegressionModel(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super(AgeRegressionModel, self).__init__()\n", + " self.model = nn.Sequential(\n", + " nn.Linear(input_dim, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\n", + " return self.model(x)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0\n", + " for X_batch, y_batch in loader:\n", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item() * X_batch.size(0)\n", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in loader:\n", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item() * X_batch.size(0)\n", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = X_train_tensor.shape[1] * X_train_tensor.shape[2] * X_train_tensor.shape[3]\n", + "model = AgeRegressionModel(input_dim).to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "if len(train_losses) == 0 or len(val_losses) == 0:\n", + " raise ValueError(\"train_losses or val_losses is empty. Run the training loop first.\")\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "epochs_range = range(1, len(train_losses)+1)\n", + "plt.plot(epochs_range, train_losses, label='Train Loss', marker='o')\n", + "plt.plot(epochs_range, val_losses, label='Validation Loss', marker='o')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Training and Validation Loss over Epochs')\n", + "plt.legend()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "X_sample, y_sample = next(iter(test_loader))\n", + "X_sample, y_sample = X_sample.to(device), y_sample.to(device)\n", + "with torch.no_grad():\n", + " y_pred = model(X_sample)\n", + "\n", + "ig, axes = plt.subplots(1,5, figsize=(15,3))\n", + "for i in range(5):\n", + " img = X_sample[i].cpu().permute(1,2,0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Pred: {y_pred[i].item():.0f}\\nActual: {y_sample[i].item():.0f}\")\n", + " axes[i].axis('off')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1016/Q3.ipynb b/submissions_extracted/1016/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ea79c3ace6464f2d029d927dd03b78521670f9b6 --- /dev/null +++ b/submissions_extracted/1016/Q3.ipynb @@ -0,0 +1,276 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "data = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 rows of the dataset:\")\n", + "display(data.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\nDataset Info:\")\n", + "data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nStatistical Description:\")\n", + "display(data.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "\n", + "for col in data.columns:\n", + " if data[col].dtype in ['float64', 'int64']:\n", + " data[col].fillna(data[col].mean(), inplace=True)\n", + " else:\n", + " data[col].fillna(data[col].mode()[0], inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = data.select_dtypes(include=['object']).columns\n", + "if len(categorical_cols) > 0:\n", + " for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = data.select_dtypes(include=['float64', 'int64']).columns.tolist()\n", + "numerical_cols.remove('B_3')\n", + "scaler = StandardScaler()\n", + "data[numerical_cols] = scaler.fit_transform(data[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_col = 'S_3'\n", + "target_counts = data[target_col].value_counts()\n", + "print(f\"Target distribution:\\n{target_counts}\")\n", + "imbalance_ratio = target_counts.min() / target_counts.max()\n", + "print(f\"Imbalance ratio (min/max): {imbalance_ratio:.2f}\")\n", + "if imbalance_ratio < 0.5:\n", + " print(\"The dataset is imbalanced.\")\n", + "else:\n", + " print(\"The dataset is reasonably balanced.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "!pip install catboost --quiet\n", + "\n", + "\n", + "import pandas as pd\n", + "import os\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n", + "import kagglehub\n", + "\n", + "avg_f1 = np.mean(f1_scores)\n", + "print(f\"\\nAverage F1 Score across 5 folds: {avg_f1:.4f}\")\n", + "\n", + "X = data.drop(columns=[target_col])\n", + "y = data[target_col]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores = []\n", + "\n", + "for fold, (train_index, val_index) in enumerate(kf.split(X, y), 1):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model = CatBoostClassifier(iterations=500, learning_rate=0.1, depth=6, verbose=0, random_seed=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores.append(f1)\n", + " print(f\"Fold {fold} - F1 Score: {f1:.4f}\")\n", + "\n", + "avg_f1 = np.mean(f1_scores)\n", + "print(f\"\\nAverage F1 Score across 5 folds: {avg_f1:.4f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "feature_importances = model.get_feature_importance()\n", + "importance_df = pd.DataFrame({\n", + " 'Feature': X.columns,\n", + " 'Importance': feature_importances\n", + "}).sort_values(by='Importance', ascending=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Top 10 features by importance:\")\n", + "display(importance_df.head(10))\n", + "\n", + "plt.figure(figsize=(10,5))\n", + "plt.barh(importance_df['Feature'][:10][::-1], importance_df['Importance'][:10][::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.title(\"Top 10 Feature Importances\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores_golden = []\n", + "\n", + "for fold, (train_index, val_index) in enumerate(kf.split(X_golden, y), 1):\n", + " X_train, X_val = X_golden.iloc[train_index], X_golden.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model_golden = CatBoostClassifier(\n", + " iterations=500,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " verbose=0,\n", + " random_seed=42\n", + " )\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " y_pred = model_golden.predict(X_val)\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores_golden.append(f1)\n", + " print(f\"Fold {fold} - F1 Score (Golden Feature only): {f1:.4f}\")\n", + "\n", + "avg_f1_golden = np.mean(f1_scores_golden)\n", + "print(f\"\\nAverage F1 Score using only the Golden Feature: {avg_f1_golden:.4f}\")\n", + "\n", + "print(f\"Full model Average F1: {avg_f1:.4f}\")\n", + "print(f\"Golden Feature only Average F1: {avg_f1_golden:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1017/Q1.ipynb b/submissions_extracted/1017/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..44bdc1ba229ebb68166a06c3a9f15fc7981f3007 --- /dev/null +++ b/submissions_extracted/1017/Q1.ipynb @@ -0,0 +1,381 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Download dataset from Kaggle\n", + "Q1_data = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 & 2:\n", + "df_cleaned = df.drop(\"Order_ID\", axis=1)\n", + "\n", + "print(\"Missing values before imputation:\")\n", + "print(df_cleaned.isnull().sum()[df_cleaned.isnull().sum() > 0])\n", + "\n", + "for col in df_cleaned.select_dtypes(include=np.number).columns:\n", + " if df_cleaned[col].isnull().any():\n", + " median_val = df_cleaned[col].median()\n", + " df_cleaned[col].fillna(median_val, inplace=True)\n", + "\n", + "\n", + "for col in df_cleaned.select_dtypes(include='object').columns:\n", + " if df_cleaned[col].isnull().any():\n", + " mode_val = df_cleaned[col].mode()[0]\n", + " df_cleaned[col].fillna(mode_val, inplace=True)\n", + "\n", + "print(\"\\nMissing values after imputation:\")\n", + "print(df_cleaned.isnull().sum()[df_cleaned.isnull().sum() > 0])\n", + "\n", + "df = df_cleaned.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def check_duplicates(df_param):\n", + " duplicates = df_param.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_param.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + " return df_param\n", + "\n", + "df = check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "categorical_cols = df.select_dtypes(include='object').columns.tolist()\n", + "\n", + "if categorical_cols:\n", + " print(f\"Categorical Columns to encode: {categorical_cols}\")\n", + " encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + " encoded_features = encoder.fit_transform(df[categorical_cols])\n", + " encoded_df = pd.DataFrame(encoded_features, columns=encoder.get_feature_names_out(categorical_cols), index=df.index)\n", + "\n", + " df = pd.concat([df.drop(columns=categorical_cols), encoded_df], axis=1)\n", + " print(\"\\nDataFrame after One-Hot Encoding:\")\n", + " display(df.head())\n", + "else:\n", + " print(\"No categorical columns found for encoding.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "X_features = df.drop(columns=['Delivery_Time'])\n", + "y_target = df['Delivery_Time']\n", + "\n", + "\n", + "numerical_cols_for_scaling = X_features.select_dtypes(include=np.number).columns.tolist()\n", + "\n", + "if numerical_cols_for_scaling:\n", + " print(f\"Applying StandardScaler to {len(numerical_cols_for_scaling)} numerical features.\")\n", + " scaler = StandardScaler()\n", + " X_features[numerical_cols_for_scaling] = scaler.fit_transform(X_features[numerical_cols_for_scaling])\n", + " print(\"\\nFeatures after scaling:\")\n", + " display(X_features.head())\n", + "else:\n", + " print(\"No numerical features found for scaling.\")\n", + "\n", + "\n", + "df = pd.concat([X_features, y_target], axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 5: Write your code here:\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "print(\"Shape of X:\", X.shape)\n", + "print(\"Shape of y:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "models = []\n", + "\n", + "print(f\"Performing {n_splits}-fold cross-validation...\")\n", + "\n", + "for fold, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\n--- Fold {fold+1}/{n_splits} ---\")\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " models.append(model)\n", + "\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + " print(f\"Mean Absolute Error (MAE) for Fold {fold+1}: {mae:.4f}\")\n", + "\n", + "\n", + "print(f\"\\nAverage Mean Absolute Error (MAE) across {n_splits} folds: {np.mean(mae_scores):.4f}\")\n", + "print(f\"Standard Deviation of MAE across {n_splits} folds: {np.std(mae_scores):.4f}\")\n", + "\n", + "\n", + "best_model_idx = np.argmin(mae_scores)\n", + "trained_model = models[best_model_idx]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "import seaborn as sns\n", + "\n", + "if 'trained_model' in locals():\n", + " feature_importances = trained_model.feature_importances_\n", + " features = X.columns\n", + " importance_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances})\n", + " importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + " plt.figure(figsize=(12, 7))\n", + " sns.barplot(x='Importance', y='Feature', data=importance_df)\n", + " plt.title('Feature Importances from RandomForestRegressor')\n", + " plt.xlabel('Importance')\n", + " plt.ylabel('Feature')\n", + " plt.tight_layout()\n", + " plt.show()\n", + "else:\n", + " print(\"No trained model found. Please run the modeling cell first.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "\n", + "full_model = RandomForestRegressor(random_state=42)\n", + "full_model.fit(X, y)\n", + "y_pred_full = full_model.predict(X)\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred_full, bins=30, edgecolor='black', alpha=0.7, label='Predicted Delivery Time')\n", + "plt.hist(y, bins=30, edgecolor='red', alpha=0.5, label='Actual Delivery Time') # Overlay actual for comparison\n", + "plt.title('Distribution of Predicted vs Actual Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "n_splits_ensemble = 5\n", + "kf_ensemble = KFold(n_splits=n_splits_ensemble, shuffle=True, random_state=42)\n", + "\n", + "ensemble_mae_scores = []\n", + "\n", + "print(f\"Performing {n_splits_ensemble}-fold cross-validation with ensemble models...\")\n", + "\n", + "for fold, (train_index, test_index) in enumerate(kf_ensemble.split(X, y)):\n", + " print(f\"\\n--- Ensemble Fold {fold+1}/{n_splits_ensemble} ---\")\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " rf_model = RandomForestRegressor(random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_preds = rf_model.predict(X_test)\n", + "\n", + " rf_model = RandomForestClassifier(random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_test)\n", + "\n", + "\n", + "\n", + " ensemble_preds = (rf_preds + rf_pred) / 2\n", + "\n", + "\n", + " mae = mean_absolute_error(y_test, ensemble_preds)\n", + " ensemble_mae_scores.append(mae)\n", + " print(f\"Ensemble Mean Absolute Error (MAE) for Fold {fold+1}: {mae:.4f}\")\n", + "\n", + "print(f\"\\nAverage Ensemble Mean Absolute Error (MAE) across {n_splits_ensemble} folds: {np.mean(ensemble_mae_scores):.4f}\")\n", + "print(f\"Standard Deviation of Ensemble MAE across {n_splits_ensemble} folds: {np.std(ensemble_mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1017/Q2.ipynb b/submissions_extracted/1017/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0eb1dfc7b84e9e2bc7a561cdb9efac3d4e4c109f --- /dev/null +++ b/submissions_extracted/1017/Q2.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " plt.imshow(images[i].permute(1, 2, 0).cpu().numpy())\n", + " plt.title(f\"Age: {labels[i].item():.0f}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "import torch.nn.functional as F # Import F for consistency, though not strictly needed for this regression validation\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch).squeeze(1) # Ensure outputs are 1D for regression\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 128\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "num_epochs = 20\n", + "learning_rate = 0.0001\n", + "\n", + "# Define criterion (loss function) - using MSELoss for regression\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(range(1, num_epochs + 1), train_losses, label='Training Loss')\n", + "plt.plot(range(1, num_epochs + 1), val_losses, label='Validation Loss')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.title('Training and Validation Loss Over Epochs')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus):\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " images_test, labels_test = next(iter(test_loader))\n", + " images_test_flattened = images_test.view(images_test.size(0), -1).to(device)\n", + " predictions = model(images_test_flattened).squeeze(1).cpu().numpy() #\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "for i in range(min(6, len(images_test))):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images_test[i].permute(1, 2, 0).cpu().numpy())\n", + " plt.title(f\"True Age: {labels_test[i].item():.0f}\\nPred Age: {predictions[i]:.0f}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1017/Q3.ipynb b/submissions_extracted/1017/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..511665ee221eb0ed768da8ee5aef162a8893431c --- /dev/null +++ b/submissions_extracted/1017/Q3.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "# Download dataset from Kaggle\n", + "Q3_data = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values before imputation:\")\n", + "print(df.isnull().sum()[df.isnull().sum() > 0])\n", + "\n", + "\n", + "for col in df.select_dtypes(include=np.number).columns:\n", + " if df[col].isnull().any():\n", + " median_val = df[col].median()\n", + " df[col].fillna(median_val, inplace=True)\n", + "\n", + "for col in df.select_dtypes(include='object').columns:\n", + " if df[col].isnull().any():\n", + " mode_val = df[col].mode()[0]\n", + " df[col].fillna(mode_val, inplace=True)\n", + "\n", + "print(\"\\nMissing values after imputation:\")\n", + "print(df.isnull().sum()[df.isnull().sum() > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def check_duplicates(df_param):\n", + " duplicates = df_param.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_param.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + " return df_param\n", + "\n", + "df = check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "categorical_cols = df.select_dtypes(include='object').columns\n", + "\n", + "if len(categorical_cols) > 0:\n", + " print(f\"Encoding {len(categorical_cols)} categorical features: {list(categorical_cols)}\")\n", + " df = pd.get_dummies(df, columns=categorical_cols, dummy_na=False)\n", + " print(\"Categorical features encoded.\")\n", + "else:\n", + " print(\"No categorical features found for encoding.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "numerical_cols_for_scaling = df.select_dtypes(include=np.number).columns.drop('Target', errors='ignore')\n", + "\n", + "if len(numerical_cols_for_scaling) > 0:\n", + " print(f\"Applying StandardScaler to {len(numerical_cols_for_scaling)} numerical features.\")\n", + " scaler = StandardScaler()\n", + " df[numerical_cols_for_scaling] = scaler.fit_transform(df[numerical_cols_for_scaling])\n", + " print(\"Numerical features scaled.\")\n", + "else:\n", + " print(\"No numerical features found for scaling.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Check for target imbalance\n", + "target_counts = df['Target'].value_counts(normalize=True)\n", + "print(\"Target variable distribution:\")\n", + "print(target_counts)\n", + "\n", + "if target_counts.min() < 0.3:\n", + " print(\"The target variable is imbalanced.\")\n", + "else:\n", + " print(\"The target variable is not significantly imbalanced.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop('Target', axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# Initialize StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Store F1 scores for each fold\n", + "f1_scores = []\n", + "\n", + "for fold, (train_index, val_index) in enumerate(skf.split(X, y)):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " # Initialize and train CatBoostClassifier\n", + " model = CatBoostClassifier(random_state=42, verbose=0, iterations=100)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Make predictions on the validation set\n", + " y_pred = model.predict(X_val)\n", + "\n", + " # Calculate F1 score\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores.append(f1)\n", + " print(f\"Fold {fold+1} F1 Score: {f1:.4f}\")\n", + "\n", + "# Print the averaged F1 score across all folds\n", + "print(f\"\\nAverage F1 Score across all folds: {np.mean(f1_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "feature_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "\n", + "importance_series = pd.Series(feature_importances, index=feature_names)\n", + "\n", + "\n", + "sorted_importance = importance_series.sort_values(ascending=False)\n", + "\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "sorted_importance.head(20).plot(kind='barh')\n", + "plt.title('Top 20 Feature Importances')\n", + "plt.xlabel('Feature Importance')\n", + "plt.ylabel('Feature Name')\n", + "plt.gca().invert_yaxis() # To have the most important feature at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "most_important_feature = sorted_importance.index[0]\n", + "\n", + "print(f\"The golden feature (most important predictor) is: {most_important_feature}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus:\n", + "x = df['P_2']\n", + "f1_scores_for_x = []\n", + "for fold, (train_index, val_index) in enumerate(skf.split(X, y)):\n", + " X_train, X_val = X.iloc[x], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[x], y.iloc[val_index]\n", + "\n", + " # Initialize and train CatBoostClassifier\n", + " model = CatBoostClassifier(random_state=42, verbose=0, iterations=100)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Make predictions on the validation set\n", + " y_pred = model.predict(X_val)\n", + "\n", + " # Calculate F1 score\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores_for_x.append(f1)\n", + " print(f\"Fold {fold+1} F1 Score: {f1:.4f}\")\n", + "\n", + "# Print the averaged F1 score across all folds\n", + "print(f\"\\nAverage F1 Score across all folds: {np.mean(f1_scores_for_x):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1018/Q1.ipynb b/submissions_extracted/1018/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c2ff34d84b41094b823a02fe9d1622c562c5b614 --- /dev/null +++ b/submissions_extracted/1018/Q1.ipynb @@ -0,0 +1,365 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_file_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n--- First 5 rows of the data ---\")\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\n--- Dataset Information ---\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\n--- Statistical Description ---\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(8, 5))\n", + "sns.histplot(df['Delivery_Time'], kde=True, color='green')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import pandas as pd\n", + "\n", + "if 'Order_ID' in df.columns:\n", + " df = df.drop(columns=['Order_ID'])\n", + " print(\"Column 'Order_ID' dropped.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values before cleaning:\")\n", + "print(df.isnull().sum())\n", + "\n", + "initial_rows = df.shape[0]\n", + "df.dropna(subset=['Delivery_Time'], inplace=True)\n", + "print(f\"Dropped {initial_rows - df.shape[0]} rows with missing 'Delivery_Time'.\")\n", + "for column in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " if column in df.columns and df[column].isnull().any():\n", + " mode_val = df[column].mode()[0]\n", + " df[column].fillna(mode_val, inplace=True)\n", + " print(f\"Imputed missing values in '{column}' with mode: {mode_val}\")\n", + "\n", + "if df['Courier_Experience_yrs'].isnull().any():\n", + " median_val = df['Courier_Experience_yrs'].median()\n", + " df['Courier_Experience_yrs'].fillna(median_val, inplace=True)\n", + " print(f\"Imputed missing values with median:: {median_val}\")\n", + "else:\n", + " print(\"has no missing values or already handled\")\n", + "\n", + "\n", + "\n", + "print(\"\\nMissing values after handling::\")\n", + "print(df.isnull().sum())\n", + "\n", + "duplicate_count = df.duplicated().sum()\n", + "print(f\"\\nFound {duplicate_count} duplicate rows.\")\n", + "if duplicate_count > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"Duplicates removed.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Encode categorical variables using One-Hot Encoding\n", + "df = pd.get_dummies(df, drop_first=True)\n", + "print(\"\\nCategorical variables encoded using One-Hot Encoding.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "\n", + "features = df.drop(columns=['Delivery_Time'])\n", + "target = df['Delivery_Time']\n", + "\n", + "scaled_features = scaler.fit_transform(features)\n", + "df_cleaned = pd.DataFrame(scaled_features, columns=features.columns)\n", + "df_cleaned['Delivery_Time'] = target.values\n", + "\n", + "print(\"\\nFeature scaling finished using StandardScaler.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "\n", + "\n", + "features = df.drop(columns=['Delivery_Time'])\n", + "target = df['Delivery_Time']\n", + "\n", + "scaled_features = scaler.fit_transform(features)\n", + "\n", + "df_cleaned = pd.DataFrame(scaled_features, columns=features.columns)\n", + "df_cleaned['Delivery_Time'] = target.values\n", + "\n", + "print(\"\\nFeature scaling finished using StandardScaler.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(\"\\n--- Target Data Check ---\")\n", + "print(df_cleaned['Delivery_Time'].describe())\n", + "print(\"\\nFinal data shape:\", df_cleaned.shape)\n", + "print(df_cleaned.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "X = df_cleaned.drop(columns=['Delivery_Time'])\n", + "y = df_cleaned['Delivery_Time']\n", + "\n", + "print(\"Dataset split into features (X) and target (y).\")\n", + "print(\"Shape of X:\", X.shape)\n", + "print(\"Shape of y:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "print(\"Starting model training with K-Fold...\")\n", + "\n", + "# 3-Train a RandomForest:\n", + "fold_number = 1\n", + "for train_index, test_index in kf.split(X):\n", + " X_train_fold, X_test_fold = X.iloc[train_index], X.iloc[test_index]\n", + " y_train_fold, y_test_fold = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " predictions = model.predict(X_test_fold)\n", + "\n", + " # task-4:\n", + " mae = mean_absolute_error(y_test_fold, predictions)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold_number} MAE: {mae:.4f}\")\n", + " fold_number += 1\n", + "\n", + "\n", + "average_mae = np.mean(mae_scores)\n", + "print(\"\\n--- Final Evaluation ---\")\n", + "print(f\"Average MAE across all folds: {average_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "importances = model.feature_importances_\n", + "feature_names = features.columns\n", + "\n", + "\n", + "importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})\n", + "\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(x='Importance', y='Feature', data=importance_df)\n", + "plt.title('Feature Importance (What affects delivery time most?)')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "predicted_times = model.predict(X_test_fold)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(predicted_times, kde=True, bins=30)\n", + "\n", + "plt.title('Histogram of Predicted Delivery Times')\n", + "plt.xlabel('Predicted Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "print(\"\\nSample:\")\n", + "for i in range(5):\n", + " print(f\"Actual: {y_test_fold.iloc[i]:.2f} mins | Predicted: {predicted_times[i]:.2f} mins\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "!pip install catboost\n", + "from catboost import CatBoostRegressor\n", + "\n", + "ensemble_mae_scores = []\n", + "\n", + "print(\"Starting ensemble model training with K-Fold...\")\n", + "\n", + "for train_index, test_index in kf.split(X):\n", + " X_train_fold, X_test_fold = X.iloc[train_index], X.iloc[test_index]\n", + " y_train_fold, y_test_fold = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # model 1:\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train_fold, y_train_fold)\n", + " rf_predictions = rf_model.predict(X_test_fold)\n", + "\n", + " # model 2:\n", + " cb_model = CatBoostRegressor(iterations=100, learning_rate=0.1, depth=6, random_seed=42, verbose=False)\n", + " cb_model.fit(X_train_fold, y_train_fold)\n", + " cb_predictions = cb_model.predict(X_test_fold)\n", + " averaged_predictions = (rf_predictions + cb_predictions) / 2\n", + "\n", + " ensemble_mae = mean_absolute_error(y_test_fold, averaged_predictions)\n", + " ensemble_mae_scores.append(ensemble_mae)\n", + "\n", + "\n", + "\n", + " print(f\"Fold {len(ensemble_mae_scores)} Ensemble MAE: {ensemble_mae:.4f}\")\n", + "\n", + "average_ensemble_mae = np.mean(ensemble_mae_scores)\n", + "print(\"\\n--- Final Ensemble Evaluation ---\")\n", + "print(f\"Average Ensemble MAE across all folds: {average_ensemble_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1018/Q2.ipynb b/submissions_extracted/1018/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2304ecbc0172f086dedbbfce2192462e377933b6 --- /dev/null +++ b/submissions_extracted/1018/Q2.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n", + "print(\"Tensors created successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images_batch, labels_batch = next(iter(train_loader))\n", + "print(f\"Batch images shape::{images_batch.shape}\")\n", + "print(f\"Batch labels shape:{labels_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(12,4))\n", + "for i in range(5):\n", + " plt.subplot(1,5,i+1)\n", + "\n", + " display_img = images_batch[i].permute(1,2 ,0).numpy()\n", + " plt.imshow(display_img)\n", + " plt.title(f\"Age: {int(labels_batch[i].item())}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "class AgePredictionModel(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgePredictionModel, self).__init__()\n", + " # Layer 1:\n", + " self.fc1 = nn.Linear(input_size, 512)\n", + " # Layer2:\n", + " self.fc2 = nn.Linear(512, 256)\n", + " # Layer3:\n", + " self.fc3 = nn.Linear(256, 64)\n", + " # Layer4:\n", + " self.fc4 = nn.Linear(64, 1)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_model(model, train_loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for images, ages in train_loader:\n", + " images, ages = images.to(device), ages.to(device)\n", + "\n", + " outputs = model(images)\n", + " loss = criterion(outputs, ages)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + " return total_loss / len(train_loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate_model(model, test_loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for images, ages in test_loader:\n", + " images, ages = images.to(device), ages.to(device)\n", + " outputs = model(images)\n", + " loss = criterion(outputs, ages)\n", + " total_loss += loss.item()\n", + " return total_loss / len(test_loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "\n", + "model = AgePredictionModel(input_size=input_dim).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"Starting train\")\n", + "for epoch in range(20):\n", + " train_loss = train_model(model, train_loader, criterion, optimizer, device)\n", + " val_loss = validate_model(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"epochs: {epoch+1}/20: Train Loss= { train_loss:.4f}, Val Loss= {val_loss:.4f}\")\n", + "\n", + "print(\"Train completes\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(train_losses, label='Training Loss', color='blue')\n", + "plt.plot(val_losses, label='Validation Loss', color='red')\n", + "\n", + "plt.title('Model Loss Over Epochs')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "images, ages = next(iter(test_loader))\n", + "images, ages = images.to(device), ages.to(device)\n", + "\n", + "with torch.no_grad():\n", + " predictions = model(images)\n", + "\n", + "plt.figure(figsize=(15,5))\n", + "for i in range(5):\n", + " plt.subplot(1,5 , i+1)\n", + " img = images[i].cpu().permute(1 ,2 ,0).numpy()\n", + " plt.imshow(img)\n", + "\n", + " actual_age = ages[i].item()\n", + " pred_age = predictions[i].item()\n", + " plt.title(f\"actual: {actual_age:.0f}\\n\\n:{pred_age:.1f}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1018/Q3.ipynb b/submissions_extracted/1018/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f626e92aa396a91d0e5237fbe0a13c29f8514b5c --- /dev/null +++ b/submissions_extracted/1018/Q3.ipynb @@ -0,0 +1,336 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path,\"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\ndataset:\")\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"data Info:\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "print(\"\\ndescription:\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import pandas as pd\n", + "\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "print(\"\\nMissing values handled\")\n", + "\n", + "if len(categorical_cols) > 0:\n", + "\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + " print(\"Categorical variables encoded.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"\\nNumber of duplicate rows: {duplicates}\")\n", + "\n", + "if duplicates > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"Duplicates removed successfully.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "print(f\"\\nCategorical columns founded are: {list(categorical_cols)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "X = df.drop(columns=['Target'])\n", + "y = df['Target']\n", + "\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "df_cleaned = pd.DataFrame(X_scaled, columns=X.columns)\n", + "df_cleaned['Target'] = y.values\n", + "\n", + "print(\"\\nFeature scaling done.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_counts = df['Target'].value_counts()\n", + "print(\"Target Class Distribution:\")\n", + "print(target_counts)\n", + "\n", + "imbalance_ratio = target_counts.min() / target_counts.max()\n", + "if imbalance_ratio < 0.5:\n", + " print(\"State imbalanced.\")\n", + "elif imbalance_ratio < 0.75:\n", + " print(\"State slightly imbalanced.\")\n", + "else:\n", + " print(\"State is balanced.\")\n", + "\n", + "\n", + "\n", + "print(f\"\\nClean data shape: {df_cleaned.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "X = df_cleaned.drop(columns=['target'])\n", + "y = df_cleaned['target']\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + " # task2:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "\n", + "print(\"Starting training with CatBoost\")\n", + "\n", + "# task-3:\n", + "for fold, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " X_train_fold, X_test_fold = X.iloc[train_index], X.iloc[test_index]\n", + " y_train_fold, y_test_fold = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = CatBoostClassifier(iterations=200, learning_rate=0.1, depth=6, silent=True)\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + "\n", + " y_pred = model.predict(X_test_fold)\n", + "\n", + " # Task-4:\n", + " score = f1_score(y_test_fold, y_pred)\n", + " f1_scores.append(score)\n", + "\n", + " print(f\"Fold {fold + 1} - F1 Score: {score:.4f}\")\n", + "\n", + "# Task-5:\n", + "average_f1 = np.mean(f1_scores)\n", + "print(\"\\n--- Model Evaluation Summary ---\")\n", + "print(f\"Average F1 Score: {average_f1:.4f}\")\n", + "import numpy as np\n", + "import pandas as pd\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier\n", + "\n", + "X = df_cleaned.drop(columns=['Target'])\n", + "y = df_cleaned['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "importances = model.feature_importances_\n", + "feature_names = X.columns\n", + "\n", + "feature_importance_df = pd.DataFrame({\n", + " 'Feature': feature_names,\n", + " 'Importance': importances\n", + "})\n", + "\n", + "feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task-2:\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "sns.barplot(x='Importance', y='Feature', data=feature_importance_df.head(20))\n", + "\n", + "plt.title('Feature Importance - Searching for the Golden Feature')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Anonymized Features')\n", + "plt.show()\n", + "\n", + "\n", + "golden_feature = feature_importance_df.iloc[0]['Feature']\n", + "golden_score = feature_importance_df.iloc[0]['Importance']\n", + "\n", + "print(\"\\n\" + \"=\"*30)\n", + "print(f\"THE GOLDEN FEATURE IS: {golden_feature}\")\n", + "print(f\"Importance Score: {golden_score:.2f}\")\n", + "print(\"=\"*30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "golden_model_scores = []\n", + "\n", + "print(f\"Retraining: {golden_feature}...\")\n", + "\n", + "for train_index, test_index in skf.split(X_golden, y):\n", + "\n", + " X_train_fold, X_test_fold = X_golden.iloc[train_index], X_golden.iloc[test_index]\n", + " y_train_fold, y_test_fold = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + "\n", + "\n", + " model_golden = CatBoostClassifier(iterations=100, silent=True, random_state=42)\n", + "\n", + " model_golden.fit(X_train_fold, y_train_fold)\n", + "\n", + " preds = model_golden.predict(X_test_fold)\n", + " score = f1_score(y_test_fold, preds)\n", + " golden_model_scores.append(score)\n", + "\n", + "average_golden_f1 = np.mean(golden_model_scores)\n", + "\n", + "\n", + "print(\"Performence:\")\n", + "print(f\"Full Model F1 Score: {average_f1:.4f}\")\n", + "print(f\"Golden Feature Only: {average_golden_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1019/Q1.ipynb b/submissions_extracted/1019/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2ffa87e940452666a8e76c5b8656772921edac20 --- /dev/null +++ b/submissions_extracted/1019/Q1.ipynb @@ -0,0 +1,328 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Load the CSV file\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(df_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "#Inspect the first few rows\n", + "print(f\"Shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "# Display dataset information\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "# Descriptive statistics for numerical columns\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# Delivery_Time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Drop the 'Order_ID' column from the data\n", + "df_clean = df_food.drop('Order_ID', axis=1).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "# For Handle Missing Values\n", + "categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in [categorical_cols]:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill numrical columns with the mean\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mode()[0])\n", + "\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "from sklearn.preprocessing import LabelEncoder , StandardScaler\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Split the dataset into features (X) and target (y)\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "# Use the correct split: KFold\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + " model.fit(X_train, y_train)\n", + " print(\"Model trained!\")\n", + "\n", + " # Validate\n", + " # Predictions and metrics\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Plot for the feature importance from your trained model\n", + "\n", + "# Define features and target\n", + "importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "# Plot predicted delivery time histogram\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "\n", + "plt.title(\"Predicted Target Distribution\")\n", + "plt.xlabel(\"Predicted Value\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1019/Q2.ipynb b/submissions_extracted/1019/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7d2df567e73706a027b7dabdcb056569e8ae288e --- /dev/null +++ b/submissions_extracted/1019/Q2.ipynb @@ -0,0 +1,398 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super().__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).long()\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).long()\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " predicted = outputs.argmax(dim=1)\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + " return avg_loss, accuracy\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "sample_x, _ = next(iter(train_loader))\n", + "input_dim = sample_x[0].numel()\n", + "hidden_dim = 14\n", + "output_dim = 10\n", + "\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1019/Q3.ipynb b/submissions_extracted/1019/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f119478d75565aaf7558b41e576a46c9e57b3d3f --- /dev/null +++ b/submissions_extracted/1019/Q3.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "# Load the CSV file\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "#Inspect the first few rows\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "# Display dataset information\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "# Descriptive statistics for numerical columns\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df['Target'].value_counts()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "from sklearn.preprocessing import LabelEncoder , StandardScaler\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "scaler = StandardScaler()\n", + "df = scaler.fit_transform(df)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1:\n", + "# Split the dataset into features (X) and target (y)\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2,3,4,5:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "# Use the correct split: KFold\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + " model.fit(X_train, y_train)\n", + " print(\"Model trained!\")\n", + "\n", + " # Validate\n", + " # Predictions and metrics\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1:\n", + "# Plot for the feature importance from your trained model\n", + "\n", + "# Define features and target\n", + "importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 2:\n", + "# Plot predicted delivery time histogram\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "\n", + "plt.title(\"Predicted Target Distribution\")\n", + "plt.xlabel(\"Predicted Value\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/102/Q1.ipynb b/submissions_extracted/102/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3880362f7c5bf117570707360bb29842f7028066 --- /dev/null +++ b/submissions_extracted/102/Q1.ipynb @@ -0,0 +1,344 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df_food, target_column):\n", + " df_food[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_food, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_cleand = df_food.drop(columns=['Order_ID'])\n", + "df_cleand.info() # to check if its droped" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df_cleand):\n", + " missing_values = df_cleand.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_cleand)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop rows of with missing of Delivery_Time values\n", + "stat_cols = ['Delivery_Time']\n", + "\n", + "df_cleand = df_cleand.dropna(subset=stat_cols).copy() # since the missing value for delivery time is very small comaring to the number of rows drop the missing rows will not affect much\n", + "print(f\"Shape after cleaning: {df_cleand.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# handel missing values\n", + "df_cleand['Weather'] = df_cleand['Weather'].fillna('none')\n", + "df_cleand['Traffic_Level'] = df_cleand['Traffic_Level'].fillna('none')\n", + "df_cleand['Time_of_Day'] = df_cleand['Time_of_Day'].fillna('none')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df_cleand):\n", + " missing_values = df_cleand.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_cleand)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df_cleand):\n", + " duplicates = df_cleand.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_cleand.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_cleand)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_cleand.info() # to check if its droped" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "df_cleand['Weather'] = le.fit_transform(df_cleand['Weather'])\n", + "df_cleand['Traffic_Level'] = le.fit_transform(df_cleand['Traffic_Level'])\n", + "df_cleand['Time_of_Day'] = le.fit_transform(df_cleand['Time_of_Day'])\n", + "df_cleand['Vehicle_Type'] = le.fit_transform(df_cleand['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "df_scaled = df_cleand[feature_cols]\n", + "\n", + "df_scaled = scaler.fit_transform(df_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_distribution(df_cleand, target_column):\n", + " df_cleand[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_cleand, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_scaled.astype(float)\n", + "y = df_cleand['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/102/Q3.ipynb b/submissions_extracted/102/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..554719163ee5763b4ac9325a4e6c2b0f3c4b13c7 --- /dev/null +++ b/submissions_extracted/102/Q3.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(20, 10))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "importances['CatBoost']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1020/Q1.ipynb b/submissions_extracted/1020/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4836dac61daddc934eb407d4075bbc9f921c302b --- /dev/null +++ b/submissions_extracted/1020/Q1.ipynb @@ -0,0 +1,316 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Load the CSV file\n", + "# Load the CSV file\n", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Target distribution\n", + "# Attack distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop('Order_ID',axis=1).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "print(df_clean.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "\n", + "\n", + "\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "print(df_clean.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Check for duplicates\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = ['Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type'\t]\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "\n", + "df_clean.head()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df_clean.head()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features and target\n", + "\n", + "features = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "\n", + "X = df_clean[features]\n", + "\n", + "y = df_clean['Delivery_Time']\n", + "print(y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Stratified split\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "predicted = []\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "for train_idx, val_idx in kfold.split(X):\n", + " X_fold_train, X_fold_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_fold_train, y_fold_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + " predicted.append(y_fold_pred)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(predicted, bins=30, edgecolor='black')\n", + "plt.title('Predicted Delivery_time Distribution')\n", + "plt.xlabel('Predicted delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1020/Q2.ipynb b/submissions_extracted/1020/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ca26cbec48d8e273fd3a6cf93a1ef28ed9fa47a5 --- /dev/null +++ b/submissions_extracted/1020/Q2.ipynb @@ -0,0 +1,397 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + " # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1020/Q3.ipynb b/submissions_extracted/1020/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/1020/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1021/Q1.ipynb b/submissions_extracted/1021/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5934b4fb64c40d5d41574691428e114eaf8afe3f --- /dev/null +++ b/submissions_extracted/1021/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 Attempt the partical exam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1021/Q2.ipynb b/submissions_extracted/1021/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..99ae08cfca900dbc6089e30607a6e783b8326f5c --- /dev/null +++ b/submissions_extracted/1021/Q2.ipynb @@ -0,0 +1,193 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "attempt partical exam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1021/Q3.ipynb b/submissions_extracted/1021/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d1f9b318e74dbf04889ab2aaa8d1fc189a4d4734 --- /dev/null +++ b/submissions_extracted/1021/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: attempt partical exam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1022/Q1.ipynb b/submissions_extracted/1022/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..aa7f4f88336438423e4f12cdd3f97380e5e10e5a --- /dev/null +++ b/submissions_extracted/1022/Q1.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import gdown\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import os\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns='Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])\n", + "check_missing_values(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "for train_index, test_index in skf.split(X, y):\n", + " X_Train = X.iloc[train_index, :]\n", + " X_Test = X.iloc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " model.fit(X_Train, y_Train)\n", + " y_pred = model.predict(X_Test)\n", + "\n", + "mae = mean_absolute_error(y_Test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "tree_importance = list(zip(X.columns, model.feature_importances_))\n", + "\n", + "features, coefficients = zip(*tree_importance)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, coefficients, color='darkblue')\n", + "plt.xlabel('Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(df[\"Delivery_Time\"])\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1022/Q2.ipynb b/submissions_extracted/1022/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..85617dc1263792551cde08716b205b5440e307b1 --- /dev/null +++ b/submissions_extracted/1022/Q2.ipynb @@ -0,0 +1,421 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import AdamW\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_train.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].permute(1,2,0))\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + "\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 32 * 32\n", + "\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "output_dim = 1\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(running_loss, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1022/Q3.ipynb b/submissions_extracted/1022/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dbfdc2f8575df6c9a7a47a21e5ef38dc865a8cc5 --- /dev/null +++ b/submissions_extracted/1022/Q3.ipynb @@ -0,0 +1,198 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import gdown\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_values = df.isnull().sum()\n", + "print(\"Missing values in each column:\")\n", + "print(missing_values)\n", + "df.fillna(df.mean(), inplace=True)\n", + "missing_values = df.isnull().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaled_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[scaled_cols] = scaler.fit_transform(df[scaled_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1023/Q1.ipynb b/submissions_extracted/1023/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..261667cdfc997773b63ad18e589d5a9defe78f86 --- /dev/null +++ b/submissions_extracted/1023/Q1.ipynb @@ -0,0 +1,271 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.datasets import make_regression\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])\n", + "\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(numerical_cols)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df):\n", + " print(\"Target Distribution:\")\n", + " print(df.value_counts(normalize=True))\n", + "\n", + "check_target_imbalance(df['Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#2\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "#3\n", + "X, y = make_regression(n_samples=1000, n_features=10, noise=10, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X, y = make_regression(n_samples=1000, n_features=10, noise=10, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "# Random Forest\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + "\n", + "# Feature importance\n", + "print(\"\\nTop 3 important features (Random Forest):\")\n", + "importances = rf.feature_importances_\n", + "for i in np.argsort(importances)[-3:][::-1]:\n", + " print(f\" Feature {i}: {importances[i]:.3f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1023/Q2.ipynb b/submissions_extracted/1023/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fd380a5216a8993ae7a6143acdd20e4696674ac3 --- /dev/null +++ b/submissions_extracted/1023/Q2.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import torch\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch.nn as nn\n", + "from PIL import Image\n", + "import matplotlib.pyplot as plt\n", + "from torch.optim import AdamW\n", + "import torch.nn.functional as F\n", + "from sklearn.model_selection import train_test_split\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train_tensor = torch.FloatTensor(X_train)\n", + "y_train_tensor = torch.LongTensor(y_train)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 3 * 32 * 32\n", + "\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "images, labels = next(iter(test_loader))\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1023/Q3.ipynb b/submissions_extracted/1023/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7d53b10f101aed7a0c794fd04efb0dda756b2133 --- /dev/null +++ b/submissions_extracted/1023/Q3.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.datasets import make_regression\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "#df['S_3'].fillna(df['S_3'].mean(), inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])\n", + "\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(numerical_cols)\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df):\n", + " print(\"Target Distribution:\")\n", + " print(df.value_counts(normalize=True))\n", + " sns.countplot(x=df)\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df['B_1'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"B_1\", axis=1).astype(float)\n", + "y = df['P_2'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n", + " \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n", + "}\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "atboost_model = models[\"CatBoost Classifier\"]\n", + "catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n", + "sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_catboost_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X, y = make_regression(n_samples=1000, n_features=10, noise=10, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "# Random Forest\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + "\n", + "# Feature importance\n", + "print(\"\\nTop 3 important features (Random Forest):\")\n", + "importances = rf.feature_importances_\n", + "for i in np.argsort(importances)[-3:][::-1]:\n", + " print(f\" Feature {i}: {importances[i]:.3f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "sklearn_models = {\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )\n", + "}\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1024/Q1.ipynb b/submissions_extracted/1024/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9590838c85e595305700f1981cadf826f3cebdaa --- /dev/null +++ b/submissions_extracted/1024/Q1.ipynb @@ -0,0 +1,260 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "food_path = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('deliveryTime Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_clean = df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food)\n", + "\n", + "df_clean['Weather'] = df_clean['Weather'].fillna('none')\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna('none')\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna('none')\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna('none')\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna('none')\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_food)\n", + "#duplicates cause maybe outlaires" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "le = LabelEncoder()\n", + "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n", + "#that makes it numric bacause ml dont understand text\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "eature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level','Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n", + "X = df_clean[eature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42 , stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "# Train-test split (80% train, 20% test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1024/Q2.ipynb b/submissions_extracted/1024/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff966b88455489874072f9297a44854e901a333e --- /dev/null +++ b/submissions_extracted/1024/Q2.ipynb @@ -0,0 +1,336 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "\n", + "im_path = os.path.join(path, '/kaggle/input/q2-exam-data/labels.csv')\n", + "df_im = pd.read_csv(im_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # 4 linear layer: hidden layer -> hidden layer\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer5 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + " # Third hidden layer\n", + " a4= self.relu(self.layer3(a3))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer5(a4) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "ef validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1024/Q3.ipynb b/submissions_extracted/1024/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..adfb38cd9f9d80a6c27739f736d93c220a1479b0 --- /dev/null +++ b/submissions_extracted/1024/Q3.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "cor_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df_cor = pd.read_csv(cor_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_cor.shape}\")\n", + "df_cor.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_cor.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_cor.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_cor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1025/Q1.ipynb b/submissions_extracted/1025/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f869eb11a0299e4a27b4f3bf0570458b4edb2d7a --- /dev/null +++ b/submissions_extracted/1025/Q1.ipynb @@ -0,0 +1,300 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sb\n", + "sb.histplot(df[\"Delivery_Time\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "clean_df = df.drop(\"Order_ID\",axis=1)\n", + "clean_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " print()\n", + "\n", + "check_missing_values(clean_df)\n", + "\n", + "#now for the handling\n", + "df.head()\n", + "\n", + "clean_df = clean_df.dropna(subset=[\"Delivery_Time\"])\n", + "\n", + "for col in ['Weather','Traffic_Level','Time_of_Day']:\n", + " clean_df[col] = clean_df[col].fillna(\"unknown\")\n", + "\n", + "\n", + "\n", + "clean_df[\"Courier_Experience_yrs\"] = clean_df[\"Courier_Experience_yrs\"].fillna(clean_df[\"Courier_Experience_yrs\"].mean())\n", + "\n", + "check_missing_values(clean_df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + "\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(clean_df)\n", + "check_duplicates(clean_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = clean_df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " clean_df[col] = le.fit_transform(clean_df[col].values)\n", + "\n", + "categorical_cols = clean_df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = clean_df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "clean_df[numerical_cols] = scaler.fit_transform(clean_df[numerical_cols])\n", + "clean_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# this is not a classification problem" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = clean_df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = clean_df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "n_splits = 5 # K=5 Folds\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "mae_lst = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train\n", + " rfg = RandomForestRegressor()\n", + " print(f\"Training...\")\n", + " rfg.fit(X_train, y_train)\n", + " y_pred = rfg.predict(X_test)\n", + " mae_lst.append(mean_absolute_error(y_test,y_pred))\n", + "\n", + "print(sum(mae_lst)/len(mae_lst))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = rfg.feature_importances_\n", + "sb.histplot(importance)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Note: my understanding is that the task wants the average of all MAEs and not the MAEs for each model so that is how i did it\n", + "\n", + "%pip install catboost\n", + "from catboost import CatBoostRegressor\n", + "models = {\"catboost\":CatBoostRegressor(),\"randomf\":RandomForestRegressor()}\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "mae_lst = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train\n", + " for model in models:\n", + " print(f\"Training...\")\n", + " models[model].fit(X_train, y_train)\n", + " y_pred = models[model].predict(X_test)\n", + " mae_lst.append(mean_absolute_error(y_test,y_pred))\n", + "\n", + "print()\n", + "print(sum(mae_lst)/len(mae_lst))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1025/Q2.ipynb b/submissions_extracted/1025/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..907c75b526b574d7ddf1ef7abc575287797d98e3 --- /dev/null +++ b/submissions_extracted/1025/Q2.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].view(-1,36,3), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # fourth linear layer: hidden layer -> hidden layer\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer5 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #third\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " #fourth\n", + " z4 = self.layer4(a3)\n", + " a4 = self.relu(z4)\n", + "\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer5(a4) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1025/Q3.ipynb b/submissions_extracted/1025/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b9bb8be6bd7233113144270ff4896b56a6b07785 --- /dev/null +++ b/submissions_extracted/1025/Q3.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " print()\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "# no encoding nedded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1026/Q1.ipynb b/submissions_extracted/1026/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..156c4136775d8ef37ba767de7fbff80dbd336a56 --- /dev/null +++ b/submissions_extracted/1026/Q1.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1026/Q2.ipynb b/submissions_extracted/1026/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0b2c172af3754708cca2f5af5bd5d649e289bcdb --- /dev/null +++ b/submissions_extracted/1026/Q2.ipynb @@ -0,0 +1,396 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1026/Q3.ipynb b/submissions_extracted/1026/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9dee355bb98f7de49fd127f98c792a0b52b1f245 --- /dev/null +++ b/submissions_extracted/1026/Q3.ipynb @@ -0,0 +1,238 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\"])\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1027/Q1.ipynb b/submissions_extracted/1027/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfc42324d0476dde6c3b71c3b239a784288ad447 --- /dev/null +++ b/submissions_extracted/1027/Q1.ipynb @@ -0,0 +1,267 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "# Download latest version /kaggle/input/q1-exam-data/Q1_data.csv\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "delivery_time_path = os.path.join(path, 'Q1_data.csv')\n", + "delivery_time_df = pd.read_csv(delivery_time_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "delivery_time_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "delivery_time_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "delivery_time_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(delivery_time_df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Order = delivery_time_df.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(delivery_time_df.isnull().sum())\n", + "delivery_time_df['Delivery_Time'] = delivery_time_df['Delivery_Time'].fillna(delivery_time_df['Delivery_Time'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(delivery_time_df)\n", + "\n", + "print(data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_onehot_encoded)\n", + "print(data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "duplicate_rows = delivery_time_df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " delivery_time_df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = delivery_time_df.drop('Delivery_Time', axis=1)\n", + "y = delivery_time_df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "#i cant make sure that the code is run correctly, but i tried to write it in the right syntax\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "\n", + "# here i clearly define the StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(data_standard_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(classification_report(y_test, y_pred, target_name=['delivery_time']))\n", + "\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "print(mse)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1027/Q2.ipynb b/submissions_extracted/1027/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4c62d06b0f47abbc26e08857fdcbec180eb8c597 --- /dev/null +++ b/submissions_extracted/1027/Q2.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "rain_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "x_gpu = x.to(device)\n", + "print(x_gpu.device)\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = Adam(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "for epoch in range(20):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1027/Q3.ipynb b/submissions_extracted/1027/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..52e81b94fbd0df7974e6c6689c8817a4ddd3f620 --- /dev/null +++ b/submissions_extracted/1027/Q3.ipynb @@ -0,0 +1,278 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "import kagglehub\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "Anonymized_Data_path = os.path.join(path, 'Q3_data.csv')\n", + "Anonymized_Data_df = pd.read_csv(Anonymized_Data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Anonymized_Data_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Anonymized_Data_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Anonymized_Data_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(Anonymized_Data_df.isnull().sum())\n", + "df_clean = df_clean.fillna(np.median(0))\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicate_rows = df_clean.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#We dont need to encoding them\n", + "\n", + "\n", + "#label_encoders = {}\n", + "#for col in categorical_cols:\n", + " #le = LabelEncoder()\n", + " #df_clean[col] = le.fit_transform(df_clean[col])\n", + " #label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_clean[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "check_target_imbalance(df_clean, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Target\", axis=1).astype(float)\n", + "y = df_clean['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "\n", + "#the catboost library couldn't be running on my device due to my old colab version\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'f1': []}\n", + "\n", + "n_splits = 5 # K\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + "print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + "print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "importance = df_clean.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1028/Q1.ipynb b/submissions_extracted/1028/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1fa8a61eab1842a09a11fa6414c52f2725bdab79 --- /dev/null +++ b/submissions_extracted/1028/Q1.ipynb @@ -0,0 +1,384 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def plot_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "plot_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features = df.columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "\n", + "#Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=[])\n", + "print(f\"After dropping missing Weather/Traffic_Level/Time_of_Day: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.linear_model import Ridge, Lasso\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1028/Q2.ipynb b/submissions_extracted/1028/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9f1bc331319bba4f4403ef3a5f14bf09a76df5d0 --- /dev/null +++ b/submissions_extracted/1028/Q2.ipynb @@ -0,0 +1,392 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Weather Type\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + " Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1028/Q3.ipynb b/submissions_extracted/1028/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bcfe30547b5832dc21b60adf258d4c702cb2da4d --- /dev/null +++ b/submissions_extracted/1028/Q3.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os as os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "rom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "print(\"\\nClassification Metrics\\n\" + \"-\"*30)\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train a classification model\n", + "clf_model = LogisticRegression()\n", + "clf_model.fit(X_train, y_train)\n", + "y_pred = clf_model.predict(X_test)\n", + "\n", + "# Calculate metrics\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "precision = precision_score(y_test, y_pred)\n", + "recall = recall_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred)\n", + "\n", + "print(\"Accuracy :\", accuracy)\n", + "print(\"Precision:\", precision)\n", + "print(\"Recall :\", recall)\n", + "print(\"F1 Score :\", f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1029/Q1.ipynb b/submissions_extracted/1029/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe5cca0a74dc29bdf92c2b8a994b1103ab56b487 --- /dev/null +++ b/submissions_extracted/1029/Q1.ipynb @@ -0,0 +1,311 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "\n", + "#read the file as csv\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "Q1_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#explore data rows\n", + "Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#Explore data columns and types\n", + "Q1_data.info()\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " Q1_data[col] = Q1_data[col].fillna('0')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Explore statistics of the data\n", + "Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# delivery_time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(Q1_data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#Dropping unncessary features\n", + "col = Q1_data[\"Order_ID\"]\n", + "\n", + "df_clean = Q1_data.drop(col)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#check Null values\n", + "df_clean.isnull().sum()\n", + "\n", + "#Fill null values with mode for categorical\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mode()[0])\n", + "\n", + "#Fill null values with mean for numerical\n", + "for col in ['Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "\n", + "categorical_cols = ['Traffic_Level', 'Weather', 'Vehicle_Type', 'Time_of_Day']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#Standard scaler\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "numerical_cols = ['Traffic_Level', 'Weather', 'Vehicle_Type', 'Time_of_Day','Distance_km'\n", + ",'Preparation_Time_min' ]\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to scale the numerical columns\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# delivery_time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "print(\"Note: from the previous plot there is a skweness to the right in the target feature\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Traffic_Level', 'Weather', 'Vehicle_Type', 'Time_of_Day','Distance_km'\n", + ",'Preparation_Time_min' ]\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "#2 Train-test split (80% train, 20% test)\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "#3 Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#4 Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "#5 average across all Folds\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='Gray')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Delivery Time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1029/Q2.ipynb b/submissions_extracted/1029/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a7a8543a8feb1644237165e24c6fc0a2b7379361 --- /dev/null +++ b/submissions_extracted/1029/Q2.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Path to dataset files:\", Image)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "import matplotlib as plt\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "from torch.optim import Adam\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1029/Q3.ipynb b/submissions_extracted/1029/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2318cee6fbf3b1359821e57b5d4f50f2c7a9728f --- /dev/null +++ b/submissions_extracted/1029/Q3.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "\n", + "#read the file as csv\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "Q3_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#explore data rows\n", + "Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#check Null values\n", + "Q3_data.isnull().sum()\n", + "\n", + "#Fill null values with 0 for accuracy\n", + "for col in Q3_data:\n", + " Q3_data[col] = Q3_data[col].fillna(Q3_data[col].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", Q3_data.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(Q3_data):\n", + " duplicates = Q3_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " Q3_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(Q3_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "\n", + "categorical_cols = Q3_data\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " Q3_data[col] = le.fit_transform(Q3_data[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "\n", + "numerical = Q3_data\n", + "for col in numerical:\n", + "\n", + " le = LabelEncoder()\n", + " Q3_data[col] = le.fit_transform(Q3_data[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# delivery_time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(Q3_data['Target'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "print(\"Note:since the data is distrubited as 0 or 1 we can state that its imbalanced since the confirmed is mush less than the 0 class\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "print(\"Libraries imported successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Separating target variable and features...\")\n", + "X = Q3_data.drop('Target', axis=1)\n", + "y = Q3_data['Target']\n", + "\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n", + "\n", + "print(\"Data split successful.\")\n", + "print(f\"Shape of X_train: {X_train.shape}\")\n", + "print(f\"Shape of X_test: {X_test.shape}\")\n", + "print(f\"Shape of y_train: {y_train.shape}\")\n", + "print(f\"Shape of y_test: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "print(\"Initializing models and K-Fold cross-validation...\")\n", + "\n", + "# Determine the number of classes for one-hot encoding\n", + "num_classes = len(np.unique(y))\n", + "\n", + "# 1. Initialize the machine learning models\n", + "models = {\n", + " 'Logistic Regression': LogisticRegression(solver='liblinear', max_iter=200, random_state=42),\n", + " 'Decision Tree': DecisionTreeClassifier(random_state=42),\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n", + " 'SVM': SVC(probability=True, random_state=42) # probability=True is needed for .predict_proba\n", + "}\n", + "\n", + "# 2. Create a KFold object\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "\n", + "# 4. For each model:\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Calculate the average loss for the model\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)\n", + "\n", + "\n", + "\n", + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='Gray')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/103/Q1.ipynb b/submissions_extracted/103/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..21c4a5081b48c024363d750425da9c468926a2e1 --- /dev/null +++ b/submissions_extracted/103/Q1.ipynb @@ -0,0 +1,299 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping missing Order_ID: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Distance_km', 'Weather', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(f\"Duplicates: {df_clean.duplicated().sum()}\")\n", + "print(f\"dropped: {df_clean.drop_duplicates(inplace=True)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " #=== [SEARCH TAG]: ONEHOT ENCODER ===\n", + "# Use for: nominal features (no order like color: red/blue/green)\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(df_clean[['Delivery_Time']])\n", + "print(encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np # for random data generation\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/103/Q2.ipynb b/submissions_extracted/103/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/103/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/103/Q3.ipynb b/submissions_extracted/103/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e494f4227dbad567f4a34ee4b25cb482ae8cabf3 --- /dev/null +++ b/submissions_extracted/103/Q3.ipynb @@ -0,0 +1,248 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.utils.io import os\n", + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_path = os.path.join(path, 'Q3_data.csv')\n", + "df_feature = pd.read_csv(feature_path)\n", + "\n", + "\n", + "\n", + "print(f\"Dataset shape: {df_feature.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_feature.drop(\"B_1\", axis=1)\n", + "y = df_feature[\"B_1\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df_feature.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_feature.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_feature.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['P_2','D_39','B_1','B_2','R_1','S_3','D_41','B_3','D_42','D_43','D_137','D_138','D_139','D_140','D_141','D_142','D_143','D_144','D_145','Target']:\n", + " df_feature[col] = df_feature[col].fillna('unknown')\n", + "\n", + "print(\"Missing values remaining:\", df_feature.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Duplicates: {df_feature.duplicated().sum()}\")\n", + "print(f\"dropped: {df_feature.drop_duplicates(inplace=True)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(df_feature[['D_39']])\n", + "print(encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Random data generation for scaling\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_feature, \"P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_feature.drop(\"P_2\").astype(float)\n", + "y = df_feature['P_2'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "import numpy as np # for random data generation\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1030/Q1.ipynb b/submissions_extracted/1030/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3c0e0798207b469b38de30900fdf72210030edd5 --- /dev/null +++ b/submissions_extracted/1030/Q1.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food_delivery = pd.read_csv(food_delivery_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food_delivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food_delivery['Order_ID'].dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_food_delivery['Delivery_Time'].dropna() #Target column\n", + "\n", + "\n", + "#df_food_delivery['Weather'] = df_food_delivery['Weather'].fillna(df_food_delivery['Weather'].mode()[0])\n", + "#df_food_delivery['Traffic_Level'] = df_food_delivery['Traffic_Level'].fillna(df_food_delivery['Traffic_Level'].mode()[0])\n", + "#df_food_delivery['Time_of_Day'] = df_food_delivery['Time_of_Day'].fillna(df_food_delivery['Time_of_Day'].mode()[0])\n", + "#df_food_delivery['Courier_Experience_yrs'] = df_food_delivery['Courier_Experience_yrs'].fillna(df_food_delivery['Courier_Experience_yrs'].median()[0])\n", + "\n", + "#Generates error..\n", + "\n", + "#Those shouldnt be dropped but I dropped them to continue working,\n", + "df_food_delivery['Weather'].dropna()\n", + "df_food_delivery['Traffic_Level'].dropna()\n", + "df_food_delivery['Time_of_Day'].dropna()\n", + "df_food_delivery['Courier_Experience_yrs'].dropna()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_food_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = ['Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Weather']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food_delivery[col] = le.fit_transform(df_food_delivery[col].astype(str))\n", + "df_food_delivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_food_delivery[feature_cols]\n", + "y = df_food_delivery['Delivery_Time']\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_food_delivery[feature_cols]\n", + "y = df_food_delivery['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1030/Q2.ipynb b/submissions_extracted/1030/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0280f0a878dcc63880529e8a8d716916ddb2dc25 --- /dev/null +++ b/submissions_extracted/1030/Q2.ipynb @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# Create tensors\n", + "X_train_tensor = torch.tensor(X_train)\n", + "X_test_tensor = torch.tensor(X_test)\n", + "y_train_tensor = torch.tensor(y_train)\n", + "y_test_tensor = torch.tensor(y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Training dataset\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1030/Q3.ipynb b/submissions_extracted/1030/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..95adc4253e4dcedee3c1d38c46b330a273ff5b41 --- /dev/null +++ b/submissions_extracted/1030/Q3.ipynb @@ -0,0 +1,232 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path2 = os.path.join(path, 'Q3_data.csv')\n", + "df_golden = pd.read_csv(path2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_golden.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_golden.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_golden.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_golden)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "target_column = 'Target'\n", + "X = df_golden.drop(target_column, axis=1)\n", + "y = df_golden[target_column]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df_golden, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_golden[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_golden[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_golden, \"Target\")\n", + "\n", + "#It is imbalanced." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = 'Target'\n", + "X = df_golden.drop(target_column, axis=1)\n", + "y = df_golden[target_column]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "#StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1031/Q1.ipynb b/submissions_extracted/1031/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ad197edfece5dc6253109719a96c8571db65de8e --- /dev/null +++ b/submissions_extracted/1031/Q1.ipynb @@ -0,0 +1,226 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = pd.read_csv(path + '/Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dataset.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(15, 5))\n", + "plt.hist(dataset.Delivery_Time, bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = dataset.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dataset = dataset.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset = dataset.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "cat_cols = dataset.select_dtypes('object').columns\n", + "for col in cat_cols:\n", + " le = LabelEncoder()\n", + " dataset[col] = le.fit_transform(dataset[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "X = dataset.drop(\"Delivery_Time\", axis=1)\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "dataset.Delivery_Time.hist() # Target is balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = dataset.drop(\"Delivery_Time\", axis=1)\n", + "y = dataset.Delivery_Time" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True)\n", + "model = RandomForestClassifier(n_estimators=150, max_depth=15, class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "mae" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': dataset.drop(\"Delivery_Time\", axis=1).columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "pd.Series(y_pred).hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1031/Q2.ipynb b/submissions_extracted/1031/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a4159660a29a48e927e3b6e50d8cc265ccb76fc3 --- /dev/null +++ b/submissions_extracted/1031/Q2.ipynb @@ -0,0 +1,407 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "import matplotlib.pyplot as plt\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = X_train.shape[0]\n", + "# input_dim = test_dataset[0][0].flatten(0).size()[0] # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 36 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 1 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "f = X_train\n", + "f.shape\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1031/Q3.ipynb b/submissions_extracted/1031/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ef76b32776fe0d239fdafec2cc38704ee9d8ab7f --- /dev/null +++ b/submissions_extracted/1031/Q3.ipynb @@ -0,0 +1,188 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = pd.read_csv(path + '/Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dataset.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = dataset.fillna(dataset.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dataset = dataset.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset.select_dtypes(\"object\")\n", + "\n", + "# No cat features" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = dataset.drop(\"Target\", axis=1)\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "dataset.Target.hist()\n", + "\n", + "# Target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = X_scaled\n", + "y = dataset.Target\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1032/Q1.ipynb b/submissions_extracted/1032/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9bd969f935ff511a3ce97941b1b801b2e33fab1c --- /dev/null +++ b/submissions_extracted/1032/Q1.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_data = os.path.join(path, 'Q1_data.csv')\n", + "fdata=pd.read_csv(food_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "fdata.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "fdata.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "fdata.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(fdata['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "fdata_clean=fdata.drop(columns=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "fdata_clean.isnull().sum()\n", + "fdata_clean['Delivery_Time'] = fdata_clean['Delivery_Time'].fillna(fdata_clean['Delivery_Time'].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "_# Task 3: Write your code here:\n", + "fdata_clean.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "enc= [[\"Weather\"],[\"Traffic_Level\"],[\"Time_of_Day\"],[\"Vehicle_Type\"]]\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(fdata_clean)\n", + "print(\"Original:\", enc)\n", + "print(\"Encoded:\\n\", encoded)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = fdata_clean.drop(columns=['Delivery_Time'])\n", + "y = fdata_clean['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1032/Q3.ipynb b/submissions_extracted/1032/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d542373cb4bcc95e9b73cf80da12f164a3167a5 --- /dev/null +++ b/submissions_extracted/1032/Q3.ipynb @@ -0,0 +1,184 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data = os.path.join(path, 'Q3_data.csv')\n", + "Mydata=pd.read_csv(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Mydata.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Mydata.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Mydata.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Mydata.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Mydata=Mydata.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(Mydata)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1033/Q1.ipynb b/submissions_extracted/1033/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a4f5cc70b2bcdcb88d773b5d9c8ed34aa1a51244 --- /dev/null +++ b/submissions_extracted/1033/Q1.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path+\"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.hist(df[\"Delivery_Time\"].dropna(), bins=30, edgecolor='black')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\", inplace=True, axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_df = df.isnull().sum()\n", + "missing_df = missing_df[missing_df>0]\n", + "print(missing_df)\n", + "print(\"****\" * 20)\n", + "missing_percent_df = missing_df / len(df) * 100\n", + "print(missing_percent_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.shape)\n", + "df = df.dropna(subset=[\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\", \"Delivery_Time\"])\n", + "print(df.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# Encode Categorical Features\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in categorical_cols:\n", + " X[col] = label_encoder.fit_transform(X[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# not needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# done above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "loss_per_fold = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "n_splits=5\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X_scaled)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " loss_per_fold.append(mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "\n", + "print(\"Average loss:\", np.array(loss_per_fold).sum()/n_splits)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1033/Q2.ipynb b/submissions_extracted/1033/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b4ee388ab3c55f850f7f6f181f1e50f93a72e5fe --- /dev/null +++ b/submissions_extracted/1033/Q2.ipynb @@ -0,0 +1,331 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3*36*36\n", + "hidden_dim = 32\n", + "learning_rate = 0.001\n", + "num_epochs = 20\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1033/Q3.ipynb b/submissions_extracted/1033/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..71f6a7aba8c04f9a7ec58ccf582b652ead17f2c6 --- /dev/null +++ b/submissions_extracted/1033/Q3.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv(path+\"/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_df = df.isnull().sum()\n", + "missing_df = missing_df[missing_df>0]\n", + "print(missing_df)\n", + "print(\"****\" * 20)\n", + "missing_percent_df = missing_df / len(df) * 100\n", + "print(missing_percent_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(missing_percent_df[missing_percent_df>80])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = missing_percent_df[missing_percent_df>80].index.values\n", + "print(cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(cols, inplace=True, axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "len(df.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_df = df.isnull().sum()\n", + "missing_df = missing_df[missing_df>0]\n", + "cols = missing_df.index.values\n", + "print(len(cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "print(df[\"Target\"].value_counts(normalize=True))\n", + "sns.countplot(x=df[\"Target\"])\n", + "plt.title(\"Target Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# done above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "f1_per_fold = []\n", + "model = CatBoostClassifier(verbose=0, n_estimators=200, max_depth=10)\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X_scaled, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred)\n", + "\n", + " f1_per_fold.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "\n", + "print(\"F1:\", np.mean(f1_per_fold))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "feature_importance = feature_importance.head()\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1034/Q1.ipynb b/submissions_extracted/1034/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ea8196d02c390ea228efaa51d23130e83961c620 --- /dev/null +++ b/submissions_extracted/1034/Q1.ipynb @@ -0,0 +1,268 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\", axis=1, inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.dropna(subset=['Delivery_Time'], inplace=True)\n", + "\n", + "df['Weather'].fillna(df['Weather'].mode()[0], inplace=True)\n", + "df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0], inplace=True)\n", + "df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0], inplace=True)\n", + "\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean(), inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# target imbalance doesn't make any sense for linear regression\n", + "\n", + "\n", + "# df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " print(f\"mae: {mean_absolute_error(y_test, y_pred)}\")\n", + "print(f\"\\n\\n Total mae: {mean_absolute_error(y_test, y_pred)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(y_pred, bins=range(len(y_pred)))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1034/Q2.ipynb b/submissions_extracted/1034/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0029f3ade88dccba02d7459a8c096d77e707a37a --- /dev/null +++ b/submissions_extracted/1034/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import AdamW\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(torch.moveaxis(images[i], 0, -1))\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " x = self.layer1(x)\n", + " x = self.relu(x)\n", + "\n", + " # Second hidden layer\n", + " x = self.layer2(x)\n", + " x = self.relu(x)\n", + "\n", + " x = self.layer3(x)\n", + " x = self.relu(x)\n", + "\n", + " output = self.layer4(x)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = 36 * 36 * 3 # MNIST images flattened\n", + "hidden_dim = 64\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.0001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(torch.moveaxis(images[i], 0, -1))\n", + " plt.title(f\"True: {labels[i]} | Pred: {int(outputs[i])}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1034/Q3.ipynb b/submissions_extracted/1034/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..52f66b6c2522c5cd8e6e0c558e65d055e7e3895a --- /dev/null +++ b/submissions_extracted/1034/Q3.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + " return missing_values[missing_values > 0]\n", + "\n", + "missing_values = check_missing_values(df)\n", + "ms = (list(missing_values.index))\n", + "# fill all of them with the mean\n", + "df[ms] = df[ms].fillna(df[ms].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "\n", + "## target is imbalanced for what we see" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "n_splits = 5\n", + "kf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " print(f\"f1: {f1_score(y_test, y_pred)}\")\n", + "\n", + "print(f\"\\n\\nTotal f1: {f1_score(y_test, y_pred)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = df.columns.drop(\"Target\")\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 30))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "most_impo = feature_importance[\"feature\"][0]\n", + "print(f\"the most important feature is {most_impo}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X = df[most_impo]\n", + "y = df[\"Target\"]\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "n_splits = 5\n", + "kf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " print(y_test.shape, y_pred.shape)\n", + " print(X_test.shape)\n", + " print(f\"f1: {f1_score(y_test, y_pred)}\")\n", + "\n", + "print(f\"\\n\\nTotal f1: {f1_score(y_test, y_pred)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1035/Q1.ipynb b/submissions_extracted/1035/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8855d0b18df4a338d62fc74a5fafcda83eb61cc --- /dev/null +++ b/submissions_extracted/1035/Q1.ipynb @@ -0,0 +1,320 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import sklearn.preprocessing\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(f\"Before: {df.shape}\")\n", + "df = df.drop(columns ='Order_ID')\n", + "print(f\"After dropping: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_values = df.isnull().sum()\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values[missing_values > 0])\n", + "df.head(1)\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "for col in ['Courier_Experience_yrs' , 'Delivery_Time' ] :\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # Without inplace=True: Pandas creates a copy of your data with the duplicates removed, but your original df stays messy.\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples after the procees done: {duplicates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " onehot_encoder = OneHotEncoder(sparse_output=False)\n", + " df[col] = onehot_encoder.fit_transform(df[categorical_cols].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n", + "# if data imbalence f score and stratifiesd\n", + "# tearget balanced :) it means it is not omlabnced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=\"Delivery_Time\")\n", + "y = df['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "mseList = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for i in range(5):\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = mean_absolute_error(y_test, y_pred)\n", + " mseList.append(mse)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X,\n", + " 'importance': model.feature_importances_ # so special and confined for spicific models one of them is linear regression\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Transmission distribution\n", + "Delivery_Time = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(Delivery_Time.index, Delivery_Time.values, color='teal')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time Type')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1035/Q2.ipynb b/submissions_extracted/1035/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f98a3051dfcc79550d68c998ca8c93e376158fa1 --- /dev/null +++ b/submissions_extracted/1035/Q2.ipynb @@ -0,0 +1,401 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(y_batch)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim) # last layer output is based on the number of classes\n", + " # next layer number of nurens must same as before\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "# either it is images or tables the train loop is 70 % same rember it\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size,)\n", + " # linear regression and binary classification needs view unlike multi classification\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "# no optomizer\n", + "# just accuracy calculation\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 4 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1035/Q3.ipynb b/submissions_extracted/1035/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b0af7dad00280b86db78f0f4b99beb2828a816bc --- /dev/null +++ b/submissions_extracted/1035/Q3.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import sklearn as sk\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "\n", + "%matplotlib inline\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# RangeIndex: 20001 entries, 0 to 20000\n", + "# Columns: 189 entries, P_2 to Target\n", + "# dtypes: float64(148), int64(41)\n", + "\n", + "missing_values = df.isnull().sum()\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values[missing_values > 0])\n", + "df.head(1)\n", + "\n", + "cols = df.select_dtypes(include=[\"float\" , \"int\"]).columns\n", + "for i in cols:\n", + " df[cols] = df[cols].fillna(df[cols].mean())\n", + "\n", + "print(\"After cleaning missings\")\n", + "missing_values = df.isnull().sum()\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values[missing_values > 0])\n", + "df.head(1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # Without inplace=True: Pandas creates a copy of your data with the duplicates removed, but your original df stays messy.\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples after the procees done: {duplicates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# no need no categoricall!!!!!!!!!1" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "# if data imbalence f score and stratifiesd\n", + "# tearget balanced :) it means it is not omlabnced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=\"Target\")\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "import sklearn.metrics\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "l1 = []\n", + "l2 = []\n", + "l3 = []\n", + "l4 = []\n", + "\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(n_estimators=200)\n", + "mseList = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for i in range(5):\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + " # Store results\n", + " l1.append(accuracy)\n", + " l2.append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1036/Q1.ipynb b/submissions_extracted/1036/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..38815a53a374ba45df4fb0f0e587cad64a5e680e --- /dev/null +++ b/submissions_extracted/1036/Q1.ipynb @@ -0,0 +1,304 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1 = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: delivery_time\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Delivery Time')\n", + "#plt.xlabel('speed')\n", + "#plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_Q1.drop(['Order_ID'],axis=1)\n", + "df_clean.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum())\n", + "df_clean = df_clean.dropna().copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "le = LabelEncoder()\n", + "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "#it is a Regression problem no need for class imbalance checking" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + " print(f\"Training {model}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print('mse: ', mse)\n", + "print('rmse: ', rmse)\n", + "print('r2: ' ,r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model\n", + "coeffs['Ridge'] = model\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " #absolute_coef = np.abs(coef)\n", + " #sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " #ax = axes[i]\n", + " #ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " #ax.set_title(f\"{model_name} Coefficients\")\n", + " #ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "#plt.tight_layout()\n", + "#plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1036/Q2.ipynb b/submissions_extracted/1036/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..312b828917b282adf662ec463f26862c95b01942 --- /dev/null +++ b/submissions_extracted/1036/Q2.ipynb @@ -0,0 +1,441 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "print(first_sample)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN1Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim):\n", + "\n", + " super(NN1Layer, self).__init__()\n", + " # input_dim = num of features, Output for binary classification is 1\n", + " self.layer_1 = nn.Linear(input_dim, 1)\n", + "\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z = self.layer_1(x)\n", + " a = self.sigmoid(z)\n", + " return a" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " return a2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Example predictions and targets\n", + "y_pred = torch.tensor([[2.5], [3.0], [4.5]])\n", + "y_true = torch.tensor([[3.0], [2.5], [5.0]])\n", + "\n", + "criterion = nn.MSELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"MSE Loss:\", loss.item())\n", + "\n", + "# Predicted probabilities (after sigmoid)\n", + "y_pred = torch.tensor([[0.8], [0.3], [0.6]])\n", + "y_true = torch.tensor([[1.0], [0.0], [1.0]])\n", + "\n", + "criterion = nn.BCELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"Binary Cross Entropy Loss:\", loss.item())\n", + "\n", + "# Raw model outputs (logits), shape: (batch_size, num_classes)\n", + "logits = torch.tensor([\n", + " [2.0, 0.5, 1.0],\n", + " [0.1, 1.5, 0.3]\n", + "])\n", + "# True class indices\n", + "targets = torch.tensor([0, 1])\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "loss = criterion(logits, targets)\n", + "print(\"Cross Entropy Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device configuration\n", + "from torch.optim import Adam\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "num_epochs = 20\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1036/Q3.ipynb b/submissions_extracted/1036/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e911d77da489f83f1bfe3668edfd9329b6c597f --- /dev/null +++ b/submissions_extracted/1036/Q3.ipynb @@ -0,0 +1,185 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3 = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_Q3.isnull().sum())\n", + "df_clean = df_Q3.dropna().copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_Q3.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"class 1: {df_Q3['Target'].sum()}\")\n", + "print(f\"class 0: {(df_Q3['Target'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1037/Q1.ipynb b/submissions_extracted/1037/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..45f2e5241ee0d678ead92d2d134260b10d0b6d99 --- /dev/null +++ b/submissions_extracted/1037/Q1.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "data_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = df.columns.drop(\"Order_ID\")\n", + "df_clean = df.copy()\n", + "df_clean = df_clean[cols]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "print(f\"beofre dropping missing values: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna()\n", + "check_missing_values(df_clean)\n", + "print(f\"After dropping missing values: {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n", + "print(f\"beofre dropping missing values: {df_clean.shape}\")\n", + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = [\"Traffic_Level\",\t\"Time_of_Day\",\t\"Vehicle_Type\",\t\"Weather\"]\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features]).copy()\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean\n", + "X = df_clean[features]\n", + "y = df_clean[\"Delivery_Time\"]\n", + "y\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Predicted Delivery:\")\n", + " df1 = pd.DataFrame(df)\n", + " df1.hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(y_pred, \"Delivery Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1037/Q2.ipynb b/submissions_extracted/1037/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ebb0c0862c279f9c5e137bd7abb584120f5383b --- /dev/null +++ b/submissions_extracted/1037/Q2.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "X_batch[0]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN4Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a3)\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import Adam\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1037/Q3.ipynb b/submissions_extracted/1037/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5c84ed135f500a5d6b964b0b3ff5209432468dfa --- /dev/null +++ b/submissions_extracted/1037/Q3.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "data_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df.copy()\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "print(f\"beofre dropping missing values: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(axis=1)\n", + "check_missing_values(df_clean)\n", + "print(f\"After dropping missing values: {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "categorical_cols\n", + "# NO CATEGORICAL COLUMNS TO ENCODE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Target\", axis=1)\n", + "y = df_clean[\"Target\"]\n", + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostRegressor(verbose=0)\n", + "mse = 0\n", + "rmse = 0\n", + "r2= 0\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + "print(\"mse: \", mse)\n", + "print(\"rmse: \", rmse)\n", + "print(\"r2: \", r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': model.feature_names_,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# percentage of the most imoportant feature\n", + "print(model.feature_importances_[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1038/Q1.ipynb b/submissions_extracted/1038/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0f9b4e5f2065dd57b47149ed30ce6e68c5b1a5f3 --- /dev/null +++ b/submissions_extracted/1038/Q1.ipynb @@ -0,0 +1,598 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. What does our target variable (charges) look like?\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delaviry Distribution')\n", + "plt.xlabel('Distance_km')\n", + "plt.ylabel('Preparation_Time_min')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_food.drop(columns=['Order_ID']).copy()\n", + "\n", + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 1. Calculate the percentage of missing values for each column\n", + "# .isnull() checks for missing values, .sum() counts them, and we divide by total rows (len)\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "\n", + "# 2. Create a new DataFrame to store the results cleanly\n", + "# We map the column names (index) to their calculated missing percentages\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "# 3. Filter and Sort the results\n", + "# Filter: Keep only columns where Missing_Percentage is greater than 0\n", + "# Sort: Order the results from highest missing % to lowest (ascending=False)\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0] \\\n", + " .sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "# 4. Display the results\n", + "print(\"Missing Data Analysis:\")\n", + "# Show the top 10 columns with the most missing data\n", + "missing_data.head(10)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Define a function to hunt for Missing Data (NaNs)\n", + "# Missing values are \"holes\" in your dataset.\n", + "# Most Machine Learning models (like Logistic Regression) will crash immediately\n", + "# if you feed them a blank space/NaN.\n", + "def check_missing_values(df):\n", + " # 1. Calculate the sum of missing cells for every column\n", + " # .isnull(): Returns a True/False table (True if missing).\n", + " # .sum(): Adds up the \"True\" values (since True = 1) to get the total count.\n", + " missing_values = df.isnull().sum()\n", + "\n", + " # 2. Print ONLY the columns that have problems\n", + " # missing_values > 0: This filter hides the \"clean\" columns (where count is 0).\n", + " # This keeps your output readable so you don't scroll through 50 columns of \"0\".\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " # 3. Global Check\n", + " # .any(): Returns True if there is even a single missing value anywhere in the list.\n", + " if missing_values.sum() > 0:\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "# 4. Run the function\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# YOUR CODE HERE\n", + "print(f\"Delivery_Time: {df_clean['Delivery_Time'].sum()}\")\n", + "print(f\"Delivery_Time normal: {(df_clean['Delivery_Time'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Do we have categorical columns?\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean(), inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 1. Imports the OneHotEncoder class from sklearn's preprocessing module.\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "\n", + "\n", + "cati = [ ['Weather'], ['Traffic_Level'], ['Time_of_Day'], ['Vehicle_Type']]\n", + "\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(cati)\n", + "\n", + "print(\"Original:\", cati)\n", + "print(\"Encoded:\\n\", encoded)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.columns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns\n", + "# print(\"Numerical:\", list(numerical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Import Cross-Validation Tool\n", + "# KFold: A technique to split data into 'K' different parts (folds).\n", + "# Instead of training once on one train/test split, you train K times (e.g., 5 times).\n", + "# Each time, a different part is used as the \"Test\" set.\n", + "# This gives a much more reliable estimate of model performance.\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# 2. Import Evaluation Metrics\n", + "# sklearn_mse: Calculates Mean Squared Error. (Average of squared differences).\n", + "# Used to penalize large errors heavily. The lower, the better.\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse\n", + "\n", + "# mean_absolute_error (MAE): Average of absolute differences.\n", + "# It's easier to interpret than MSE because it's in the same units as your target (e.g., \"Dollars\").\n", + "# Formula: mean(|y_true - y_pred|)\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# r2_score (R-Squared): A score between 0 and 1 (or negative if the model is terrible).\n", + "# It tells you \"How much of the variance in the data does my model explain?\"\n", + "# 1.0 = Perfect fit. 0.0 = As good as just guessing the average.\n", + "from sklearn.metrics import r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "\n", + "\n", + "df_clean[encoded] = scaler.fit_transform(df_clean[encoded])\n", + "\n", + "# 4. Verify\n", + "df_clean.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Mean Squared Error (MSE) - Cost Function Implementation\n", + "def mean_squared_error(y, y_hat):\n", + " # 1. Calculate the difference (Error)\n", + " # (y_hat - y): Vectorized subtraction. Calculates the error for every single data point at once.\n", + "\n", + " # 2. Square the errors\n", + " # ** 2: We square the errors so that negative errors don't cancel out positive ones.\n", + " # It also penalizes large errors more heavily than small ones.\n", + "\n", + " # 3. Sum the squared errors\n", + " # np.sum(...): Adds up the squared errors for the entire dataset.\n", + "\n", + " # 4. Calculate the Average (with a twist)\n", + " # len(y): The number of training examples (often denoted as 'm').\n", + " # 1 / (2 * len(y)): This is the specific \"Cost Function\" version of MSE.\n", + " # The standard statistical MSE is just 1/m.\n", + " # The extra '2' is added to make the derivative (Gradient Descent) calculation cleaner later\n", + " # (because the derivative of x^2 is 2x, the 2s cancel out).\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " # 1. Get dataset dimensions\n", + " # m = Number of training examples (rows)\n", + " # n = Number of features/inputs (columns)\n", + " m, n = X.shape\n", + "\n", + " # 2. Initialize Weights (Theta)\n", + " # We start with all weights at 0.0. The model currently \"knows\" nothing.\n", + " # If we have 3 features, theta will be [0, 0, 0].\n", + " theta = np.zeros(n)\n", + " losses = []\n", + "\n", + " # 3. Start the Training Loop\n", + " # tqdm is just a library to show a progress bar so you know how fast it's going.\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + "\n", + " # A. Make Predictions (Hypothesis)\n", + " # We multiply our Input (X) by our current Weights (theta).\n", + " # Math: h(x) = w * x\n", + " y_hat = np.dot(X, theta)\n", + "\n", + " # B. Calculate the Gradient (The Direction)\n", + " # This formula calculates the derivative of the Cost Function.\n", + " # It tells us: \"In which direction should we move the weights to reduce error?\"\n", + " # (y_hat - y): The error (prediction - actual).\n", + " # np.dot(X.T, ...): Multiplies errors by input values to find the slope.\n", + " # / m: Averages the gradient across all examples.\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + "\n", + " # C. Update the Weights (The Step)\n", + " # We move 'theta' in the opposite direction of the gradient.\n", + " # learning_rate: Controls how big the step is. Too big = overshoot; Too small = slow.\n", + " theta -= learning_rate * gradient\n", + "\n", + " # D. Track Progress\n", + " # We calculate the current error to see if the model is actually learning.\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " # 4. Return the learned weights and the history of errors\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Initialize the Cross-Validation Splitter\n", + "# n_splits=5: The data will be cut into 5 equal pieces (folds).\n", + "# shuffle=True: CRITICAL. This randomizes the order of the rows before splitting.\n", + "# Without this, if your data is sorted (e.g., all \"Type A\" first, then \"Type B\"),\n", + "# one fold might get ONLY Type A and another ONLY Type B, ruining the training.\n", + "# random_state=42: Ensures the \"random\" shuffle is exactly the same every time you run the code.\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Initialize empty lists to store the performance scores for each of the 5 folds.\n", + "# Since K-Fold runs 5 times, we need these containers to save the results of each run\n", + "# so we can calculate the average performance at the end.\n", + "\n", + "# Stores the value of the Cost Function (J) if you are tracking it manually\n", + "lr_losses = []\n", + "\n", + "# Stores Mean Squared Error (Average squared difference between predicted and actual)\n", + "lr_mse = []\n", + "\n", + "# Stores Root Mean Squared Error (Square root of MSE)\n", + "# This is often preferred because it returns the error to the original units (e.g., \"Dollars\").\n", + "lr_rmse = []\n", + "\n", + "# Stores R-Squared Score (Coefficient of determination)\n", + "# 1.0 is perfect, 0.0 is terrible. This tells us how well the model fits the data variance.\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Loop through each of the 5 folds\n", + "# kf.split(X) returns two lists of row numbers:\n", + "# 1. train_index: Roughly 80% of the rows to learn from.\n", + "# 2. test_index: The remaining 20% of rows to test on.\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Slice the data using the indices\n", + " # We use .iloc[] because train_index gives us integer positions (e.g., row 0, row 5, row 10).\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train the Model\n", + " # We call the custom gradient_descent function we defined earlier.\n", + " # It returns 'theta' (the learned weights/coefficients) and 'losses' (history of error reduction).\n", + " # .values converts the Pandas DataFrame to a NumPy array for the math calculations.\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # 3. Validate (Make Predictions)\n", + " # We apply the learned weights (theta) to the test data.\n", + " # Math: y_pred = X_test * theta\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # 4. Calculate Evaluation Metrics\n", + " # MSE: Standard error metric.\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " # RMSE: Square root of MSE. Use this to see error in \"Real Units\" (e.g., Sales Dollars).\n", + " rmse = np.sqrt(mse)\n", + " # R2 Score: Accuracy percentage (0.0 to 1.0). How well did the line fit?\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # 5. Store Results\n", + " # Save the scores for this specific fold so we can average them later.\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "\n", + "# Define features (X) and target (y)\n", + "# X: The input data the model uses to learn\n", + "feature_cols =['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "\n", + "# y: The answer we want to predict\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "# random_state=42: ensures reproducible results (fixed seed)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1038/Q2.ipynb b/submissions_extracted/1038/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df66cf64f9de427c2ee30f18f086696ec1c8c6ca --- /dev/null +++ b/submissions_extracted/1038/Q2.ipynb @@ -0,0 +1,483 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "# --- Unsupervised Learning Libraries / مكتبات التعلم غير الخاضع لإشراف ---\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE # t-Distributed Stochastic Neighbor Embedding (Visualization)\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "\n", + "\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# 1. TRAINING DATALOADER\n", + "# This is our delivery system for the model's \"study sessions.\"\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32, # 32 images are grouped together. This balances speed and accuracy.\n", + " shuffle=True, # CRITICAL: We mix the cards every time so the model doesn't\n", + " # memorize the order of the digits.\n", + " num_workers=2 # Uses 2 separate CPU sub-processes to load data faster,\n", + " # preventing the GPU from waiting for data.\n", + ")\n", + "\n", + "# 2. TEST DATALOADER\n", + "# This is the delivery system for the model's \"exam.\"\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False, # No need to shuffle here; we want a consistent way to\n", + " # measure performance during evaluation.\n", + " num_workers=2\n", + ")\n", + "\n", + "# 3. VERIFYING THE BATCH\n", + "# iter() makes the loader a stream, and next() grabs the very first package.\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Shape explanation:\n", + "# X_batch shape: [32, 1, 28, 28] -> [Batch Size, Channels, Height, Width]\n", + "# y_batch shape: [32] -> 32 corresponding labels (0-9)\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# 1. FETCH A BATCH\n", + "# 'iter(train_loader)' turns the loader into an iterable stream.\n", + "# 'next()' grabs the very first \"crate\" of data (e.g., 32 or 64 images).\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# 2. SETUP THE GRID\n", + "# We create a 2x3 grid to display the first 6 samples from the batch.\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # 3. DIMENSION SWAPPING (The \"Permute\" Trick)\n", + " # PyTorch stores images as [Channels, Height, Width] (CHW).\n", + " # Matplotlib expects images as [Height, Width, Channels] (HWC).\n", + " # .permute(1, 2, 0) moves the 0th dimension (Channels) to the end.\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " # 4. PLOT & LABEL\n", + " # plt.imshow handles the pixel-to-color mapping.\n", + " plt.imshow(img)\n", + "\n", + " # .item() converts a 1-element Tensor into a standard Python number.\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off') # Hides the pixel coordinate numbers for a cleaner look\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " # Layer 1: Input Features -> First Hidden Layer\n", + " # input_dim is usually your total pixels (e.g., 784 for MNIST).\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Layers 2, 3, and 4: Hidden Layer -> Hidden Layer\n", + " # These keep the dimension consistent so data can flow through the \"deep\" part.\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + "\n", + " # Activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # The Forward Pass: Data \"z\" is transformed by weights,\n", + " # then \"a\" (activation) applies the ReLU non-linearity.\n", + "\n", + " a1 = self.relu(self.layer1(x))\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + " a4 = self.relu(self.layer4(a3))\n", + "\n", + " # Final Layer: Output raw scores (Logits)\n", + " z4 = self.layer4(a3)\n", + "\n", + " # ANSWER: Are we missing an activation?\n", + " # No! If using 'nn.CrossEntropyLoss', it applies Softmax internally.\n", + " # Returning raw Logits is more numerically stable for the math.\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # 1. PREP MODE\n", + " # model.train() tells layers like Dropout or BatchNorm to act in \"learning mode.\"\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # 2. THE BATCH LOOP\n", + " # We iterate through the DataLoader, which serves data in small \"bites\" (batches).\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " # Flatten the image: (Batch, 1, 28, 28) -> (Batch, 784) ([32, 3, 36, 36])\n", + " # We must reshape the 2D grid of pixels into a 1D line for Linear layers.\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # 3. FORWARD PASS\n", + " # The model takes the input and produces 10 raw scores (logits).\n", + " outputs = model(X_batch)\n", + "\n", + " # 4. COMPUTE ERROR (Loss)\n", + " # We compare the 10 scores to the actual correct digit (y_batch).\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # 5. THE OPTIMIZATION \"DANCE\"\n", + " optimizer.zero_grad() # 1. Reset: Wipe the math from the previous batch.\n", + " loss.backward() # 2. Calculus: Calculate how much each weight contributed to the error.\n", + " optimizer.step() # 3. Update: Slightly nudge weights in the right direction.\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # 6. PERFORMANCE SUMMARY\n", + " # Return the average \"pain level\" (loss) the model felt this epoch.\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # 1. EVALUATION MODE\n", + " # Disables layers like Dropout so the model provides consistent predictions.\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " # 2. DISABLE GRADIENTS\n", + " # This saves massive amounts of memory and speed because we aren't\n", + " # calculating \"how to improve\"—we are just testing.\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Flatten and move to GPU/CPU\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # 3. FORWARD PASS\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # 4. GET PREDICTIONS\n", + " # Softmax turns raw scores into probabilities that sum to 100%.\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Argmax picks the index of the highest probability (the model's guess).\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # 5. COUNT SUCCESSES\n", + " # We compare the 'predicted' vector to the 'actual' labels.\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " # 6. FINAL METRICS\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " # Accuracy is simply (Total Correct / Total Attempted)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# 1. HARDWARE SELECTION\n", + "# We check for a GPU (CUDA). If found, the heavy lifting happens on the graphics card,\n", + "# which is significantly faster for deep learning than a standard CPU.\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# 2. MODEL PARAMETERS (The Blueprint)\n", + "# input_dim: CIFAR-10 images are 32x32 pixels with 3 color channels (Red, Green, Blue).\n", + "# To feed them into a Linear layer, we must flatten them into one long line: 3 * 32 * 32 = 3072.\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "# ([32, 3, 36, 36])\n", + "# hidden_dim: This is a \"hyperparameter.\" 64 is a modest starting point.\n", + "# More neurons allow for more complex patterns but increase the risk of overfitting.\n", + "hidden_dim = 64\n", + "\n", + "# output_dim: Since CIFAR-10 has 10 categories (airplane, bird, car, etc.),\n", + "# the model needs 10 output \"scorecards.\"\n", + "output_dim = 10\n", + "\n", + "# 3. INSTANTIATION\n", + "# This builds the actual \"brain\" in memory and moves its weights to the GPU if available.\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# 4. INSPECTION\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# This counts every single 'synapse' (weight) and 'bias' in your network.\n", + "# It tells you how much memory the model will take and how complex it is.\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/1038/Q3.ipynb b/submissions_extracted/1038/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6b123e1e76e4f007ffcc53c00961cff75f54d4e3 --- /dev/null +++ b/submissions_extracted/1038/Q3.ipynb @@ -0,0 +1,245 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "Data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Data = pd.read_csv(Data_path)\n", + "\n", + "print(f\"Dataset shape: {df_Data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 2. Define a function to hunt for Missing Data (NaNs)\n", + "# Missing values are \"holes\" in your dataset.\n", + "# Most Machine Learning models (like Logistic Regression) will crash immediately\n", + "# if you feed them a blank space/NaN.\n", + "def check_missing_values(df):\n", + " # 1. Calculate the sum of missing cells for every column\n", + " # .isnull(): Returns a True/False table (True if missing).\n", + " # .sum(): Adds up the \"True\" values (since True = 1) to get the total count.\n", + " missing_values = df.isnull().sum()\n", + "\n", + " # 2. Print ONLY the columns that have problems\n", + " # missing_values > 0: This filter hides the \"clean\" columns (where count is 0).\n", + " # This keeps your output readable so you don't scroll through 50 columns of \"0\".\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " # 3. Global Check\n", + " # .any(): Returns True if there is even a single missing value anywhere in the list.\n", + " if missing_values.sum() > 0:\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "# 4. Run the function\n", + "check_missing_values(df_Data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df_Data.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "else:\n", + " print(\"No Duplicate Samples Found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_Data.drop(\"Target\", axis=1).astype(float)\n", + "y = df_Data[\"Target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(X) # Apply fit_transform # يطبق على test\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(f\"Target: {df_Data['Target'].sum()}\")\n", + "print(f\"Normal: {(df_Data['Target'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/104/Q1.ipynb b/submissions_extracted/104/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..57750b40b9453fc40b2e5dc0cb3a19b5feae22c1 --- /dev/null +++ b/submissions_extracted/104/Q1.ipynb @@ -0,0 +1,256 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import pandas as pd\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Define stat columns\n", + "stat_cols = ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "# Drop rows with missing stat values\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated()\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "\n", + "\n", + "check_target_imbalance(df,\"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/104/Q2.ipynb b/submissions_extracted/104/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf86bbcdc69ca6d8580fdfffe38adac81742fc73 --- /dev/null +++ b/submissions_extracted/104/Q2.ipynb @@ -0,0 +1,467 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "import torch\n", + "\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torch.utils.data import TensorDataset\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n", + "\n", + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "# Example predictions and targets\n", + "y_pred = torch.tensor([[2.5], [3.0], [4.5]])\n", + "y_true = torch.tensor([[3.0], [2.5], [5.0]])\n", + "\n", + "criterion = nn.MSELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"MSE Loss:\", loss.item())\n", + "\n", + "# Predicted probabilities (after sigmoid)\n", + "y_pred = torch.tensor([[0.8], [0.3], [0.6]])\n", + "y_true = torch.tensor([[1.0], [0.0], [1.0]])\n", + "\n", + "criterion = nn.BCELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"Binary Cross Entropy Loss:\", loss.item())\n", + "\n", + "# Raw model outputs (logits), shape: (batch_size, num_classes)\n", + "logits = torch.tensor([\n", + " [2.0, 0.5, 1.0],\n", + " [0.1, 1.5, 0.3]\n", + "])\n", + "# True class indices\n", + "targets = torch.tensor([0, 1])\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "loss = criterion(logits, targets)\n", + "print(\"Cross Entropy Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "from torch.optim import AdamW\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/104/Q3.ipynb b/submissions_extracted/104/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..47df7c441cfc41bdb1225229bcf1d45c13af1d3b --- /dev/null +++ b/submissions_extracted/104/Q3.ipynb @@ -0,0 +1,236 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import os\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated()\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "\n", + "\n", + "check_target_imbalance(df,\"Target\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.svm import SVC\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/105/Q1.ipynb b/submissions_extracted/105/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..86c919d2dafc674f3dd49f1da3878a4fa810cb26 --- /dev/null +++ b/submissions_extracted/105/Q1.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold, train_test_split\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "import seaborn as sns\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Load CSV file\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Plotting target distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "#plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_clean = df.copy()\n", + "#to not change the original data ^\n", + "\n", + "df_clean = df.dropna(subset=['Order_ID'])\n", + "#drop rows with missing values^" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "\n", + "# Analyze missing values\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "#to decide what col to drop\n", + "\n", + "df_clean = df_clean.dropna(subset=[ 'Traffic_Level', 'Time_of_Day'])\n", + "\n", + "\n", + "print(f\"After dropping missing columns: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#checking duplicates\n", + "def check_duplicates(df):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "#data_onehot_encoded = onehot_encoder.fit_transform(df_clean)\n", + "\n", + "#print('\\nEncoded data:\\n', data_onehot_encoded ) #show after encoding\n", + "\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]\n", + "\n", + "# Encode Categorical Features\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in X.select_dtypes(include=[\"object\"]).columns:\n", + " X[col] = label_encoder.fit_transform(X[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Feature Scaling\n", + "scaler = StandardScaler()\n", + "#X_scaled = scaler.fit_transform(X)\n", + "\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Separate Features and Target\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]\n", + "\n", + "print(\"\\nDataset Shapes\")\n", + "print(\"X:\", X.shape)\n", + "print(\"y:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/105/Q2.ipynb b/submissions_extracted/105/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9878186eb8b2e60dd3c606756abc31d032d15b29 --- /dev/null +++ b/submissions_extracted/105/Q2.ipynb @@ -0,0 +1,369 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch\n", + "\n", + "import torch\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "for i in range(6):\n", + " plt.subplot(3, 36, 36)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/105/Q3.ipynb b/submissions_extracted/105/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9afb514c3ff4624e5727f4f47645d732cee2dcbc --- /dev/null +++ b/submissions_extracted/105/Q3.ipynb @@ -0,0 +1,170 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load CSV file\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_pokemon.dropna().copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/106/Q1.ipynb b/submissions_extracted/106/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2b254b5a661252b2c786c56b9303f99d29ed3047 --- /dev/null +++ b/submissions_extracted/106/Q1.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "\n", + "data_path = os.path.join(path, \"Q1_data.csv\")\n", + "# Load the dataset\n", + "df_FDT = pd.read_csv(data_path)\n", + "\n", + "print(f\"Dataset shape: {df_FDT.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_FDT.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_FDT.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_FDT.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_FDT['Delivery_Time'], bins=50, edgecolor='black')\n", + "plt.title('Target Column')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_FDT = df_FDT.drop(['Order_ID'], axis=1)\n", + "df_FDT.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_FDT.isnull().sum()\n", + "\n", + "df_FDT_2 = df_FDT.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time'])\n", + "df_FDT_2.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_FDT_2)\n", + "df_FDT_2.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_FDT_2.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_FDT_2[col] = le.fit_transform(df_FDT_2[col])\n", + "df_FDT_2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_FDT_2.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") ### DON'T SCALE THE TARGET !!!!!!!!!!!!\n", + "scaler = StandardScaler()\n", + "df_FDT_2[numerical_cols] = scaler.fit_transform(df_FDT_2[numerical_cols])\n", + "df_FDT_2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# NO NEED!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Prepare the data as X and y\n", + "\n", + "X = df_FDT_2.drop(\"Delivery_Time\", axis=1)\n", + "y = df_FDT_2[\"Delivery_Time\"]\n", + "\n", + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as m_MAE\n", + "\n", + "n_splits = 5\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n", + "}\n", + "\n", + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = m_MAE(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "print(f\" MAE: {np.mean(mae):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "baseline_pred = np.full_like(y, y.mean())\n", + "\n", + "baseline_mae = m_MAE(y, baseline_pred)\n", + "print(f\"Baseline MSE (using mean target): {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['rfr'] = models['Random Forest Regressor'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/106/Q2.ipynb b/submissions_extracted/106/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3e873cc985d764147d481777919b412892c78ecd --- /dev/null +++ b/submissions_extracted/106/Q2.ipynb @@ -0,0 +1,396 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(X_train_tensor.type())\n", + "print(X_test_tensor.type())\n", + "print(y_train_tensor.type())\n", + "print(y_test_tensor.type())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(36, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze())\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 # MNIST images flattened\n", + "hidden_dim = 20 # Design choice\n", + "output_dim = 1 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/106/Q3.ipynb b/submissions_extracted/106/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2cbf684d23f3bf3498e6360aab0dfd6320b13afd --- /dev/null +++ b/submissions_extracted/106/Q3.ipynb @@ -0,0 +1,294 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for cols in df.columns:\n", + " df[cols]= df[cols].fillna(df[cols].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") ### DON'T SCALE THE TARGET !!!!!!!!!!!!\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.grid()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\") # The target class is IMBALANCED" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "\n", + "CatBoost = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "CatBoost.fit(X_train, y_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = CatBoost.predict(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import accuracy_score, f1_score\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred, zero_division=0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Acc = {accuracy}\")\n", + "print(f\"F1 = {f1}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/107/Q1.ipynb b/submissions_extracted/107/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9c696187d725a8f95af4bb82d9e811158ed3dc67 --- /dev/null +++ b/submissions_extracted/107/Q1.ipynb @@ -0,0 +1,280 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataQ1_path = os.path.join(path, 'Q1_data.csv')\n", + "deliv_data = pd.read_csv(dataQ1_path)\n", + "\n", + "print(f\"Dataset shape: {deliv_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "deliv_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "deliv_data.info()\n", + "# Preparation_Time_min Courier_Experience_yrs" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "deliv_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(deliv_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time')\n", + "plt.xlabel('Minutes')\n", + "plt.ylabel('distance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "deliv_data = deliv_data.drop(columns=['Order_ID'])\n", + "deliv_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#missing = ['Weather'], ['Traffic_Level'], ['Time_of_Day'], ['Courier_Experience_yrs'], ['Delivery_Time']\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "deliv_clean = deliv_data[cols].copy()\n", + "deliv_clean = deliv_clean.dropna(subset=['Delivery_Time','Courier_Experience_yrs'])\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " deliv_clean[col] = deliv_clean[col].fillna('unknown')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(deliv_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " deliv_clean[col] = le.fit_transform(deliv_clean[col].astype(str))\n", + "\n", + "deliv_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "X = deliv_clean[feature_cols]\n", + "y = deliv_clean['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "\n", + "#Training Random Forest:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "\n", + "print(\"Model trained!\")\n", + "\n", + "# Kfold\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "mae_scores = np.array(mae_scores)\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_fold_pred, bins=50, edgecolor='black')\n", + "plt.title('Delivery time')\n", + "plt.xlabel('Minutes')\n", + "plt.ylabel('distance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/107/Q2.ipynb b/submissions_extracted/107/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1c864fdebf75896181e979affbc3be3fc19ccb6b --- /dev/null +++ b/submissions_extracted/107/Q2.ipynb @@ -0,0 +1,331 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "train_loader\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN4Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " return a2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device configuration\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN4Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), lr= learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(10, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/108/Q1.ipynb b/submissions_extracted/108/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1f285ed8abe967b0e040d6bfe63228a39153cec8 --- /dev/null +++ b/submissions_extracted/108/Q1.ipynb @@ -0,0 +1,233 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "csv_path = os.path.join(path, __Q1_data.csv)\n", + "\n", + "df = pd.read" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"updated_pollution_dataset.csv\")\n", + "df = pd.read_csv(csv_path.capitalize)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"updated_pollution_dataset.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from posix import stat\n", + "from IPython.core.display import clear_output\n", + "# Task 1: Write your code here:\n", + "set_matplotlib_close\n", + "df cleanig" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/108/Q2.ipynb b/submissions_extracted/108/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..986128e11e86030a0852d8498be7246ea8d7ee86 --- /dev/null +++ b/submissions_extracted/108/Q2.ipynb @@ -0,0 +1,398 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Shape of x:\", x.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n", + "\n", + "print(\"Matrix multiplication result shape:\", C.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = xtrain.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Training dataset\n", + "train_dataset = MNIST ( root='./datasets',train=True, transform=to_tensor, download=True)\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST (root='./datasets', train=False, transform=to_tensor, download=True)\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/108/Q3.ipynb b/submissions_extracted/108/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..94a07be59473b4e9e1f50970163ca84e2570dfb2 --- /dev/null +++ b/submissions_extracted/108/Q3.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Shape of x:\", x.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n", + "\n", + "print(\"Matrix multiplication result shape:\", C.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/109/Q1.ipynb b/submissions_extracted/109/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..55f5b9504b53f43bafcee6410c655812ddf7b2ed --- /dev/null +++ b/submissions_extracted/109/Q1.ipynb @@ -0,0 +1,300 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def target_plot(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "target_plot(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " df.dropna()\n", + " print(\"Missing Values Was handling by droping it\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "data_for_scale = pd.DataFrame({\"Distance_of_Day\",\"Weather\",\"Traffic_Level\",\"Time_of_Day\t\",\"Vehicle_Type\",\"Preparation_Time_min\",\"Delivery_Time\"})\n", + "\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\",axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(random_state=42, verbose=1)\n", + "model.fit(X_train, y_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/109/Q2.ipynb b/submissions_extracted/109/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6ceec337dc0471a9ab6ae8da6538e0bb0c1cbe35 --- /dev/null +++ b/submissions_extracted/109/Q2.ipynb @@ -0,0 +1,390 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3=self.layer3(a2)\n", + " a3= self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.002\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/109/Q3.ipynb b/submissions_extracted/109/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9149f1bda48dee0cfcb4de16a5dd9e46c1e2c88c --- /dev/null +++ b/submissions_extracted/109/Q3.ipynb @@ -0,0 +1,235 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " df.dropna()\n", + " print(\"Missing Values Was handling by droping it\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data_for_scale = pd.DataFrame({})\n", + "\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/11/Q1.ipynb b/submissions_extracted/11/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..51e4ea77f3b1ed1a656ad4227be33860e84163ed --- /dev/null +++ b/submissions_extracted/11/Q1.ipynb @@ -0,0 +1,224 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food= df.dropna('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_food.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "le = LabelEncoder()\n", + "df_food['Weather'] = le.fit_transform(df_food['Weather'])\n", + "df_food['Traffic_Level'] = le.fit_transform(df_food['Traffic_Level'])\n", + "df_food['Time_of_Day'] = le.fit_transform(df_food['Time_of_Day'])\n", + "df_food['Vehicle_Type'] = le.fit_transform(df_food['Vehicle_Type'])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = model.predict(X_test_scaled)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/11/Q2.ipynb b/submissions_extracted/11/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..42c6dd04b7ff773fae42780a0f3576fb5bbc4f4f --- /dev/null +++ b/submissions_extracted/11/Q2.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + ")\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:class NN2Layer(nn.Module):\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim,output_dim):\n", + "\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + "\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + "\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + "\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "print(model)\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/11/Q3.ipynb b/submissions_extracted/11/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/11/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/110/Q1.ipynb b/submissions_extracted/110/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f9de12e057056702759f8824e77aedbe3bf07b21 --- /dev/null +++ b/submissions_extracted/110/Q1.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "d_path = os.path.join(path, 'Q1_data.csv')\n", + "df_q1 = pd.read_csv(d_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_q1.shape}\")\n", + "df_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# delivery_time (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_q1['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery distance')\n", + "plt.ylabel('delivery_time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_q1.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_q1[col] = le.fit_transform(df_q1[col].astype(str))\n", + "\n", + "df_q1.head()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_q1.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_q1[numerical_cols] = scaler.fit_transform(df_q1[numerical_cols])\n", + "df_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_q1, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_q1['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Mean Squared Error in NumPy\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Linear Regression Results\")\n", + "print(f\" Average MSE: {np.mean(lr_mse):.4f}\")\n", + "print(f\" Average RMSE: {np.mean(lr_rmse):.4f}\")\n", + "print(f\" Average R2: {np.mean(lr_r2):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "from catboost import CatBoostRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/110/Q2.ipynb b/submissions_extracted/110/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f30cec8a5f647228ce5b492de5bd250e095c9289 --- /dev/null +++ b/submissions_extracted/110/Q2.ipynb @@ -0,0 +1,357 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/110/Q3.ipynb b/submissions_extracted/110/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5a42691b0606c237ca2c04fde96c1bbd50441bed --- /dev/null +++ b/submissions_extracted/110/Q3.ipynb @@ -0,0 +1,367 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "d_path = os.path.join(path, 'Q3_data.csv')\n", + "df_q3 = pd.read_csv(d_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_q3.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q3['B_2'].fillna(df_q3['B_2'].mean())\n", + "df_q3['P_2'].fillna(df_q3['B_2'].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# SINCE OUR DATA ALL NUMRIC ENCODING CANT BE DONE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_q3.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_q3[numerical_cols] = scaler.fit_transform(df_q3[numerical_cols])\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_q3, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q3.drop(\"Target\", axis=1).astype(float)\n", + "y = df_q3['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + "\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/111/Q1.ipynb b/submissions_extracted/111/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a6b9f3ebafcc9e7ef5b83908393f9d0c3cb4a964 --- /dev/null +++ b/submissions_extracted/111/Q1.ipynb @@ -0,0 +1,260 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from matplotlib import figure\n", + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10 , 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna())\n", + "plt.title(\"Distribution of delivery time\")\n", + "plt.xlabel(\"delivery time \")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = [\"Distance_km\" , \"Preparation_Time_min\" , \"Courier_Experience_yrs\" , \"Delivery_Time\" ]\n", + "df_clean = df_food[stat_cols].copy()\n", + "print(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_values = df_clean.isnull().sum()\n", + "df_dropna = df_clean.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df_clean.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(df_dropna)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "X = df_dropna[stat_cols]\n", + "y = df_dropna[\"Delivery_Time\"]\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_importance = df_clean({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10 , 5))\n", + "plt.hist(y_pred)\n", + "plt.title(\"Delivery_Time distribution\")\n", + "plt.xlabel(\"Delivery_Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/111/Q2.ipynb b/submissions_extracted/111/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9f2244dbb222a8914140a662141901484c022ae4 --- /dev/null +++ b/submissions_extracted/111/Q2.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset , batch_size = 32 , shuffle = True)\n", + "test_loader = DataLoader(test_dataset , batch_size = 32 , shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim , output_dim):\n", + " super(NN4Layer, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim , hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim , hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim , hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + " output = self.layer4(a3)\n", + " return output\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss/ len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "import torch.nn.functional as F\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + " return avg_loss, accuracy\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 14\n", + "output_dim = 4\n", + "model = NN4Layer(input_dim , hidden_dim , output_dim).to(device)\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "\n", + "criterion = nn.MSELoss()\n", + "learning_rate = 0.001\n", + "optimizer = AdamW(model.parameters() , learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model , optimizer , criterion , train_loader , device)\n", + " val_loss = validate(model , criterion , test_loader , device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/111/Q3.ipynb b/submissions_extracted/111/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f8517574c31c1155d255389e76367f56b83ee015 --- /dev/null +++ b/submissions_extracted/111/Q3.ipynb @@ -0,0 +1,198 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "f = os.path.join(path, 'Q3_data.csv')\n", + "df_cards = pd.read_csv(f)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_cards.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_cards.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_cards.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for col in [\"S_3\" , \"D_42\" ,\"D_43\" , \"D_137\" , \"D_138\" ,\"D_142\" ]:\n", + " df_cards[col] = df_cards[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df_cards.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_cards.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "else:\n", + " print(\"No Duplicate Samples Found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "le = LabelEncoder()\n", + "df_cards = le.fit_transform(df_cards[\"S_3\"].astype(str))\n", + "df_cards = le.fit_transform(df_cards[\"D_42\"].astype(str))\n", + "df_cards = le.fit_transform(df_cards[\"D_43\"].astype(str))\n", + "df_cards = le.fit_transform(df_cards[\"D_137\"].astype(str))\n", + "df_cards = le.fit_transform(df_cards[\"D_138\"].astype(str))\n", + "df_cards = le.fit_transform(df_cards[\"D_142\"].astype(str))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(df_cards)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/112/Q1.ipynb b/submissions_extracted/112/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..49f67c9416a8fc1d5145eb680e076787dafbdaf5 --- /dev/null +++ b/submissions_extracted/112/Q1.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + \"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop(columns=['Order_ID']).copy()\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# we have missing values in: weather (categorical), traffic level (categorical), time of day (cat), courier experience years (num), delivery time (num)\n", + "# since delivery time is our target we need to drop the rows with missing delivery time\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "\n", + "df_clean.info()\n", + "df_clean.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean = df_clean.drop_duplicates()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()\n", + "\n", + "#i thought i saved the file that had the one hot label encoder :(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean[features]\n", + "y = df_clean[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from tqdm import tqdm\n", + "def gradient_descent(X, y, learning_rate, n_iters=1000):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "maes = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " maes.append(mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(maes, label='Train Loss')\n", + "plt.title('Loss over folds')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MAE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/112/Q2.ipynb b/submissions_extracted/112/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..57ebbb97e42ef09b56e52ddf05a335a89cc9ec2c --- /dev/null +++ b/submissions_extracted/112/Q2.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 36\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 128 # Design choice\n", + "\n", + "output_dim = 1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/112/Q3.ipynb b/submissions_extracted/112/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7f784717a59a1d8d621fc597a4ec6d60b45aff56 --- /dev/null +++ b/submissions_extracted/112/Q3.ipynb @@ -0,0 +1,179 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "columns = []\n", + "for col in df:\n", + " df = df.fillna(df[col].mean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/113/Q1.ipynb b/submissions_extracted/113/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1e8d1401c219c625df5e9e29028e458ecfb32c9 --- /dev/null +++ b/submissions_extracted/113/Q1.ipynb @@ -0,0 +1,299 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Part 1 ---------------------------------------------------------\n", + "\n", + "\n", + "data_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(data_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(6,4))\n", + "df[\"Delivery_Time\"].hist(bins=30)\n", + "plt.xlabel(\"Delivery_Time\")\n", + "plt.ylabel(\"count\")\n", + "plt.title(\"Delivery time distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Part 2 ---------------------------------------------------------\n", + "df = df.drop(columns=[\"Order_ID\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "for c in num_cols:\n", + " df[c] = df[c].fillna(df[c].median())\n", + "for c in cat_cols:\n", + " df[c] = df[c].fillna(df[c].mode()[0])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_col = \"Delivery_Time\"\n", + "feature_cols = [c for c in df.columns if c != target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "df[feature_cols] = scaler.fit_transform(df[feature_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(\"Target is continuous → imbalance concept not applicable.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Part 3 ---------------------------------------------------------\n", + "X = df[feature_cols].values\n", + "y = df[target_col].values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X[train_idx], X[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + " model = RandomForestRegressor(\n", + " n_estimators=300,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + "\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "print(\"MAE scores:\", mae_scores)\n", + "print(\"Average MAE:\", np.mean(mae_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Part 4 ---------------------------------------------------------\n", + "importances = model.feature_importances_\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.bar(range(len(feature_cols)), importances[sorted_idx])\n", + "plt.xticks(range(len(feature_cols)),\n", + " np.array(feature_cols)[sorted_idx],\n", + " rotation=90)\n", + "plt.title(\"Feature importance (RandomForest)\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred_full = model.predict(X)\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(y_pred_full, bins=30)\n", + "plt.xlabel(\"Predicted delivery_time\")\n", + "plt.ylabel(\"count\")\n", + "plt.title(\"Predicted delivery time distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:# Part 5 (Bonus) -----------------------------------------------\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "ensemble_mae_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X[train_idx], X[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + " rf = RandomForestRegressor(\n", + " n_estimators=300,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " cd= CatBoostRegressor(\n", + " depth=6,\n", + " learning_rate=0.05,\n", + " n_estimators=500,\n", + " verbose=False,\n", + " random_state=42\n", + " )\n", + "\n", + " rf.fit(X_train, y_train)\n", + " cd.fit(X_train, y_train)\n", + "\n", + " rf_pred = rf.predict(X_val)\n", + " cd_pred = cd.predict(X_val)\n", + "\n", + " y_pred_ens = (rf_pred + cd_pred) / 2.0\n", + "\n", + " mae = mean_absolute_error(y_val, y_pred_ens)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + "print(\"Ensemble MAE scores:\", ensemble_mae_scores)\n", + "print(\"Average Ensemble MAE:\", np.mean(ensemble_mae_scores))\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/113/Q2.ipynb b/submissions_extracted/113/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e01a50e585d1ab616a9ebc1a7ce8e506d7aee10e --- /dev/null +++ b/submissions_extracted/113/Q2.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors# Part 1 -------------------------------------------------\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "batch_size = 32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images_batch, ages_batch = next(iter(train_loader))\n", + "print(images_batch.shape, ages_batch.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "def show_samples(loader, n=6):\n", + " imgs, ages = next(iter(loader))\n", + " imgs = imgs[:n]\n", + " ages = ages[:n]\n", + "\n", + " plt.figure(figsize=(10,4))\n", + " for i in range(n):\n", + " plt.subplot(2, n//2, i+1)\n", + " img = imgs[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {ages[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "show_samples(train_loader)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " # flatten from (C,H,W) → N\n", + " c, h, w = X_train.shape[1], X_train.shape[2], X_train.shape[3]\n", + " in_features = c * h * w\n", + "\n", + " self.net = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(in_features, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1) # regression output\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.net(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " for x, y in loader:\n", + " x = x.to(device)\n", + " y = y.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(x)\n", + " loss = criterion(preds, y)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item() * x.size(0)\n", + "\n", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " with torch.no_grad():\n", + " for x, y in loader:\n", + " x = x.to(device)\n", + " y = y.to(device)\n", + "\n", + " preds = model(x)\n", + " loss = criterion(preds, y)\n", + " running_loss += loss.item() * x.size(0)\n", + "\n", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = AgeRegressor().to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=1e-3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(1, num_epochs + 1):\n", + " train_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " val_loss = validate(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch {epoch:02d} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.plot(range(1, num_epochs+1), train_losses, label=\"Train\")\n", + "plt.plot(range(1, num_epochs+1), val_losses, label=\"Val\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"MSE Loss\")\n", + "plt.title(\"Training & Validation Loss\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "x_batch, y_batch = next(iter(test_loader))\n", + "x_batch = x_batch.to(device)\n", + "with torch.no_grad():\n", + " preds = model(x_batch).cpu().squeeze()\n", + "\n", + "x_batch = x_batch.cpu()\n", + "\n", + "n = 6\n", + "plt.figure(figsize=(10,4))\n", + "for i in range(n):\n", + " plt.subplot(2, n//2, i+1)\n", + " img = x_batch[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred: {preds[i].item():.1f}\\nTrue: {y_batch[i].item():.1f}\")\n", + " plt.axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/113/Q3.ipynb b/submissions_extracted/113/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..189f722da0e9324deb9508ada33b22a3b07d34a5 --- /dev/null +++ b/submissions_extracted/113/Q3.ipynb @@ -0,0 +1,245 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.metrics import f1_score\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.tolist()\n", + "cat_cols = df.select_dtypes(include=[\"object\", \"category\"]).columns.tolist()\n", + "\n", + "for c in num_cols:\n", + " df[c] = df[c].fillna(df[c].median())\n", + "for c in cat_cols:\n", + " df[c] = df[c].fillna(df[c].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "feature_cols = [c for c in df.columns if c != target_col]\n", + "scaler = StandardScaler()\n", + "df[feature_cols] = scaler.fit_transform(df[feature_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(df[target_col].value_counts(normalize=True))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df[feature_cols].values\n", + "y = df[target_col].values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "models = []\n", + "\n", + "for train_idx, val_idx in skf.split(X, y):\n", + " X_train, X_val = X[train_idx], X[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " depth=6,\n", + " learning_rate=0.05,\n", + " n_estimators=500,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"F1\",\n", + " verbose=False,\n", + " random_state=42\n", + " )\n", + "\n", + " model.fit(X_train, y_train, eval_set=(X_val, y_val), verbose=False)\n", + " y_pred = model.predict(X_val)\n", + "\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores.append(f1)\n", + " models.append(model)\n", + "\n", + "print(\"F1 scores:\", f1_scores)\n", + "print(\"Average F1:\", np.mean(f1_scores))\n", + "\n", + "best_model = models[np.argmax(f1_scores)]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Part 4 -------------------------------------------------\n", + "importances = best_model.get_feature_importance()\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "sorted_features = np.array(feature_cols)[sorted_idx]\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.bar(range(20), importances[sorted_idx][:20])\n", + "plt.xticks(range(20), sorted_features[:20], rotation=90)\n", + "plt.title(\"Top 20 Feature Importances\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = sorted_features[0]\n", + "print(\"Golden feature:\", golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = df[[golden_feature]].values\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_golden = []\n", + "\n", + "for train_idx, val_idx in skf.split(X_golden, y):\n", + " X_train, X_val = X_golden[train_idx], X_golden[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + "\n", + "print(\"Golden-only F1 scores:\", f1_golden)\n", + "print(\"Average F1 (golden only):\", np.mean(f1_golden))\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/114/Q1.ipynb b/submissions_extracted/114/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf07db3244ba979ba2f0fcb690b21d0ba15954a9 --- /dev/null +++ b/submissions_extracted/114/Q1.ipynb @@ -0,0 +1,421 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_time_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery_time = pd.read_csv(delivery_time_path)\n", + "\n", + "print(f\"Dataset shape: {df_delivery_time.shape}\")\n", + "df_delivery_time.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:(head)\n", + "# Analyze missing values\n", + "missing_percentage = (df_delivery_time.isnull().sum() / len(df_delivery_time)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "df_delivery_time.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information using info():\n", + "df_delivery_time.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4(Show statistical description using (describe): Write your code here:\n", + "df_delivery_time.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5-Plot the target distribution (delivery_time)\n", + "\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df_delivery_time, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + "\n", + " df_delivery_time[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_delivery_time, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_delivery_time, \"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Do we have missing values?\n", + "def check_missing_values(df_delivery_time):\n", + " missing_values = df_delivery_time.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery_time)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check for duplicates\n", + "def check_duplicates(df_delivery_time):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_delivery_time.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_delivery_time.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery_time)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Do we have categorical columns?\n", + "categorical_cols = df_delivery_time.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df_delivery_time.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = MinMaxScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df_delivery_time[numerical_cols] = scaler.fit_transform(df_delivery_time[numerical_cols])\n", + "\n", + "df_delivery_time.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "# Do we have different scales in the data?\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df_delivery_time['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'] = le.fit_transform(df_delivery_time['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'])\n", + "\n", + "df_delivery_time\n", + "df_delivery_time.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df_delivery_time.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = MinMaxScaler()\n", + "df_delivery_time[features] = scaler.fit_transform(df_delivery_time[features])\n", + "df_delivery_time.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_delivery_time.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_delivery_time['Delivery_Time'].astype(float)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Mean Squared Error in NumPy\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "####\n", + " def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#5-Print the averaged score across all folds\n", + "\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/114/Q2.ipynb b/submissions_extracted/114/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7e3c58d47899ab9e96f910379513d0c93867b0fa --- /dev/null +++ b/submissions_extracted/114/Q2.ipynb @@ -0,0 +1,433 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "mse = mean_squared_error(y_test.numpy(), predictions)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/114/Q3.ipynb b/submissions_extracted/114/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a759f69fb1489ab12c594bc6dfa1248ac15e193 --- /dev/null +++ b/submissions_extracted/114/Q3.ipynb @@ -0,0 +1,501 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "\n", + "print(\"Libraries imported successfully.\")\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Read the dataset Q3_data.csv using read_csv()\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Inspect the first few rows using head()\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check for duplicates\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"P_2\",\"B_2\",\"\")\n", + "\n", + "scaler = MinMaxScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Prepare the data as X and y\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df[\"Target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# The softmax function\n", + "def softmax(z):\n", + " z_shifted = z - np.max(z, axis=1, keepdims=True)\n", + " exp_z = np.exp(z_shifted)\n", + " return exp_z / np.sum(exp_z, axis=1, keepdims=True)\n", + " # Categorical cross entropy loss function using NumPy\n", + "def categorical_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n", + "\n", + " loss = -np.mean(np.sum(y * np.log(y_hat), axis=1))\n", + " return loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, num_classes, lr, n_iters=1000):\n", + " # Get the number of samples (m) and number of features (n)\n", + " m, n = X.shape\n", + "\n", + " # Initialize weight matrix with shape (n, num_classes)\n", + " theta = np.zeros((n, num_classes))\n", + "\n", + " # One-hot encode the labels\n", + " y_onehot = one_hot_encode(y, num_classes)\n", + "\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Multiclass Logistic Regression\"):\n", + " # Calculate the logits z\n", + " z = np.dot(X, theta)\n", + "\n", + " # Get class probabilities using softmax\n", + " y_pred = softmax(z)\n", + "\n", + " # Compute the gradient of Categorical Cross-Entropy with Softmax\n", + " # ∂J/∂θ = (1/m) * X^T * (y_pred - y_onehot)\n", + " gradient = np.dot(X.T, (y_pred - y_onehot)) / m\n", + "\n", + " # Update weights\n", + " theta -= lr * gradient\n", + "\n", + " # Track loss\n", + " loss = categorical_cross_entropy(y_onehot, y_pred)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train using gradient descent with learning rate = 0.5\n", + " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n", + "\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#TODO: Calculate the average losses across folds\n", + "avg_loss = np.mean(sr_results['loss'], axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Training', color='purple')\n", + "plt.title('Loss Curve')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Categorical Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"SOFTMAX REGRESSION Performance:\")\n", + "# TODO: Print the average of each evaluation metric across folds\n", + "print(f\" Accuracy: {np.mean(sr_results['acc']):.4f}\")\n", + "print(f\" F1-Score: {np.mean(sr_results['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " # TODO: Define models with hyperparameters of your choice\n", + "\n", + "models = {\n", + " \"LR\": LogisticRegression(\n", + " max_iter=1000\n", + " ),\n", + " \"KNN\": KNeighborsClassifier(\n", + " n_neighbors=3,\n", + " ),\n", + " \"SVM\": SVC(\n", + " kernel='rbf',\n", + " C=1.0\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=16\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=280,\n", + " max_depth=10,\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/115/Q1.ipynb b/submissions_extracted/115/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0c7f6f4ca553db95204132397261053a1d64ec57 --- /dev/null +++ b/submissions_extracted/115/Q1.ipynb @@ -0,0 +1,246 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Import needed Libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Load the dataset and read it\n", + "foods_path = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "df_foods = pd.read_csv(foods_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "print(f\"Dataset shape: {df_foods.shape}\")\n", + "df_foods.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Disply data set and information\n", + "df_foods.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe():\n", + "df_foods.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_foods['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Order')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_foods.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Do we have missing values?\n", + "def check_missing_values(df_foods):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df_foods.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_foods)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check for duplicates\n", + "def check_duplicates(df_foods):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_foods.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_foods.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_foods)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Do we have categorical columns?\n", + "categorical_cols = df_foods.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df_foods['Weather'] = le.fit_transform(df_foods['Weather'])\n", + "\n", + "df_foods" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/115/Q2.ipynb b/submissions_extracted/115/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b6c66e1bd2fd4afb8cc7089f3f76c262a5ada9f1 --- /dev/null +++ b/submissions_extracted/115/Q2.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "import torch.nn as nn\n", + "# Create 1st linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Create 2nd linear layer: 3 input features -> 1 output\n", + "linear2 = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Create 3rd linear layer: 3 input features -> 1 output\n", + "linear3 = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Create 4th linear layer: 3 input features -> 1 output\n", + "linear4 = nn.Linear(in_features=3, out_features=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "in_features = 4\n", + "out_features = 1\n", + "\n", + "# Instantiate model\n", + "model = nn.linear(in_features, out_features).to(device)\n", + "\n", + "logits = torch.tensor([\n", + " [2.0, 0.5, 1.0],\n", + " [0.1, 1.5, 0.3]\n", + "])\n", + "# True class indices\n", + "targets = torch.tensor([0, 1])\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "loss = criterion(logits, targets)\n", + "print(\"Cross Entropy Loss:\", loss.item())\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/115/Q3.ipynb b/submissions_extracted/115/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5393ca06aecfed205da1f2ae14903a81800164cc --- /dev/null +++ b/submissions_extracted/115/Q3.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Import needed Libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Load the dataset and read it\n", + "An_data_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df_An = pd.read_csv(An_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "print(f\"Dataset shape: {df_An.shape}\")\n", + "df_An.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Disply data set and information\n", + "df_An.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe():\n", + "df_An.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Do we have missing values?\n", + "def check_missing_values(df_An):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df_An.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_An)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check for duplicates\n", + "def check_duplicates(df_An):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_An.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_An.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_An)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have categorical columns?\n", + "categorical_cols = df_An.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/116/Q1.ipynb b/submissions_extracted/116/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..396cbdf7eb6d5ba8acdf720ea193e84d721af87f --- /dev/null +++ b/submissions_extracted/116/Q1.ipynb @@ -0,0 +1,230 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Load the dataset\n", + "delivery_time_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delivery_time_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "delivery_time = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Q1_data. Columns:\", list(delivery_time))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in delivery_time:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/116/Q2.ipynb b/submissions_extracted/116/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..35918576ffb469484eb1a1de700d274a17acfb75 --- /dev/null +++ b/submissions_extracted/116/Q2.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "images = []\n", + "labels = []\n", + "\n", + "for idx in indices:\n", + " img, label = train_dataset[idx]\n", + " img = img.numpy().flatten() # Flatten makes each 28x28 image into 784D\n", + " images.append(img)\n", + " labels.append(label)\n", + "\n", + "X = np.array(images) # Shape: (5000, 784)\n", + "y = np.array(labels) # Ground truth labels (for visualization)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/116/Q3.ipynb b/submissions_extracted/116/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5b0b1ba3d94734b2873d87262d2c71d2345c60c5 --- /dev/null +++ b/submissions_extracted/116/Q3.ipynb @@ -0,0 +1,180 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "delivery_time_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(delivery_time_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(describe)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/117/Q1.ipynb b/submissions_extracted/117/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..72f45c22a0ff668713ef437b1b1eb213394331df --- /dev/null +++ b/submissions_extracted/117/Q1.ipynb @@ -0,0 +1,208 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 :\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "cols = ['price', 'year', 'manufacturer', 'condition', 'cylinders', 'fuel', 'odometer', 'transmission', 'type']\n", + "df_clean = df. [cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['price', 'year', 'odometer'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/117/Q2.ipynb b/submissions_extracted/117/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ec7329359a20f7af7e43c5ef0b0affe926bab67 --- /dev/null +++ b/submissions_extracted/117/Q2.ipynb @@ -0,0 +1,347 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "print(\"Shape of x:\", x.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n", + "x = torch.randn(32, 3, 28, 28)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape) # (32, 2352)\n", + "\n", + "# 2️⃣ Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 28, 28)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n", + "\n", + "# 3️⃣ Unsqueeze - Add a new dimension of size 1\n", + "x = torch.randn(3, 28, 28)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n", + "\n", + "# 4️⃣ View - Reshape freely while keeping same number of elements\n", + "x = torch.randn(32, 28, 28, 3)\n", + "x_view = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Create a float32 tensor\n", + "x = torch.tensor([1.2, 2.3, 3.4], dtype=torch.float32)\n", + "print(x.dtype) # Output: torch.float32\n", + "\n", + "# Convert to float16\n", + "x_half = x.to(torch.float16)\n", + "print(x_half.dtype) # Output: torch.float16" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: start rtaining for 20 epechs:\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/117/Q3.ipynb b/submissions_extracted/117/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b3fb8551a521aef1f41a6f34b2a08731da2ec994 --- /dev/null +++ b/submissions_extracted/117/Q3.ipynb @@ -0,0 +1,184 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path = kagglehub.dataset_download(\"nikhil7280/weather-type-classification\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "df = pd.read_csv(f\"{path}/weather_classification_data.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/118/Q1.ipynb b/submissions_extracted/118/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a69447423d16df9ab2dcb0cf9b5414c371954950 --- /dev/null +++ b/submissions_extracted/118/Q1.ipynb @@ -0,0 +1,207 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np # for random data generation\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#read the csv file using pandas\n", + "df= pd.read_csv(path + \"/Q1_data.csv\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(15,5))\n", + "plt.plot(df['Delivery_Time'])\n", + "plt.title(\"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#droping order id column\n", + "df = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()\n", + "\n", + "df.dropna()\n", + "print(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df.isnull().sum())\n", + "\n", + "df.duplicated()\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "cat =pd.DataFrame({\"Food Delivery Time\": ['distance_km', 'Weather', 'Traffic_Level' , 'Time_of_Day', 'Vehicle_Type','Preparation_Time_min' ,'Courier_Experience_yrs' ,'Delivery_Time']})\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(cat[\"Food Delivery Time\"]) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(4)})\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(4) * 0.5\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/118/Q2.ipynb b/submissions_extracted/118/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1ebdc7deeca6fddf1586f9f37f22e36d0b53477 --- /dev/null +++ b/submissions_extracted/118/Q2.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " img = images[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f'Label: {labels[i].item()}')\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer5 = nn.Linear(hidden_dim, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " z4 = self.layer4(a3)\n", + " a4 = self.relu(z4)\n", + "\n", + " z5 = self.layer5(a4)\n", + "\n", + "\n", + " return z5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + "\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = 3 * 32 * 32\n", + "\n", + "\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "num_epochs = 15\n", + "learning_rate = 0.001\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "plt.plot(age_losses, label='Train Loss')\n", + "plt.plot(age_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/118/Q3.ipynb b/submissions_extracted/118/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0585197ec3936791f7ba38dbb30039c4164c406 --- /dev/null +++ b/submissions_extracted/118/Q3.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df= pd.read_csv(path + '/Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.isnull().sum()\n", + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated()\n", + "\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/119/Q1.ipynb b/submissions_extracted/119/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..461db9b62c08c3bb98f23d36020e5ec192e2c91e --- /dev/null +++ b/submissions_extracted/119/Q1.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# The dataset Q1_data.csv has been successfully loaded into a pandas DataFrame named df from the /content/ directory. This DataFrame is now ready for further inspection and analysis.\n", + "\n", + "import pandas as pd\n", + "\n", + "# Read the CSV file into a pandas DataFrame named df\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(\"Dataset loaded successfully into DataFrame 'df' from the /content/ directory.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# The df.head() method displays the first few rows of the DataFrame, which is useful for quickly verifying that the data has been loaded correctly and to get a preliminary look at its structure and content.\n", + "\n", + "display(df.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#The `df.info()` method provides a concise summary of the DataFrame, including the data types of each column, the number of non-null values, and memory usage. This helps in understanding the data structure and identifying potential issues like missing values or incorrect data types.\n", + "\n", + "display(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# The `df.describe()` method generates descriptive statistics that summarize the central tendency, dispersion, and shape of a dataset's distribution, excluding NaN values. This is useful for quickly understanding the main characteristics of numerical data.\n", + "\n", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# This code generates a histogram of the 'Delivery_Time' column, showing its distribution. The Kernel Density Estimate (KDE) overlay helps visualize the shape of the distribution, while the title and labels make the plot understandable.\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(df['Delivery_Time'], kde=True, bins=30)\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.grid(True, linestyle='--', alpha=0.7)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# The 'Order_ID' column is unique for each entry and typically serves no analytical purpose in prediction models.\n", + "# Dropping it helps reduce dimensionality and ensures it doesn't accidentally get treated as a feature.\n", + "\n", + "df = df.drop('Order_ID', axis=1)\n", + "\n", + "print(\"Dropped 'Order_ID' column.\")\n", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Let's first see how many missing values we have in each column.\n", + "print(\"Missing values before handling:\")\n", + "display(df.isnull().sum())\n", + "\n", + "# For text-based categories like Weather, Traffic_Level, and Time_of_Day, it's often best to fill missing spots with the most common value (the 'mode').\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " if df[col].isnull().any():\n", + " mode_value = df[col].mode()[0]\n", + " df[col].fillna(mode_value, inplace=True)\n", + " print(f\"Filled missing values in '{col}' with its most frequent option: {mode_value}\")\n", + "\n", + "# For 'Courier_Experience_yrs', which is a number, using the middle value (the 'median') is a good way to fill in gaps without being too affected by extreme values.\n", + "if df['Courier_Experience_yrs'].isnull().any():\n", + " median_value = df['Courier_Experience_yrs'].median()\n", + " df['Courier_Experience_yrs'].fillna(median_value, inplace=True)\n", + " print(f\"Filled missing values in 'Courier_Experience_yrs' with the middle experience value: {median_value}\")\n", + "\n", + "# Our main goal is to predict 'Delivery_Time'. If this value is missing, that row isn't useful for training, so we'll remove those rows.\n", + "initial_rows = len(df)\n", + "df.dropna(subset=['Delivery_Time'], inplace=True)\n", + "dropped_rows = initial_rows - len(df)\n", + "print(f\"Removed {dropped_rows} rows because 'Delivery_Time' was missing.\")\n", + "\n", + "# Now, let's check again to make sure all missing values are gone.\n", + "print(\"\\nMissing values after handling:\")\n", + "display(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Let's find out if there are any exact duplicate rows. Duplicates can sometimes mess up our model training.\n", + "duplicates_before = df.duplicated().sum()\n", + "print(f\"Number of duplicate rows before removal: {duplicates_before}\")\n", + "\n", + "if duplicates_before > 0:\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Okay, we found and removed the duplicate rows.\")\n", + " duplicates_after = df.duplicated().sum()\n", + " print(f\"Number of duplicate rows after removal: {duplicates_after}\")\n", + "else:\n", + " print(\"Good news! No duplicate rows were found in our dataset.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Our model needs numbers, so we need to convert text categories like 'Weather' or 'Traffic_Level' into numbers.\n", + "# One-Hot Encoding creates new columns for each unique category, turning them into 0s and 1s.\n", + "# We use 'drop_first=True' to avoid a common issue called multicollinearity.\n", + "categorical_cols = df.select_dtypes(include='object').columns\n", + "print(f\"Columns that look like categories to encode: {list(categorical_cols)}\")\n", + "\n", + "if len(categorical_cols) > 0:\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + " print(\"Categorical columns have been transformed into numbers using One-Hot Encoding.\")\n", + "else:\n", + " print(\"No text-based (categorical) columns found that needed encoding.\")\n", + "\n", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Imagine comparing apples and oranges – if one feature has huge numbers and another has tiny ones, our model might get confused.\n", + "# Scaling makes sure all our numerical features are on a similar playing field (mean of 0, standard deviation of 1).\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# First, we separate our prediction target (Delivery_Time) from the features we'll use to predict it.\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "# Now, we get our StandardScaler ready.\n", + "scaler = StandardScaler()\n", + "\n", + "# We 'fit' the scaler to our features and then 'transform' them.\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "# To keep things tidy and understandable, we put our scaled features back into a DataFrame.\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns, index=X.index)\n", + "\n", + "print(\"All numerical features have been scaled so they're all on a similar scale.\")\n", + "display(X_scaled.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# For prediction tasks like ours (where we predict a number, 'Delivery_Time'), 'imbalance' isn't really about having too many of one category like in classification.\n", + "# It's more about whether the numbers we're trying to predict are very skewed or have unusual outliers.\n", + "# We already looked at the distribution of 'Delivery_Time' in Part 1 with a histogram. That's usually how we check this for regression.\n", + "\n", + "print(\"For this kind of prediction task (regression), 'target imbalance' isn't about having uneven groups like in classification. We already checked the overall shape of 'Delivery_Time' in Part 1. If it were extremely skewed, we might consider transforming it, but for now, the distribution was visualized.\")\n", + "\n", + "# If we wanted to get super technical, we could calculate skewness or look at a box plot, but the histogram gives us a good sense.\n", + "# print(f\"Target skewness: {y.skew():.2f}\")\n", + "# plt.figure(figsize=(8, 5))\n", + "# sns.boxplot(y=y)\n", + "# plt.title('Box Plot of Delivery Time')\n", + "# plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# We already prepared X as X_scaled (scaled features) and y (Delivery_Time) in the previous data cleaning step.\n", + "# So, X_scaled contains our features ready for modeling, and y is our target.\n", + "# X will refer to X_scaled for consistency.\n", + "\n", + "X = X_scaled" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# For regression tasks, KFold is the appropriate cross-validation strategy as we are not dealing with discrete classes.\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# We'll use 5 folds for cross-validation to get a robust evaluation of our model.\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "# Let's keep track of our MAE scores from each fold.\n", + "mae_scores = []\n", + "\n", + "# Loop through each fold generated by KFold\n", + "for train_index, test_index in kf.split(X):\n", + " # Split the data for this fold into training and testing sets\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Initialize our RandomForestRegressor model\n", + " # We'll use a random_state for reproducibility\n", + " model = RandomForestRegressor(random_state=42)\n", + "\n", + " # Train the model on the training data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Make predictions on the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate the Mean Absolute Error (MAE) for this fold\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "# Once all folds are done, we'll calculate the average MAE to see our model's overall performance.\n", + "average_mae = np.mean(mae_scores)\n", + "\n", + "print(f\"Mean Absolute Errors for each fold: {mae_scores}\")\n", + "print(f\"Averaged Mean Absolute Error across all folds: {average_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Getting the feature importances from the trained Random Forest model.\n", + "# This tells us which features the model found most influential in making predictions.\n", + "feature_importances = model.feature_importances_\n", + "features = X.columns\n", + "\n", + "# Let's create a DataFrame to easily sort and visualize these importances.\n", + "importance_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances})\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "# Now, let's plot them to see which features stand out!\n", + "plt.figure(figsize=(12, 7))\n", + "sns.barplot(x='Importance', y='Feature', data=importance_df)\n", + "plt.title('Feature Importance from Random Forest Model')\n", + "plt.xlabel('Importance (higher means more impact)')\n", + "plt.ylabel('Feature')\n", + "plt.grid(axis='x', linestyle='--', alpha=0.7)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# We'll use the predictions from the last fold of our KFold cross-validation.\n", + "# This plot helps us understand the distribution of the delivery times our model is predicting.\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(y_pred, kde=True, bins=30, color='orange')\n", + "plt.title('Distribution of Predicted Delivery Times')\n", + "plt.xlabel('Predicted Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.grid(True, linestyle='--', alpha=0.7)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Install CatBoost\n", + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor # Import CatBoostRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "# Ensure X and y are defined from previous steps (X_scaled and y)\n", + "# X = X_scaled\n", + "# y = y\n", + "\n", + "# Set up KFold cross-validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# List to store MAE scores for the ensemble predictions\n", + "ensemble_mae_scores = []\n", + "\n", + "# Loop through each fold\n", + "for train_index, test_index in kf.split(X):\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Initialize and train RandomForestRegressor\n", + " rf_model = RandomForestRegressor(random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_predictions = rf_model.predict(X_test)\n", + "\n", + " # Initialize and train CatBoostRegressor\n", + " # verbose=0 to suppress training output for cleanliness\n", + " # random_seed for reproducibility\n", + " cat_model = CatBoostRegressor(random_seed=42, verbose=0, allow_writing_files=False)\n", + " cat_model.fit(X_train, y_train)\n", + " cat_predictions = cat_model.predict(X_test)\n", + "\n", + " # Average the predictions from both models\n", + " averaged_predictions = (rf_predictions + cat_predictions) / 2\n", + "\n", + " # Calculate MAE for the averaged predictions\n", + " mae = mean_absolute_error(y_test, averaged_predictions)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + "# Calculate the average MAE across all folds for the ensemble model\n", + "average_ensemble_mae = np.mean(ensemble_mae_scores)\n", + "\n", + "print(f\"Mean Absolute Errors for ensemble in each fold: {ensemble_mae_scores}\")\n", + "print(f\"Averaged Mean Absolute Error for Ensemble across all folds: {average_ensemble_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/119/Q2.ipynb b/submissions_extracted/119/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d8c5486ea9657d7db280c0107704445278abfbe4 --- /dev/null +++ b/submissions_extracted/119/Q2.ipynb @@ -0,0 +1,428 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# X_train, X_test are image data (N, C, H, W), y_train, y_test are age labels\n", + "# Images are converted to float32 for model input\n", + "# Labels are converted to float32 and reshaped to (N, 1) for regression task\n", + "X_train_tensor = torch.from_numpy(X_train).float()\n", + "X_test_tensor = torch.from_numpy(X_test).float()\n", + "y_train_tensor = torch.from_numpy(y_train).float().view(-1, 1)\n", + "y_test_tensor = torch.from_numpy(y_test).float().view(-1, 1)\n", + "\n", + "print(f\"X_train_tensor shape: {X_train_tensor.shape}\")\n", + "print(f\"X_test_tensor shape: {X_test_tensor.shape}\")\n", + "print(f\"y_train_tensor shape: {y_train_tensor.shape}\")\n", + "print(f\"y_test_tensor shape: {y_test_tensor.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# TensorDataset wraps tensors, providing a way to access corresponding slices of tensors\n", + "# along the first dimension.\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "print(f\"Train dataset size: {len(train_dataset)}\")\n", + "print(f\"Test dataset size: {len(test_dataset)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "# DataLoader provides an iterable over the dataset, supporting batching, shuffling, and multiprocessing.\n", + "batch_size = 32\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n", + "\n", + "print(f\"Number of batches in train_loader: {len(train_loader)}\")\n", + "print(f\"Number of batches in test_loader: {len(test_loader)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get one batch to verify its shape\n", + "for images, labels in train_loader:\n", + " print(f\"Shape of one batch of images: {images.shape}\") # Expected: [batch_size, channels, height, width]\n", + " print(f\"Shape of one batch of labels: {labels.shape}\") # Expected: [batch_size, 1]\n", + " break # Only get the first batch" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get a batch of training data to visualize\n", + "dataiter = iter(train_loader)\n", + "images, labels = next(dataiter)\n", + "\n", + "# Convert images to numpy for matplotlib display.\n", + "# PyTorch images are typically (N, C, H, W). Matplotlib expects (H, W, C) for color images.\n", + "# Transpose dimensions from (C, H, W) to (H, W, C) for correct display.\n", + "images_np = images.numpy().transpose(0, 2, 3, 1)\n", + "\n", + "# Create a figure and a set of subplots to display 5 images\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "\n", + "# Display 5 sample images with their age labels\n", + "for i in range(5):\n", + " ax = axes[i]\n", + " ax.imshow(images_np[i])\n", + " ax.set_title(f\"Age: {int(labels[i].item())}\") # Display age as an integer\n", + " ax.axis('off') # Hide axes for cleaner visualization\n", + "\n", + "plt.suptitle(\"Sample Images from Training Data\", fontsize=16)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class AgePredictorCNN(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictorCNN, self).__init__()\n", + " # Convolutional Block 1\n", + " # Input: 3x64x64 (RGB image)\n", + " self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1) # Output: 16x64x64\n", + " self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # Output: 16x32x32\n", + "\n", + " # Convolutional Block 2\n", + " self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) # Output: 32x32x32\n", + " # After pooling: 32x16x16\n", + "\n", + " # Convolutional Block 3\n", + " self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1) # Output: 64x16x16\n", + " # After pooling: 64x8x8\n", + "\n", + " # Convolutional Block 4\n", + " self.conv4 = nn.Conv2d(64, 128, kernel_size=3, padding=1) # Output: 128x8x8\n", + " # After pooling: 128x4x4 (THIS IS THE ERROR. Should be 128x2x2 for 36x36 input)\n", + "\n", + " # Calculate the size of the flattened output from the convolutional layers\n", + " # Original calculation 128 channels * 4 (height) * 4 (width) was for 64x64 input\n", + " # For 36x36 input and 4 MaxPool2d(2,2) layers:\n", + " # 36 -> 18 -> 9 -> 4 -> 2\n", + " # So, it should be 128 * 2 * 2 = 512\n", + " self.fc_input_size = 128 * 2 * 2 # Corrected from 128 * 4 * 4\n", + "\n", + " # Fully Connected (Linear) Layers for regression prediction\n", + " # These are the 4 linear layers requested.\n", + " self.fc1 = nn.Linear(self.fc_input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1) # Output a single scalar value (age)\n", + "\n", + " def forward(self, x):\n", + " # Apply convolutional layers followed by ReLU activation and Max Pooling\n", + " x = self.pool(F.relu(self.conv1(x)))\n", + " x = self.pool(F.relu(self.conv2(x)))\n", + " x = self.pool(F.relu(self.conv3(x)))\n", + " x = self.pool(F.relu(self.conv4(x)))\n", + "\n", + " # Flatten the feature maps for input to the fully connected layers\n", + " x = x.view(-1, self.fc_input_size) # -1 infers the batch size dynamically\n", + "\n", + " # Apply fully connected layers with ReLU activation for hidden layers\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x) # Output layer has no activation function for regression\n", + "\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_epoch(model, dataloader, loss_fn, optimizer, device):\n", + " model.train() # Set the model to training mode\n", + " total_loss = 0\n", + " # Iterate over batches in the dataloader\n", + " for batch_idx, (images, labels) in enumerate(dataloader):\n", + " images, labels = images.to(device), labels.to(device) # Move data to the specified device\n", + "\n", + " # Zero the gradients accumulated from the previous iteration\n", + " optimizer.zero_grad()\n", + "\n", + " # Forward pass: Compute predicted outputs by passing inputs to the model\n", + " outputs = model(images)\n", + "\n", + " # Calculate the loss between predicted outputs and actual labels\n", + " loss = loss_fn(outputs, labels)\n", + "\n", + " # Backward pass: Compute gradient of the loss with respect to model parameters\n", + " loss.backward()\n", + "\n", + " # Update model parameters using the calculated gradients\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item() # Accumulate the loss\n", + "\n", + " # Return the average loss for the epoch\n", + " return total_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate_epoch(model, dataloader, loss_fn, device):\n", + " model.eval() # Set the model to evaluation mode (disables dropout, batch normalization, etc.)\n", + " total_loss = 0\n", + " # Disable gradient calculation, as it's not needed for validation\n", + " with torch.no_grad():\n", + " for images, labels in dataloader:\n", + " images, labels = images.to(device), labels.to(device) # Move data to device\n", + "\n", + " # Forward pass\n", + " outputs = model(images)\n", + "\n", + " # Calculate loss\n", + " loss = loss_fn(outputs, labels)\n", + " total_loss += loss.item() # Accumulate the loss\n", + "\n", + " # Return the average loss for the epoch\n", + " return total_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Set the device to GPU if available, otherwise use CPU\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# Instantiate the AgePredictorCNN model and move it to the selected device\n", + "model = AgePredictorCNN().to(device)\n", + "print(model)\n", + "\n", + "# Define the loss function: Mean Squared Error (MSE) is suitable for regression tasks\n", + "loss_fn = nn.MSELoss()\n", + "\n", + "# Define the optimizer: Adam is a popular choice for its efficiency\n", + "learning_rate = 0.001\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20 # Define the total number of training epochs\n", + "\n", + "# Lists to store loss values for plotting later\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"Starting training...\")\n", + "for epoch in range(num_epochs):\n", + " # Perform one training epoch and get the average training loss\n", + " avg_train_loss = train_epoch(model, train_loader, loss_fn, optimizer, device)\n", + "\n", + " # Perform one validation epoch and get the average validation loss\n", + " avg_val_loss = validate_epoch(model, test_loader, loss_fn, device)\n", + "\n", + " # Store the losses\n", + " train_losses.append(avg_train_loss)\n", + " val_losses.append(avg_val_loss)\n", + "\n", + " # Print epoch-wise statistics\n", + " print(f\"Epoch {epoch+1}/{num_epochs}: Train Loss = {avg_train_loss:.4f}, Val Loss = {avg_val_loss:.4f}\")\n", + "\n", + "print(\"Training complete!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Task 1: Plot the training and validation loss over epochs\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, label='Training Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Training and Validation Loss Over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval() # Set the model to evaluation mode before making predictions\n", + "fig, axes = plt.subplots(1, 5, figsize=(20, 4)) # Create a figure with 5 subplots\n", + "\n", + "# Get a batch of images and labels from the test loader\n", + "dataiter = iter(test_loader)\n", + "images, actual_labels = next(dataiter)\n", + "\n", + "# Move images and labels to the same device as the model\n", + "images = images.to(device)\n", + "actual_labels = actual_labels.to(device)\n", + "\n", + "# Make predictions with the trained model without calculating gradients\n", + "with torch.no_grad():\n", + " predicted_labels = model(images)\n", + "\n", + "# Convert images back to numpy for matplotlib display (transpose dimensions)\n", + "images_np = images.cpu().numpy().transpose(0, 2, 3, 1)\n", + "\n", + "# Convert actual and predicted labels to numpy for display\n", + "actual_labels_np = actual_labels.cpu().numpy()\n", + "predicted_labels_np = predicted_labels.cpu().numpy()\n", + "\n", + "# Display 5 sample images with their actual and predicted ages\n", + "for i in range(5):\n", + " ax = axes[i]\n", + " ax.imshow(images_np[i])\n", + " ax.set_title(f\"Actual: {int(actual_labels_np[i].item())}\\nPred: {predicted_labels_np[i].item():.1f}\")\n", + " ax.axis('off')\n", + "\n", + "plt.suptitle(\"Sample Predictions (Actual vs. Predicted Age)\", fontsize=16)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/119/Q3.ipynb b/submissions_extracted/119/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b13c5d952b4e5149dfaff7384f5d4815817a9030 --- /dev/null +++ b/submissions_extracted/119/Q3.ipynb @@ -0,0 +1,434 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "# Task 1: Write your code here:\n", + "\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Inspect the first few rows using head()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Display dataset information using info()\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Calculate missing percentages\n", + "missing_percentages = df.isnull().sum() / len(df) * 100\n", + "\n", + "# Identify columns to drop (more than 70% missing)\n", + "columns_to_drop = missing_percentages[missing_percentages > 70].index\n", + "\n", + "# Drop columns from the DataFrame\n", + "df_cleaned = df.drop(columns=columns_to_drop)\n", + "\n", + "print(f\"Dropped {len(columns_to_drop)} columns with more than 70% missing values.\")\n", + "print(\"Remaining columns after dropping high-missing-value columns:\", df_cleaned.shape[1])\n", + "\n", + "# Identify numerical columns with remaining missing values and impute with median\n", + "numerical_cols_with_missing = df_cleaned.select_dtypes(include=['number']).columns[df_cleaned.select_dtypes(include=['number']).isnull().any()].tolist()\n", + "\n", + "for col in numerical_cols_with_missing:\n", + " median_val = df_cleaned[col].median()\n", + " df_cleaned[col] = df_cleaned[col].fillna(median_val) # Assign back to avoid SettingWithCopyWarning\n", + "\n", + "print(f\"Imputed missing values in {len(numerical_cols_with_missing)} numerical columns with their median.\")\n", + "\n", + "# Verify that there are no more missing values in numerical columns\n", + "print(\"\\nMissing values after imputation:\")\n", + "print(df_cleaned.select_dtypes(include=['number']).isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "initial_rows = df_cleaned.shape[0]\n", + "duplicate_rows = df_cleaned.duplicated().sum()\n", + "\n", + "if duplicate_rows > 0:\n", + " df_cleaned.drop_duplicates(inplace=True)\n", + " print(f\"Found and removed {duplicate_rows} duplicate rows.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n", + "\n", + "rows_after_deduplication = df_cleaned.shape[0]\n", + "print(f\"Number of rows before deduplication: {initial_rows}\")\n", + "print(f\"Number of rows after deduplication: {rows_after_deduplication}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "categorical_cols = df_cleaned.select_dtypes(include='object').columns\n", + "\n", + "if len(categorical_cols) > 0:\n", + " print(f\"Found {len(categorical_cols)} categorical columns: {categorical_cols.tolist()}\")\n", + " # Apply one-hot encoding if needed. 'drop_first=True' prevents multicollinearity.\n", + " df_encoded = pd.get_dummies(df_cleaned, columns=categorical_cols, drop_first=True)\n", + " df_cleaned = df_encoded # Update df_cleaned with encoded data\n", + " print(\"Categorical columns one-hot encoded.\")\n", + " print(f\"Shape after encoding: {df_cleaned.shape}\")\n", + "else:\n", + " print(\"No 'object' type categorical columns found. All features are numerical or already handled.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Task 4: Write your code here:\n", + "\n", + "# Create a copy to avoid modifying the original df_cleaned directly and prevent SettingWithCopyWarning\n", + "df_for_scaling = df_cleaned.copy()\n", + "\n", + "# Separate features (X) and target (y)\n", + "X = df_for_scaling.drop('Target', axis=1)\n", + "y = df_for_scaling['Target']\n", + "\n", + "# Initialize StandardScaler\n", + "scaler = StandardScaler()\n", + "\n", + "# Apply scaling to all features in X\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "# Convert scaled features back to a DataFrame, preserving column names and index\n", + "X_scaled_df = pd.DataFrame(X_scaled, columns=X.columns, index=X.index)\n", + "\n", + "# Combine scaled features with the target variable to form the final processed DataFrame\n", + "df_processed = X_scaled_df.copy()\n", + "df_processed['Target'] = y\n", + "\n", + "print(\"Numerical features scaled using StandardScaler.\")\n", + "print(f\"Shape of processed DataFrame after scaling: {df_processed.shape}\")\n", + "print(f\"First 5 rows of scaled features (including target):\\n{df_processed.head()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "target_distribution = df_processed['Target'].value_counts(normalize=True)\n", + "print(\"Target Variable Distribution:\")\n", + "print(target_distribution)\n", + "\n", + "# Determine if the target is imbalanced. A common heuristic is if the minority class is < 20-30%.\n", + "imbalance_threshold = 0.20 # Define a threshold for what constitutes significant imbalance\n", + "if target_distribution.min() < imbalance_threshold:\n", + " print(f\"Conclusion: The target variable is imbalanced. The minority class (label {target_distribution.idxmin()}) accounts for {target_distribution.min():.2%} of the data.\")\n", + "else:\n", + " print(\"Conclusion: The target variable is not significantly imbalanced.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "# X and y are already defined from the previous scaling step using df_processed\n", + "X = df_processed.drop('Target', axis=1)\n", + "y = df_processed['Target']\n", + "\n", + "print(f\"Shape of X (features): {X.shape}\")\n", + "print(f\"Shape of y (target): {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "print(\"\\n--- Part 3: Modeling ---\")\n", + "\n", + "# Task 1: Split the dataset into features (X) and target (y)\n", + "# X and y are already defined from the previous scaling step using df_processed\n", + "X = df_processed.drop('Target', axis=1)\n", + "y = df_processed['Target']\n", + "\n", + "print(f\"Shape of X (features): {X.shape}\")\n", + "print(f\"Shape of y (target): {y.shape}\")\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Use the correct split: StratifiedKFold\n", + "# StratifiedKFold is appropriate due to the target imbalance identified in Part 2.\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# List to store F1-scores from each fold\n", + "f1_scores = []\n", + "\n", + "print(\"\\nStarting Stratified K-Fold Cross-Validation...\")\n", + "for fold, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train a CatBoostClassifier model\n", + " # Using default parameters for simplicity; can be tuned for better performance\n", + " model = CatBoostClassifier(\n", + " iterations=100, # Number of boosting rounds\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function='Logloss',\n", + " eval_metric='F1', # Evaluate using F1-score\n", + " random_seed=42,\n", + " verbose=0, # Suppress verbose output\n", + " early_stopping_rounds=10 # Stop if F1 doesn't improve for 10 rounds\n", + " )\n", + "\n", + " print(f\"\\nTraining Fold {fold+1}...\")\n", + " model.fit(X_train, y_train, eval_set=(X_test, y_test), early_stopping_rounds=10, verbose=0)\n", + "\n", + " # Evaluate using the appropriate metric (F1 Score)\n", + " y_pred = model.predict(X_test)\n", + " f1 = f1_score(y_test, y_pred)\n", + " f1_scores.append(f1)\n", + " print(f\"Fold {fold+1} F1-Score: {f1:.4f}\")\n", + "\n", + "# Print the averaged score across all folds\n", + "average_f1_score = np.mean(f1_scores)\n", + "print(f\"\\nAverage F1-Score across all folds: {average_f1_score:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import pandas as pd\n", + "\n", + "# Ensure X (features) and model are available from Part 3\n", + "# If this cell is run independently, X and model might not be in scope.\n", + "# Assuming the previous cells have been run, X and model are available.\n", + "\n", + "# Get feature importances from the trained model\n", + "feature_importances = model.get_feature_importance()\n", + "\n", + "# Create a Series with feature names and their importances\n", + "feature_names = X.columns\n", + "importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': feature_importances})\n", + "\n", + "# Sort the features by importance in descending order\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plot feature importance from your trained model\n", + "plt.figure(figsize=(12, 8))\n", + "sns.barplot(x='Importance', y='Feature', data=importance_df.head(20))\n", + "plt.title('Top 20 Feature Importances from CatBoost Model')\n", + "plt.xlabel('Importance')\n", + "plt.ylabel('Feature')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "golden_feature = importance_df.iloc[0]['Feature']\n", + "golden_feature_importance = importance_df.iloc[0]['Importance']\n", + "\n", + "print(f\"\\nThe 'Golden Feature' (most important predictor) is: '{golden_feature}' with an importance of {golden_feature_importance:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Retrain with Golden Feature Only\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "print(\"\\n--- Part 5: Bonus - Retrain with Golden Feature Only ---\")\n", + "\n", + "# 1. Create new X with only the golden feature\n", + "X_golden = df_processed[[golden_feature]]\n", + "y = df_processed['Target'] # Target remains the same\n", + "\n", + "print(f\"Shape of X_golden (single golden feature): {X_golden.shape}\")\n", + "\n", + "# 2. Run the same KFold loop with this single feature\n", + "skf_golden = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "golden_f1_scores = []\n", + "\n", + "print(\"\\nStarting Stratified K-Fold Cross-Validation with Golden Feature...\")\n", + "for fold, (train_index, test_index) in enumerate(skf_golden.split(X_golden, y)):\n", + " X_train_golden, X_test_golden = X_golden.iloc[train_index], X_golden.iloc[test_index]\n", + " y_train_golden, y_test_golden = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train a CatBoostClassifier model with only the golden feature\n", + " model_golden = CatBoostClassifier(\n", + " iterations=100, # Number of boosting rounds\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function='Logloss',\n", + " eval_metric='F1', # Evaluate using F1-score\n", + " random_seed=42,\n", + " verbose=0, # Suppress verbose output\n", + " early_stopping_rounds=10 # Stop if F1 doesn't improve for 10 rounds\n", + " )\n", + "\n", + " print(f\"Training Fold {fold+1} (Golden Feature Only)...\")\n", + " model_golden.fit(X_train_golden, y_train_golden, eval_set=(X_test_golden, y_test_golden), early_stopping_rounds=10, verbose=0)\n", + "\n", + " # Evaluate using F1 Score\n", + " y_pred_golden = model_golden.predict(X_test_golden)\n", + " f1_golden = f1_score(y_test_golden, y_pred_golden)\n", + " golden_f1_scores.append(f1_golden)\n", + " print(f\"Fold {fold+1} F1-Score (Golden Feature Only): {f1_golden:.4f}\")\n", + "\n", + "# Print the averaged score across all folds for the golden feature model\n", + "average_golden_f1_score = np.mean(golden_f1_scores)\n", + "print(f\"\\nAverage F1-Score across all folds (Golden Feature Only): {average_golden_f1_score:.4f}\")\n", + "\n", + "# 3. Print and compare the accuracy (F1-score) with the full model\n", + "# Assuming 'average_f1_score' from the full model is available from Part 3\n", + "print(f\"\\n--- Comparison with Full Model ---\")\n", + "print(f\"Full Model Average F1-Score: {average_f1_score:.4f}\")\n", + "print(f\"Golden Feature Only Model Average F1-Score: {average_golden_f1_score:.4f}\")\n", + "\n", + "if average_golden_f1_score > average_f1_score:\n", + " print(\"Conclusion: The Golden Feature model performed better than the Full Model.\")\n", + "elif average_golden_f1_score == average_f1_score:\n", + " print(\"Conclusion: The Golden Feature model performed equally to the Full Model.\")\n", + "else:\n", + " print(\"Conclusion: The Full Model performed better than the Golden Feature model.\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/12/Q1.ipynb b/submissions_extracted/12/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f744bf54822bfcb52b1a3f7210e205cb7993e752 --- /dev/null +++ b/submissions_extracted/12/Q1.ipynb @@ -0,0 +1,257 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pokemon_path = os.path.join(path, 'Q1_data.csv')\n", + "df_pokemon = pd.read_csv(Q1_data.csv)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_pokemon.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_pokemon.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_pokemon.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = Q1_data.csv[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing Order_ID: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_pokemon.isnull().sum())\n", + "\n", + "## First, let's convert the target variable to numeric\n", + "# status: Placed = 1, Not Placed = 0\n", + "df['status'] = df['status'].map({'Placed': 1, 'Not Placed': 0})\n", + "\n", + "# Drop unnecessary columns\n", + "df = df.drop(['salary', 'sl_no'], axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:def check_duplicates(df):\n", + "\n", + "\n", + "duplicates = df_pokemon.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_pokemon.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + "y_train, y_test = y.iloc[train_index], y.iloc[test_index]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/12/Q2.ipynb b/submissions_extracted/12/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8f531ce474dcc0ca87de4c9a72145da75e09a00a --- /dev/null +++ b/submissions_extracted/12/Q2.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch= next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "y_pred = torch.tensor([[2.5], [3.0], [4.5]])\n", + "y_true = torch.tensor([[3.0], [2.5], [5.0]])\n", + "\n", + "criterion = nn.MSELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"MSE Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 50\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/12/Q3.ipynb b/submissions_extracted/12/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eec065a2dc01fbb128982b2d5cd58487899326f7 --- /dev/null +++ b/submissions_extracted/12/Q3.ipynb @@ -0,0 +1,234 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pokemon_path = os.path.join(path, 'Q3_data.csv')\n", + "df_pokemon = pd.read_csv(Q3_data.csv)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_pokemon.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_pokemon.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_pokemon.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_pokemon.isnull().sum())\n", + "\n", + "## First, let's convert the target variable to numeric\n", + "# status: Placed = 1, Not Placed = 0\n", + "df['status'] = df['status'].map({'Placed': 1, 'Not Placed': 0})\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df_pokemon.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_pokemon.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + "y_train, y_test = y.iloc[train_index], y.iloc[test_index]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/120/Q1.ipynb b/submissions_extracted/120/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5121e233184b501495162bde305b763b1c03927a --- /dev/null +++ b/submissions_extracted/120/Q1.ipynb @@ -0,0 +1,172 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.read_csv(path + \"/Q1_data.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['/Q1_data']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df_/Q1_data.dropna(subset=stat-cols).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x = df_clean[feature_cols]\n", + "y = df_clean[target]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/120/Q2.ipynb b/submissions_extracted/120/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..76d561dcf147e5dc6a25d793e7b119ffe572ba16 --- /dev/null +++ b/submissions_extracted/120/Q2.ipynb @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/120/Q3.ipynb b/submissions_extracted/120/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a7562315f2e3808b9199625358e84b659dbe6db2 --- /dev/null +++ b/submissions_extracted/120/Q3.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.read_csv(path + \"/Q3_data.csv\")\n", + "df.head" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df_/Q1_data.dropna(subset=stat-cols).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "for col in ['manufacturer', 'condition', 'fuel', 'transmission', 'type']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "df_clean['cylinders'] = df_clean['cylinders'].fillna(df_clean['cylinders'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/121/Q1.ipynb b/submissions_extracted/121/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7fa34a9cd445dcb20e4cf6e80bbf309fc7a515ab --- /dev/null +++ b/submissions_extracted/121/Q1.ipynb @@ -0,0 +1,399 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x = os.path.join(path, 'Q1_data.csv')\n", + "xx = pd.read_csv(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Shape: {xx.shape}\")\n", + "xx.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "xx.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "xx.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "xx.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (xx.isnull().sum() / len(xx)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(xx):\n", + " duplicates = xx.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " xx.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(xx)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n", + "df_clean = xx[cols].copy()\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Courier_Experience_yrs', 'Time_of_Day','Traffic_Level','Weather'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Separating target variable and features...\")\n", + "X = xx.drop('Delivery_Time', axis=1)\n", + "y = xx['Delivery_Time']\n", + "\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "\n", + "print(\"Verification of encoded data shapes:\")\n", + "print(f\"Shape of X_encoded: {X_encoded.shape}\")\n", + "print(f\"Shape of y_encoded: {y_encoded.shape}\")\n", + "\n", + "print(\"First 5 rows of X_encoded:\")\n", + "display(X_encoded.head())\n", + "print(\"First 5 elements of y_encoded:\")\n", + "print(y_encoded[:5])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_encoded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = X_encoded.drop(\"Courier_Experience_yrs_nan\", axis=1).astype(float)\n", + "y = X_encoded['Courier_Experience_yrs_nan'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error as sklearn_mse, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(xx)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.linear_model import Ridge, Lasso\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n", + " \"Support Vector Machine\": SVR(kernel='rbf'),\n", + " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = ['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = ['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = xx.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/121/Q2.ipynb b/submissions_extracted/121/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6af144ef5b36b7f9c6cb62a96488fbff5ae717a1 --- /dev/null +++ b/submissions_extracted/121/Q2.ipynb @@ -0,0 +1,230 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/121/Q3.ipynb b/submissions_extracted/121/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9ae0e61c65c60e33b711541a30e1532363a6f5b4 --- /dev/null +++ b/submissions_extracted/121/Q3.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x = os.path.join(path, 'Q3_data.csv')\n", + "xx = pd.read_csv(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Shape: {xx.shape}\")\n", + "xx.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "xx.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "xx.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (xx.isnull().sum() / len(xx)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(xx):\n", + " duplicates = xx.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " xx.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(xx)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3',\t'D_41',\t'B_3',\t'D_42',\t'D_43',\t'D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145',\t'Target']\n", + "df_clean = xx[cols].copy()\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['D_87', 'D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Separating target variable and features...\")\n", + "X = xx.drop('Target', axis=1)\n", + "y = xx['Target']\n", + "\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=get_feature_names_out(X.columns))\n", + "\n", + "print(\"Verification of encoded data shapes:\")\n", + "print(f\"Shape of X_encoded: {X_encoded.shape}\")\n", + "print(f\"Shape of y_encoded: {y_encoded.shape}\")\n", + "onehot_encoder\n", + "print(\"First 5 rows of X_encoded:\")\n", + "display(X_encoded.head())\n", + "print(\"First 5 elements of y_encoded:\")\n", + "print(y_encoded[:5])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(xx, 'Target')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = X_encoded.drop(\"D_145_nan\", axis=1).astype(float)\n", + "y = X_encoded['D_145_nan'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/122/Q1.ipynb b/submissions_extracted/122/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b0596413b428c9dc0f2bad06571e4617f17362b0 --- /dev/null +++ b/submissions_extracted/122/Q1.ipynb @@ -0,0 +1,333 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# bouns hot encode !" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"/content/Q1_data.csv\")\n", + "\n", + "# reading the data\n", + "df = pd.read_csv(csv_path)\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: checking the first few rows\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Showing statistical description:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: plotting the target dist\n", + "# What does our target variable (Delivery_Time) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Drop the 'Order_ID' column from the data:\n", + "\n", + "df_clean = df.drop(columns=\"Order_ID\").copy()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) ):\n", + "\n", + "# Do we have missing values?\n", + "def check_missing_values(df_clean):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_clean.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in categorical_cols:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill numerical columns with mean\n", + "df_clean['Delivery_Time'].fillna(df_clean[\"Delivery_Time\"].mean())\n", + "df_clean['Courier_Experience_yrs'].fillna(df_clean[\"Courier_Experience_yrs\"].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Check and remove duplicates if any exist:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Apply feature scaling for all features (Use StandardScaler):\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_clean) #show after scal" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: heck for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed):\n", + "\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df_clean, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_clean[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_clean[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier\n", + "# Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/122/Q2.ipynb b/submissions_extracted/122/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..24ec30e6022fea3bf9567c8dad3da497b6084c65 --- /dev/null +++ b/submissions_extracted/122/Q2.ipynb @@ -0,0 +1,365 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X, dtype=torch.float32)\n", + "X_test = torch.tensor(X, dtype=torch.float32)\n", + "y_train = torch.tensor(y, dtype=torch.long)\n", + "y_test = torch.tensor(y, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# create our datasets\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Create our DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=True)\n", + "\n", + " # num_workers=2 ?\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:Create a model class with 4 linear layers\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)#\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim) #\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim) #\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim) #\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x) #\n", + " a1 = self.relu(z1) #\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1) #\n", + " a2 = self.relu(z2) # <\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2) #\n", + " a3 = self.relu(z3) #\n", + "\n", + " # Output Layer TODO\n", + " z4 = self.layer4(a3) #\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) ##\n", + " y_batch = y_batch.to(device) ##\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 * 3 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9 (bc we have 10 classes)\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 5\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss() #\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate) #\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/122/Q3.ipynb b/submissions_extracted/122/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6c2ad8b006a264693eb410430788c4a2f1a64cfc --- /dev/null +++ b/submissions_extracted/122/Q3.ipynb @@ -0,0 +1,156 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/123/Q1.ipynb b/submissions_extracted/123/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c09225aaa73e5cdd1768e4224743c1a7f85e508d --- /dev/null +++ b/submissions_extracted/123/Q1.ipynb @@ -0,0 +1,225 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(\"Order_ID\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0 ])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = stat_cols + ['total_stats', 'Delivery_Time', 'type1', 'type2']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = RandomForestClassifier(n_estimators=100, max_depth=15," + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/123/Q2.ipynb b/submissions_extracted/123/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5effebf54ce303567bf8181f67e23b071c5b3c52 --- /dev/null +++ b/submissions_extracted/123/Q2.ipynb @@ -0,0 +1,267 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = MNIST(\n", + "root='./datasets',\n", + "train=True,\n", + "transform=to_tensor,\n", + "download=True\n", + "\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "test_dataset = MNIST(\n", + " root='./datasets',\n", + " train=False,\n", + " transform=to_tensor,\n", + " download=True\n", + "\n", + " )\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = (root='./datasets', train=True, transform=to_tensor, download=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " return z4\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.train()\n", + "\n", + "running_loss = 0.0\n", + "\n", + "optimizer.zero_grad()\n", + "loss.backward()\n", + "optimizer.step()\n", + "\n", + "running_loss += loss.item()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/123/Q3.ipynb b/submissions_extracted/123/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..14a2b39be7f527e6f2a9567597239f2d447623d6 --- /dev/null +++ b/submissions_extracted/123/Q3.ipynb @@ -0,0 +1,203 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0 ])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/124/Q1.ipynb b/submissions_extracted/124/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..adf69ea941ec3a697f183eb63d2673eeb2df7cda --- /dev/null +++ b/submissions_extracted/124/Q1.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "import os\n", + "tqdm.pandas()\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "from sklearn.linear_model import Ridge, Lasso\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "\n", + "\n", + "import warnings\n", + "warnings.simplefilter(action='ignore', category=FutureWarning)\n", + "pd.options.mode.chained_assignment = None # default='warn'\n", + "#pd.set_option('display.float_format', lambda x: '%.3f' % x)\n", + "plt.rcParams[\"figure.figsize\"] = (12, 8)\n", + "pd.set_option('display.max_columns', None)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Read the dataset Q1_data.csv using read_csv()\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "food_df = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "food_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "food_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "food_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"fast {food_df['Delivery_Time'].sum()}\")\n", + "print(f\"slow {(food_df['Delivery_Time'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Drop the 'Order_ID' column from the data\n", + "df_clean =food_df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(food_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(food_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features = food_df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "food_df[features] = scaler.fit_transform(food_df[features])\n", + "food_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(food_df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Split the dataset into features (X) and target (y)\n", + "feature_cols = ['Distance_km', 'Weather', 'Time_of_Day', 'Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "skf = KFold(n_splits=5)\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "def mean_absolute_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Plot feature importance from your trained model\n", + "# Retrieve CatBoost feature importances and sort them\n", + "catboost_model = models[\"CatBoost Classifier\"]\n", + "catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n", + "sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_catboost_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Plot predicted delivery time histogram\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/124/Q2.ipynb b/submissions_extracted/124/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..50c9aef94953a54265d3c97b5a7caf4545b37548 --- /dev/null +++ b/submissions_extracted/124/Q2.ipynb @@ -0,0 +1,329 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import AdamW\n", + "\n", + "\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "# Loop\n", + "for epoch in range(10):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer)\n", + " val_loss = validate_step(model, test_loader, criterion)\n", + " print(f\"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/124/Q3.ipynb b/submissions_extracted/124/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e61b097ae0fad88fbac45a0450b31ba82cee96d3 --- /dev/null +++ b/submissions_extracted/124/Q3.ipynb @@ -0,0 +1,247 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "import pandas as pd\n", + "import os\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pay_path = os.path.join(path, 'Q3_data.csv')\n", + "pay_df = pd.read_csv(pay_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "pay_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "pay_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:food_df.head()\n", + "pay_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(pay_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(pay_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#no need all coloums are numerical." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "data_scaled = scaler.fit_transform(df[numerical_cols])\n", + "data_scaled = scaler.transform(df[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(pay_df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['P_2']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = KFold(n_splits=5)\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "def mean_absolute_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "mae = mean_absolute_error(y_test, y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot feature importances\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print('golden feature')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/125/Q1.ipynb b/submissions_extracted/125/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b5e751101486cd423114cea4cdb2e7439d29dfeb --- /dev/null +++ b/submissions_extracted/125/Q1.ipynb @@ -0,0 +1,314 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error, classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_foodDel = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(f\"shape: {df_foodDel.shape}\")\n", + "df_foodDel.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_foodDel.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_foodDel.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(f\"Delivery_Time: {df_foodDel['Delivery_Time'].sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_foodDel = df_foodDel.drop(columns=['Order_ID'])\n", + "\n", + "df_foodDel" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_foodDel)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#missing values = [Weather, Traffic_Level, Time_of_Day, Courier_Experience_yrs, Delivery_Time]\n", + "df_foodDel['Weather'] = df_foodDel['Weather'].fillna('Clear')\n", + "df_foodDel['Traffic_Level'] = df_foodDel['Traffic_Level'].fillna('Low')\n", + "df_foodDel['Courier_Experience_yrs'] = df_foodDel['Courier_Experience_yrs'].fillna('0')\n", + "df_foodDel['Delivery_Time'] = df_foodDel['Delivery_Time'].fillna('0')\n", + "\n", + "df_foodDel" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_foodDel)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_foodDel.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_foodDel[col] = le.fit_transform(df_foodDel[col].astype(str))\n", + "\n", + "df_foodDel" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df_foodDel.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to scale the numerical columns\n", + "df_foodDel[numerical_cols] = scaler.fit_transform(df_foodDel[numerical_cols])\n", + "\n", + "df_foodDel.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "#we will use check_target_imbalance function to check automatic for saving time\n", + "#it will give us how much by % the data appear for seeing if it's balance or not\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_foodDel, \"Delivery_Time\")\n", + "\n", + "#so, the data is balance because there is no Delivery_Time that take like 60% or heigher" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_foodDel.drop('Delivery_Time', axis = 1).astype(float)\n", + "y = df_foodDel['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Task 2\n", + "#kf = KFold(n_splits= 5, shuffle=True, random_state=42)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"time in Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"time in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "# Task 3\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Task 4\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae_scores = []\n", + "\n", + "mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "# Task 5\n", + "\n", + "for train_idx, test_idx in kf.split(X_scaled):\n", + " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "model.fit(X_train, y_train)\n", + "\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/125/Q2.ipynb b/submissions_extracted/125/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/125/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/125/Q3.ipynb b/submissions_extracted/125/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/125/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/126/Q1.ipynb b/submissions_extracted/126/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3beeba3a6c6596fb1fb6455fc01a2723863ffa72 --- /dev/null +++ b/submissions_extracted/126/Q1.ipynb @@ -0,0 +1,236 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data types and structure\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=50, edgecolor='black')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df.drop(columns=\"Order_ID\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "df.drop_duplicates(inplace=True)\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/126/Q2.ipynb b/submissions_extracted/126/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8dcd9cd4a1f88b833139e770a0b27546bc631171 --- /dev/null +++ b/submissions_extracted/126/Q2.ipynb @@ -0,0 +1,399 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + " # Layer 1:\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " z4 = self.layer5(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + "\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + " #Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(10):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer)\n", + " val_loss = validate_step(model, test_loader, criterion)\n", + " print(f\"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}\")\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/126/Q3.ipynb b/submissions_extracted/126/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/126/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/127/Q1.ipynb b/submissions_extracted/127/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5016fefa269a25ca40c1d6711bebb4a1ae53fed1 --- /dev/null +++ b/submissions_extracted/127/Q1.ipynb @@ -0,0 +1,329 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['(delivery_time)'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Year Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Order_ID\", axis=1).astype(float)\n", + "y = df['Sales'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs',\n", + " 'Delivery_Time']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs',\n", + " 'Delivery_Time']\n", + "df= df[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df.shape}\")\n", + "df = df.dropna(subset=['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs',\n", + " 'Delivery_Time'])\n", + "print(f\"After dropping missing price/year/odometer: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs',\n", + " 'Delivery_Time']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=50, max_depth=10, random_state=42,)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/127/Q2.ipynb b/submissions_extracted/127/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ba2b568d323977f1d7e6f0ce9f76706427cc14e9 --- /dev/null +++ b/submissions_extracted/127/Q2.ipynb @@ -0,0 +1,403 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(4):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels_df[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36* 36 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 3 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs: Training batch input shape: torch.Size([32, 3, 36, 36])\n", + "#Training batch labels shape: torch.Size([32])\n", + "\n", + " #Image shape: torch.Size([3, 36, 36])\n", + "Label: 14\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/127/Q3.ipynb b/submissions_extracted/127/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..813a02d1859333b038b963535b553a8b6915fc29 --- /dev/null +++ b/submissions_extracted/127/Q3.ipynb @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.dropna(subset=['D_87', 'D_88', 'B_39', \"D_110\", \"D_111\", \"D_108\",\"B_42\" ,\"D_73\", \"D_135\", \"D_136\" ])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = [\"P_2\",\t\"D_39\",\t\"B_1\",\t\"B_2\",\t\"R_1\",\t\"S_3\",\t\"D_41\",]\n", + "\n", + "X = df[feature_cols]\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/128/Q1.ipynb b/submissions_extracted/128/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a8ea2528b99449c25ec3f706f93c01dc52085a56 --- /dev/null +++ b/submissions_extracted/128/Q1.ipynb @@ -0,0 +1,284 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Import Required Libraries\n", + "import numpy as np\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "#Load CSV file\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data types and structure\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Distance_km'].dropna(), bins=45, edgecolor='black')\n", + "plt.title('Dilevery time')\n", + "plt.xlabel('Distance_km')\n", + "plt.ylabel('Dilevery time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Select relevant columns\n", + "cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_food[cols].copy()\n", + "# Drop cols where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.drop(columns=['Order_ID'])\n", + "print(f\"After dropping missing Order_ID: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill Delivery_Time with mode - discrete feature, mode is most representative\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Analyze missing values\n", + "missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/128/Q2.ipynb b/submissions_extracted/128/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..54bde6cb3f70a6e560545415c4ad2f1c48e4dba4 --- /dev/null +++ b/submissions_extracted/128/Q2.ipynb @@ -0,0 +1,354 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/128/Q3.ipynb b/submissions_extracted/128/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..47a796213e8b8631a52459e246363a2978ac42ec --- /dev/null +++ b/submissions_extracted/128/Q3.ipynb @@ -0,0 +1,246 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "gold_path = os.path.join(path, 'Q3_data.csv')\n", + "df_gold = pd.read_csv(gold_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_gold.shape}\")\n", + "df_gold.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data types and structure\n", + "df_gold.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "df_gold.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "cols = ['P_2','D_39',\t'B_1',\t'B_2','R_1'\t,'S_3','D_41','B_3','D_42','D_43','D_137','D_138','D_139','D_140'\t,'D_141','D_142','D_143','D_144','D_145','Target']\n", + "df_clean = df_gold[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['D_42', 'D_137','D_138'])\n", + "print(f\"After dropping missing : {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['D_42','D_43','D_137','D_138','D_142']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "# Fill S_3 with mode - discrete feature, mode is most representative\n", + "df_clean['S_3'] = df_clean['S_3'].fillna(df_clean['S_3'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['B_1',\t'B_2','R_1'\t,'S_3']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_clean['B_1'] = 2026 - df_clean['S_3']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['P_2','D_39',\t'B_1',\t'B_2','R_1'\t,'S_3','D_41','B_3','D_42','D_43','D_137','D_138','D_139','D_140'\t,'D_141','D_142','D_143','D_144','D_145']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['P_2']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_gold['S_3'].dropna(), bins=45, edgecolor='black')\n", + "plt.title('importance')\n", + "plt.xlabel('x')\n", + "plt.ylabel('y')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_gold['B_1'].dropna(), bins=45, edgecolor='black')\n", + "plt.title('importance')\n", + "plt.xlabel('x')\n", + "plt.ylabel('y')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/129/Q1.ipynb b/submissions_extracted/129/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1cdeb395cf58176433e72d837a57db35817a5c3e --- /dev/null +++ b/submissions_extracted/129/Q1.ipynb @@ -0,0 +1,275 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import mean_absolute_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "path = os.path.join(path, 'Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=40, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns='Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.dropna(subset='Delivery_Time')\n", + "# there is nothing you can do when the target is missing, just drop. Any other strategy will introduce noise\n", + "\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean()) # i don't think this feature matter that much\n", + "\n", + "df[['Traffic_Level', 'Time_of_Day']] = df[['Traffic_Level', 'Time_of_Day']].fillna('unkown') # i think these features are really important, i don't want to hurt performance by filling them with mean or midean\n", + "\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df.duplicated().sum())\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "ohe = OneHotEncoder()\n", + "cat_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type']\n", + "\n", + "label_encoders = {}\n", + "for col in cat_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "df[df.columns] = scaler.fit_transform(df[df.columns])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# this is a regression task, what in the world would be target imbalance?" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns='Delivery_Time').astype(float)\n", + "y = df['Delivery_Time'].astype(float)\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "folds_error = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " folds_error.append(mae)\n", + "\n", + "print(\"averaged score across all folds: \", np.mean(folds_error))\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df.drop(columns='Delivery_Time').columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(pd.DataFrame(y_pred), bins=40, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/129/Q2.ipynb b/submissions_extracted/129/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..95246088b1828cb6eb505603b8e0d5d6457b85d5 --- /dev/null +++ b/submissions_extracted/129/Q2.ipynb @@ -0,0 +1,346 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "from torch.optim import Adam\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch.flatten(1)) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch.flatten(1)) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 32\n", + "output_dim = 1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "n_epochs = 20\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(n_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{n_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/129/Q3.ipynb b/submissions_extracted/129/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff274be7c59d787d5c71b01077a2ce35cfe76773 --- /dev/null +++ b/submissions_extracted/129/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# df = df.drop(columns=['D_87', 'D_88', 'D_110', 'B_39', 'D_111', 'D_108', 'B_42', 'D_73', 'D_138', 'D_136'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.fillna(0)\n", + "df.isna().sum().sort_values(ascending=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.duplicated().sum())\n", + "df = df.drop_duplicates()\n", + "print(df.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#all features are numbers, encoding not needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "df[df.drop(columns='Target').columns] = scaler.fit_transform(df[df.drop(columns='Target').columns])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(f\"Default: {df['Target'].sum()}\")\n", + "print(f\"No Default: {(df['Target'] == 0).sum()}\")\n", + "\n", + "# >>>>>>>>>>>>>>>>> the target is imbalanced <<<<<<<<<<<\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# %pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns='Target').astype(float)\n", + "y = df['Target'].astype(float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n = 8\n", + "skf = StratifiedKFold(n_splits=n, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + "f1_scores = []\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + " f1_scores.append(f1)\n", + "\n", + "print('Training done ^^')\n", + "\n", + "\n", + "print(\"averaged f1 score across all folds\", np.mean(f1_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df.drop(columns='Target').columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 50))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print('the golden feature is', 'P_2')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\n", + "X = df[['P_2']].astype(float)\n", + "y = df['Target'].astype(float)\n", + "\n", + "n = 8\n", + "skf = StratifiedKFold(n_splits=n, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + "f1_scores = []\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + " f1_scores.append(f1)\n", + "\n", + "print('Training done ^^')\n", + "print(\"averaged f1 score across all folds\", np.mean(f1_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# we astonomically reduced dimensenality and yet the f1 score difference is still good, we did not lose much" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/13/Q1.ipynb b/submissions_extracted/13/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b9e1db98916781550cba9dd933122dd6285164d5 --- /dev/null +++ b/submissions_extracted/13/Q1.ipynb @@ -0,0 +1,306 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df,\"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns()\n", + "\n", + "scaler= MinMaxScaler()\n", + "df[features] =scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(str)\n", + "y = df[\"Delivery_Time\"].astype(str)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "n_splits = 5\n", + "\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/13/Q2.ipynb b/submissions_extracted/13/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ba270ae9e1bd29ea7bcb9eebec319e040df698a --- /dev/null +++ b/submissions_extracted/13/Q2.ipynb @@ -0,0 +1,353 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch.nn as nn\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "import torch\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import Adam\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/13/Q3.ipynb b/submissions_extracted/13/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5270a7ae296bc03b93d8c8b0d0705d43c672c902 --- /dev/null +++ b/submissions_extracted/13/Q3.ipynb @@ -0,0 +1,207 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(str)\n", + "y = df[\"Delivery_Time\"].astype(str)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/130/Q1.ipynb b/submissions_extracted/130/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..52248467af82e4804c4ad845dd9dfbc51864401c --- /dev/null +++ b/submissions_extracted/130/Q1.ipynb @@ -0,0 +1,352 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Import Libraries\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Read the dataset Q1_data.csv using read_csv()\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:#Inspect the first few rows using head()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Plot the target distribution (delivery_time)\n", + "# target distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(df['Delivery_Time'].dropna())\n", + "plt.title('target Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# target distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=2, edgecolor='black')\n", + "plt.title('target Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Drop the 'Order_ID' column from the data\n", + "#delivery distance, restaurant preparation time, traffic conditions, and order details.\n", + "# Select relevant columns, we do not select 'Order_ID'\n", + "cols= ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df[cols].copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Handle missing values appropriately\n", + "# Do we have missing values?\n", + "def check_missing_values(df):\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "# Fill Courier_Experience_yrs with mode - discrete feature, mode is most representative\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "# Fill Delivery_Time with mode - discrete feature, mode is most representative\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "#Check for duplicates\n", + "def check_duplicates(df):\n", + "#TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables if needed\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "# Encode categorical columns - converts text to integers i try to make it with OneHotEncoder but i don't what is wrong\n", + "categorical_cols = pd.DataFrame({\"Weather\": ['Rainy', 'Snowy', 'Foggy', 'Clear', 'Windy'],\"Traffic_Level\":['Medium','Low','High'],\"Time_of_Day\":['Afternoon','Night','Evening'],\"Vehicle_Type\":['Scooter','Bike','Car']}) # DataFrame of one column\n", + "for col in categorical_cols:\n", + " oh = OneHotEncoder(sparse_output=False)\n", + " data_onehot_encoded = oh.fit_transform(col)\n", + "\n", + "data_onehot_encoded.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Split the dataset into features (X) and target (y)\n", + "# Define features and target\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "X = df_clean[cols].columns.drop(\"Delivery_Time\")\n", + "y = df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Use previously generated random data (example: regression data)\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "# Train RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + "class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "# Predictions and metrics\n", + "y_pred = model.predict(X_test)\n", + "\n", + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "from sklearn.metrics import mean_absolute_error\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Speed Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/130/Q2.ipynb b/submissions_extracted/130/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c6a0e40454660d9c178583e0ffcf5f0b4f9104ee --- /dev/null +++ b/submissions_extracted/130/Q2.ipynb @@ -0,0 +1,416 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors\n", + "# 2. Create TensorDataset objects\n", + "\n", + "# Training dataset\n", + "train_dataset = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = CIFAR10(root='./datasets', train=False, transform=to_tensor, download=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " # Layer 3 hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 32 * 32 # images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 #\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/130/Q3.ipynb b/submissions_extracted/130/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9cf91dd8131a88afcdbadcc33c2f903c6192c50e --- /dev/null +++ b/submissions_extracted/130/Q3.ipynb @@ -0,0 +1,262 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Import Libraries\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:Read the dataset Q3_data.csv using read_csv()\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 3: Write your code here:Display dataset information using info()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Do we have missing values?\n", + "def check_missing_values(df):\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Check for duplicates\n", + "def check_duplicates(df):\n", + "#TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols)) #no need encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Task 5: Write your code here:Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:Split the dataset into features (X) and target (y)\n", + "# Define features and target\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "X = df.columns.drop(\"Target\")\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#2.Use the correct split: KFold OR StratifiedKFold\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "#3. Train a CatBoostClassifier model\n", + "\n", + "#4. Evaluate using the appropriate metric only (Accuracy vs. F1 Score).\n", + "\n", + "#5. Print the averaged score across all folds" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/131/Q1.ipynb b/submissions_extracted/131/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fcd2709478cc7096ecc4a8655b5f458a1202538b --- /dev/null +++ b/submissions_extracted/131/Q1.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Data manipulation and analysis\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "# Data visualization\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Machine learning - preprocessing and evaluation\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "# Machine learning - regression models\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.svm import SVR\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "import xgboost as xgb\n", + "\n", + "# Suppress warnings for cleaner output\n", + "import warnings\n", + "warnings.simplefilter('ignore')\n", + "\n", + "# Set visualization style\n", + "sns.set_style('whitegrid')\n", + "plt.rcParams['figure.figsize'] = (12, 6)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.read_csv(path + \"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sns.set_style(\"whitegrid\")\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "\n", + "# Histogram\n", + "sns.histplot(df['Distance_km'], kde=True, color='blue', bins=30)\n", + "plt.title('Target Distribution of delivery_time', fontsize=16)\n", + "plt.xlabel('delivery_time', fontsize=12)\n", + "plt.ylabel('Frequency', fontsize=12)\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[['Order_ID']].dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# task 4 :\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "def encode_categorical_features(df, columns):\n", + " df_encoded = df.copy()\n", + " for col in columns:\n", + " # Initialize OneHotEncoder, handling unknown categories with ignore\n", + " # and setting sparse_output to False for dense array output\n", + " one_hot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + " # Fit and transform the column, then create a DataFrame for the new columns\n", + " encoded_data = one_hot_encoder.fit_transform(df_encoded[[col]])\n", + " encoded_df = pd.DataFrame(encoded_data, columns=one_hot_encoder.get_feature_names_out([col]), index=df_encoded.index)\n", + "\n", + " # Concatenate the new one-hot encoded columns and drop the original column\n", + " df_encoded = pd.concat([df_encoded, encoded_df], axis=1)\n", + " df_encoded = df_encoded.drop(col, axis=1)\n", + "\n", + " print(f\"Encoded '{col}' into new columns: {list(one_hot_encoder.get_feature_names_out([col]))}\")\n", + " return df_encoded\n", + "\n", + "categorical_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "\n", + "df_encoded = encode_categorical_features(df, categorical_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def scale_numerical_features(df, numerical_cols):\n", + "\n", + " scaler = StandardScaler()\n", + " df_scaled = df.copy()\n", + " df_scaled[numerical_cols] = scaler.fit_transform(df_scaled[numerical_cols])\n", + " return df_scaled, scaler\n", + "\n", + "numerical_features_to_scale = ['Courier_Experience_yrs','Delivery_Time']\n", + "# Apply scaling to the selected numerical features using the function\n", + "df_scaled, scaler = scale_numerical_features(df_encoded, numerical_features_to_scale)\n", + "df_scaled.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'].fillna(df['Delivery_Time'].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plot_df = df[['Distance_km', 'Time_of_Day','Delivery_Time']].dropna()\n", + "plt.figure()\n", + "plt.scatter(\n", + " plot_df['Distance_km'],\n", + " plot_df['Time_of_Day'],\n", + " c=plot_df['Delivery_Time']\n", + ")\n", + "plt.xlabel('PT08.S1(CO)')\n", + "plt.ylabel('PT08.S2(NMHC)')\n", + "plt.title('Sensor Responses Colored by CO(GT)')\n", + "plt.colorbar(label='Delivery_Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred, bins=20, color='skyblue', edgecolor='black')\n", + "plt.title(\"Histogram of Validation Predictions\")\n", + "plt.xlabel(\"Predicted Value\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(axis='y', linestyle='--', alpha=0.7)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/131/Q2.ipynb b/submissions_extracted/131/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2873cc509c0f2a4044f959c6edd273c4557e025c --- /dev/null +++ b/submissions_extracted/131/Q2.ipynb @@ -0,0 +1,422 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.read_csv(path + \"/labels.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df[col] = le.fit_transform(df[col])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# TODO: Split features from target\n", + "X = df.drop(\"age\",axis=1)\n", + "y = df['age']\n", + "\n", + "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/131/Q3.ipynb b/submissions_extracted/131/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9aa058eaf581daa7b314a7f132b1d69a54edfb2a --- /dev/null +++ b/submissions_extracted/131/Q3.ipynb @@ -0,0 +1,226 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# from the data i see we dont need\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "for col in df.columns:\n", + " if df[col].dtype == 'object':\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "def scale_numerical_features(df, numerical_cols):\n", + "\n", + " scaler = StandardScaler()\n", + " df_scaled = df.copy()\n", + " df_scaled[numerical_cols] = scaler.fit_transform(df_scaled[numerical_cols])\n", + " return df_scaled, scaler\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/132/Q1.ipynb b/submissions_extracted/132/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f1a1c0d784011257aea01a8d13fc8be524586e3b --- /dev/null +++ b/submissions_extracted/132/Q1.ipynb @@ -0,0 +1,422 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "from IPython.display import clear_output\n", + "clear_output()\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# مكتبات scikit-learn\n", + "from sklearn.model_selection import train_test_split, KFold ,r2_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder ,MinMaxScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.dummy import DummyClassifier\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings(\"ignore\")\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:y=df['score']#target\n", + "\n", + "X=df.drop('Delivery_Time',axis=1)\n", + "y=df['Delivery_Time']#target\n", + "\n", + "# delivery_time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Preparation_Time_min')\n", + "plt.ylabel('Distance_km')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df= df.drop('Order_ID', axis=1)# there is an error but the column has already droped" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "ohe = OneHotEncoder(sparse_output=False)\n", + "df_encoded = pd.DataFrame(ohe.fit_transform(df[[\"Preparation_Time_min\"]]), columns=ohe.get_feature_names_out([\"Preparation_Time_min\"]))\n", + "print(df_encoded)\n", + "\n", + "#le = LabelEncoder()\n", + "#df[\"Preparation_Time_min\"] = le.fit_transform(df[\"Preparation_Time_min\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#split first\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42 , stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"distance in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "#standard scaler يعتمد على المسافات والرجرشن\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, Delivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df[Delivery_Time].value_counts(normalize=True))\n", + " sns.countplot(x=df[Delivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "y=df['Delivery_Time']#target\n", + "X=df.drop('Delivery_Time',axis=1)\n", + "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, shuffle=True, random_state=42)\n", + "\n", + "model = LinearRegression()\n", + "\n", + "model.fit(X_train, y_train)\n", + "\n", + "y_pred = model.predict(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#k fold\n", + "\n", + " # لو ارقام هذا مع الرجرشن\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " # Train RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Mean Absolute Error\n", + "from sklearn.metrics import mean_absolute_error\n", + "def mean_absolute_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y))\n", + "\n", + " def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_absolute_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)\n", + "\n", + " average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n", + "\n", + "print(\"Linear Regression Results\")\n", + "print(f\" Average MSE: {np.mean(lr_mse):.4f}\")\n", + "print(f\" Average RMSE: {np.mean(lr_rmse):.4f}\")\n", + "print(f\" Average R2: {np.mean(lr_r2):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.hist(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)],\n", + " [min(y_test), max(y_test)],\n", + " 'r--', linewidth=2)\n", + "\n", + "plt.xlabel(\"Actual y_test \")\n", + "plt.ylabel(\"Predicted y_pred \")\n", + "plt.title(\"Predictions of devlivery time\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/132/Q2.ipynb b/submissions_extracted/132/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9076e738d6fe725c8069c0401f88214363f6ec83 --- /dev/null +++ b/submissions_extracted/132/Q2.ipynb @@ -0,0 +1,415 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "df (X_train.astype(\"torch))\n", + "df(X_test.astype(\"torch\"))\n", + "df(y_train.astype(\"torch\"))\n", + "df(y_test.astype(\"torch\"))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch._C import TensorType\n", + "# 3. Create DataLoaders\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "#validation\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "#train and evaluate\n", + "\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "mse = mean_squared_error(y_test.numpy(), predictions)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/132/Q3.ipynb b/submissions_extracted/132/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7fdd0a368bc010b520ac79b96f9bd914f1017f9f --- /dev/null +++ b/submissions_extracted/132/Q3.ipynb @@ -0,0 +1,344 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "!pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "from IPython.display import clear_output\n", + "clear_output()\n", + "\n", + "# استيراد المكتبات الأساسية\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# مكتبات scikit-learn\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder ,MinMaxScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.dummy import DummyClassifier\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings(\"ignore\")\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df[\"D_137\"] = df[\"D_137\"].fillna(df[\"D_137\"].mean())\n", + "df[\"D_39\"] = df[\"D_39\"].fillna(df[\"D_39\"].mean())\n", + "\n", + "df[\"D_138\"] = df[\"D_138\"].fillna(df[\"D_138\"].mean())\n", + "df[\"D_139\"] = df[\"D_139\"].fillna(df[\"D_139\"].mean())\n", + "df[\"D_140\t\"] = df[\"D_140\"].fillna(df[\"D_140\t\"].mean())\n", + "df[\"D_141\t\"] = df[\"D_141\"].fillna(df[\"D_141\t\"].mean())\n", + "df[\" D_143\"] = df[\" D_143\"].fillna(df[\" D_143\"].mean())\n", + "df[\"Target\"] = df[\"Target\"].fillna(df[\"Target\"].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "le = LabelEncoder()\n", + "df[\"D_43\"] = le.fit_transform(df[\"D_43\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#split first\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42 , stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"distance in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "#standard scaler يعتمد على المسافات والرجرشن\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df[\"Target\"].value_counts()#عد القيم لكل فئه\n", + "df[\"Target\"].value_counts(normalize=True)#نسب مئويه من1" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "y=df['Target']#target\n", + "x=df.drop('Target',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#StratifiedKFold for classification\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# مثال: استخدام البيانات السابقة للتصنيف\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# عرض توزيع الفئات في كامل البيانات\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\"y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"_\" * 40)\n", + "\n", + "# تعريف Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"_\" * 40)\n", + "\n", + "# تكرار عبر الطيات\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # تقسيم البيانات لكل طية\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # طباعة أشكال البيانات\n", + " print(f\"Fold {fold}\")\n", + " print(\"X_train shape:\", X_train.shape)\n", + " print(\"X_test shape:\", X_test.shape)\n", + " print(\"y_train shape:\", y_train.shape)\n", + " print(\"y_test shape:\", y_test.shape)\n", + "\n", + " # عرض توزيع الفئات لكل Fold\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + " print(\"y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\"y_test class percentages:\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + " print(\"_\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install xgboost\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + " model =(\"CatBoost\": CatBoostClassifier\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + " results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [],\n", + " for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1), , 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:D_140" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/133/Q1.ipynb b/submissions_extracted/133/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d62d6f4657bb8b1dc464e25ebcadea026a68b76e --- /dev/null +++ b/submissions_extracted/133/Q1.ipynb @@ -0,0 +1,390 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import os\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Load the dataset from CSV file\n", + "dil_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(dil_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Is the target imbalanced?\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day'\t,'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "lr_losses = []\n", + "\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " #Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': feature_importance\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Delivery_Time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Price')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/133/Q2.ipynb b/submissions_extracted/133/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f35ec09f709ff267b0dba1dc8baa3e399d14267e --- /dev/null +++ b/submissions_extracted/133/Q2.ipynb @@ -0,0 +1,480 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load the dataset from CSV file\n", + "labels_df = pd.read_csv(os.path.join(path, \"/kaggle/input/q2-exam-data/labels.csv\"))\n", + "img_dir = os.path.join(path, \"labels_df\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset =MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + " #DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Performance ', fontsize=12)\n", + "plt.ylabel('Predicted Performance ', fontsize=12)\n", + "plt.title('Performance', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/133/Q3.ipynb b/submissions_extracted/133/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..58e4b2e056b344a5d246cce66a0fccf3a56fc102 --- /dev/null +++ b/submissions_extracted/133/Q3.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=[missing_values])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(columns=['col'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'f1': []}\n", + "\n", + " n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + "\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/134/Q1.ipynb b/submissions_extracted/134/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a91e4f1973f4d8e82eae4cf5c6617a6f316c889f --- /dev/null +++ b/submissions_extracted/134/Q1.ipynb @@ -0,0 +1,314 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "#/kaggle/input/q1-exam-data/Q1_data.csv\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#target distribution (delivery_time)\n", + "# ماعرفت اضبط التوقيت بالقراف بحيث يكون مضبوط\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=12, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "df_clean.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum())\n", + "#عبيت القيم الفاضية للDelivery_Time بالمتوسط الحسابي\n", + "df_clean['Delivery_Time']= df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].median())\n", + "#عبيت القيم الفاضية Courier_Experience_yrs بالمتوسط الحسابي\n", + "df_clean['Courier_Experience_yrs']=df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].median())\n", + "#عبيت القيم الفاضية Time_of_Day  بعبارة unknown\n", + "df_clean['Time_of_Day']=df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna('unknown')\n", + "df_clean['Traffic_Level']=df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna('Medium')\n", + "\n", + "df_clean['Weather']=df_clean['Weather'] = df_clean['Weather'].fillna('Clear')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "##Check and remove duplicates\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Split the dataset into features (X) and target (y)\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "feature_cols = ['Order_ID','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train_scaled, y_train)\n", + " print(\"Model trained!\")\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/134/Q2.ipynb b/submissions_extracted/134/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b86d7dccb22ec7ee8fbd7a8a5d8f661d36d3b389 --- /dev/null +++ b/submissions_extracted/134/Q2.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "from torch.optim import Adam\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 14\n", + "output_dim = 4\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "############################################\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/134/Q3.ipynb b/submissions_extracted/134/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d0b73118d07ed3e64a2e4a31220c95b5aab4e28c --- /dev/null +++ b/submissions_extracted/134/Q3.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/135/Q1.ipynb b/submissions_extracted/135/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f23de3bf92c161bdd07a8925e966fb1196d7ce63 --- /dev/null +++ b/submissions_extracted/135/Q1.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "# If someone is reading this and is not just throwing this through unit tests,\n", + "# I do want to apologize for the lack of comments, I've had to juggle studying with work and my brain is too fried to explain.\n", + "# I've kept most things within the scope of the course. I've also relied on the labs quite a bit\n", + "path = path + '/Q1_data.csv'\n", + "df = pd.read_csv(path)\n", + "\n", + "print(\"Dataset loaded successfully into DataFrame 'df' from the /content/ directory.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "display(df.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(df['Delivery_Time'], kde=True, bins=50)\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop('Order_ID', axis=1)\n", + "\n", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(\"Missing values before handling:\")\n", + "display(df.isnull().sum())\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " if df[col].isnull().any():\n", + " mode_value = df[col].mode()[0]\n", + " df[col] = df[col].fillna(mode_value)\n", + "\n", + "if df['Courier_Experience_yrs'].isnull().any():\n", + " median_value = df['Courier_Experience_yrs'].median()\n", + " df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(median_value)\n", + "\n", + "initial_rows = len(df)\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "dropped_rows = initial_rows - len(df)\n", + "\n", + "\n", + "display(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "duplicates_before = df.duplicated().sum()\n", + "\n", + "if duplicates_before > 0:\n", + " df.drop_duplicates(inplace=True)\n", + " duplicates_after = df.duplicated().sum()\n", + " print('Dupes removed')\n", + "else:\n", + " print(\"No duper\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#I was going to use one-hot but, honestly, get_dummy feels more intuitive to me.\n", + "categorical_cols = df.select_dtypes(include='object').columns\n", + "if len(categorical_cols) > 0:\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + "\n", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns, index=X.index)\n", + "\n", + "X_scaled.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = X_scaled" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import KFold\n", + "\n", + "kf = KFold(n_splits=6, shuffle=True, random_state=21)\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_index, test_index in kf.split(X):\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "average_mae = np.mean(mae_scores)\n", + "\n", + "print(f\"MAE for each fold: {mae_scores}\")\n", + "print(f\"Averaged Mean Absolute Error across all folds: {average_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "feature_importances = model.feature_importances_\n", + "features = X.columns\n", + "importance_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances})\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "plt.figure()\n", + "sns.barplot(x='Importance', y='Feature', data=importance_df)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(y_pred, kde=True, bins=30, color = 'red') #wanted a red colour for this one :)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/135/Q2.ipynb b/submissions_extracted/135/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..15b4e4ae65b4b0532113271bab4b07203a5840bf --- /dev/null +++ b/submissions_extracted/135/Q2.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# If someone is reading this and is not just throwing this through unit tests,\n", + "# I do want to apologize for the lack of comments, I've had to juggle studying with work and my brain is too fried to explain.\n", + "# I've kept most things within the scope of the course. I've also relied on the labs quite a bit\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "X_train_tensor = torch.from_numpy(X_train).float()\n", + "X_test_tensor = torch.from_numpy(X_test).float()\n", + "y_train_tensor = torch.from_numpy(y_train).float().view(-1, 1)\n", + "y_test_tensor = torch.from_numpy(y_test).float().view(-1, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "batch_size = 32\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for images, labels in train_loader:\n", + " print(f\"Shape of one batch of images: {images.shape}\")\n", + " print(f\"Shape of one batch of labels: {labels.shape}\")\n", + " break # I did this so I only get the first. I am feeling quite fried." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataiter = iter(train_loader)\n", + "images, labels = next(dataiter)\n", + "\n", + "images_np = images.numpy().transpose(0, 2, 3, 1)\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " ax = axes[i]\n", + " ax.imshow(images_np[i])\n", + "\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class AgePredictorCNN(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictorCNN, self).__init__()\n", + " self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)\n", + " self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n", + " self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)\n", + " self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)\n", + " self.conv4 = nn.Conv2d(64, 128, kernel_size=3, padding=1)\n", + " self.fc_input_size = (128 * 2 * 2)\n", + " self.fc1 = nn.Linear(self.fc_input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + "\n", + " def forward(self, x):\n", + " x = self.pool(F.relu(self.conv1(x)))\n", + " x = self.pool(F.relu(self.conv2(x)))\n", + " x = self.pool(F.relu(self.conv3(x)))\n", + " x = self.pool(F.relu(self.conv4(x)))\n", + "\n", + " x = x.view(-1, self.fc_input_size)\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_epoch(model, dataloader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for batch_idx, (images, labels) in enumerate(dataloader):\n", + " images, labels = images.to(device), labels.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(images)\n", + " loss = loss_fn(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate_epoch(model, dataloader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for images, labels in dataloader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + "\n", + " loss = loss_fn(outputs, labels)\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "model = AgePredictorCNN().to(device)\n", + "print(model)\n", + "loss_fn = nn.MSELoss()\n", + "learning_rate = 0.001\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " avg_train_loss = train_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " avg_val_loss = validate_epoch(model, test_loader, loss_fn, device)\n", + " train_losses.append(avg_train_loss)\n", + " val_losses.append(avg_val_loss)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "plt.figure()\n", + "plt.plot(train_losses, label='Training Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "fig, axes = plt.subplots(1, 5, figsize=(20, 4))\n", + "\n", + "dataiter = iter(test_loader)\n", + "images, actual_labels = next(dataiter)\n", + "\n", + "images = images.to(device)\n", + "actual_labels = actual_labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " predicted_labels = model(images)\n", + "\n", + "images_np = images.cpu().numpy().transpose(0, 2, 3, 1)\n", + "\n", + "actual_labels_np = actual_labels.cpu().numpy()\n", + "predicted_labels_np = predicted_labels.cpu().numpy()\n", + "\n", + "\n", + "for i in range(5):\n", + " ax = axes[i]\n", + " ax.imshow(images_np[i])\n", + " ax.set_title(f\"Actual: {int(actual_labels_np[i].item())}\\nPredicted: {predicted_labels_np[i].item():.1f}\")\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/135/Q3.ipynb b/submissions_extracted/135/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f9a4c1052ac77533a9d60ad6fae2dc497b57ba82 --- /dev/null +++ b/submissions_extracted/135/Q3.ipynb @@ -0,0 +1,260 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "%pip install catboost -q\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "\n", + "\n", + "full_path = path + \"/Q3_data.csv\"\n", + "df = pd.read_csv(full_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "print('pre-cleaning: \\n')\n", + "check_missing_values(df)\n", + "\n", + "\n", + "df_clean = df.dropna(axis=1)\n", + "\n", + "print('\\n\\npost-cleaning:')\n", + "check_missing_values(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols)) # Since there are no categorical variables, no categorical encoding necessary (If we did we could just use one hot scaler.)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "X_scale = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\") # I am fairly certain that it is imbalanced with a heavy skew towards 0." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_clean.drop(\"Target\", axis=1).astype(float)\n", + "y = df_clean['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "import numpy as np\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'f1': []}\n", + "\n", + "skf = StratifiedKFold(n_splits=6, shuffle=True, random_state=64)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{6}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['f1'].append(f1)\n", + "print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Out of Time anything that works here is fine!!\n", + "\n", + "importances= {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 60))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# D47 as per our graph" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/136/Q1.ipynb b/submissions_extracted/136/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5197f4ce187f7dabb5a9f0fc0c35e5c2318c68e9 --- /dev/null +++ b/submissions_extracted/136/Q1.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(['Order_ID'], axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categories = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "for col in categories:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler =StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Distribution')\n", + "plt.xlabel('Delivery')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "#it is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)\n", + "\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_erro" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/136/Q2.ipynb b/submissions_extracted/136/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..067d246e5204a679c6e5cdfeff5462c6faf75d0e --- /dev/null +++ b/submissions_extracted/136/Q2.ipynb @@ -0,0 +1,416 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Second hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3888\n", + "hidden_dim = 14\n", + "output_dim = 10\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/136/Q3.ipynb b/submissions_extracted/136/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b8ab15436143bb75a48ddf930a263ecef211714c --- /dev/null +++ b/submissions_extracted/136/Q3.ipynb @@ -0,0 +1,211 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_path)\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categories = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "for col in categories:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categories = ['D_42','D_49','D_43','D_142']\n", + "for col in categories:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler =StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/137/Q1.ipynb b/submissions_extracted/137/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2c023d7f778b4807c944f74655218d69f956dbe3 --- /dev/null +++ b/submissions_extracted/137/Q1.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Food Delivery Time')\n", + "plt.xlabel('time')\n", + "plt.ylabel('time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', Traffic_Level)\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=True)\n", + "#data_onehot_encoded = onehot_encoder.fit_transform(Traffic_Level)\n", + "\n", + "#print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', Preparation_Time_min)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(Preparation_Time_min)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "food = [\"Distance_km\" ,\"Weather\", \"Traffic_Level\",\t\"Time_of_Day\",\t\"Vehicle_Type\",\t\"Preparation_Time_min\", \"Courier_Experience_yrs\"]\n", + "X = df[food]\n", + "y = df['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('Food Delivery Time')\n", + "plt.xlabel('food')\n", + "plt.ylabel('Delivery Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='blue')\n", + "plt.title('Food Delivery Time')\n", + "plt.xlabel('Weather')\n", + "plt.ylabel('Distance_km')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/137/Q2.ipynb b/submissions_extracted/137/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..58398d48d8e061f7e7b6d6fa108f5376b5ed61df --- /dev/null +++ b/submissions_extracted/137/Q2.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "#plt.plot(train_losses, label='Train Loss')\n", + "#plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/137/Q3.ipynb b/submissions_extracted/137/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ba4c23e7464e3b8a8564ec7c63a85367870e4a9c --- /dev/null +++ b/submissions_extracted/137/Q3.ipynb @@ -0,0 +1,233 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df['D_42'] = le.fit_transform(df['D_42'])\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"D_42\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "golden = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3']\n", + "X = df[golden]\n", + "y = df['Target']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=30, edgecolor='black', color='orange')\n", + "plt.title('fueature golden')\n", + "plt.xlabel('feature')\n", + "plt.ylabel('garden')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/138/Q1.ipynb b/submissions_extracted/138/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3dcfbe01236e84b4971931414bd56e946569f3aa --- /dev/null +++ b/submissions_extracted/138/Q1.ipynb @@ -0,0 +1,267 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "\n", + "# Drop rows where target (Delivery_Time) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_food.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Courier_Experience_yrs'])\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Time_of_Day', 'Traffic_Level']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "print(f\"After: {df_clean.shape}\")\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum()) # sums column‑wise, the second sum() adds up the values in that Series." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Vehicle_Type',\n", + " 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse\n", + "\n", + "RF_mse = []\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1): # enumerate adds a counter to the loop.\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Train\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Validate\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + "\n", + " # Store results\n", + " RF_mse.append(mse)\n", + "\n", + "print(f\" Average MSE: {np.mean(RF_mse):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/138/Q2.ipynb b/submissions_extracted/138/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d8cab9dbfd6c000c0752fc382c6d6d17750b44ae --- /dev/null +++ b/submissions_extracted/138/Q2.ipynb @@ -0,0 +1,345 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # flatten each sample into a 1D vector\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "# Model parameters\n", + "input_dim = 36 * 36 # images flattened\n", + "hidden_dim = 14 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "\n", + "# Hyperparameters\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/138/Q3.ipynb b/submissions_extracted/138/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5c2ac309f9b0cdf8b462358f652032e81a0e6a3 --- /dev/null +++ b/submissions_extracted/138/Q3.ipynb @@ -0,0 +1,175 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import os\n", + "anon_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(anon_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum() # Series showing the number of missing values per column\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/139/Q1.ipynb b/submissions_extracted/139/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..661907ab4987915b7af446f6975c388299231b03 --- /dev/null +++ b/submissions_extracted/139/Q1.ipynb @@ -0,0 +1,278 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "df['Delivery_Time'].hist(bins=30, edgecolor='black')\n", + "\n", + "plt.title(f\"Delivery Distribution ({ df['Delivery_Time'] })\")\n", + "plt.xlabel(df['Delivery_Time'])\n", + "plt.ylabel(\"Delivery_Time\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.columns.drop('Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "df.dropna(subset=['Weather'])\n", + "df.dropna(subset=['Time_of_Day'])\n", + "df.dropna(subset=['Traffic_Level'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "\n", + "# Encode Location feature\n", + "le = LabelEncoder()\n", + "df = le.fit_transform(df[categorical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\") #no imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = df.copy(), df.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42, stratify=y)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/139/Q2.ipynb b/submissions_extracted/139/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..203bd647765830fc8066901ec353f9f16c58d64a --- /dev/null +++ b/submissions_extracted/139/Q2.ipynb @@ -0,0 +1,365 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + " a4 = self.relu(z4)\n", + "\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + "\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3 * 32 * 32\n", + "\n", + "hidden_dim = 64\n", + "output_dim = 10\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/139/Q3.ipynb b/submissions_extracted/139/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0cc4bce5cf7f1a868ba9e132d121523235ac82c8 --- /dev/null +++ b/submissions_extracted/139/Q3.ipynb @@ -0,0 +1,245 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df.drop(columns=['D_142'])\n", + "\n", + "df['P_2'].fillna(df['P_2'].mean())\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "print(\"there is no categorical columns so there is no need to encode\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"P_2\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"P_2\")\n", + "print('no imbalance')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + "\n", + " print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" F1-Score: {np.mean(lr_f1):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/14/Q1.ipynb b/submissions_extracted/14/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e0dd684c5cf78721211ac3d570bb6968b572c8a --- /dev/null +++ b/submissions_extracted/14/Q1.ipynb @@ -0,0 +1,280 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Distance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.dropna(subset=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df['Delivery_Time'].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Air Quality\")\n", + "#Not Very Balanced TBH ):" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID',\t'Distance_km',\t'Weather'\t,'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/14/Q2.ipynb b/submissions_extracted/14/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0ffc52904dde80445d6d4568876a6bc757fca1fe --- /dev/null +++ b/submissions_extracted/14/Q2.ipynb @@ -0,0 +1,403 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + "\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\\\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20 # 20 epochs\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/14/Q3.ipynb b/submissions_extracted/14/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffd255081c752e6723d82876c6a106a2a75b27d8 --- /dev/null +++ b/submissions_extracted/14/Q3.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "# thats alot of missing values!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode features and target using LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=20, edgecolor='black')\n", + "plt.title('Check for Imbalance ')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "#imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3'\t,'D_41'\t,'B_3',\t'D_42',\t'D_43',\t'D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145']\n", + "\n", + "X = df[feature_cols]\n", + "y = df['Target']\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "model = CatBoostClassifier()\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f' Our most important feature is P_2 !')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file