{"id":1247,"date":"2026-11-25T10:01:31","date_gmt":"2026-11-25T04:31:31","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=1247"},"modified":"2026-11-25T10:01:34","modified_gmt":"2026-11-25T04:31:34","slug":"machine-learning-interview-questions","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/machine-learning-interview-questions\/","title":{"rendered":"100 Machine Learning Interview Questions and Answers (Freshers to Experienced)"},"content":{"rendered":"\n<style>.cdai{--cd-brand:#3c3fde;--cd-brand-soft:#eceeff;--cd-ink:#14162b;--cd-muted:#5b5f7a;--cd-line:#dfe1ee;--cd-card:#ffffff;--cd-bg:#f6f7fc;--cd-good:#0f8a5f;--cd-good-soft:#e3f6ee;--cd-bad:#c2410c;--cd-bad-soft:#fdebe1;--cd-warn:#b7791f;--cd-on-brand:#ffffff;\nfont-family:Inter,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;color:var(--cd-ink);background:var(--cd-bg);border:1px solid var(--cd-line);border-radius:14px;padding:22px;margin:28px 0;line-height:1.55;font-size:16px;box-sizing:border-box;max-width:100%;overflow:hidden}\n.s-dark .cdai,.cdai.cd-dark{--cd-brand:#8d90ff;--cd-brand-soft:#23254a;--cd-ink:#e8e9f5;--cd-muted:#a3a6c2;--cd-line:#32354f;--cd-card:#1b1d33;--cd-bg:#14162a;--cd-good:#4ccf98;--cd-good-soft:#163a2c;--cd-bad:#ff9a6b;--cd-bad-soft:#3d2316;--cd-warn:#f2c46b;--cd-on-brand:#0f1030}\n.cdai *,.cdai *::before,.cdai *::after{box-sizing:border-box}\n.cdai h4.cd-h{font-family:Outfit,Inter,sans-serif;font-size:1.25rem;font-weight:700;margin:0 0 4px;color:var(--cd-ink);line-height:1.3}\n.cdai .cd-sub{color:var(--cd-muted);font-size:.95rem;margin:0 0 16px}\n.cdai .cd-tag{display:inline-block;font-size:.72rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--cd-brand);background:var(--cd-brand-soft);padding:3px 9px;border-radius:99px;margin-bottom:10px}\n.cdai button.cd-btn,.cdai .cd-chip{font:inherit;font-size:.92rem;font-weight:600;cursor:pointer;border-radius:10px;border:1.5px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink);padding:9px 14px;line-height:1.3;transition:transform .15s ease,border-color .15s ease,background .15s ease;text-transform:none;letter-spacing:normal;box-shadow:none;margin:0;min-height:0;height:auto}\n.cdai button.cd-btn:hover,.cdai .cd-chip:hover{border-color:var(--cd-brand);transform:translateY(-1px)}\n.cdai button.cd-btn:focus-visible,.cdai .cd-chip:focus-visible,.cdai input:focus-visible{outline:3px solid var(--cd-brand);outline-offset:2px}\n.cdai .cd-primary,.cdai button.cd-primary{background:var(--cd-brand);border-color:var(--cd-brand);color:var(--cd-on-brand)}\n.cdai .cd-chip[aria-pressed=\"true\"]{background:var(--cd-brand);border-color:var(--cd-brand);color:var(--cd-on-brand)}\n.cdai .cd-row{display:flex;flex-wrap:wrap;gap:10px;align-items:center}\n.cdai .cd-grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr));gap:12px}\n.cdai .cd-card{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;padding:14px}\n.cdai .cd-stat{font-family:Outfit,Inter,sans-serif;font-size:2rem;font-weight:700;color:var(--cd-brand);line-height:1.1;font-variant-numeric:tabular-nums}\n.cdai .cd-small{font-size:.85rem;color:var(--cd-muted)}\n.cdai label.cd-lab{font-weight:600;font-size:.92rem;display:flex;justify-content:space-between;gap:10px;margin:14px 0 6px}\n.cdai input[type=range]{width:100%;accent-color:var(--cd-brand);margin:0;height:28px;background:transparent;border:0;padding:0}\n.cdai canvas{display:block;width:100%;height:auto;border-radius:10px;background:var(--cd-card);border:1px solid var(--cd-line);touch-action:pan-y}\n\/* hero *\/\n.cdai.cd-hero{padding:0;position:relative;background:#101233;border-color:#24275a}\n.cdai.cd-hero canvas{border:0;border-radius:0;background:transparent;height:200px}\n.cdai.cd-hero .cd-hero-txt{position:absolute;left:0;right:0;bottom:0;padding:16px 20px;background:linear-gradient(transparent,rgba(16,18,51,.92) 55%);color:#fff}\n.cdai.cd-hero .cd-hero-txt b{font-family:Outfit,Inter,sans-serif;font-size:1.15rem}\n.cdai.cd-hero .cd-hero-txt span{display:block;color:#c9cbff;font-size:.9rem}\n\/* planner *\/\n.cdai .cd-timeline{display:flex;flex-direction:column;gap:7px;margin-top:6px}\n.cdai .cd-tl-row{display:grid;grid-template-columns:minmax(0,150px) 1fr 62px;gap:10px;align-items:center;font-size:.88rem}\n.cdai .cd-tl-name{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.cdai .cd-tl-name a{color:inherit;text-decoration:none}\n.cdai .cd-tl-name a:hover{color:var(--cd-brand)}\n.cdai .cd-tl-track{height:14px;background:var(--cd-brand-soft);border-radius:99px;overflow:hidden}\n.cdai .cd-tl-bar{height:100%;background:var(--cd-brand);border-radius:99px;width:0;transition:width .6s cubic-bezier(.2,.8,.2,1)}\n.cdai .cd-tl-bar.cd-skim{background:repeating-linear-gradient(45deg,var(--cd-brand),var(--cd-brand) 6px,transparent 6px,transparent 10px)}\n.cdai .cd-tl-w{text-align:right;font-variant-numeric:tabular-nums;color:var(--cd-muted)}\n.cdai .cd-prog{height:10px;border-radius:99px;background:var(--cd-brand-soft);overflow:hidden;margin-top:8px}\n.cdai .cd-prog i{display:block;height:100%;background:var(--cd-good);width:0;transition:width .4s ease}\n@media (max-width:520px){.cdai{padding:16px}.cdai .cd-tl-row{grid-template-columns:minmax(0,110px) 1fr 50px;font-size:.8rem}}\n\/* game *\/\n.cdai .cd-game-card{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;padding:18px;min-height:96px;font-size:1.05rem;font-weight:600;display:flex;align-items:center}\n.cdai .cd-feedback{margin-top:12px;padding:12px 14px;border-radius:10px;font-size:.93rem}\n.cdai .cd-feedback.cd-ok{background:var(--cd-good-soft);color:var(--cd-ink);border-left:4px solid var(--cd-good)}\n.cdai .cd-feedback.cd-no{background:var(--cd-bad-soft);color:var(--cd-ink);border-left:4px solid var(--cd-bad)}\n.cdai .cd-venn{position:relative;width:min(100%,300px);aspect-ratio:1\/1;margin:6px auto 0}\n.cdai .cd-venn div{position:absolute;border-radius:50%;border:2px solid var(--cd-brand);display:flex;justify-content:center;font-weight:700;font-size:.8rem;color:var(--cd-ink);padding-top:6px;transition:background .3s ease,transform .3s ease}\n.cdai .cd-venn div.cd-lit{background:var(--cd-brand-soft);transform:scale(1.03)}\n.cdai .cd-v1{inset:0}.cdai .cd-v2{inset:12%}.cdai .cd-v3{inset:26%}.cdai .cd-v4{inset:40%;align-items:center;padding-top:0!important}\n\/* checklist *\/\n.cdai.cd-check{padding:16px 18px;background:var(--cd-card)}\n.cdai.cd-check ul{list-style:none;margin:8px 0 0;padding:0}\n.cdai.cd-check li{margin:0;padding:0}\n.cdai.cd-check label{display:flex;gap:10px;align-items:flex-start;padding:7px 4px;cursor:pointer;font-size:.95rem;border-radius:8px}\n.cdai.cd-check label:hover{background:var(--cd-bg)}\n.cdai.cd-check input{width:18px;height:18px;margin-top:3px;accent-color:var(--cd-good);flex:none}\n.cdai.cd-check .cd-done{color:var(--cd-good);font-weight:700}\n\/* tokens *\/\n.cdai .cd-bars{display:flex;flex-direction:column;gap:6px;margin-top:10px}\n.cdai .cd-bar-row{display:grid;grid-template-columns:110px 1fr 52px;gap:10px;align-items:center;font-size:.9rem}\n.cdai .cd-bar-row b{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-weight:600}\n.cdai .cd-bar-row .cd-tl-bar{transition:width .35s ease}\n.cdai .cd-out{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:12px;margin-top:12px;min-height:46px;font-size:.92rem;word-break:break-word}\n.cdai .cd-out mark{background:var(--cd-brand-soft);color:var(--cd-brand);padding:1px 4px;border-radius:4px;animation:cdpop .4s ease}\n@keyframes cdpop{from{transform:scale(1.4);opacity:0}to{transform:none;opacity:1}}\n.cdai .cd-meter{font-family:Outfit,Inter,sans-serif;font-weight:700;font-size:1.6rem;font-variant-numeric:tabular-nums}\n@media (prefers-reduced-motion:reduce){.cdai *{transition:none!important;animation:none!important}}\n.cdai .cd-tbl-wrap{overflow-x:auto;margin-top:10px}\n.cdai table.cd-tbl{border-collapse:collapse;width:100%;font-size:.88rem;font-variant-numeric:tabular-nums;background:var(--cd-card);margin:0}\n.cdai table.cd-tbl th,.cdai table.cd-tbl td{border:1px solid var(--cd-line);padding:6px 8px;text-align:center;color:var(--cd-ink)}\n.cdai table.cd-tbl th{background:var(--cd-brand-soft);font-weight:700;font-size:.8rem}\n.cdai table.cd-tbl input{width:64px;font:inherit;padding:4px 6px;border:1.5px solid var(--cd-line);border-radius:6px;background:var(--cd-bg);color:var(--cd-ink);text-align:center;margin:0}\n.cdai .cd-steps{margin-top:12px;display:grid;gap:6px;font-size:.92rem}\n.cdai .cd-steps div{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:8px;padding:8px 12px}\n.cdai .cd-steps code,.cdai .cd-eq{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9rem;background:transparent;color:var(--cd-ink);padding:0}\n.cdai .cd-eq{display:inline-block;background:var(--cd-brand-soft);color:var(--cd-brand);padding:4px 10px;border-radius:8px;font-weight:700}\n.cdai.cd-codebox{padding:0;background:#16182c;border-color:#2a2d48}\n.cdai.cd-codebox .cd-codehead{display:flex;justify-content:space-between;align-items:center;padding:8px 14px;border-bottom:1px solid #2a2d48;color:#a3a6c2;font-size:.8rem;font-weight:600}\n.cdai.cd-codebox pre{margin:0;padding:14px 16px;overflow-x:auto;background:transparent;border:0;color:#e6e7f2;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.86rem;line-height:1.6;white-space:pre}\n.cdai.cd-codebox pre code{background:transparent;color:inherit;padding:0;font:inherit}\n.cdai.cd-codebox .cd-copy{font:inherit;font-size:.78rem;font-weight:600;cursor:pointer;background:#2a2d48;color:#e6e7f2;border:0;border-radius:6px;padding:5px 10px;margin:0;text-transform:none;letter-spacing:normal}\n.cdai.cd-codebox .cd-outp{border-top:1px dashed #2a2d48;color:#8fe3b8}\n.cdai .cd-legend{display:flex;flex-wrap:wrap;gap:14px;font-size:.82rem;color:var(--cd-muted);margin-top:8px}\n.cdai .cd-legend i{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:5px;vertical-align:middle}\n.cdai canvas.cd-touch{touch-action:none;cursor:crosshair}\n.cdai canvas.cd-grab{touch-action:none;cursor:grab}\n.cdai .cd-q-opts{display:grid;gap:8px;margin-top:12px}\n.cdai .cd-q-opts button.cd-btn{text-align:left;width:100%}\n.cdai .cd-q-opts button.cd-right{border-color:var(--cd-good);background:var(--cd-good-soft)}\n.cdai .cd-q-opts button.cd-wrong{border-color:var(--cd-bad);background:var(--cd-bad-soft)}\n.cdai .cd-odds-dots{display:grid;grid-template-columns:repeat(10,1fr);gap:6px;max-width:320px;margin-top:10px}\n.cdai .cd-odds-dots i{display:block;aspect-ratio:1\/1;border-radius:50%;background:var(--cd-line);transition:background .25s ease}\n.cdai .cd-cm{display:grid;grid-template-columns:auto 1fr 1fr;gap:6px;font-size:.88rem;max-width:420px;margin-top:12px}\n.cdai .cd-cm div{padding:10px 8px;border-radius:8px;text-align:center}\n.cdai .cd-cm .cd-cm-h{color:var(--cd-muted);font-weight:600;font-size:.78rem;align-self:center}\n.cdai .cd-cm .cd-cm-c{background:var(--cd-card);border:1px solid var(--cd-line)}\n.cdai .cd-cm .cd-cm-c b{display:block;font-family:Outfit,Inter,sans-serif;font-size:1.5rem;font-variant-numeric:tabular-nums}\n.cdai .cd-cm .cd-cm-good{border-color:var(--cd-good);background:var(--cd-good-soft)}\n.cdai .cd-cm .cd-cm-bad{border-color:var(--cd-bad);background:var(--cd-bad-soft)}\n.cdai.cd-q{background:var(--cd-card);padding:18px 20px;margin:18px 0;border-left:4px solid var(--cd-brand)}\n.cdai.cd-q[hidden]{display:none!important}\n.cdai.cd-q.cd-is-known{border-left-color:var(--cd-good)}\n.cdai.cd-q .cd-q-meta{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:6px}\n.cdai .cd-pill{font-size:.72rem;font-weight:700;padding:3px 9px;border-radius:99px;background:var(--cd-brand-soft);color:var(--cd-brand);letter-spacing:.02em}\n.cdai .cd-pill.cd-lv-Freshers{background:var(--cd-good-soft);color:var(--cd-good)}\n.cdai .cd-pill.cd-lv-Experienced{background:var(--cd-bad-soft);color:var(--cd-bad)}\n.cdai.cd-q h3.cd-q-title{font-family:Outfit,Inter,sans-serif;font-size:1.15rem;line-height:1.35;margin:4px 0 10px;color:var(--cd-ink)}\n.cdai.cd-q .cd-q-body{font-size:.97rem}\n.cdai.cd-q .cd-q-body p{margin:0 0 10px}\n.cdai.cd-q .cd-q-body ul,.cdai.cd-q .cd-q-body ol{margin:0 0 10px 1.2em;padding:0}\n.cdai.cd-q .cd-q-body li{margin:3px 0}\n.cdai.cd-q .cd-q-body code,.cdai.cd-fc .cd-fc-a code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.86em;background:var(--cd-brand-soft);color:var(--cd-ink);padding:1px 5px;border-radius:4px}\n.cdai.cd-q .cd-q-body pre code,.cdai.cd-fc .cd-fc-a pre code{background:transparent;color:inherit;padding:0;font-size:inherit}\n.cdai.cd-q .cd-q-body table,.cdai.cd-fc table{border-collapse:collapse;width:100%;font-size:.88rem;margin:6px 0 12px}\n.cdai.cd-q .cd-q-body th,.cdai.cd-q .cd-q-body td,.cdai.cd-fc th,.cdai.cd-fc td{border:1px solid var(--cd-line);padding:6px 8px;text-align:left;color:var(--cd-ink)}\n.cdai.cd-q .cd-q-body th,.cdai.cd-fc th{background:var(--cd-brand-soft)}\n.cdai.cd-q .cd-codebox,.cdai.cd-fc .cd-codebox{margin:12px 0 4px}\n.cdai.cd-q .cd-q-foot{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-top:10px;flex-wrap:wrap}\n.cdai.cd-q .cd-known[aria-pressed=\"true\"]{background:var(--cd-good-soft);border-color:var(--cd-good);color:var(--cd-good)}\n.cdai.cd-q .cd-show{display:none}\n.cdai.cd-q.cd-practice:not(.cd-revealed) .cd-q-body{display:none}\n.cdai.cd-q.cd-practice:not(.cd-revealed) .cd-show{display:inline-block}\n.cdai .cd-q-top{font-size:.8rem;color:var(--cd-muted);text-decoration:none}\n.cdai.cd-pyq-tool .cd-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:10px;margin:12px 0}\n.cdai.cd-pyq-tool select,.cdai.cd-pyq-tool input[type=search]{font:inherit;font-size:.92rem;padding:9px 12px;border:1.5px solid var(--cd-line);border-radius:10px;background:var(--cd-card);color:var(--cd-ink);margin:0;min-width:0;width:100%;height:auto}\n.cdai.cd-pyq-tool .cd-filters{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}\n@media (max-width:560px){.cdai.cd-pyq-tool .cd-filters{grid-template-columns:1fr}}\n.cdai.cd-pyq-tool label.cd-tog{display:flex;align-items:center;gap:8px;font-size:.9rem;cursor:pointer}\n.cdai.cd-pyq-tool label.cd-tog input{width:18px;height:18px;accent-color:var(--cd-brand);margin:0}\n.cdai a.cd-btn{display:inline-block;text-decoration:none}\n.cdai a.cd-dl{background:var(--cd-good);border-color:var(--cd-good);color:#fff}\n.cdai.cd-fc{position:fixed;inset:0;z-index:99999;background:rgba(10,12,30,.72);display:flex;align-items:center;justify-content:center;margin:0;border:0;border-radius:0;padding:max(12px,env(safe-area-inset-top,0px)) max(12px,env(safe-area-inset-right,0px)) max(12px,env(safe-area-inset-bottom,0px)) max(12px,env(safe-area-inset-left,0px))}\n.cdai.cd-fc[hidden]{display:none}\n.cdai.cd-fc .cd-fc-card{background:var(--cd-card);color:var(--cd-ink);border-radius:16px;padding:20px;width:min(720px,100%);max-height:100%;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.35)}\n.cdai.cd-fc .cd-fc-meta{display:flex;gap:6px;margin:12px 0 6px}\n.cdai.cd-fc .cd-fc-q{font-family:Outfit,Inter,sans-serif;font-size:1.3rem;font-weight:700;line-height:1.35;margin-bottom:14px}\n.cdai.cd-fc .cd-fc-a{border-top:1px dashed var(--cd-line);padding-top:12px;margin-bottom:12px;font-size:.95rem}\n.cdai.cd-fc .cd-fc-a p{margin:0 0 10px}.cdai.cd-fc .cd-fc-a ul,.cdai.cd-fc .cd-fc-a ol{margin:0 0 10px 1.2em;padding:0}\n.cdai.cd-fc .cd-fc-actions{margin-top:6px}\n.cdai a.cd-btn{font:inherit;font-size:.92rem;font-weight:600;cursor:pointer;border-radius:10px;border:1.5px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink);padding:9px 14px;line-height:1.3;text-decoration:none;display:inline-block;transition:transform .15s ease,border-color .15s ease}\n.cdai a.cd-btn:hover{transform:translateY(-1px);border-color:var(--cd-brand)}\n.cdai a.cd-btn.cd-dl{background:#0f8a5f;border-color:#0f8a5f;color:#fff}\n.cdai a.cd-btn.cd-dl:hover{background:#0c7550}\n.cdai a.cd-btn:focus-visible{outline:3px solid var(--cd-brand);outline-offset:2px}\n.cdai.cd-codebox .cd-codehead .cd-acts{display:flex;gap:6px;flex-wrap:wrap}\n.cdai.cd-codebox .cd-run{font:inherit;font-size:.78rem;font-weight:700;cursor:pointer;background:#3c3fde;color:#fff;border:0;border-radius:6px;padding:5px 12px;margin:0;text-transform:none;letter-spacing:normal}\n.cdai.cd-codebox .cd-run:disabled{opacity:.7;cursor:wait}\n.cdai.cd-codebox .cd-edit,.cdai.cd-codebox .cd-reset{font:inherit;font-size:.78rem;font-weight:600;cursor:pointer;background:transparent;color:#c9cbff;border:1px solid #3a3d5c;border-radius:6px;padding:4px 10px;margin:0;text-transform:none;letter-spacing:normal}\n.cdai.cd-codebox.cd-editing pre:first-of-type{outline:2px dashed #8d90ff;outline-offset:-6px}\n.cdai.cd-codebox pre code[contenteditable=\"true\"]{display:block;outline:none;caret-color:#fff}\n.cdai.cd-codebox .cd-live{background:var(--cd-card);color:var(--cd-ink);padding:12px 14px;border-top:1px solid #2a2d48}\n.cdai.cd-codebox .cd-live-head{font-size:.78rem;font-weight:700;color:var(--cd-good);margin-bottom:8px}\n.cdai.cd-codebox .cd-live-head span{font-weight:500;color:var(--cd-muted);margin-left:6px}\n.cdai .cd-sql-err{background:var(--cd-bad-soft);color:var(--cd-ink);border-left:4px solid var(--cd-bad);padding:8px 12px;border-radius:6px;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.85rem;margin-bottom:8px}\n.cdai table.cd-res{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.8rem}\n.cdai table.cd-res th,.cdai table.cd-res td{text-align:left;white-space:nowrap;padding:5px 9px}\n.cdai table.cd-res td.cd-null{color:var(--cd-muted);font-style:italic}\n.cdai.cd-sql-play textarea{width:100%;min-height:150px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.88rem;line-height:1.55;padding:12px;border-radius:10px;border:1.5px solid var(--cd-line);background:#16182c;color:#e6e7f2;resize:vertical;margin:0;box-sizing:border-box}\n.cdai.cd-sql-play .cd-play-out{margin-top:12px;background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:12px}\n.cdai .cd-schema{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:10px;margin:10px 0 14px}\n.cdai .cd-schema .cd-card b{font-family:ui-monospace,Menlo,Consolas,monospace;color:var(--cd-brand)}\n.cdai .cd-schema .cd-card code{font-size:.78rem;color:var(--cd-muted);background:transparent;padding:0;line-height:1.6;display:block}\n.cdai .cd-pill.cd-ty-Query{background:#fff4e0;color:#9a5b00}\n.s-dark .cdai .cd-pill.cd-ty-Query{background:#3a2c12;color:#f2c46b}\n.cdai .cd-play-out .cd-live-head{font-size:.78rem;font-weight:700;color:var(--cd-good);margin-bottom:8px}\n.cdai .cd-play-out .cd-live-head span{font-weight:500;color:var(--cd-muted);margin-left:6px}\n.cdai.cd-q .wp-block-table{overflow-x:auto;margin:0}\n.cdai.cd-q .wp-block-kevinbatdorf-code-block-pro{margin:10px 0 12px;border-radius:8px;overflow:hidden}\n.cdai.cd-q h3.cd-q-title{margin-top:4px}\n.cdai.cd-q .cd-q-body sup{font-size:.7em}\n.cdai .cd-brief{background:var(--cd-card);border:1px solid var(--cd-line);border-left:5px solid var(--cd-brand);border-radius:12px;padding:16px 18px}\n.cdai .cd-brief h4{font-family:Outfit,Inter,sans-serif;margin:0 0 8px;font-size:1.1rem;color:var(--cd-ink)}\n.cdai .cd-brief ul{margin:0;padding-left:20px}.cdai .cd-brief li{margin:4px 0}\n.cdai .cd-pre{display:grid;gap:10px;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:10px}\n.cdai .cd-pre a{display:block;text-decoration:none;color:var(--cd-ink);background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;padding:12px 14px}\n.cdai .cd-pre a:hover{border-color:var(--cd-brand)}\n.cdai .cd-pre a b{display:block;color:var(--cd-brand);font-size:.95rem}.cdai .cd-pre a span{font-size:.85rem;color:var(--cd-muted)}\n.cdai button.cd-btn:disabled{cursor:default;transform:none;opacity:.8}\n\n.cdai .cd-ctl{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}\n.cdai .cd-ctl .cd-small{margin-left:auto}\n.cdai input.cd-in,.cdai select.cd-in{font:inherit;font-size:.95rem;padding:8px 10px;border-radius:10px;border:1.5px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink);min-width:0;max-width:100%}\n\n.cdai pre.cd-sl-code{margin:0;padding:10px 0;background:#1e1e1e;border-radius:10px;overflow-x:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.78rem;line-height:1.55;color:#d4d4d4;white-space:pre}\n.cdai pre.cd-sl-code .cd-cl{display:block;padding:0 12px}\n.cdai pre.cd-sl-code .cd-cl.hl{background:rgba(255,107,107,.18);box-shadow:inset 3px 0 0 #ff6b6b}\n.cdai pre.cd-sl-code.good .cd-cl.hl{background:rgba(76,207,152,.16);box-shadow:inset 3px 0 0 #4ccf98}\n.cdai .cd-ob-top{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:12px}\n.cdai .cd-ob-panel{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:12px}\n.cdai .cd-ob-panel h5{margin:0 0 8px;font-size:.92rem;color:var(--cd-ink)}\n.cdai .cd-ob-form{display:grid;gap:8px}\n.cdai .cd-ob-form label{display:grid;grid-template-columns:70px 1fr;gap:8px;align-items:center;font-size:.85rem;font-family:ui-monospace,Menlo,Consolas,monospace}\n.cdai .cd-ob-form input{width:100%}\n.cdai .cd-ob-crow{display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:.85rem}\n.cdai .cd-ob-crow code{background:transparent;padding:0;color:var(--cd-brand);font-weight:700}\n.cdai .cd-ob-crow input{flex:1 1 90px;width:90px}\n.cdai .cd-ob-objs{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:10px;margin-top:12px}\n.cdai .cd-ob-obj{border:2px solid var(--cd-brand);border-radius:12px;padding:10px;background:var(--cd-card)}\n.cdai .cd-ob-oname{font-family:ui-monospace,Menlo,Consolas,monospace;font-weight:700;color:var(--cd-brand);margin-bottom:6px}\n.cdai .cd-ob-row{display:flex;justify-content:space-between;gap:8px;font-size:.8rem;padding:4px 6px;border-radius:6px;background:var(--cd-bg);margin-top:3px}\n.cdai .cd-ob-row span{color:var(--cd-muted);font-family:ui-monospace,Menlo,Consolas,monospace}\n.cdai .cd-ob-row b{font-family:ui-monospace,Menlo,Consolas,monospace;color:var(--cd-ink);overflow-wrap:anywhere;text-align:right}\n.cdai .cd-ob-row.cls{border:1px dashed var(--cd-warn);background:transparent}\n.cdai .cd-ob-row.cls.own{border-style:solid}\n.cdai .cd-ob-btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:8px}\n.cdai .cd-ob-btns .cd-btn{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.74rem;padding:5px 8px}\n.cdai .cd-ob-code{margin-top:12px;max-height:340px;overflow:auto}\n.cdai .cd-mr-wrap{display:grid;grid-template-columns:1.1fr 1fr;gap:14px;margin-top:12px;align-items:start}\n.cdai .cd-mr-svg{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:6px}\n.cdai .cd-mr-svg svg{display:block;width:100%;height:auto}\n.cdai .cd-mr-node rect{fill:var(--cd-bg);stroke:var(--cd-muted);stroke-width:1.5;transition:fill .2s,stroke .2s}\n.cdai .cd-mr-node.cur rect{fill:var(--cd-brand-soft);stroke:var(--cd-brand);stroke-width:3}\n.cdai .cd-mr-node.hit rect{fill:var(--cd-good-soft);stroke:var(--cd-good);stroke-width:3}\n.cdai .cd-mr-n{font:700 17px Inter,system-ui,sans-serif;fill:var(--cd-ink)}\n.cdai .cd-mr-m{font:500 12px ui-monospace,Menlo,Consolas,monospace;fill:var(--cd-muted)}\n.cdai .cd-mr-edge{stroke:var(--cd-muted);stroke-width:1.6}\n.cdai .cd-mr-ah{fill:var(--cd-muted)}\n.cdai .cd-mr-ord{fill:var(--cd-warn)}\n.cdai .cd-mr-ordt{font:700 12px Inter,sans-serif;fill:#fff}\n.cdai .cd-mr-dot{fill:var(--cd-good)}\n.cdai .cd-mr-list{margin-top:12px}\n.cdai .cd-mr-chips{display:flex;flex-wrap:wrap;gap:4px;align-items:center}\n.cdai .cd-mr-chips i{color:var(--cd-muted);font-style:normal}\n.cdai .cd-mr-chip{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.82rem;font-weight:700;padding:5px 9px;border-radius:8px;border:2px solid var(--cd-line);background:var(--cd-card);color:var(--cd-ink)}\n.cdai .cd-mr-chip.done{opacity:.5}\n.cdai .cd-mr-chip.cur{border-color:var(--cd-brand);background:var(--cd-brand-soft)}\n.cdai .cd-mr-chip.hit{border-color:var(--cd-good);background:var(--cd-good-soft)}\n.cdai .cd-mr-meths{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}\n.cdai .cd-mr-meths .cd-chip{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.8rem}\n.cdai .cd-mr-msg{margin-top:12px;font-size:.92rem;line-height:1.55}\n.cdai .cd-sl-steps{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}\n.cdai h5.cd-sl-title{font-family:Outfit,Inter,sans-serif;font-size:1.1rem;margin:0;display:flex;align-items:center;gap:10px;color:var(--cd-ink)}\n.cdai .cd-sl-letter{display:inline-flex;width:34px;height:34px;border-radius:9px;background:var(--cd-brand);color:var(--cd-on-brand,#fff);align-items:center;justify-content:center;font-size:1.1rem}\n.cdai .cd-nm-q{margin:14px 0 0}\n@media (max-width:640px){.cdai .cd-ob-top,.cdai .cd-mr-wrap{grid-template-columns:1fr}.cdai pre.cd-sl-code{font-size:.72rem}.cdai .cd-ctl .cd-small{margin-left:0;width:100%}}\n\n.cdai .cd-ml-chart{width:100%;height:340px;background:var(--cd-card);border:1px solid var(--cd-line);border-radius:12px;overflow:hidden}\n.cdai .cd-ml-short{height:240px;margin-top:12px}\n.cdai .cd-ml-two{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px}\n.cdai .cd-ml-two .cd-ml-chart{height:300px}\n.cdai .cd-ml-cards3{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:12px}\n.cdai .cd-ml-cards3 .cd-stat{font-size:1.5rem}\n.cdai .cd-ml-note{background:var(--cd-card);border:1px solid var(--cd-line);border-radius:10px;padding:12px 14px;margin-top:12px;font-size:.93rem}\n.cdai .cd-mq-opts{display:grid;gap:8px}\n.cdai .cd-mq-opts .cd-btn{text-align:left}\n.cdai button.cd-btn:disabled{cursor:default;transform:none;opacity:1}\n.cdai .cd-ap-q{margin:12px 0}\n.cdai .cd-ap-q>b{display:block;font-size:.92rem;margin-bottom:6px}\n.cdai .cd-ap-q .cd-chip{font-size:.86rem;padding:7px 11px}\n.cdai .cd-ap-out{margin-top:14px;border-left:4px solid var(--cd-brand)}\n.cdai .cd-ap-main{font-family:Outfit,Inter,sans-serif;font-size:1.25rem;font-weight:700;color:var(--cd-brand);margin-top:2px}\n.cdai .cd-ap-out a{color:var(--cd-brand)}\n@media (max-width:640px){.cdai .cd-ml-two{grid-template-columns:1fr}.cdai .cd-ml-chart{height:290px}.cdai .cd-ml-cards3{gap:6px}.cdai .cd-ml-cards3 .cd-card{padding:10px}.cdai .cd-ml-cards3 .cd-stat{font-size:1.15rem}}\n<\/style>\n\n\n\n<p class=\"wp-block-paragraph\">Machine learning interviews in India now range from campus drives for data science trainees to ML engineer rounds at product companies and AI startups. Freshers get &#8220;what is overfitting?&#8221; and &#8220;precision vs recall&#8221;. Experienced candidates get questions on drift, deployment, XGBoost internals and, more and more, transformers, RAG and LLMs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This page has the <strong>100 machine learning interview questions<\/strong> asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates. 30 answers include a short Python example that was actually run, so the output you see is real. Four interactive tools let you see the bias-variance tradeoff, practise choosing metrics, watch gradient descent with different learning rates, and get a model suggestion for your problem. Prefer to study offline? <a href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/11\/machine-learning-interview-questions-code-and-debug.pdf\">Download all 100 questions as a free PDF<\/a>.<\/p>\n\n\n\n<div class=\"cdai cd-pdf-top\" style=\"padding:14px 18px;margin:18px 0;display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between\"><div><span class=\"cd-tag\" style=\"margin-bottom:4px\">Free PDF<\/span><div style=\"font-weight:700;font-size:1.05rem;line-height:1.35\">All 100 machine learning interview questions with answers<\/div><div style=\"color:var(--cd-muted);font-size:.9rem\">42 pages, ready to print or read offline. No sign-up needed.<\/div><\/div><a href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/11\/machine-learning-interview-questions-code-and-debug.pdf\" download style=\"display:inline-block;background:var(--cd-brand);color:#fff;font-weight:700;padding:11px 20px;border-radius:10px;text-decoration:none;white-space:nowrap\">Download PDF<\/a><\/div>\n\n\n\n<div class=\"cdai\" style=\"padding:18px\"><div class=\"cd-brief\"><h4>What you will find on this page<\/h4><ul>\n<li><b>100 questions with answers<\/b> in three levels: 40 for freshers, 35 intermediate, 25 for experienced candidates.<\/li>\n<li><b>Core machine learning plus the new topics:<\/b> about 85 questions on ML fundamentals, models, evaluation and production, and about 15 on neural networks, transformers, RAG and LLMs.<\/li>\n<li><b>Four interactive tools:<\/b> a bias-variance slider, a &#8220;pick the right metric&#8221; game, a gradient descent visualiser and an algorithm picker.<\/li>\n<li><b>30 Python examples<\/b> with real output, mostly with scikit-learn.<\/li>\n<li><b>Study tools:<\/b> filters by level and topic, search, and a &#8220;Done&#8221; button on every question that remembers your progress.<\/li>\n<li><b>A free 42-page PDF<\/b> and a 10-question quiz at the end.<\/li><\/ul><\/div>\n<p class=\"cd-small\" style=\"margin:14px 0 0\"><b>Helpful to know first<\/b> (each opens our own guide):<\/p>\n<div class=\"cd-pre\">\n<a href=\"https:\/\/codeanddebug.in\/blog\/how-to-learn-ai-ml-from-scratch-roadmap\/\"><b>AI and ML roadmap<\/b><span>The full learning path, if you are starting out.<\/span><\/a>\n<a href=\"https:\/\/codeanddebug.in\/blog\/python-interview-questions\/\"><b>Python interview questions<\/b><span>The language every example here uses.<\/span><\/a>\n<a href=\"https:\/\/codeanddebug.in\/blog\/confusion-matrix-in-machine-learning\/\"><b>Confusion matrix guide<\/b><span>The metrics behind a dozen of these questions.<\/span><\/a>\n<\/div><\/div>\n\n\n\n<div class=\"cdai cd-mlq-tool\" id=\"cd-mlq-tool\">\n<span class=\"cd-tag\">Study tools<\/span>\n<h4 class=\"cd-h\">Study these 100 questions your way<\/h4>\n<p class=\"cd-sub\">Filter the machine learning interview questions by level or topic, or search them. Press &#8220;Mark as done&#8221; under each question you have finished; your progress is saved in this browser.<\/p>\n<div class=\"cd-stats\">\n<div class=\"cd-card\"><div class=\"cd-small\">Showing<\/div><div class=\"cd-stat\"><span class=\"cd-mlq-shown\">100<\/span><span style=\"font-size:1rem;color:var(--cd-muted)\"> \/ 100<\/span><\/div><\/div>\n<div class=\"cd-card\"><div class=\"cd-small\">Done<\/div><div class=\"cd-stat\"><span class=\"cd-mlq-done\">0<\/span><span style=\"font-size:1rem;color:var(--cd-muted)\"> \/ 100<\/span><\/div><div class=\"cd-prog cd-mlq-bar\"><i><\/i><\/div><\/div>\n<\/div>\n<div class=\"cd-row\" role=\"group\" aria-label=\"Level\">\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"all\" aria-pressed=\"true\">All levels<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Freshers\" aria-pressed=\"false\">Freshers (40)<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Intermediate\" aria-pressed=\"false\">Intermediate (35)<\/button>\n<button type=\"button\" class=\"cd-chip cd-lvl\" data-l=\"Experienced\" aria-pressed=\"false\">Experienced (25)<\/button>\n<\/div>\n<div class=\"cd-filters\">\n<select class=\"cd-mlq-topic\" aria-label=\"Topic\"><option value=\"all\">All topics<\/option><\/select>\n<input type=\"search\" class=\"cd-mlq-search\" placeholder=\"Search questions, e.g. overfitting\" aria-label=\"Search questions\">\n<\/div>\n<div class=\"cd-row\" style=\"margin-top:14px\">\n<a class=\"cd-btn cd-primary cd-dl\" href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/11\/machine-learning-interview-questions-code-and-debug.pdf\" download>Download PDF (42 pages)<\/a>\n<button type=\"button\" class=\"cd-btn cd-mlq-reset\">Reset done<\/button>\n<\/div>\n<p class=\"cd-small cd-mlq-none\" hidden style=\"margin:12px 0 0\">No questions match these filters. Try another topic or clear the search.<\/p>\n<\/div>\n\n\n\n<h2 id=\"how-to-prepare\" class=\"wp-block-heading\">How to prepare for a machine learning interview<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Explain every concept with an example.<\/strong> &#8220;Overfitting is when the model memorises noise&#8221; is fine, but &#8220;my degree-12 polynomial had near-zero training error and huge test error&#8221; is what convinces an interviewer.<\/li>\n\n\n\n<li><strong>Know the classic comparisons:<\/strong> bias vs variance, precision vs recall, L1 vs L2, bagging vs boosting, k-means vs KNN, ROC vs PR curve, generative vs discriminative.<\/li>\n\n\n\n<li><strong>Be able to code the basics.<\/strong> Train and evaluate a model with scikit-learn, write gradient descent and k-means in NumPy, and build a Pipeline without leakage.<\/li>\n\n\n\n<li><strong>Prepare one project story in depth:<\/strong> the problem, the data, the metric and why, the baseline, what you tried, what failed and how it would run in production.<\/li>\n\n\n\n<li><strong>For experienced and GenAI roles<\/strong>, revise drift and monitoring, deployment, gradient boosting internals, transformers, RAG and how to evaluate LLM outputs.<\/li>\n<\/ul>\n\n\n\n<h2 id=\"interactive-tools\" class=\"wp-block-heading\">Learn the key ideas by doing<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Four ideas come up in almost every machine learning interview, often as follow-up questions: why a model overfits, which metric to use, how the learning rate affects training, and which algorithm to pick. These tools let you see each one. Spend ten minutes with them before you read the questions below.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Bias-variance slider: from underfitting to overfitting<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A polynomial is fitted to 18 noisy points from a sine wave. Drag the degree to make the model more or less complex, and watch the training and test errors. Turn on &#8220;Show other samples&#8221; to see why complex models have high variance.<\/p>\n\n\n\n<div class=\"cdai cd-bv\"><span class=\"cd-tag\">Try it<\/span><h4 class=\"cd-h\">Bias-variance tradeoff<\/h4>\n<label class=\"cd-lab\" for=\"cd-bv-deg\"><span>Model complexity (polynomial degree)<\/span><span class=\"cd-bv-dv\"><\/span><\/label>\n<input type=\"range\" id=\"cd-bv-deg\" class=\"cd-bv-deg\" min=\"0\" max=\"14\" step=\"1\" value=\"1\">\n<div class=\"cd-row\" style=\"margin:8px 0 10px\"><label class=\"cd-tog\"><input type=\"checkbox\" class=\"cd-bv-many\"> Show other samples<\/label><button type=\"button\" class=\"cd-btn cd-bv-new\">New training sample<\/button><\/div>\n<div class=\"cd-ml-chart cd-bv-fit\"><p class=\"cd-small\" style=\"padding:20px;margin:0\">Loading the chart&#8230;<\/p><\/div>\n<div class=\"cd-bv-cards cd-ml-cards3\"><\/div>\n<div class=\"cd-ml-note cd-bv-note\" aria-live=\"polite\"><\/div>\n<div class=\"cd-ml-chart cd-ml-short cd-bv-err\"><\/div>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Start at degree 1, then move to 3 or 4, then to 12. The bottom chart is the curve from question 8: training error keeps falling as complexity grows, while test error falls and then rises again.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Pick the right metric: a scenario game<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers rarely ask &#8220;what is recall?&#8221; on its own. They describe a business problem and ask which metric you would use. Eight scenarios, one answer each.<\/p>\n\n\n\n<div class=\"cdai cd-mg\"><span class=\"cd-tag\">Game<\/span><h4 class=\"cd-h\">Which metric would you choose?<\/h4><div class=\"cd-mg-body\"><p class=\"cd-sub\">8 scenarios, about three minutes.<\/p><button type=\"button\" class=\"cd-btn cd-primary cd-mg-start\">Start<\/button><\/div><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Gradient descent and the learning rate<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The contour chart shows a loss surface shaped like an oval valley, with the minimum at the green star. Gradient descent starts at the top left and takes 40 steps. Change the learning rate and watch the path and the loss curve.<\/p>\n\n\n\n<div class=\"cdai cd-gd\"><span class=\"cd-tag\">Try it<\/span><h4 class=\"cd-h\">Gradient descent visualiser<\/h4>\n<div class=\"cd-row\" role=\"group\" aria-label=\"Presets\"><button type=\"button\" class=\"cd-chip cd-gd-pre\" data-v=\"-2.3\">Too small<\/button><button type=\"button\" class=\"cd-chip cd-gd-pre\" data-v=\"-1.046\">Just right<\/button><button type=\"button\" class=\"cd-chip cd-gd-pre\" data-v=\"-0.745\">Oscillating<\/button><button type=\"button\" class=\"cd-chip cd-gd-pre\" data-v=\"-0.678\">Too big<\/button><\/div>\n<label class=\"cd-lab\" for=\"cd-gd-lr\"><span>Learning rate<\/span><span class=\"cd-gd-lv\"><\/span><\/label>\n<input type=\"range\" id=\"cd-gd-lr\" class=\"cd-gd-lr\" min=\"-3\" max=\"-0.6\" step=\"0.001\" value=\"-1.046\">\n<div class=\"cd-ml-two\"><div class=\"cd-ml-chart cd-gd-con\"><p class=\"cd-small\" style=\"padding:20px;margin:0\">Loading the chart&#8230;<\/p><\/div><div class=\"cd-ml-chart cd-gd-loss\"><\/div><\/div>\n<div class=\"cd-gd-cards cd-ml-cards3\"><\/div>\n<div class=\"cd-ml-note cd-gd-note\" aria-live=\"polite\"><\/div>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">This is why learning rate is the first hyperparameter to tune for neural networks, and why optimisers like Adam, which adapt the step size for each parameter, are so popular.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Which algorithm should I use?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A common interview question is &#8220;how would you choose a model for this problem?&#8221;. Answer a few questions and see a sensible starting point, with the reasons an interviewer expects to hear.<\/p>\n\n\n\n<div class=\"cdai cd-ap\"><span class=\"cd-tag\">Try it<\/span><h4 class=\"cd-h\">Algorithm picker<\/h4><p class=\"cd-sub\">A rule of thumb to start from, not a law. Always compare against a simple baseline.<\/p><div class=\"cd-ap-q \" data-k=\"task\"><b>What do you want to do?<\/b><div class=\"cd-row\"><button type=\"button\" class=\"cd-chip\" data-v=\"category\" aria-pressed=\"false\">Predict a category<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"number\" aria-pressed=\"false\">Predict a number<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"groups\" aria-pressed=\"false\">Find groups (no labels)<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"reduce\" aria-pressed=\"false\">Reduce features<\/button><\/div><\/div><div class=\"cd-ap-q cd-ap-sup\" data-k=\"data\"><b>What kind of data?<\/b><div class=\"cd-row\"><button type=\"button\" class=\"cd-chip\" data-v=\"tabular\" aria-pressed=\"false\">Tables (rows and columns)<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"text\" aria-pressed=\"false\">Text<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"images\" aria-pressed=\"false\">Images<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"time\" aria-pressed=\"false\">Time series<\/button><\/div><\/div><div class=\"cd-ap-q cd-ap-size\" data-k=\"size\"><b>How much labelled data?<\/b><div class=\"cd-row\"><button type=\"button\" class=\"cd-chip\" data-v=\"small\" aria-pressed=\"false\">Under about 10,000 rows<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"large\" aria-pressed=\"false\">More than that<\/button><\/div><\/div><div class=\"cd-ap-q cd-ap-tab\" data-k=\"explain\"><b>Must you explain every prediction (for example to a regulator)?<\/b><div class=\"cd-row\"><button type=\"button\" class=\"cd-chip\" data-v=\"yes\" aria-pressed=\"false\">Yes<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"no\" aria-pressed=\"false\">No, accuracy matters most<\/button><\/div><\/div><div class=\"cd-ap-q cd-ap-grp\" data-k=\"shape\"><b>What do you expect the groups to look like?<\/b><div class=\"cd-row\"><button type=\"button\" class=\"cd-chip\" data-v=\"round\" aria-pressed=\"false\">Roughly round, similar sizes<\/button><button type=\"button\" class=\"cd-chip\" data-v=\"odd\" aria-pressed=\"false\">Odd shapes, or with noise<\/button><\/div><\/div><div class=\"cd-card cd-ap-out\" aria-live=\"polite\"><\/div><\/div>\n\n\n\n<h2 id=\"ml-interview-questions-for-freshers\" class=\"wp-block-heading\">Machine learning interview questions for freshers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 40 basic machine learning interview questions cover what campus placements and first data science interviews ask: types of learning, overfitting and the bias-variance tradeoff, data preparation, the core algorithms, evaluation metrics, clustering, gradient descent and the basics of neural networks.<\/p>\n\n\n\n<div id=\"q-1\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q1<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">1. What is machine learning?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Machine learning is a way of building software that learns patterns from data instead of following rules a programmer wrote by hand. You show the model many examples, it adjusts its internal numbers (parameters) to fit them, and then it makes predictions on new data it has never seen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A spam filter is the classic example. Writing rules for every kind of spam is impossible, but if you give a model thousands of emails labelled &#8220;spam&#8221; or &#8220;not spam&#8221;, it learns which words and patterns matter. Tom Mitchell&#8217;s textbook definition is often quoted in interviews: a program learns from experience E on task T, measured by performance P, if its performance on T improves with E.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-2\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q2<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">2. What is the difference between AI, machine learning, deep learning and generative AI?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Term<\/th><th>What it means<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Artificial intelligence (AI)<\/td><td>The broad goal of making machines do tasks that need human intelligence<\/td><td>Chess engines, chatbots, self-driving cars<\/td><\/tr><tr><td>Machine learning (ML)<\/td><td>A part of AI where systems learn patterns from data<\/td><td>Spam filters, loan approval, price prediction<\/td><\/tr><tr><td>Deep learning (DL)<\/td><td>A part of ML that uses neural networks with many layers<\/td><td>Face recognition, speech to text<\/td><\/tr><tr><td>Generative AI<\/td><td>Deep learning models that create new text, images, audio or code<\/td><td>ChatGPT, Claude, image generators<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Each one sits inside the one before it: all deep learning is machine learning, and all machine learning is AI, but not the other way round. Our <a href=\"https:\/\/codeanddebug.in\/blog\/how-to-learn-ai-ml-from-scratch-roadmap\/\">AI and ML roadmap<\/a> shows how they connect as a learning path.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-3\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q3<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">3. What are the main types of machine learning?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Supervised learning:<\/strong> the training data has the correct answers (labels). The model learns to map inputs to outputs. Examples: predicting house prices, detecting spam.<\/li>\n\n\n\n<li><strong>Unsupervised learning:<\/strong> no labels. The model finds structure on its own, such as groups of similar customers or a compressed version of the data.<\/li>\n\n\n\n<li><strong>Reinforcement learning:<\/strong> an agent takes actions in an environment and learns from rewards and penalties. Examples: game-playing agents, robot control.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Two in-between types also come up: <strong>semi-supervised learning<\/strong> uses a few labelled examples plus many unlabelled ones, and <strong>self-supervised learning<\/strong> creates labels from the data itself, such as predicting the next word. Large language models are trained mostly with self-supervised learning.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-4\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q4<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">4. What is the difference between supervised and unsupervised learning?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Point<\/th><th>Supervised<\/th><th>Unsupervised<\/th><\/tr><\/thead><tbody><tr><td>Labels<\/td><td>Needed for every training example<\/td><td>Not needed<\/td><\/tr><tr><td>Goal<\/td><td>Predict a known target<\/td><td>Find hidden structure or groups<\/td><\/tr><tr><td>Typical tasks<\/td><td>Classification, regression<\/td><td>Clustering, dimensionality reduction, anomaly detection<\/td><\/tr><tr><td>Algorithms<\/td><td>Linear and logistic regression, decision trees, SVM, random forest<\/td><td>K-means, DBSCAN, hierarchical clustering, PCA<\/td><\/tr><tr><td>How you evaluate<\/td><td>Compare predictions with true labels<\/td><td>Harder; use measures like silhouette score or business judgement<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A simple way to remember it: if you know what the right answer looks like for past data, it is supervised.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-5\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q5<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">5. What is the difference between classification and regression?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both are supervised learning. <strong>Classification<\/strong> predicts a category: spam or not spam, which digit is in an image, whether a loan will default. <strong>Regression<\/strong> predicts a continuous number: a house price, tomorrow&#8217;s temperature, a delivery time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The difference also changes how you measure success. Classification uses accuracy, precision, recall and F1; regression uses MAE, RMSE and R\u00b2. Note that <a href=\"https:\/\/codeanddebug.in\/blog\/logistic-regression-in-machine-learning\/\">logistic regression<\/a> is a classification algorithm despite its name, because it outputs a probability that is turned into a class.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-6\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q6<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">6. What are features, labels and training data?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Features<\/strong> (also called inputs, predictors or independent variables) are the pieces of information the model uses, such as a flat&#8217;s size, location and floor. The <strong>label<\/strong> (target or dependent variable) is what you want to predict, such as its rent. <strong>Training data<\/strong> is the set of past examples that have both features and labels.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In code, features are usually a 2D array or DataFrame called <code>X<\/code>, with one row per example and one column per feature, and labels are a 1D array called <code>y<\/code>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-7\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q7<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">7. Why do we split data into training, validation and test sets?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A model must be judged on data it has not seen, otherwise a model that simply memorised the training data would look perfect. So the data is split:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Training set<\/strong> (often 60 to 80%): the model learns from it.<\/li>\n\n\n\n<li><strong>Validation set<\/strong>: used to compare models and tune hyperparameters. Cross-validation can replace a fixed validation set.<\/li>\n\n\n\n<li><strong>Test set<\/strong> (often 10 to 20%): touched only once, at the very end, to estimate real-world performance.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\n\nX, y = load_iris(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, stratify=y, random_state=42)\n\nprint(\"Train:\", X_train.shape, \"| Test:\", X_test.shape)\nprint(\"Class counts in test:\", &#91;int((y_test == c).sum()) for c in range(3)&#93;)<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_iris<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_iris(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_train, X_test, y_train, y_test = train_test_split(<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    X, y, <\/span><span style=\"color: #9CDCFE\">test_size<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0.2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">stratify<\/span><span style=\"color: #D4D4D4\">=y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">42<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Train:&quot;<\/span><span style=\"color: #D4D4D4\">, X_train.shape, <\/span><span style=\"color: #CE9178\">&quot;| Test:&quot;<\/span><span style=\"color: #D4D4D4\">, X_test.shape)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Class counts in test:&quot;<\/span><span style=\"color: #D4D4D4\">, &#91;<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">((y_test == c).sum()) <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> c <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">)&#93;)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Train: (120, 4) | Test: (30, 4)\nClass counts in test: &#91;10, 10, 10&#93;<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Train: (120, 4) | Test: (30, 4)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Class counts in test: &#91;10, 10, 10&#93;<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Using <code>stratify=y<\/code> keeps the class proportions the same in both parts, which matters for small or imbalanced datasets. If you keep checking the test set while tuning, it stops being an honest estimate.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-8\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q8<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">8. What are overfitting and underfitting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Overfitting<\/strong> means the model has learned the training data too closely, including its noise. It scores very well on training data and badly on new data. <strong>Underfitting<\/strong> means the model is too simple to capture the real pattern, so it does badly on both.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here a polynomial is fitted to 15 noisy points from a sine curve. Degree 1 (a straight line) underfits, degree 3 is about right, and degree 12 overfits: its training error is the lowest, but its test error explodes.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\n\nrng = np.random.default_rng(1)\nx = rng.uniform(0, 1, 15).reshape(-1, 1)\ny = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 15)\nx_test = rng.uniform(0, 1, 200).reshape(-1, 1)\ny_test = np.sin(2 * np.pi * x_test).ravel() + rng.normal(0, 0.2, 200)\n\nfor degree in &#91;1, 3, 12&#93;:\n    model = make_pipeline(PolynomialFeatures(degree), LinearRegression()).fit(x, y)\n    print(f\"degree {degree:2d}: train MSE={mean_squared_error(y, model.predict(x)):.3f}  \"\n          f\"test MSE={mean_squared_error(y_test, model.predict(x_test)):.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LinearRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> mean_squared_error<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_pipeline<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> PolynomialFeatures<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rng = np.random.default_rng(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">x = rng.uniform(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">15<\/span><span style=\"color: #D4D4D4\">).reshape(-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y = np.sin(<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * np.pi * x).ravel() + rng.normal(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">15<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">x_test = rng.uniform(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">200<\/span><span style=\"color: #D4D4D4\">).reshape(-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_test = np.sin(<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * np.pi * x_test).ravel() + rng.normal(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">200<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> degree <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">12<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    model = make_pipeline(PolynomialFeatures(degree), LinearRegression()).fit(x, y)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;degree <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">degree<\/span><span style=\"color: #569CD6\">:2d}<\/span><span style=\"color: #CE9178\">: train MSE=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">mean_squared_error(y, model.predict(x))<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">  &quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">          <\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;test MSE=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">mean_squared_error(y_test, model.predict(x_test))<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>degree  1: train MSE=0.298  test MSE=0.251\ndegree  3: train MSE=0.016  test MSE=0.060\ndegree 12: train MSE=0.007  test MSE=3.418<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">degree  1: train MSE=0.298  test MSE=0.251<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">degree  3: train MSE=0.016  test MSE=0.060<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">degree 12: train MSE=0.007  test MSE=3.418<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The bias-variance slider further up this page lets you see the same thing visually.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-9\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q9<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">9. What is the bias-variance tradeoff?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Bias<\/strong> is error from wrong or overly simple assumptions: a straight line can never fit a curve, however much data you give it. <strong>Variance<\/strong> is error from being too sensitive to the particular training data: a very flexible model changes a lot if you train it on a slightly different sample.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Simple models have high bias and low variance (they underfit). Complex models have low bias and high variance (they overfit). Expected test error is roughly bias\u00b2 + variance + irreducible noise, so the best model sits in the middle, where the total is lowest. More data lowers variance, which is why complex models need a lot of it.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-10\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Basics\"><span class=\"cd-pill\">Q10<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">10. How can you prevent overfitting?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Get more training data, or use data augmentation for images and text.<\/li>\n\n\n\n<li>Use a simpler model or fewer features.<\/li>\n\n\n\n<li>Add regularisation (L1, L2, dropout for neural networks).<\/li>\n\n\n\n<li>Use cross-validation to choose hyperparameters honestly.<\/li>\n\n\n\n<li>Limit model complexity: <code>max_depth<\/code> for trees, fewer layers or units for neural networks.<\/li>\n\n\n\n<li>Stop training early when the validation score stops improving.<\/li>\n\n\n\n<li>Use ensembles such as random forests, which average out the variance of single models.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In an interview, mention that you first <em>detect<\/em> overfitting by comparing training and validation scores. A large gap is the signal.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-11\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q11<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">11. What is feature engineering?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Feature engineering is creating, transforming or selecting input features so the model can learn more easily. Good features often matter more than the choice of algorithm.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Extracting parts of a date: day of week, month, is_weekend, is_festival_season.<\/li>\n\n\n\n<li>Ratios and differences: price per square foot, debt-to-income ratio.<\/li>\n\n\n\n<li>Aggregates: a customer&#8217;s average order value over the last 30 days.<\/li>\n\n\n\n<li>Text features: word counts, TF-IDF, embeddings.<\/li>\n\n\n\n<li>Encoding categories, scaling numbers and handling missing values (the next few questions).<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-12\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q12<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">12. How do you handle missing values?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First find out <em>why<\/em> values are missing, because that decides the fix. Then choose:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Drop<\/strong> rows or columns, if very few rows are affected or a column is mostly empty.<\/li>\n\n\n\n<li><strong>Impute<\/strong> with the mean or median (numbers) or the most frequent value (categories).<\/li>\n\n\n\n<li><strong>Model-based imputation<\/strong>, such as KNN imputation or iterative imputation.<\/li>\n\n\n\n<li><strong>Add a &#8220;was missing&#8221; indicator<\/strong> column, because missingness itself can carry information.<\/li>\n\n\n\n<li>Use models that handle missing values natively, such as gradient boosting libraries.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nimport pandas as pd\nfrom sklearn.impute import SimpleImputer\n\ndf = pd.DataFrame({\"age\": &#91;25, np.nan, 40, 35, np.nan&#93;,\n                   \"city\": &#91;\"Surat\", \"Pune\", np.nan, \"Pune\", \"Pune\"&#93;})\n\nnum = SimpleImputer(strategy=\"median\").fit_transform(df[&#91;\"age\"&#93;])\ncat = SimpleImputer(strategy=\"most_frequent\").fit_transform(df[&#91;\"city\"&#93;])\nprint(\"age: \", num.ravel())\nprint(\"city:\", cat.ravel())<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> pandas <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> pd<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.impute <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> SimpleImputer<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">df = pd.DataFrame({<\/span><span style=\"color: #CE9178\">&quot;age&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">25<\/span><span style=\"color: #D4D4D4\">, np.nan, <\/span><span style=\"color: #B5CEA8\">40<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">35<\/span><span style=\"color: #D4D4D4\">, np.nan&#93;,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                   <\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #CE9178\">&quot;Surat&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, np.nan, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">&#93;})<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">num = SimpleImputer(<\/span><span style=\"color: #9CDCFE\">strategy<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;median&quot;<\/span><span style=\"color: #D4D4D4\">).fit_transform(df[&#91;<\/span><span style=\"color: #CE9178\">&quot;age&quot;<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">cat = SimpleImputer(<\/span><span style=\"color: #9CDCFE\">strategy<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;most_frequent&quot;<\/span><span style=\"color: #D4D4D4\">).fit_transform(df[&#91;<\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;age: &quot;<\/span><span style=\"color: #D4D4D4\">, num.ravel())<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;city:&quot;<\/span><span style=\"color: #D4D4D4\">, cat.ravel())<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>age:  &#91;25. 35. 40. 35. 35.&#93;\ncity: &#91;'Surat' 'Pune' 'Pune' 'Pune' 'Pune'&#93;<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">age:  &#91;25. 35. 40. 35. 35.&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">city: &#91;&#39;Surat&#39; &#39;Pune&#39; &#39;Pune&#39; &#39;Pune&#39; &#39;Pune&#39;&#93;<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Fit the imputer on the training data only and reuse it on the test data, otherwise information leaks from the test set. A scikit-learn Pipeline (question 64) does this for you.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-13\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q13<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">13. What is the difference between normalisation and standardisation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Normalisation<\/strong> (min-max scaling) squeezes values into a fixed range, usually 0 to 1: <code>(x \u2212 min) \/ (max \u2212 min)<\/code>. <strong>Standardisation<\/strong> (z-score) rescales values to mean 0 and standard deviation 1: <code>(x \u2212 mean) \/ std<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n\nsalary = np.array([&#91;20000&#93;, &#91;35000&#93;, &#91;50000&#93;, &#91;120000&#93;])\n\nprint(\"Min-max:     \", MinMaxScaler().fit_transform(salary).ravel().round(3))\nprint(\"Standardised:\", StandardScaler().fit_transform(salary).ravel().round(3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> MinMaxScaler, StandardScaler<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">salary = np.array([&#91;<\/span><span style=\"color: #B5CEA8\">20000<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">35000<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">50000<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">120000<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Min-max:     &quot;<\/span><span style=\"color: #D4D4D4\">, MinMaxScaler().fit_transform(salary).ravel().round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Standardised:&quot;<\/span><span style=\"color: #D4D4D4\">, StandardScaler().fit_transform(salary).ravel().round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Min-max:      &#91;0.   0.15 0.3  1.  &#93;\nStandardised: &#91;-0.946 -0.555 -0.163  1.664&#93;<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Min-max:      &#91;0.   0.15 0.3  1.  &#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Standardised: &#91;-0.946 -0.555 -0.163  1.664&#93;<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Standardisation is the usual default and copes better with outliers; one extreme salary squashes all other min-max values towards 0. Min-max is handy when you need a bounded range, such as pixel values. Scaling matters for distance-based and gradient-based models (KNN, k-means, SVM, linear models, neural networks) but not for tree-based models.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-14\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q14<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">14. How do you encode categorical variables?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Models need numbers, so text categories must be encoded:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>One-hot encoding:<\/strong> one 0\/1 column per category. Safe for categories with no order, like city.<\/li>\n\n\n\n<li><strong>Ordinal (label) encoding:<\/strong> one integer per category. Use it only when the categories have a real order, like S, M, L, or with tree models.<\/li>\n\n\n\n<li><strong>Target encoding:<\/strong> replace each category with the average target for it. Useful for many categories, but it must be done inside cross-validation to avoid leakage.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder, OrdinalEncoder\n\ndf = pd.DataFrame({\"city\": &#91;\"Surat\", \"Pune\", \"Delhi\", \"Pune\"&#93;,\n                   \"size\": &#91;\"S\", \"L\", \"M\", \"S\"&#93;})\n\nonehot = OneHotEncoder(sparse_output=False).fit(df[&#91;\"city\"&#93;])\nprint(onehot.get_feature_names_out())\nprint(onehot.transform(df[&#91;\"city\"&#93;]))\n\nordinal = OrdinalEncoder(categories=[&#91;\"S\", \"M\", \"L\"&#93;])\nprint(\"size:\", ordinal.fit_transform(df[&#91;\"size\"&#93;]).ravel())<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> pandas <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> pd<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> OneHotEncoder, OrdinalEncoder<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">df = pd.DataFrame({<\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #CE9178\">&quot;Surat&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Delhi&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">&#93;,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                   <\/span><span style=\"color: #CE9178\">&quot;size&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #CE9178\">&quot;S&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;L&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;M&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;S&quot;<\/span><span style=\"color: #D4D4D4\">&#93;})<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">onehot = OneHotEncoder(<\/span><span style=\"color: #9CDCFE\">sparse_output<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\">).fit(df[&#91;<\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(onehot.get_feature_names_out())<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(onehot.transform(df[&#91;<\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">&#93;]))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">ordinal = OrdinalEncoder(<\/span><span style=\"color: #9CDCFE\">categories<\/span><span style=\"color: #D4D4D4\">=[&#91;<\/span><span style=\"color: #CE9178\">&quot;S&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;M&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;L&quot;<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;size:&quot;<\/span><span style=\"color: #D4D4D4\">, ordinal.fit_transform(df[&#91;<\/span><span style=\"color: #CE9178\">&quot;size&quot;<\/span><span style=\"color: #D4D4D4\">&#93;]).ravel())<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>&#91;'city_Delhi' 'city_Pune' 'city_Surat'&#93;\n[&#91;0. 0. 1.&#93;\n &#91;0. 1. 0.&#93;\n &#91;1. 0. 0.&#93;\n &#91;0. 1. 0.&#93;]\nsize: &#91;0. 2. 1. 0.&#93;<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">&#91;&#39;city_Delhi&#39; &#39;city_Pune&#39; &#39;city_Surat&#39;&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">[&#91;0. 0. 1.&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;0. 1. 0.&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;1. 0. 0.&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;0. 1. 0.&#93;]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">size: &#91;0. 2. 1. 0.&#93;<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Giving cities the numbers 0, 1 and 2 with a linear model would wrongly tell it that Delhi &lt; Pune &lt; Surat. That is why one-hot encoding is the default for unordered categories.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-15\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q15<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">15. What is data leakage?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Data leakage happens when information that would not be available at prediction time sneaks into training. The model looks great in testing and fails in real use. Common causes:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A feature that is created after the outcome, such as &#8220;refund issued&#8221; when predicting fraud.<\/li>\n\n\n\n<li>Scaling, imputing or selecting features on the whole dataset before splitting.<\/li>\n\n\n\n<li>Duplicate or near-duplicate rows in both train and test.<\/li>\n\n\n\n<li>Random splits on time series, so the model trains on the future.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here the labels are pure coin flips, so no model can beat 50%. Selecting features on all the data first gives a fake 85%:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.feature_selection import SelectKBest, f_classif\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.pipeline import make_pipeline\n\nrng = np.random.default_rng(0)\nX = rng.normal(size=(100, 5000))        # pure noise features\ny = rng.integers(0, 2, 100)             # random labels: nothing to learn\n\n# WRONG: pick the \"best\" features using all the data, then cross-validate\nX_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)\nleaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5).mean()\n\n# RIGHT: feature selection happens inside each training fold\npipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))\nhonest = cross_val_score(pipe, X, y, cv=5).mean()\n\nprint(f\"Leaky accuracy:  {leaky:.2f}\")\nprint(f\"Honest accuracy: {honest:.2f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.feature_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> SelectKBest, f_classif<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> cross_val_score<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_pipeline<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rng = np.random.default_rng(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X = rng.normal(<\/span><span style=\"color: #9CDCFE\">size<\/span><span style=\"color: #D4D4D4\">=(<\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">5000<\/span><span style=\"color: #D4D4D4\">))        <\/span><span style=\"color: #6A9955\"># pure noise features<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y = rng.integers(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">)             <\/span><span style=\"color: #6A9955\"># random labels: nothing to learn<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># WRONG: pick the &quot;best&quot; features using all the data, then cross-validate<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_sel = SelectKBest(f_classif, <\/span><span style=\"color: #9CDCFE\">k<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">).fit_transform(X, y)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">leaky = cross_val_score(LogisticRegression(<\/span><span style=\"color: #9CDCFE\">max_iter<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">), X_sel, y, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">).mean()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># RIGHT: feature selection happens inside each training fold<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">pipe = make_pipeline(SelectKBest(f_classif, <\/span><span style=\"color: #9CDCFE\">k<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">), LogisticRegression(<\/span><span style=\"color: #9CDCFE\">max_iter<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">honest = cross_val_score(pipe, X, y, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">).mean()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;Leaky accuracy:  <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">leaky<\/span><span style=\"color: #569CD6\">:.2f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;Honest accuracy: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">honest<\/span><span style=\"color: #569CD6\">:.2f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Leaky accuracy:  0.85\nHonest accuracy: 0.48<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Leaky accuracy:  0.85<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Honest accuracy: 0.48<\/span><\/span><\/code><\/pre><\/div>\n<\/div><\/div>\n\n\n\n<div id=\"q-16\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q16<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">16. What are outliers and how do you handle them?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Outliers are values far away from the rest of the data, such as a salary of \u20b95 crore in a dataset of students&#8217; first jobs. Detect them with box plots, the IQR rule (below Q1 \u2212 1.5 \u00d7 IQR or above Q3 + 1.5 \u00d7 IQR), z-scores above about 3, or models like Isolation Forest.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then decide whether each one is an error or a real but rare value. Fix or remove errors. Keep real ones but reduce their effect: cap them (winsorising), apply a log transform, use robust models (trees, median-based methods) or robust losses (MAE, Huber). Never drop outliers blindly; in fraud detection the outliers are often the whole point.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-17\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q17<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">17. What is the curse of dimensionality?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As the number of features grows, the space the data lives in grows so fast that the data becomes very sparse. You would need exponentially more data to cover it. Distances also become less meaningful, because in high dimensions the nearest and furthest points are almost the same distance away.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This hurts distance-based models like KNN and k-means the most, and raises the risk of overfitting for everything. Fixes are feature selection, dimensionality reduction (PCA), regularisation, or simply collecting more data.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-18\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Regression\"><span class=\"cd-pill\">Q18<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Regression<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">18. How does linear regression work, and what are its assumptions?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Linear regression predicts a number as a weighted sum of the features plus a constant: <code>\u0177 = w\u2081x\u2081 + w\u2082x\u2082 + \u2026 + b<\/code>. Training finds the weights that minimise the mean squared error between predictions and actual values, either with a closed-form solution (ordinary least squares) or with gradient descent.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The classic assumptions are: a linear relationship between features and target, independent errors, constant error variance (homoscedasticity), normally distributed errors (mainly for confidence intervals), and little multicollinearity between features. Our <a href=\"https:\/\/codeanddebug.in\/blog\/linear-regression-in-machine-learning\/\">linear regression guide<\/a> shows each one visually.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-19\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Regression\"><span class=\"cd-pill\">Q19<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Regression<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">19. What is the difference between MAE, MSE and RMSE?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>MAE<\/strong> (mean absolute error): the average size of the errors. Easy to explain and treats all errors equally.<\/li>\n\n\n\n<li><strong>MSE<\/strong> (mean squared error): the average of squared errors. Big errors count much more. Its unit is squared, which is hard to read.<\/li>\n\n\n\n<li><strong>RMSE<\/strong>: the square root of MSE, back in the original unit, still punishing big errors.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n\ny_true = np.array(&#91;50, 60, 70, 80, 90&#93;)     # actual flat prices (lakh)\ny_pred = np.array(&#91;52, 58, 75, 78, 70&#93;)     # one big miss on the last flat\n\nprint(\"MAE: \", mean_absolute_error(y_true, y_pred))\nprint(\"MSE: \", mean_squared_error(y_true, y_pred))\nprint(\"RMSE:\", round(np.sqrt(mean_squared_error(y_true, y_pred)), 2))\nprint(\"R2:  \", round(r2_score(y_true, y_pred), 3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> mean_absolute_error, mean_squared_error, r2_score<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_true = np.array(&#91;<\/span><span style=\"color: #B5CEA8\">50<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">60<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">70<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">80<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">90<\/span><span style=\"color: #D4D4D4\">&#93;)     <\/span><span style=\"color: #6A9955\"># actual flat prices (lakh)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_pred = np.array(&#91;<\/span><span style=\"color: #B5CEA8\">52<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">58<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">75<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">78<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">70<\/span><span style=\"color: #D4D4D4\">&#93;)     <\/span><span style=\"color: #6A9955\"># one big miss on the last flat<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;MAE: &quot;<\/span><span style=\"color: #D4D4D4\">, mean_absolute_error(y_true, y_pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;MSE: &quot;<\/span><span style=\"color: #D4D4D4\">, mean_squared_error(y_true, y_pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;RMSE:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(np.sqrt(mean_squared_error(y_true, y_pred)), <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;R2:  &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(r2_score(y_true, y_pred), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>MAE:  6.2\nMSE:  87.4\nRMSE: 9.35\nR2:   0.563<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">MAE:  6.2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">MSE:  87.4<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">RMSE: 9.35<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">R2:   0.563<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">One flat is off by \u20b920 lakh. MAE says the typical miss is 6.2 lakh, while RMSE (9.35) is pulled up by that single large miss. Choose RMSE when big errors are especially costly, and MAE when you want a measure that outliers do not dominate.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-20\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Regression\"><span class=\"cd-pill\">Q20<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Regression<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">20. What is R\u00b2 (the coefficient of determination)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">R\u00b2 tells you what share of the variation in the target your model explains, compared with always predicting the average. R\u00b2 = 1 \u2212 (sum of squared errors of the model \/ sum of squared errors of the mean). 1 is perfect, 0 means no better than predicting the mean, and it can be negative for a model worse than that. In the example above, R\u00b2 is 0.563.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Plain R\u00b2 never goes down when you add features, even useless ones. <strong>Adjusted R\u00b2<\/strong> corrects for the number of features, so it is better for comparing models with different feature counts.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-21\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Classification\"><span class=\"cd-pill\">Q21<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">21. How does logistic regression work, and why not use linear regression for classification?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Logistic regression computes a weighted sum of the features, just like linear regression, and then passes it through the sigmoid function to get a probability between 0 and 1. If the probability is above a threshold (usually 0.5), it predicts the positive class. It is trained by minimising log loss, not MSE.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\nhours = np.array([&#91;1&#93;, &#91;2&#93;, &#91;3&#93;, &#91;4&#93;, &#91;5&#93;, &#91;6&#93;, &#91;7&#93;, &#91;8&#93;])\npassed = np.array(&#91;0, 0, 0, 1, 0, 1, 1, 1&#93;)\n\nmodel = LogisticRegression().fit(hours, passed)\nfor h in &#91;2, 4.5, 7&#93;:\n    print(f\"{h} hours -> P(pass) = {model.predict_proba([&#91;h&#93;])&#91;0, 1&#93;:.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">hours = np.array([&#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">6<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">7<\/span><span style=\"color: #D4D4D4\">&#93;, &#91;<\/span><span style=\"color: #B5CEA8\">8<\/span><span style=\"color: #D4D4D4\">&#93;])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">passed = np.array(&#91;<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">model = LogisticRegression().fit(hours, passed)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> h <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">4.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">7<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">h<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\"> hours -&gt; P(pass) = <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">model.predict_proba([&#91;h&#93;])&#91;<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>2 hours -> P(pass) = 0.103\n4.5 hours -> P(pass) = 0.500\n7 hours -> P(pass) = 0.897<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">2 hours -&gt; P(pass) = 0.103<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">4.5 hours -&gt; P(pass) = 0.500<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">7 hours -&gt; P(pass) = 0.897<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Linear regression is a poor fit for classification because its output is not limited to 0 to 1, so it cannot be read as a probability, and a few extreme points can shift the line and move the decision boundary badly. Our <a href=\"https:\/\/codeanddebug.in\/blog\/logistic-regression-in-machine-learning\/\">logistic regression guide<\/a> walks through this with interactive charts.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-22\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Classification\"><span class=\"cd-pill\">Q22<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">22. What is the sigmoid function?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The sigmoid (logistic) function is <code>\u03c3(z) = 1 \/ (1 + e<sup>\u2212z<\/sup>)<\/code>. It turns any real number into a value between 0 and 1: large positive inputs go close to 1, large negative inputs go close to 0, and 0 maps to exactly 0.5.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That makes it ideal for turning a score into a probability in logistic regression and in the output layer of binary neural networks. Its derivative is simple, \u03c3(z) \u00d7 (1 \u2212 \u03c3(z)), which is useful in backpropagation. Its weakness is that it flattens at both ends, so gradients become tiny there (question 70).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-23\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Classification\"><span class=\"cd-pill\">Q23<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">23. How does the KNN algorithm work, and how do you choose K?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">K-nearest neighbours stores the training data and, for a new point, finds the K closest training points (usually by Euclidean distance). For classification it takes a majority vote of their labels; for regression it averages their values. It has no real training step, so it is called a lazy learner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Small K (like 1) follows the noise and overfits; large K smooths too much and underfits. Choose K with cross-validation, use an odd K for two classes to avoid ties, and always scale features first.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nX, y = load_breast_cancer(return_X_y=True)\nfor k in &#91;1, 3, 5, 11, 21, 51&#93;:\n    model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))\n    print(f\"K={k:2d}  CV accuracy={cross_val_score(model, X, y, cv=5).mean():.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_breast_cancer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> cross_val_score<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.neighbors <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> KNeighborsClassifier<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_pipeline<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> StandardScaler<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_breast_cancer(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> k <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">11<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">21<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">51<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    model = make_pipeline(StandardScaler(), KNeighborsClassifier(<\/span><span style=\"color: #9CDCFE\">n_neighbors<\/span><span style=\"color: #D4D4D4\">=k))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;K=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">k<\/span><span style=\"color: #569CD6\">:2d}<\/span><span style=\"color: #CE9178\">  CV accuracy=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">cross_val_score(model, X, y, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">).mean()<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>K= 1  CV accuracy=0.954\nK= 3  CV accuracy=0.960\nK= 5  CV accuracy=0.965\nK=11  CV accuracy=0.965\nK=21  CV accuracy=0.956\nK=51  CV accuracy=0.951<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">K= 1  CV accuracy=0.954<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K= 3  CV accuracy=0.960<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K= 5  CV accuracy=0.965<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=11  CV accuracy=0.965<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=21  CV accuracy=0.956<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=51  CV accuracy=0.951<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Here K = 5 and K = 11 do best. KNN is easy to understand but slow to predict on large datasets and weak in high dimensions. Do not confuse it with <a href=\"https:\/\/codeanddebug.in\/blog\/k-means-clustering\/\">k-means clustering<\/a>, where K means the number of clusters.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-24\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Classification\"><span class=\"cd-pill\">Q24<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">24. What is Naive Bayes, and why is it called naive?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Naive Bayes is a classifier based on Bayes&#8217; theorem: P(class | features) \u221d P(features | class) \u00d7 P(class). It is called naive because it assumes every feature is independent of the others once you know the class. In spam filtering, that means it treats &#8220;free&#8221; and &#8220;prize&#8221; as unrelated words, which is not true, but the model still works surprisingly well.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\n\ntexts = &#91;\"win a free prize now\", \"free cash offer win\", \"meeting at 5 pm\",\n         \"project report due tomorrow\", \"claim your free prize\", \"lunch tomorrow?\"&#93;\nlabels = &#91;1, 1, 0, 0, 1, 0&#93;                  # 1 = spam\n\nvec = CountVectorizer()\nmodel = MultinomialNB().fit(vec.fit_transform(texts), labels)\n\nnew = &#91;\"free prize for you\", \"report meeting tomorrow\"&#93;\nprint(model.predict(vec.transform(new)))\nprint(model.predict_proba(vec.transform(new)).round(3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.feature_extraction.text <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> CountVectorizer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.naive_bayes <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> MultinomialNB<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">texts = &#91;<\/span><span style=\"color: #CE9178\">&quot;win a free prize now&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;free cash offer win&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;meeting at 5 pm&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">         <\/span><span style=\"color: #CE9178\">&quot;project report due tomorrow&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;claim your free prize&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;lunch tomorrow?&quot;<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">labels = &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">&#93;                  <\/span><span style=\"color: #6A9955\"># 1 = spam<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">vec = CountVectorizer()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">model = MultinomialNB().fit(vec.fit_transform(texts), labels)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">new = &#91;<\/span><span style=\"color: #CE9178\">&quot;free prize for you&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;report meeting tomorrow&quot;<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(model.predict(vec.transform(new)))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(model.predict_proba(vec.transform(new)).round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>&#91;1 0&#93;\n[&#91;0.095 0.905&#93;\n &#91;0.944 0.056&#93;]<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">&#91;1 0&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">[&#91;0.095 0.905&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;0.944 0.056&#93;]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Variants: Gaussian NB for continuous features, Multinomial NB for word counts, Bernoulli NB for yes\/no features. It is very fast, needs little data and is a strong baseline for text. Its probability estimates are often poorly calibrated (question 83).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-25\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q25<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">25. How does a decision tree work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A decision tree predicts by asking a series of yes or no questions about the features, such as &#8220;income \u2264 \u20b936,500?&#8221;. At each node it tries every feature and threshold and picks the split that makes the child nodes purest, measured with Gini impurity or entropy for classification and squared error for regression. It repeats this until a stopping rule is met, and each leaf holds the prediction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Trees are easy to explain and need no scaling, but they overfit easily, so you limit <code>max_depth<\/code> or prune them. You can grow one step by step in our <a href=\"https:\/\/codeanddebug.in\/blog\/decision-tree-in-machine-learning\/\">interactive decision tree guide<\/a>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-26\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q26<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">26. What are Gini impurity and entropy?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both measure how mixed the classes in a node are. <strong>Gini impurity<\/strong> = 1 \u2212 \u03a3 p\u1d62\u00b2, the chance of mislabelling a random point if you guess using the node&#8217;s class mix. <strong>Entropy<\/strong> = \u2212\u03a3 p\u1d62 log\u2082 p\u1d62, the uncertainty in the node. Both are 0 for a pure node; for two classes Gini peaks at 0.5 and entropy at 1.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The tree picks the split with the largest drop in impurity; with entropy this drop is called <strong>information gain<\/strong>. Gini and entropy choose the same split in most cases. Gini is the scikit-learn default and is slightly faster because it needs no logarithm.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-27\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Classification\"><span class=\"cd-pill\">Q27<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">27. What is a support vector machine (SVM)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An SVM finds the boundary that separates two classes with the widest possible gap, called the margin. Only the points closest to the boundary, the <strong>support vectors<\/strong>, decide where it goes. The <code>C<\/code> parameter controls how many points may sit inside the margin or on the wrong side: small C gives a wide, tolerant margin, large C a narrow, strict one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With the <strong>kernel trick<\/strong> (question 59), an SVM can draw curved boundaries without ever computing new features. SVMs work well on small to medium datasets with many features, but need scaled features and get slow on very large data. Try it in our <a href=\"https:\/\/codeanddebug.in\/blog\/support-vector-machine-in-machine-learning\/\">SVM playground<\/a>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-28\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q28<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">28. What is a confusion matrix?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A confusion matrix is a table that compares predicted classes with actual classes. For two classes it has four cells: true positives (TP), false positives (FP), false negatives (FN) and true negatives (TN). Every classification metric, from accuracy to F1, is built from these four numbers.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.metrics import (confusion_matrix, accuracy_score,\n                             precision_score, recall_score, f1_score)\n\n# 10 patients: 1 = has the disease\ny_true = &#91;1, 1, 1, 1, 0, 0, 0, 0, 0, 0&#93;\ny_pred = &#91;1, 1, 1, 0, 1, 0, 0, 0, 0, 0&#93;\n\nprint(confusion_matrix(y_true, y_pred))      # rows: actual 0, 1\nprint(\"Accuracy: \", accuracy_score(y_true, y_pred))\nprint(\"Precision:\", precision_score(y_true, y_pred))\nprint(\"Recall:   \", recall_score(y_true, y_pred))\nprint(\"F1:       \", f1_score(y_true, y_pred))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> (confusion_matrix, accuracy_score,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                             precision_score, recall_score, f1_score)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># 10 patients: 1 = has the disease<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_true = &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_pred = &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(confusion_matrix(y_true, y_pred))      <\/span><span style=\"color: #6A9955\"># rows: actual 0, 1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Accuracy: &quot;<\/span><span style=\"color: #D4D4D4\">, accuracy_score(y_true, y_pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Precision:&quot;<\/span><span style=\"color: #D4D4D4\">, precision_score(y_true, y_pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Recall:   &quot;<\/span><span style=\"color: #D4D4D4\">, recall_score(y_true, y_pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;F1:       &quot;<\/span><span style=\"color: #D4D4D4\">, f1_score(y_true, y_pred))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>[&#91;5 1&#93;\n &#91;1 3&#93;]\nAccuracy:  0.8\nPrecision: 0.75\nRecall:    0.75\nF1:        0.75<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">[&#91;5 1&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;1 3&#93;]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Accuracy:  0.8<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Precision: 0.75<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Recall:    0.75<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">F1:        0.75<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">scikit-learn puts actual classes in rows and predicted classes in columns, with class 0 first, so the layout is [[TN, FP], [FN, TP]]. Here: 5 true negatives, 1 false positive, 1 false negative, 3 true positives. Our <a href=\"https:\/\/codeanddebug.in\/blog\/confusion-matrix-in-machine-learning\/\">interactive confusion matrix guide<\/a> covers every metric built from it.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-29\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q29<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">29. Why can accuracy be misleading?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Accuracy is the share of correct predictions. On imbalanced data it can look excellent while the model is useless. If 99% of transactions are genuine, a model that always says &#8220;not fraud&#8221; scores 99% accuracy and catches no fraud at all:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.metrics import accuracy_score, recall_score\n\ny = np.array(&#91;0&#93; * 990 + &#91;1&#93; * 10)          # 1% fraud\nX = np.zeros((1000, 1))\n\nlazy = DummyClassifier(strategy=\"most_frequent\").fit(X, y)\npred = lazy.predict(X)\nprint(\"Accuracy:\", accuracy_score(y, pred))\nprint(\"Fraud caught (recall):\", recall_score(y, pred))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.dummy <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> DummyClassifier<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> accuracy_score, recall_score<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y = np.array(&#91;<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">&#93; * <\/span><span style=\"color: #B5CEA8\">990<\/span><span style=\"color: #D4D4D4\"> + &#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93; * <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">)          <\/span><span style=\"color: #6A9955\"># 1% fraud<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X = np.zeros((<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">lazy = DummyClassifier(<\/span><span style=\"color: #9CDCFE\">strategy<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;most_frequent&quot;<\/span><span style=\"color: #D4D4D4\">).fit(X, y)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">pred = lazy.predict(X)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Accuracy:&quot;<\/span><span style=\"color: #D4D4D4\">, accuracy_score(y, pred))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Fraud caught (recall):&quot;<\/span><span style=\"color: #D4D4D4\">, recall_score(y, pred))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Accuracy: 0.99\nFraud caught (recall): 0.0<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Accuracy: 0.99<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Fraud caught (recall): 0.0<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">For imbalanced problems, report precision, recall, F1, PR AUC or a confusion matrix instead, and always compare against a simple baseline like this one.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-30\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q30<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">30. What is the difference between precision and recall?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Precision<\/strong> = TP \/ (TP + FP): of everything the model flagged as positive, how much really was positive. <strong>Recall<\/strong> (sensitivity) = TP \/ (TP + FN): of all the real positives, how many the model found.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Favour <strong>recall<\/strong> when missing a positive is costly: cancer screening, fraud detection.<\/li>\n\n\n\n<li>Favour <strong>precision<\/strong> when false alarms are costly: spam filtering (you do not want real email in spam), recommending a risky medical procedure.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">They usually trade off: lowering the decision threshold raises recall and lowers precision (question 48). The &#8220;Pick the right metric&#8221; game above lets you practise this choice.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-31\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q31<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">31. What is the F1 score?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The F1 score is the harmonic mean of precision and recall: F1 = 2 \u00d7 P \u00d7 R \/ (P + R). It ranges from 0 to 1 and is high only when both precision and recall are high. With precision 0.9 and recall 0.1 the simple average is 0.5, but F1 is only 0.18, which reflects how poor the model really is.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use F1 when you care about both kinds of error and the classes are imbalanced. If one matters more, use the F-beta score: \u03b2 &gt; 1 weights recall more, \u03b2 &lt; 1 weights precision more.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-32\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q32<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">32. What are the ROC curve and AUC?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ROC curve plots the true positive rate (recall) against the false positive rate for every possible threshold. AUC is the area under that curve. It equals the probability that the model gives a random positive example a higher score than a random negative one: 0.5 is random guessing and 1.0 is perfect.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">AUC is useful because it does not depend on one chosen threshold. On heavily imbalanced data, though, it can look too optimistic, and the precision-recall curve is more honest (question 47).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-33\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q33<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">33. What is cross-validation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In k-fold cross-validation the data is split into k equal parts (folds). The model is trained k times, each time on k \u2212 1 folds and tested on the remaining one, and the k scores are averaged. Every data point is used for testing exactly once.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_wine\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold\nfrom sklearn.tree import DecisionTreeClassifier\n\nX, y = load_wine(return_X_y=True)\ncv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)\nscores = cross_val_score(DecisionTreeClassifier(random_state=0), X, y, cv=cv)\n\nprint(\"Fold scores:\", scores.round(3))\nprint(f\"Mean: {scores.mean():.3f}  Std: {scores.std():.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_wine<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> cross_val_score, StratifiedKFold<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.tree <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> DecisionTreeClassifier<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_wine(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">cv = StratifiedKFold(<\/span><span style=\"color: #9CDCFE\">n_splits<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">shuffle<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">scores = cross_val_score(DecisionTreeClassifier(<\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">), X, y, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=cv)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Fold scores:&quot;<\/span><span style=\"color: #D4D4D4\">, scores.round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;Mean: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">scores.mean()<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">  Std: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">scores.std()<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Fold scores: &#91;0.917 0.833 0.972 0.971 0.943&#93;\nMean: 0.927  Std: 0.051<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Fold scores: &#91;0.917 0.833 0.972 0.971 0.943&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Mean: 0.927  Std: 0.051<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">It gives a more reliable estimate than a single split and shows how stable the model is: here scores range from 0.83 to 0.97 depending on the fold. Five or ten folds is typical. Use stratified folds for classification and time-based folds for time series (question 65). Reference: <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/cross_validation.html\" target=\"_blank\" rel=\"noopener\">scikit-learn cross-validation guide<\/a>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-34\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q34<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">34. What is clustering, and how does k-means work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Clustering is grouping similar data points without labels. K-means is the most common method:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Choose K, the number of clusters.<\/li>\n\n\n\n<li>Place K starting centroids (k-means++ spreads them out).<\/li>\n\n\n\n<li>Assign every point to its nearest centroid.<\/li>\n\n\n\n<li>Move each centroid to the mean of its points.<\/li>\n\n\n\n<li>Repeat steps 3 and 4 until nothing changes.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">It minimises the within-cluster sum of squares (inertia). It is fast but assumes round clusters of similar size, needs scaled features and only finds a local minimum, so it is run several times. Watch it step by step in our <a href=\"https:\/\/codeanddebug.in\/blog\/k-means-clustering\/\">k-means clustering playground<\/a>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-35\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q35<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">35. How do you choose the number of clusters K in k-means?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Two standard methods: the <strong>elbow method<\/strong> plots inertia against K and looks for the bend where adding clusters stops helping much, and the <strong>silhouette score<\/strong> measures how close each point is to its own cluster compared with the next nearest one, so you pick the K with the highest average.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nfrom sklearn.metrics import silhouette_score\n\nX, _ = make_blobs(n_samples=500, centers=4, random_state=7)\nfor k in range(2, 8):\n    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)\n    print(f\"K={k}  inertia={km.inertia_:8.0f}  silhouette={silhouette_score(X, km.labels_):.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.cluster <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> KMeans<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_blobs<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> silhouette_score<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, _ = make_blobs(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">500<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">centers<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">7<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> k <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">8<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    km = KMeans(<\/span><span style=\"color: #9CDCFE\">n_clusters<\/span><span style=\"color: #D4D4D4\">=k, <\/span><span style=\"color: #9CDCFE\">n_init<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">).fit(X)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;K=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">k<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">  inertia=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">km.inertia_<\/span><span style=\"color: #569CD6\">:8.0f}<\/span><span style=\"color: #CE9178\">  silhouette=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">silhouette_score(X, km.labels_)<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>K=2  inertia=   15172  silhouette=0.588\nK=3  inertia=    4313  silhouette=0.763\nK=4  inertia=     920  silhouette=0.811\nK=5  inertia=     818  silhouette=0.693\nK=6  inertia=     731  silhouette=0.578\nK=7  inertia=     651  silhouette=0.472<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">K=2  inertia=   15172  silhouette=0.588<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=3  inertia=    4313  silhouette=0.763<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=4  inertia=     920  silhouette=0.811<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=5  inertia=     818  silhouette=0.693<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=6  inertia=     731  silhouette=0.578<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">K=7  inertia=     651  silhouette=0.472<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Inertia drops sharply until K = 4 and then flattens, and the silhouette score peaks at K = 4, so both agree on four clusters. In real projects, also check whether the clusters are useful for the business.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-36\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q36<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">36. What is PCA (principal component analysis)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PCA is a dimensionality reduction technique. It finds new axes, called principal components, that are combinations of the original features. The first component points in the direction where the data varies most, the second in the next-most direction at right angles to the first, and so on. Keeping only the first few components keeps most of the information with far fewer features.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.decomposition import PCA\n\nX, _ = load_digits(return_X_y=True)           # 64 features (8x8 pixels)\npca = PCA().fit(X)\ncum = np.cumsum(pca.explained_variance_ratio_)\n\nprint(\"First 5 components explain:\", cum&#91;4&#93;.round(3))\nprint(\"Components for 90% variance:\", int(np.argmax(cum >= 0.90)) + 1)\nprint(\"Components for 95% variance:\", int(np.argmax(cum >= 0.95)) + 1)<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_digits<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.decomposition <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> PCA<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, _ = load_digits(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)           <\/span><span style=\"color: #6A9955\"># 64 features (8x8 pixels)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">pca = PCA().fit(X)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">cum = np.cumsum(pca.explained_variance_ratio_)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;First 5 components explain:&quot;<\/span><span style=\"color: #D4D4D4\">, cum&#91;<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">&#93;.round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Components for 90% variance:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">(np.argmax(cum &gt;= <\/span><span style=\"color: #B5CEA8\">0.90<\/span><span style=\"color: #D4D4D4\">)) + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Components for 95% variance:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">(np.argmax(cum &gt;= <\/span><span style=\"color: #B5CEA8\">0.95<\/span><span style=\"color: #D4D4D4\">)) + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>First 5 components explain: 0.545\nComponents for 90% variance: 21\nComponents for 95% variance: 29<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">First 5 components explain: 0.545<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Components for 90% variance: 21<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Components for 95% variance: 29<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The 64 pixel features of the digits dataset can be cut to 21 components while keeping 90% of the variance. PCA is used to speed up models, reduce noise and plot high-dimensional data in 2D. Scale features before PCA, and remember that the new components are harder to interpret than the original features.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-37\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q37<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">37. What is gradient descent?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Gradient descent is the method most models use to learn. It starts with some parameter values, computes the gradient of the loss (the direction in which the loss rises fastest), and takes a small step the opposite way. It repeats this until the loss stops falling. The size of each step is the <strong>learning rate<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\n\n# Fit y = w*x + b with plain gradient descent\nrng = np.random.default_rng(0)\nx = rng.uniform(0, 10, 100)\ny = 3 * x + 5 + rng.normal(0, 1, 100)\n\nw, b, lr = 0.0, 0.0, 0.01\nfor step in range(2001):\n    pred = w * x + b\n    dw = 2 * np.mean((pred - y) * x)       # gradient of MSE with respect to w\n    db = 2 * np.mean(pred - y)             # gradient of MSE with respect to b\n    w, b = w - lr * dw, b - lr * db\n    if step % 500 == 0:\n        print(f\"step {step:4d}  MSE={np.mean((pred - y) ** 2):8.3f}  w={w:.3f}  b={b:.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># Fit y = w*x + b with plain gradient descent<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rng = np.random.default_rng(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">x = rng.uniform(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y = <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\"> * x + <\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\"> + rng.normal(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">w, b, lr = <\/span><span style=\"color: #B5CEA8\">0.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.01<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> step <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">2001<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    pred = w * x + b<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    dw = <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * np.mean((pred - y) * x)       <\/span><span style=\"color: #6A9955\"># gradient of MSE with respect to w<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    db = <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * np.mean(pred - y)             <\/span><span style=\"color: #6A9955\"># gradient of MSE with respect to b<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    w, b = w - lr * dw, b - lr * db<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> step % <\/span><span style=\"color: #B5CEA8\">500<\/span><span style=\"color: #D4D4D4\"> == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;step <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">step<\/span><span style=\"color: #569CD6\">:4d}<\/span><span style=\"color: #CE9178\">  MSE=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">np.mean((pred - y) ** <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">)<\/span><span style=\"color: #569CD6\">:8.3f}<\/span><span style=\"color: #CE9178\">  w=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">w<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">  b=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">b<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>step    0  MSE= 539.563  w=2.892  b=0.427\nstep  500  MSE=   0.987  w=3.050  b=4.545\nstep 1000  MSE=   0.941  w=2.993  b=4.948\nstep 1500  MSE=   0.940  w=2.988  b=4.988\nstep 2000  MSE=   0.940  w=2.987  b=4.992<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">step    0  MSE= 539.563  w=2.892  b=0.427<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">step  500  MSE=   0.987  w=3.050  b=4.545<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">step 1000  MSE=   0.941  w=2.993  b=4.948<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">step 1500  MSE=   0.940  w=2.988  b=4.988<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">step 2000  MSE=   0.940  w=2.987  b=4.992<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The true line is y = 3x + 5, and gradient descent finds w \u2248 2.99 and b \u2248 4.99. If the learning rate is too small, training is slow; if it is too large, the loss jumps around or blows up. The gradient descent tool on this page shows all three cases.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-38\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q38<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">38. What is the difference between a parameter and a hyperparameter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Parameters<\/strong> are learned from the data during training: the weights of a linear model, the split thresholds of a tree, the weights of a neural network. <strong>Hyperparameters<\/strong> are set by you before training and control how learning happens: the learning rate, K in KNN, <code>max_depth<\/code> of a tree, <code>C<\/code> in an SVM, the number of layers in a network.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hyperparameters are chosen by trying different values and comparing validation scores, usually with grid search, random search or Bayesian optimisation (question 44).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-39\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q39<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">39. What is a neural network?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A neural network is a model made of layers of simple units called neurons. Each neuron takes inputs, multiplies them by weights, adds a bias and passes the result through an activation function. An input layer receives the features, one or more hidden layers learn intermediate patterns, and an output layer gives the prediction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With enough neurons and non-linear activations, a network can approximate almost any function. It learns its weights with backpropagation and gradient descent. Networks with many hidden layers are called deep neural networks, which is where the term deep learning comes from.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-40\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Freshers\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q40<\/span><span class=\"cd-pill cd-lv-Freshers\">Freshers<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">40. What is an activation function, and what are the common ones?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An activation function adds non-linearity to a neuron. Without it, stacking layers would still give a single linear model, however deep the network.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Function<\/th><th>Output<\/th><th>Where it is used<\/th><\/tr><\/thead><tbody><tr><td>ReLU: max(0, x)<\/td><td>0 to \u221e<\/td><td>Default for hidden layers; fast and avoids vanishing gradients for positive inputs<\/td><\/tr><tr><td>Sigmoid<\/td><td>0 to 1<\/td><td>Output layer for binary classification<\/td><\/tr><tr><td>Tanh<\/td><td>\u22121 to 1<\/td><td>Hidden layers in older networks and some RNNs<\/td><\/tr><tr><td>Softmax<\/td><td>Probabilities that sum to 1<\/td><td>Output layer for multiclass classification<\/td><\/tr><tr><td>GELU, Leaky ReLU<\/td><td>Smooth or slightly negative<\/td><td>Transformers (GELU); avoiding &#8220;dead&#8221; ReLU units (Leaky ReLU)<\/td><\/tr><\/tbody><\/table><\/figure>\n<\/div><\/div>\n\n\n\n<h2 id=\"intermediate-ml-interview-questions\" class=\"wp-block-heading\">Intermediate machine learning interview questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 35 questions are for candidates with a year or two of hands-on work: regularisation and tuning, imbalanced data, threshold choice, ensembles, feature importance, pipelines, time series validation and the deep learning concepts that come up in ML engineer interviews.<\/p>\n\n\n\n<div id=\"q-41\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q41<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">41. What is the difference between batch, stochastic and mini-batch gradient descent?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Type<\/th><th>Data used for each update<\/th><th>Pros<\/th><th>Cons<\/th><\/tr><\/thead><tbody><tr><td>Batch<\/td><td>The whole training set<\/td><td>Smooth, stable steps<\/td><td>Slow and memory-heavy on big data<\/td><\/tr><tr><td>Stochastic (SGD)<\/td><td>One example<\/td><td>Very fast updates; noise can help escape poor local minima<\/td><td>Noisy, zig-zagging path<\/td><\/tr><tr><td>Mini-batch<\/td><td>A small batch, such as 32 to 512 examples<\/td><td>Balance of speed and stability; fits GPUs well<\/td><td>Batch size is one more hyperparameter<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Mini-batch is what almost everyone uses for neural networks, and people often just call it SGD. Optimisers like Momentum, RMSProp and Adam build on it by adapting the step size for each parameter.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-42\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q42<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">42. What is the difference between L1 and L2 regularisation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Regularisation adds a penalty on the size of the weights to the loss, so the model prefers simpler solutions. <strong>L2 (Ridge)<\/strong> adds \u03bb \u03a3 w\u00b2, which shrinks all weights smoothly towards zero but rarely makes them exactly zero. <strong>L1 (Lasso)<\/strong> adds \u03bb \u03a3 |w|, which pushes some weights to exactly zero, so it also selects features.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.datasets import make_regression\nfrom sklearn.linear_model import Lasso, LinearRegression, Ridge\n\nX, y = make_regression(n_samples=200, n_features=20, n_informative=5, noise=10, random_state=0)\n\nfor name, model in &#91;(\"Linear\", LinearRegression()), (\"Ridge (L2)\", Ridge(alpha=10)),\n                    (\"Lasso (L1)\", Lasso(alpha=5))&#93;:\n    coef = model.fit(X, y).coef_\n    print(f\"{name:11s} zero coefs: {np.sum(np.abs(coef) &lt; 1e-6):2d}   \"\n          f\"largest |coef|: {np.abs(coef).max():.1f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_regression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> Lasso, LinearRegression, Ridge<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = make_regression(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">200<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_features<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_informative<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">noise<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> name, model <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;(<\/span><span style=\"color: #CE9178\">&quot;Linear&quot;<\/span><span style=\"color: #D4D4D4\">, LinearRegression()), (<\/span><span style=\"color: #CE9178\">&quot;Ridge (L2)&quot;<\/span><span style=\"color: #D4D4D4\">, Ridge(<\/span><span style=\"color: #9CDCFE\">alpha<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">)),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    (<\/span><span style=\"color: #CE9178\">&quot;Lasso (L1)&quot;<\/span><span style=\"color: #D4D4D4\">, Lasso(<\/span><span style=\"color: #9CDCFE\">alpha<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">))&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    coef = model.fit(X, y).coef_<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">name<\/span><span style=\"color: #569CD6\">:11s}<\/span><span style=\"color: #CE9178\"> zero coefs: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">np.sum(np.abs(coef) &lt; <\/span><span style=\"color: #B5CEA8\">1e-6<\/span><span style=\"color: #D4D4D4\">)<\/span><span style=\"color: #569CD6\">:2d}<\/span><span style=\"color: #CE9178\">   &quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">          <\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;largest |coef|: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">np.abs(coef).max()<\/span><span style=\"color: #569CD6\">:.1f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Linear      zero coefs:  0   largest |coef|: 83.8\nRidge (L2)  zero coefs:  0   largest |coef|: 79.0\nLasso (L1)  zero coefs: 15   largest |coef|: 77.8<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Linear      zero coefs:  0   largest |coef|: 83.8<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Ridge (L2)  zero coefs:  0   largest |coef|: 79.0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Lasso (L1)  zero coefs: 15   largest |coef|: 77.8<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The data has 20 features but only 5 useful ones. Lasso set 15 coefficients to zero, while Ridge kept all of them. Use L1 when you expect few useful features or want a simpler model, and L2 when many features each contribute a little or features are correlated. In scikit-learn the strength is <code>alpha<\/code> for Ridge and Lasso, and <code>C = 1\/\u03bb<\/code> for logistic regression and SVM.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-43\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q43<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">43. What is Elastic Net, and when would you use it?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Elastic Net combines the L1 and L2 penalties: \u03b1 \u00d7 (r \u00d7 \u03a3|w| + (1 \u2212 r)\/2 \u00d7 \u03a3w\u00b2), where <code>l1_ratio<\/code> (r) sets the mix. It keeps Lasso&#8217;s ability to zero out features while behaving better when features are correlated. Lasso tends to pick one feature from a correlated group at random, whereas Elastic Net tends to keep or drop the group together.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use it when you have many correlated features, or more features than rows, and tune both <code>alpha<\/code> and <code>l1_ratio<\/code> with cross-validation (<code>ElasticNetCV<\/code> does this directly).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-44\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q44<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">44. How do you tune hyperparameters?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Grid search:<\/strong> tries every combination from lists you give. Thorough, but the cost multiplies with each new hyperparameter.<\/li>\n\n\n\n<li><strong>Random search:<\/strong> tries a fixed number of random combinations. Usually finds a good result faster, because only a few hyperparameters really matter.<\/li>\n\n\n\n<li><strong>Bayesian optimisation<\/strong> (Optuna, Hyperopt): uses past results to pick promising combinations next. Best when each training run is expensive.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\nX, y = load_breast_cancer(return_X_y=True)\npipe = make_pipeline(StandardScaler(), SVC())\ngrid = GridSearchCV(pipe, {\"svc__C\": &#91;0.1, 1, 10, 100&#93;,\n                           \"svc__gamma\": &#91;0.001, 0.01, 0.1&#93;}, cv=5)\ngrid.fit(X, y)\n\nprint(\"Best params:\", grid.best_params_)\nprint(\"Best CV accuracy:\", round(grid.best_score_, 3))\nprint(\"Combinations tried:\", len(grid.cv_results_&#91;\"params\"&#93;))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_breast_cancer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> GridSearchCV<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_pipeline<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> StandardScaler<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.svm <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> SVC<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_breast_cancer(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">pipe = make_pipeline(StandardScaler(), SVC())<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">grid = GridSearchCV(pipe, {<\/span><span style=\"color: #CE9178\">&quot;svc__C&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">0.1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">&#93;,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                           <\/span><span style=\"color: #CE9178\">&quot;svc__gamma&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">0.001<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.01<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.1<\/span><span style=\"color: #D4D4D4\">&#93;}, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">grid.fit(X, y)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Best params:&quot;<\/span><span style=\"color: #D4D4D4\">, grid.best_params_)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Best CV accuracy:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(grid.best_score_, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Combinations tried:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(grid.cv_results_&#91;<\/span><span style=\"color: #CE9178\">&quot;params&quot;<\/span><span style=\"color: #D4D4D4\">&#93;))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Best params: {'svc__C': 10, 'svc__gamma': 0.01}\nBest CV accuracy: 0.979\nCombinations tried: 12<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Best params: {&#39;svc__C&#39;: 10, &#39;svc__gamma&#39;: 0.01}<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Best CV accuracy: 0.979<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Combinations tried: 12<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Always tune with cross-validation on the training data only, and put preprocessing inside a pipeline so it is refitted in every fold. Note the <code>svc__C<\/code> naming: the step name, two underscores, then the parameter.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-45\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q45<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">45. What is stratified k-fold cross-validation, and when do you need it?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Stratified k-fold makes sure every fold has roughly the same class proportions as the full dataset. With plain k-fold on imbalanced data, a fold might end up with very few or even no positive examples, which makes its score meaningless and the overall estimate noisy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use it for any classification problem, especially imbalanced ones; scikit-learn uses it by default when you pass an integer <code>cv<\/code> to a classifier. Do not use it for time series (use <code>TimeSeriesSplit<\/code>) or when rows are grouped, such as several rows per patient (use <code>GroupKFold<\/code> so one patient never appears in both train and test).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-46\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q46<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">46. How do you handle imbalanced data?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the right metrics: recall, precision, F1, PR AUC, not accuracy.<\/li>\n\n\n\n<li>Give the rare class more weight: <code>class_weight=\"balanced\"<\/code> in most scikit-learn models, <code>scale_pos_weight<\/code> in XGBoost.<\/li>\n\n\n\n<li>Resample: oversample the minority class (randomly or with SMOTE) or undersample the majority, on the training data only.<\/li>\n\n\n\n<li>Tune the decision threshold instead of using 0.5.<\/li>\n\n\n\n<li>Collect more examples of the rare class if you can, or treat it as anomaly detection when positives are extremely rare.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\n\nX, y = make_classification(n_samples=10000, weights=&#91;0.98&#93;, flip_y=0.01, random_state=3)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=3)\n\nfor cw in &#91;None, \"balanced\"&#93;:\n    pred = LogisticRegression(class_weight=cw, max_iter=1000).fit(X_tr, y_tr).predict(X_te)\n    print(f\"class_weight={str(cw):8s}  recall={recall_score(y_te, pred):.2f}  \"\n          f\"precision={precision_score(y_te, pred):.2f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_classification<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> precision_score, recall_score<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = make_classification(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">weights<\/span><span style=\"color: #D4D4D4\">=&#91;<\/span><span style=\"color: #B5CEA8\">0.98<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #9CDCFE\">flip_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0.01<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">stratify<\/span><span style=\"color: #D4D4D4\">=y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> cw <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;balanced&quot;<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    pred = LogisticRegression(<\/span><span style=\"color: #9CDCFE\">class_weight<\/span><span style=\"color: #D4D4D4\">=cw, <\/span><span style=\"color: #9CDCFE\">max_iter<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr).predict(X_te)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;class_weight=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">(cw)<\/span><span style=\"color: #569CD6\">:8s}<\/span><span style=\"color: #CE9178\">  recall=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">recall_score(y_te, pred)<\/span><span style=\"color: #569CD6\">:.2f}<\/span><span style=\"color: #CE9178\">  &quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">          <\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;precision=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">precision_score(y_te, pred)<\/span><span style=\"color: #569CD6\">:.2f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>class_weight=None      recall=0.08  precision=0.33\nclass_weight=balanced  recall=0.73  precision=0.12<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">class_weight=None      recall=0.08  precision=0.33<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">class_weight=balanced  recall=0.73  precision=0.12<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">With 2% positives, the default model caught only 8% of them. Class weights raised recall to 73%, at the cost of more false alarms. Which balance is right depends on the cost of each kind of mistake.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-47\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q47<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">47. When should you use a precision-recall curve instead of a ROC curve?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use the precision-recall (PR) curve when the positive class is rare and you mostly care about it, as in fraud, disease or defect detection. ROC uses the false positive rate, whose denominator is the huge number of negatives, so even thousands of false alarms barely move it. Precision shows those false alarms directly.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nfrom sklearn.model_selection import train_test_split\n\nX, y = make_classification(n_samples=5000, weights=&#91;0.95&#93;, random_state=1)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=1)\n\nproba = LogisticRegression(max_iter=1000).fit(X_tr, y_tr).predict_proba(X_te)&#91;:, 1&#93;\nprint(\"ROC AUC:          \", round(roc_auc_score(y_te, proba), 3))\nprint(\"PR AUC (avg prec):\", round(average_precision_score(y_te, proba), 3))\nprint(\"Positive rate:    \", round(y_te.mean(), 3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_classification<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> roc_auc_score, average_precision_score<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = make_classification(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">weights<\/span><span style=\"color: #D4D4D4\">=&#91;<\/span><span style=\"color: #B5CEA8\">0.95<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">stratify<\/span><span style=\"color: #D4D4D4\">=y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">proba = LogisticRegression(<\/span><span style=\"color: #9CDCFE\">max_iter<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr).predict_proba(X_te)&#91;:, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;ROC AUC:          &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(roc_auc_score(y_te, proba), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;PR AUC (avg prec):&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(average_precision_score(y_te, proba), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Positive rate:    &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(y_te.mean(), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>ROC AUC:           0.926\nPR AUC (avg prec): 0.621\nPositive rate:     0.054<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">ROC AUC:           0.926<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">PR AUC (avg prec): 0.621<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Positive rate:     0.054<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">With about 5% positives, ROC AUC is a comfortable 0.93, but PR AUC is only 0.62. The model is good at ranking, but many of its alerts would still be false. A random model has PR AUC equal to the positive rate (0.054 here), so always compare against that baseline.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-48\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q48<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">48. How do you choose the classification threshold?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Most classifiers output a probability, and 0.5 is only a default. Choose the threshold from the cost of each error: for cancer screening, missing a malignant tumour is far worse than an extra biopsy, so you lower the threshold to raise recall.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_breast_cancer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nX, y = load_breast_cancer(return_X_y=True)\ny = 1 - y                                  # make 1 = malignant (the class we must catch)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)\nproba = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr).predict_proba(X_te)&#91;:, 1&#93;\n\nfor t in &#91;0.5, 0.3, 0.1&#93;:\n    pred = (proba >= t).astype(int)\n    print(f\"threshold={t}  recall={recall_score(y_te, pred):.3f}  precision={precision_score(y_te, pred):.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_breast_cancer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> precision_score, recall_score<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_pipeline<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> StandardScaler<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_breast_cancer(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y = <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> - y                                  <\/span><span style=\"color: #6A9955\"># make 1 = malignant (the class we must catch)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">stratify<\/span><span style=\"color: #D4D4D4\">=y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">proba = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr).predict_proba(X_te)&#91;:, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> t <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.1<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    pred = (proba &gt;= t).astype(<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;threshold=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">t<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">  recall=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">recall_score(y_te, pred)<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">  precision=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">precision_score(y_te, pred)<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>threshold=0.5  recall=0.962  precision=1.000\nthreshold=0.3  recall=0.962  precision=0.895\nthreshold=0.1  recall=1.000  precision=0.828<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">threshold=0.5  recall=0.962  precision=1.000<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">threshold=0.3  recall=0.962  precision=0.895<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">threshold=0.1  recall=1.000  precision=0.828<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Lowering the threshold to 0.1 catches every malignant case (recall 1.0), at the cost of precision dropping to 0.83. Pick the threshold on validation data, using a cost formula, a minimum recall target, or the point that maximises F1. Never pick it on the test set.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-49\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Classification\"><span class=\"cd-pill\">Q49<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">49. What is log loss (cross-entropy)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Log loss measures how good predicted probabilities are, not just the final class. For one example with true label y and predicted probability p, it is \u2212[y log p + (1 \u2212 y) log(1 \u2212 p)]. A confident correct prediction gives a loss near 0, and a confident wrong one gives a very large loss: predicting 0.01 for a true positive costs 4.6, while 0.4 costs 0.92.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is the loss that logistic regression and classification neural networks minimise, and it comes straight from maximum likelihood (question 68). For more than two classes it becomes categorical cross-entropy: \u2212\u03a3 y\u2096 log p\u2096.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-50\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Classification\"><span class=\"cd-pill\">Q50<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">50. How do models handle multiclass classification, and what are macro, micro and weighted averages?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Some models handle many classes natively: trees, Naive Bayes, KNN, and softmax regression or neural networks. Binary models are extended with <strong>one-vs-rest<\/strong> (one model per class against all others) or <strong>one-vs-one<\/strong> (one model per pair of classes, used by SVC).<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Macro average:<\/strong> compute the metric for each class and take the plain average. Every class counts equally, so small classes matter.<\/li>\n\n\n\n<li><strong>Weighted average:<\/strong> like macro, but weighted by each class&#8217;s size.<\/li>\n\n\n\n<li><strong>Micro average:<\/strong> pool all TP, FP and FN first. For single-label problems, micro F1 equals accuracy.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Report macro F1 when rare classes matter as much as common ones.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-51\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q51<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">51. What is the difference between bagging and boosting?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><\/th><th>Bagging<\/th><th>Boosting<\/th><\/tr><\/thead><tbody><tr><td>How models are trained<\/td><td>In parallel, each on a bootstrap sample (random sample with replacement)<\/td><td>One after another, each fixing the errors of the previous ones<\/td><\/tr><tr><td>Main effect<\/td><td>Reduces variance<\/td><td>Reduces bias (and variance, when tuned)<\/td><\/tr><tr><td>Base models<\/td><td>Usually deep, low-bias trees<\/td><td>Usually shallow trees<\/td><\/tr><tr><td>Overfitting risk<\/td><td>Low<\/td><td>Higher; needs a learning rate and early stopping<\/td><\/tr><tr><td>Examples<\/td><td>Random forest, bagged trees<\/td><td>AdaBoost, gradient boosting, XGBoost, LightGBM, CatBoost<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">On tabular data, a well-tuned gradient boosting model usually beats a random forest, while the random forest needs much less tuning.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-52\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q52<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">52. How does a random forest work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A random forest trains many decision trees, each on a bootstrap sample of the rows, and at every split each tree considers only a random subset of the features (<code>max_features<\/code>). Classification takes a majority vote; regression takes the average. The two kinds of randomness make the trees different from each other, so their errors partly cancel out.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import load_breast_cancer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\n\nX, y = load_breast_cancer(return_X_y=True)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)\n\ntree = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr)\nrf = RandomForestClassifier(n_estimators=300, oob_score=True, random_state=0).fit(X_tr, y_tr)\n\nprint(\"Single tree test accuracy:  \", round(tree.score(X_te, y_te), 3))\nprint(\"Random forest test accuracy:\", round(rf.score(X_te, y_te), 3))\nprint(\"Random forest OOB score:    \", round(rf.oob_score_, 3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_breast_cancer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.ensemble <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> RandomForestClassifier<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.tree <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> DecisionTreeClassifier<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = load_breast_cancer(<\/span><span style=\"color: #9CDCFE\">return_X_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">stratify<\/span><span style=\"color: #D4D4D4\">=y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">tree = DecisionTreeClassifier(<\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rf = RandomForestClassifier(<\/span><span style=\"color: #9CDCFE\">n_estimators<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">300<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">oob_score<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Single tree test accuracy:  &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(tree.score(X_te, y_te), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Random forest test accuracy:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(rf.score(X_te, y_te), <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Random forest OOB score:    &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(rf.oob_score_, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Single tree test accuracy:   0.902\nRandom forest test accuracy: 0.944\nRandom forest OOB score:     0.962<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Single tree test accuracy:   0.902<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Random forest test accuracy: 0.944<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Random forest OOB score:     0.962<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Each tree leaves out about 37% of the rows from its bootstrap sample. Predicting each row with only the trees that did not see it gives the <strong>out-of-bag (OOB) score<\/strong>, a free validation estimate. Main hyperparameters: <code>n_estimators<\/code>, <code>max_features<\/code>, <code>max_depth<\/code>, <code>min_samples_leaf<\/code>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-53\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q53<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">53. How does gradient boosting work, and what are its key hyperparameters?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Gradient boosting builds trees one after another. It starts with a simple prediction (such as the average), then each new shallow tree is trained to predict the gradient of the loss, which for squared error is just the residuals of the current model. The new tree&#8217;s output, multiplied by a small learning rate, is added to the model. Step by step the ensemble corrects its own mistakes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>learning_rate<\/code>: how much each tree contributes. Smaller is usually better but needs more trees.<\/li>\n\n\n\n<li><code>n_estimators<\/code>: number of trees; choose it with early stopping (question 85).<\/li>\n\n\n\n<li><code>max_depth<\/code> (often 3 to 8): how complex each tree is.<\/li>\n\n\n\n<li><code>subsample<\/code> and column sampling: add randomness and reduce overfitting.<\/li>\n\n\n\n<li>Regularisation terms in XGBoost: <code>lambda<\/code>, <code>alpha<\/code>, <code>gamma<\/code>, <code>min_child_weight<\/code>.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-54\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q54<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">54. How does AdaBoost work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AdaBoost (adaptive boosting) trains a sequence of weak learners, usually one-split trees called stumps. After each round it increases the weights of the examples that were misclassified, so the next learner focuses on the hard cases. Each learner also gets a vote weight based on its accuracy, and the final prediction is the weighted vote of all of them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It was the first practical boosting algorithm. Gradient boosting generalises the idea to any differentiable loss. Because AdaBoost keeps raising the weight of misclassified points, it is sensitive to noisy labels and outliers.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-55\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q55<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">55. How do you measure feature importance?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Coefficients<\/strong> of linear models, on scaled features.<\/li>\n\n\n\n<li><strong>Impurity-based importance<\/strong> (<code>feature_importances_<\/code>) in trees: fast, but biased towards features with many unique values and computed on training data.<\/li>\n\n\n\n<li><strong>Permutation importance:<\/strong> shuffle one feature in the validation set and measure how much the score drops. Model-agnostic and more reliable.<\/li>\n\n\n\n<li><strong>SHAP values:<\/strong> how much each feature pushed each individual prediction up or down (question 88).<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.inspection import permutation_importance\nfrom sklearn.model_selection import train_test_split\n\ndata = load_diabetes()\nX_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, random_state=0)\nrf = RandomForestRegressor(random_state=0).fit(X_tr, y_tr)\n\nresult = permutation_importance(rf, X_te, y_te, n_repeats=10, random_state=0)\nfor i in np.argsort(result.importances_mean)&#91;::-1&#93;&#91;:4&#93;:\n    print(f\"{data.feature_names&#91;i&#93;:4s} drop in R2 when shuffled: {result.importances_mean&#91;i&#93;:.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> load_diabetes<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.ensemble <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> RandomForestRegressor<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.inspection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> permutation_importance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">data = load_diabetes()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rf = RandomForestRegressor(<\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">result = permutation_importance(rf, X_te, y_te, <\/span><span style=\"color: #9CDCFE\">n_repeats<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> np.argsort(result.importances_mean)&#91;::-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;&#91;:<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">data.feature_names&#91;i&#93;<\/span><span style=\"color: #569CD6\">:4s}<\/span><span style=\"color: #CE9178\"> drop in R2 when shuffled: <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">result.importances_mean&#91;i&#93;<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>bmi  drop in R2 when shuffled: 0.114\ns5   drop in R2 when shuffled: 0.094\nbp   drop in R2 when shuffled: 0.043\nage  drop in R2 when shuffled: 0.018<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">bmi  drop in R2 when shuffled: 0.114<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">s5   drop in R2 when shuffled: 0.094<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">bp   drop in R2 when shuffled: 0.043<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">age  drop in R2 when shuffled: 0.018<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Shuffling BMI drops R\u00b2 by 0.11, so the model relies on it most. If two features are strongly correlated, permutation importance can underrate both, because the model can still use the other one. Reference: <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/permutation_importance.html\" target=\"_blank\" rel=\"noopener\">scikit-learn permutation importance<\/a>.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-56\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q56<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">56. What are the main feature selection methods?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Filter methods:<\/strong> score each feature on its own, without a model: correlation, chi-square, mutual information, ANOVA F-test. Fast, but they ignore interactions.<\/li>\n\n\n\n<li><strong>Wrapper methods:<\/strong> try subsets of features with a model and keep the best: forward selection, backward elimination, recursive feature elimination (RFE). Accurate but slow.<\/li>\n\n\n\n<li><strong>Embedded methods:<\/strong> selection happens during training: Lasso, tree-based importance, <code>SelectFromModel<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Fewer features means faster training, less overfitting and simpler explanations. Whatever the method, do the selection inside cross-validation, or you get the leakage shown in question 15.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-57\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Regression\"><span class=\"cd-pill\">Q57<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Regression<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">57. What is multicollinearity, and why does it matter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Multicollinearity means two or more features are strongly correlated, such as flat size in square feet and number of rooms. Predictions may still be fine, but the individual coefficients of a linear model become unstable: they can swing wildly or even change sign with small changes in the data, so you cannot trust them for explanation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Detect it with a correlation matrix or the <strong>variance inflation factor (VIF)<\/strong>; a VIF above about 5 to 10 is a warning. Fix it by dropping or combining correlated features, using PCA, or using Ridge regression, which handles correlated features gracefully.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-58\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q58<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">58. What is pruning in decision trees?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Pruning makes a decision tree smaller so it generalises better. <strong>Pre-pruning<\/strong> stops growth early with limits such as <code>max_depth<\/code>, <code>min_samples_split<\/code>, <code>min_samples_leaf<\/code> or <code>max_leaf_nodes<\/code>. <strong>Post-pruning<\/strong> grows the full tree and then removes branches that do not earn their place; scikit-learn uses cost complexity pruning with <code>ccp_alpha<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Tune either kind with cross-validation. The <a href=\"https:\/\/codeanddebug.in\/blog\/decision-tree-in-machine-learning\/\">decision tree guide<\/a> shows a fully grown tree with 18 leaves losing to a pruned one with 11.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-59\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Classification\"><span class=\"cd-pill\">Q59<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">59. What is the kernel trick, and what do C and gamma do in an SVM?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The kernel trick lets an SVM act as if the data had been mapped into a higher-dimensional space where it becomes linearly separable, without ever computing that mapping. It only needs a kernel function that returns the dot product in that space. Common kernels: linear, polynomial and RBF (Gaussian).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>C<\/code> controls how strongly misclassified points are punished: large C fits the training data tightly and can overfit, while small C gives a wider, smoother margin. <code>gamma<\/code> (for RBF) controls how far one point&#8217;s influence reaches: large gamma gives very wiggly boundaries, small gamma very smooth ones. Tune them together on a log scale.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-60\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q60<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">60. When would you use DBSCAN instead of k-means?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">DBSCAN groups points that are packed closely together (at least <code>min_samples<\/code> points within distance <code>eps<\/code>) and marks points in sparse areas as noise. Choose it when:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>clusters have irregular shapes, such as moons or rings, which k-means cuts with straight lines;<\/li>\n\n\n\n<li>you do not know the number of clusters;<\/li>\n\n\n\n<li>you want outliers flagged instead of forced into a cluster.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Its weaknesses: it struggles when clusters have very different densities, and <code>eps<\/code> is hard to choose in high dimensions. HDBSCAN fixes much of this.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-61\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q61<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">61. How does hierarchical clustering work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Agglomerative hierarchical clustering starts with every point as its own cluster and repeatedly merges the two closest clusters until only one is left. The full history of merges is drawn as a tree called a <strong>dendrogram<\/strong>, and you choose the number of clusters by cutting the tree at a certain height.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The linkage decides what &#8220;closest&#8221; means: single (nearest points), complete (furthest points), average, or Ward (smallest increase in variance, the usual default). It needs no K up front and shows the structure at every level, but it uses O(n\u00b2) memory, so it suits small to medium datasets.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-62\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q62<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">62. How does PCA work, and how do you choose the number of components?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PCA centres (and usually scales) the data, computes the covariance matrix, and finds its eigenvectors and eigenvalues. The eigenvectors are the principal components, the directions of the new axes, and each eigenvalue tells how much variance that direction holds. In practice it is computed with singular value decomposition (SVD), which is faster and more stable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To choose how many components to keep, plot the cumulative explained variance and keep enough for 90 to 95% (question 36 needed 21 of 64 for 90%), look for an elbow in the scree plot, or tune the number of components as a hyperparameter of the model that uses them.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-63\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Unsupervised\"><span class=\"cd-pill\">Q63<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Unsupervised<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">63. How are t-SNE and UMAP different from PCA?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PCA is linear and keeps the large-scale structure, such as overall spread. t-SNE and UMAP are non-linear methods built mainly for visualisation: they keep neighbourhoods, so points that are close in the original space stay close in 2D, and clusters show up clearly.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Distances between clusters and cluster sizes in a t-SNE plot do not mean much.<\/li>\n\n\n\n<li>t-SNE is slow on large data and has no simple way to transform new points; UMAP is faster and can.<\/li>\n\n\n\n<li>Use PCA for preprocessing and compression; use t-SNE or UMAP to look at embeddings or clusters.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-64\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q64<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">64. What is a scikit-learn Pipeline, and why should you use one?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A Pipeline chains preprocessing steps and a model into a single object with one <code>fit<\/code> and one <code>predict<\/code>. A <code>ColumnTransformer<\/code> applies different steps to different columns.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import pandas as pd\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\n\ndf = pd.DataFrame({\"age\": &#91;22, 35, None, 51, 46, 29&#93;, \"city\": &#91;\"Surat\", \"Pune\", \"Pune\", None, \"Delhi\", \"Surat\"&#93;,\n                   \"income\": &#91;3.2, 8.5, 6.1, 12.0, 9.4, 4.0&#93;, \"bought\": &#91;0, 1, 0, 1, 1, 0&#93;})\nX, y = df.drop(columns=\"bought\"), df&#91;\"bought\"&#93;\n\nprep = ColumnTransformer([\n    (\"num\", Pipeline(&#91;(\"impute\", SimpleImputer(strategy=\"median\")), (\"scale\", StandardScaler())&#93;), &#91;\"age\", \"income\"&#93;),\n    (\"cat\", Pipeline(&#91;(\"impute\", SimpleImputer(strategy=\"most_frequent\")),\n                      (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\"))&#93;), &#91;\"city\"&#93;),\n])\nmodel = Pipeline(&#91;(\"prep\", prep), (\"clf\", LogisticRegression())&#93;).fit(X, y)\n\nnew = pd.DataFrame({\"age\": &#91;40&#93;, \"city\": &#91;\"Mumbai\"&#93;, \"income\": &#91;10.0&#93;})   # unseen city\nprint(\"Prediction:\", model.predict(new), \"| P(buy):\", model.predict_proba(new)&#91;0, 1&#93;.round(3))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> pandas <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> pd<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.compose <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> ColumnTransformer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.impute <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> SimpleImputer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.linear_model <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> LogisticRegression<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.pipeline <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> Pipeline<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.preprocessing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> OneHotEncoder, StandardScaler<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">df = pd.DataFrame({<\/span><span style=\"color: #CE9178\">&quot;age&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">22<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">35<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">51<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">46<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">29<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #CE9178\">&quot;Surat&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Delhi&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Surat&quot;<\/span><span style=\"color: #D4D4D4\">&#93;,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                   <\/span><span style=\"color: #CE9178\">&quot;income&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">3.2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">8.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">6.1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">12.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">9.4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">4.0<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #CE9178\">&quot;bought&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">&#93;})<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = df.drop(<\/span><span style=\"color: #9CDCFE\">columns<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;bought&quot;<\/span><span style=\"color: #D4D4D4\">), df&#91;<\/span><span style=\"color: #CE9178\">&quot;bought&quot;<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">prep = ColumnTransformer([<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    (<\/span><span style=\"color: #CE9178\">&quot;num&quot;<\/span><span style=\"color: #D4D4D4\">, Pipeline(&#91;(<\/span><span style=\"color: #CE9178\">&quot;impute&quot;<\/span><span style=\"color: #D4D4D4\">, SimpleImputer(<\/span><span style=\"color: #9CDCFE\">strategy<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;median&quot;<\/span><span style=\"color: #D4D4D4\">)), (<\/span><span style=\"color: #CE9178\">&quot;scale&quot;<\/span><span style=\"color: #D4D4D4\">, StandardScaler())&#93;), &#91;<\/span><span style=\"color: #CE9178\">&quot;age&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;income&quot;<\/span><span style=\"color: #D4D4D4\">&#93;),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    (<\/span><span style=\"color: #CE9178\">&quot;cat&quot;<\/span><span style=\"color: #D4D4D4\">, Pipeline(&#91;(<\/span><span style=\"color: #CE9178\">&quot;impute&quot;<\/span><span style=\"color: #D4D4D4\">, SimpleImputer(<\/span><span style=\"color: #9CDCFE\">strategy<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;most_frequent&quot;<\/span><span style=\"color: #D4D4D4\">)),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                      (<\/span><span style=\"color: #CE9178\">&quot;onehot&quot;<\/span><span style=\"color: #D4D4D4\">, OneHotEncoder(<\/span><span style=\"color: #9CDCFE\">handle_unknown<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;ignore&quot;<\/span><span style=\"color: #D4D4D4\">))&#93;), &#91;<\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">&#93;),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">model = Pipeline(&#91;(<\/span><span style=\"color: #CE9178\">&quot;prep&quot;<\/span><span style=\"color: #D4D4D4\">, prep), (<\/span><span style=\"color: #CE9178\">&quot;clf&quot;<\/span><span style=\"color: #D4D4D4\">, LogisticRegression())&#93;).fit(X, y)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">new = pd.DataFrame({<\/span><span style=\"color: #CE9178\">&quot;age&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">40<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #CE9178\">&quot;city&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #CE9178\">&quot;Mumbai&quot;<\/span><span style=\"color: #D4D4D4\">&#93;, <\/span><span style=\"color: #CE9178\">&quot;income&quot;<\/span><span style=\"color: #D4D4D4\">: &#91;<\/span><span style=\"color: #B5CEA8\">10.0<\/span><span style=\"color: #D4D4D4\">&#93;})   <\/span><span style=\"color: #6A9955\"># unseen city<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Prediction:&quot;<\/span><span style=\"color: #D4D4D4\">, model.predict(new), <\/span><span style=\"color: #CE9178\">&quot;| P(buy):&quot;<\/span><span style=\"color: #D4D4D4\">, model.predict_proba(new)&#91;<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;.round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Prediction: &#91;1&#93; | P(buy): 0.741<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Prediction: &#91;1&#93; | P(buy): 0.741<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It prevents leakage: during cross-validation, imputers and scalers are fitted only on the training folds.<\/li>\n\n\n\n<li>The exact same steps run in training and in production, so there is no training-serving skew.<\/li>\n\n\n\n<li>It handles unseen values safely, like the new city &#8220;Mumbai&#8221; above, thanks to <code>handle_unknown=\"ignore\"<\/code>.<\/li>\n\n\n\n<li>You can tune preprocessing and model hyperparameters together with GridSearchCV.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-65\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q65<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">65. How do you validate a model on time series data?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Never shuffle time series data before splitting. A random split lets the model train on the future and test on the past, which is leakage, and the score will look far better than it will be in production. Train on the past and test on the period right after it.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\nfrom sklearn.model_selection import TimeSeriesSplit\n\ndays = np.arange(12)                          # 12 days of data, in time order\nfor i, (train, test) in enumerate(TimeSeriesSplit(n_splits=3).split(days), 1):\n    print(f\"Fold {i}: train days {train.min()}-{train.max()}, test days {test.min()}-{test.max()}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> TimeSeriesSplit<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">days = np.arange(<\/span><span style=\"color: #B5CEA8\">12<\/span><span style=\"color: #D4D4D4\">)                          <\/span><span style=\"color: #6A9955\"># 12 days of data, in time order<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i, (train, test) <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">enumerate<\/span><span style=\"color: #D4D4D4\">(TimeSeriesSplit(<\/span><span style=\"color: #9CDCFE\">n_splits<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">).split(days), <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;Fold <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">i<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">: train days <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">train.min()<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">-<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">train.max()<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">, test days <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">test.min()<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">-<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">test.max()<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Fold 1: train days 0-2, test days 3-5\nFold 2: train days 0-5, test days 6-8\nFold 3: train days 0-8, test days 9-11<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Fold 1: train days 0-2, test days 3-5<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Fold 2: train days 0-5, test days 6-8<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Fold 3: train days 0-8, test days 9-11<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><code>TimeSeriesSplit<\/code> does this with an expanding window. Also make sure features only use information available at prediction time, for example lag features and rolling averages that stop at the day before.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-66\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Regression\"><span class=\"cd-pill\">Q66<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Regression<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">66. How do you check whether a regression model is good beyond its score?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Look at the <strong>residuals<\/strong> (actual minus predicted). Plot them against the predictions: a random cloud around zero is good. Patterns mean problems:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A curve means the relationship is not linear; add features or use a non-linear model.<\/li>\n\n\n\n<li>A funnel shape (spread growing with the prediction) is <strong>heteroscedasticity<\/strong>; try a log transform of the target or a model that handles it.<\/li>\n\n\n\n<li>Residuals that follow each other over time mean the errors are autocorrelated, often missing time features.<\/li>\n\n\n\n<li>A few huge residuals point to outliers or data errors.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Also compare against a simple baseline, such as predicting the mean or last week&#8217;s value. A model has to beat it to be worth using.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-67\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Classification\"><span class=\"cd-pill\">Q67<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Classification<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">67. What is the difference between generative and discriminative models?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <strong>discriminative<\/strong> model learns the boundary between classes directly, P(y | x). Examples: logistic regression, SVM, decision trees, most neural network classifiers. A <strong>generative<\/strong> model learns how the data of each class is produced, P(x | y) and P(y), or the joint P(x, y), and uses Bayes&#8217; rule to classify. Examples: Naive Bayes, Gaussian mixture models, hidden Markov models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Discriminative models usually classify more accurately when there is plenty of data. Generative models can work with less data, handle missing features and can generate new samples. Today&#8217;s generative AI models, such as large language models, are generative models of text.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-68\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Optimisation\"><span class=\"cd-pill\">Q68<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Optimisation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">68. What is maximum likelihood estimation, and how does it relate to loss functions?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Maximum likelihood estimation (MLE) chooses the parameters that make the observed data most probable under the model. Taking the negative log of the likelihood turns a product into a sum and a maximisation into a minimisation, which gives the familiar loss functions:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If you assume Gaussian noise around a linear prediction, MLE gives <strong>mean squared error<\/strong>, so ordinary least squares is MLE.<\/li>\n\n\n\n<li>If you assume the label follows a Bernoulli distribution with probability \u03c3(wx + b), MLE gives <strong>log loss<\/strong>, which is logistic regression.<\/li>\n\n\n\n<li>Adding a prior on the weights gives MAP estimation; a Gaussian prior is L2 regularisation, a Laplace prior is L1.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-69\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q69<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">69. How does backpropagation work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Backpropagation computes the gradient of the loss with respect to every weight in a network. In the forward pass, inputs flow through the layers to produce a prediction and a loss. In the backward pass, the chain rule is applied from the output back to the input: each layer receives the gradient from the layer after it, multiplies by its own local derivative, and passes the result back. Gradient descent then updates every weight.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\n\n# One neuron: y_hat = sigmoid(w*x + b), loss = (y_hat - y)^2\nx, y = 2.0, 1.0\nw, b = 0.5, 0.0\n\nz = w * x + b\ny_hat = 1 \/ (1 + np.exp(-z))\nloss = (y_hat - y) ** 2\n\n# Chain rule, from the loss back to the weights\ndloss_dyhat = 2 * (y_hat - y)\ndyhat_dz = y_hat * (1 - y_hat)\ndz_dw, dz_db = x, 1.0\ndw = dloss_dyhat * dyhat_dz * dz_dw\ndb = dloss_dyhat * dyhat_dz * dz_db\n\nprint(f\"prediction={y_hat:.4f}  loss={loss:.4f}\")\nprint(f\"dLoss\/dw={dw:.4f}  dLoss\/db={db:.4f}\")\nw -= 0.5 * dw; b -= 0.5 * db\nprint(f\"after one step: prediction={1 \/ (1 + np.exp(-(w * x + b))):.4f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># One neuron: y_hat = sigmoid(w*x + b), loss = (y_hat - y)^2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">x, y = <\/span><span style=\"color: #B5CEA8\">2.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1.0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">w, b = <\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">z = w * x + b<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">y_hat = <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> \/ (<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> + np.exp(-z))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">loss = (y_hat - y) ** <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #6A9955\"># Chain rule, from the loss back to the weights<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">dloss_dyhat = <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * (y_hat - y)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">dyhat_dz = y_hat * (<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> - y_hat)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">dz_dw, dz_db = x, <\/span><span style=\"color: #B5CEA8\">1.0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">dw = dloss_dyhat * dyhat_dz * dz_dw<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">db = dloss_dyhat * dyhat_dz * dz_db<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;prediction=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">y_hat<\/span><span style=\"color: #569CD6\">:.4f}<\/span><span style=\"color: #CE9178\">  loss=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">loss<\/span><span style=\"color: #569CD6\">:.4f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;dLoss\/dw=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">dw<\/span><span style=\"color: #569CD6\">:.4f}<\/span><span style=\"color: #CE9178\">  dLoss\/db=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">db<\/span><span style=\"color: #569CD6\">:.4f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">w -= <\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\"> * dw; b -= <\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\"> * db<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;after one step: prediction=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> \/ (<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> + np.exp(-(w * x + b)))<\/span><span style=\"color: #569CD6\">:.4f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>prediction=0.7311  loss=0.0723\ndLoss\/dw=-0.2115  dLoss\/db=-0.1058\nafter one step: prediction=0.7798<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">prediction=0.7311  loss=0.0723<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">dLoss\/dw=-0.2115  dLoss\/db=-0.1058<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">after one step: prediction=0.7798<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">For one neuron the chain is dLoss\/dw = dLoss\/d\u0177 \u00d7 d\u0177\/dz \u00d7 dz\/dw. After a single update the prediction moves from 0.731 towards the target of 1. Frameworks like PyTorch and TensorFlow do this automatically (autograd), but interviewers like to see that you can do it by hand.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-70\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q70<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">70. What are vanishing and exploding gradients?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In deep networks the gradient is a product of many layer derivatives. If those are mostly smaller than 1, the gradient shrinks towards zero as it travels back, so the early layers barely learn: <strong>vanishing gradients<\/strong>. Sigmoid and tanh cause this because their slopes are tiny for large inputs. If the factors are larger than 1, the gradient grows huge and training blows up: <strong>exploding gradients<\/strong>, common in RNNs.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ReLU-family activations instead of sigmoid in hidden layers.<\/li>\n\n\n\n<li>Careful weight initialisation (He for ReLU, Xavier\/Glorot for tanh).<\/li>\n\n\n\n<li>Batch normalisation or layer normalisation.<\/li>\n\n\n\n<li>Residual (skip) connections, as in ResNets and transformers.<\/li>\n\n\n\n<li>Gradient clipping for exploding gradients; LSTM or GRU cells instead of plain RNNs.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-71\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q71<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">71. What are dropout and batch normalisation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Dropout<\/strong> randomly switches off a fraction of neurons (for example 20 to 50%) in each training step, so the network cannot rely on any single neuron and learns more robust features. It acts like training many smaller networks and averaging them. Dropout is turned off at inference time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Batch normalisation<\/strong> normalises each layer&#8217;s inputs to mean 0 and variance 1 within the mini-batch, then applies a learned scale and shift. It makes training faster and more stable, allows higher learning rates and adds a little regularisation. At inference it uses running averages collected during training. Transformers use <strong>layer normalisation<\/strong> instead, which normalises across features for each example and does not depend on batch size.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-72\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q72<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">72. What is a convolutional neural network (CNN)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A CNN is a neural network designed for grid-like data such as images. Instead of connecting every pixel to every neuron, a <strong>convolutional layer<\/strong> slides small filters (for example 3\u00d73) across the image. Each filter learns to detect a pattern, like an edge or a texture, anywhere in the image. <strong>Pooling layers<\/strong> shrink the feature maps, and fully connected layers at the end make the prediction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because the same filter is reused everywhere (weight sharing), CNNs need far fewer parameters than fully connected networks and handle shifted objects well. Early layers learn edges, later layers learn shapes and objects. Uses: image classification, object detection, medical imaging, and some audio and text tasks.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-73\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q73<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">73. What are RNNs and LSTMs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A recurrent neural network (RNN) processes a sequence one step at a time and keeps a hidden state that carries information from earlier steps. That suits text, speech and time series. Plain RNNs struggle with long sequences because of vanishing gradients, so they forget early information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An <strong>LSTM<\/strong> (long short-term memory) adds a cell state and three gates (forget, input and output) that learn what to keep, add and output, so it can remember information over much longer spans. A GRU is a simpler variant with two gates. For most language tasks, transformers (question 91) have replaced RNNs because they process all positions in parallel and handle long-range context better.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-74\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q74<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">74. What are word embeddings?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Word embeddings represent each word as a dense vector of numbers, often 100 to 1,000 values, learned so that words used in similar contexts get similar vectors. Unlike one-hot vectors, they capture meaning: &#8220;king&#8221; and &#8220;queen&#8221; are close, and directions in the space can capture relationships, as in the famous king \u2212 man + woman \u2248 queen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Word2Vec and GloVe give each word one fixed vector. Modern models such as BERT and GPT produce <strong>contextual embeddings<\/strong>, where &#8220;bank&#8221; in &#8220;river bank&#8221; and &#8220;bank loan&#8221; gets different vectors. Sentence and document embeddings power semantic search and RAG systems (question 95).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-75\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Intermediate\" data-topic=\"Deep learning\"><span class=\"cd-pill\">Q75<\/span><span class=\"cd-pill cd-lv-Intermediate\">Intermediate<\/span><span class=\"cd-pill\">Deep learning<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">75. What is transfer learning?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Transfer learning reuses a model trained on a large dataset as the starting point for a new, related task. An image model trained on ImageNet already knows edges, textures and shapes, so you can replace its last layer and train only that on a few thousand images of, say, plant diseases. You can also <strong>fine-tune<\/strong> some or all of the earlier layers with a small learning rate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It needs much less data and compute, and it usually gives better accuracy than training from scratch. It is the standard approach in computer vision and NLP: fine-tuning BERT for classification and adapting large language models (question 94) are both transfer learning.<\/p>\n<\/div><\/div>\n\n\n\n<h2 id=\"ml-interview-questions-for-experienced\" class=\"wp-block-heading\">Machine learning interview questions for experienced candidates<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These 25 questions are for senior data scientists and ML engineers: production problems, drift and monitoring, deployment, boosting internals, explainability and fairness, plus transformers, LLM training, RAG and fine-tuning.<\/p>\n\n\n\n<div id=\"q-76\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q76<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">76. How do you approach an end-to-end machine learning project?<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Frame the problem:<\/strong> what decision will the model support, what does success look like in business terms, and is ML even needed? Agree on a metric and a baseline.<\/li>\n\n\n\n<li><strong>Get and understand the data:<\/strong> sources, labels, quality, leakage risks, and how the data will be available at prediction time.<\/li>\n\n\n\n<li><strong>Build a simple baseline<\/strong> (a rule, or logistic regression) to know what &#8220;good&#8221; means.<\/li>\n\n\n\n<li><strong>Iterate:<\/strong> features, models and tuning, judged with honest validation that matches how the model will be used (time-based splits, grouped splits).<\/li>\n\n\n\n<li><strong>Analyse errors:<\/strong> look at where the model fails, by segment, not just at the overall score.<\/li>\n\n\n\n<li><strong>Deploy<\/strong> with a reproducible pipeline, then <strong>monitor<\/strong> data, predictions and business metrics, and plan retraining.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers listen for the first and last steps most, because that is where real projects usually fail.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-77\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q77<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">77. Your model scored well offline but performs badly in production. What could be wrong?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Data leakage<\/strong> in training: a feature that is not really available at prediction time, or preprocessing fitted on all the data.<\/li>\n\n\n\n<li><strong>Training-serving skew:<\/strong> features computed differently in the batch training code and the live service, different units, or different handling of missing values.<\/li>\n\n\n\n<li><strong>Wrong validation:<\/strong> a random split on time-ordered or grouped data, so the offline score was too optimistic.<\/li>\n\n\n\n<li><strong>Data or concept drift<\/strong> since training (next question).<\/li>\n\n\n\n<li><strong>Feedback loops:<\/strong> the model&#8217;s own decisions change the data it later sees, for example a fraud model blocking transactions so their labels are never observed.<\/li>\n\n\n\n<li>Bugs: wrong model version, stale features, a different threshold.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Debug by logging the exact features the live model receives and comparing them with the training data for the same entities.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-78\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q78<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">78. What is the difference between data drift and concept drift, and how do you monitor them?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Data drift<\/strong> (covariate shift) means the distribution of the inputs changes: a new marketing campaign brings in younger users. <strong>Concept drift<\/strong> means the relationship between inputs and the target changes: after a policy change, the same customer profile now defaults at a different rate. Concept drift is worse, because the model&#8217;s learned rules are now wrong.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Monitor input feature distributions against training: population stability index (PSI), KL divergence, Kolmogorov-Smirnov tests.<\/li>\n\n\n\n<li>Monitor the distribution of predictions and the share of each predicted class.<\/li>\n\n\n\n<li>When labels arrive (often with a delay), track the real metrics over time and by segment.<\/li>\n\n\n\n<li>Set alerts, and retrain on a schedule or when drift crosses a limit, then validate before replacing the old model.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-79\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q79<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">79. How do you deploy a machine learning model?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first choice is between <strong>batch<\/strong> and <strong>online<\/strong> prediction. Batch scoring runs on a schedule and stores the results, which is simple and cheap and works for things like daily churn scores or nightly recommendations. Online serving exposes the model behind an API (FastAPI, TorchServe, a managed endpoint) for real-time requests such as fraud checks, where latency matters.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Package the whole pipeline (preprocessing and model) with fixed library versions, usually in a Docker container.<\/li>\n\n\n\n<li>Track model versions, training data and metrics in a model registry (MLflow and similar tools).<\/li>\n\n\n\n<li>Release safely: shadow mode (score live traffic without acting on it), canary rollout or an A\/B test.<\/li>\n\n\n\n<li>Log inputs and predictions for monitoring and future retraining, and keep a way to roll back.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-80\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q80<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">80. How do you A\/B test a new model, and why can offline and online metrics disagree?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Randomly split live users or requests between the current model (control) and the new one (treatment), decide the primary business metric and the sample size in advance, run long enough to cover weekly patterns, and check for a statistically significant difference. Also watch guardrail metrics such as latency, complaints and revenue.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Offline metrics like AUC or RMSE measure prediction quality on past data. Online metrics measure what the business cares about, such as clicks, conversions or losses, and they include effects that offline data cannot show: user behaviour changing in response to the model, position bias in recommendations, and the new model&#8217;s effect on future data. That is why a better offline model sometimes loses online.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-81\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q81<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">81. How do you train a model when the data does not fit in memory?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Start by sampling: a well-chosen sample of a few million rows is often enough to choose features and models.<\/li>\n\n\n\n<li>Use efficient types: smaller numeric types, categoricals, and columnar formats like Parquet.<\/li>\n\n\n\n<li>Process in chunks, and use models that learn incrementally with <code>partial_fit<\/code> (SGDClassifier, MiniBatchKMeans, naive Bayes).<\/li>\n\n\n\n<li>Use libraries built for big data: LightGBM and XGBoost with external memory, Dask, or Spark MLlib on a cluster.<\/li>\n\n\n\n<li>For deep learning, stream mini-batches from disk with data loaders and use several GPUs if needed.<\/li>\n\n\n\n<li>Push aggregations to the database or data warehouse with SQL, so only the features come back.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-82\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q82<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">82. How do recommendation systems work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Content-based filtering<\/strong> recommends items similar to what a user liked, using item features such as genre or product category. <strong>Collaborative filtering<\/strong> uses behaviour: users who liked the same things in the past will like similar things in future. Matrix factorisation learns a vector for every user and every item so that their dot product predicts the rating or click. Most real systems are <strong>hybrids<\/strong>, often in two stages: fast candidate generation (for example with embeddings and nearest-neighbour search), then a ranking model on the shortlist.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Topics interviewers probe: the cold-start problem for new users and items (fall back to content features or popularity), implicit feedback (clicks, watch time) versus explicit ratings, and ranking metrics like precision@k, recall@k, MAP and NDCG.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-83\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q83<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">83. What is probability calibration, and why does it matter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A model is well calibrated if, among all the cases where it predicts 70%, about 70% really are positive. Many models rank cases well but give poorly calibrated probabilities: Naive Bayes is usually overconfident, SVMs do not output probabilities at all, and boosted trees can be skewed. Calibration matters whenever the probability itself is used, such as expected loss = probability \u00d7 amount, or comparing risk across models.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.datasets import make_classification\nfrom sklearn.metrics import brier_score_loss\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\n\nX, y = make_classification(n_samples=20000, n_features=20, n_informative=4,\n                           n_redundant=10, random_state=0)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)\n\nraw = GaussianNB().fit(X_tr, y_tr)\ncal = CalibratedClassifierCV(GaussianNB(), method=\"isotonic\", cv=5).fit(X_tr, y_tr)\n\nprint(\"Brier score, raw Naive Bayes:\", round(brier_score_loss(y_te, raw.predict_proba(X_te)&#91;:, 1&#93;), 4))\nprint(\"Brier score, calibrated:     \", round(brier_score_loss(y_te, cal.predict_proba(X_te)&#91;:, 1&#93;), 4))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.calibration <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> CalibratedClassifierCV<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_classification<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.metrics <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> brier_score_loss<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.naive_bayes <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> GaussianNB<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = make_classification(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_features<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_informative<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                           <\/span><span style=\"color: #9CDCFE\">n_redundant<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">test_size<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">raw = GaussianNB().fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">cal = CalibratedClassifierCV(GaussianNB(), <\/span><span style=\"color: #9CDCFE\">method<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #CE9178\">&quot;isotonic&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">cv<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Brier score, raw Naive Bayes:&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(brier_score_loss(y_te, raw.predict_proba(X_te)&#91;:, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;), <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Brier score, calibrated:     &quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">round<\/span><span style=\"color: #D4D4D4\">(brier_score_loss(y_te, cal.predict_proba(X_te)&#91;:, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;), <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Brier score, raw Naive Bayes: 0.1852\nBrier score, calibrated:      0.1578<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Brier score, raw Naive Bayes: 0.1852<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Brier score, calibrated:      0.1578<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Fix it with Platt scaling (a logistic fit on the scores) or isotonic regression on held-out data, using <code>CalibratedClassifierCV<\/code>. Check it with a reliability curve (<code>CalibrationDisplay<\/code>) and the Brier score, which fell from 0.185 to 0.158 here. Lower is better.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-84\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Basics\"><span class=\"cd-pill\">Q84<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Basics<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">84. Explain the bias-variance decomposition.<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For squared error, the expected test error at a point x, averaged over many possible training sets, splits into three parts:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>E[(y \u2212 f\u0302(x))\u00b2] = Bias[f\u0302(x)]\u00b2 + Var[f\u0302(x)] + \u03c3\u00b2<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Bias\u00b2<\/strong>: how far the average prediction across training sets is from the truth. It comes from the model&#8217;s assumptions.<\/li>\n\n\n\n<li><strong>Variance<\/strong>: how much the prediction changes from one training set to another. It comes from sensitivity to the sample.<\/li>\n\n\n\n<li><strong>\u03c3\u00b2<\/strong>: irreducible noise in the labels, which no model can remove.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Bagging lowers variance by averaging, boosting mainly lowers bias, and regularisation trades a little bias for less variance. Very large neural networks show &#8220;double descent&#8221;, where test error falls again past the point of fitting the training data perfectly, so the classic U-shaped curve is a guide rather than a law.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-85\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q85<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">85. How do the learning rate and early stopping work together in gradient boosting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each new tree adds learning_rate \u00d7 its prediction. A large learning rate fits the training data fast but overshoots and overfits after few trees; a small one takes many more trees but generalises better. Early stopping keeps adding trees only while the score on a validation set keeps improving, so you do not have to guess <code>n_estimators<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>from sklearn.datasets import make_classification\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import train_test_split\n\nX, y = make_classification(n_samples=3000, n_features=20, flip_y=0.1, random_state=0)\nX_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)\n\nfor lr in &#91;1.0, 0.1&#93;:\n    gb = GradientBoostingClassifier(learning_rate=lr, n_estimators=1000, n_iter_no_change=20,\n                                    validation_fraction=0.2, random_state=0).fit(X_tr, y_tr)\n    print(f\"learning_rate={lr}: stopped at {gb.n_estimators_} trees, \"\n          f\"test accuracy {gb.score(X_te, y_te):.3f}\")<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.datasets <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> make_classification<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.ensemble <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> GradientBoostingClassifier<\/span><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> sklearn.model_selection <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> train_test_split<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X, y = make_classification(<\/span><span style=\"color: #9CDCFE\">n_samples<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">3000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_features<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">flip_y<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0.1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">X_tr, X_te, y_tr, y_te = train_test_split(X, y, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> lr <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">1.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.1<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    gb = GradientBoostingClassifier(<\/span><span style=\"color: #9CDCFE\">learning_rate<\/span><span style=\"color: #D4D4D4\">=lr, <\/span><span style=\"color: #9CDCFE\">n_estimators<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">1000<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n_iter_no_change<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">20<\/span><span style=\"color: #D4D4D4\">,<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                                    <\/span><span style=\"color: #9CDCFE\">validation_fraction<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0.2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">random_state<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">).fit(X_tr, y_tr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;learning_rate=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">lr<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">: stopped at <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">gb.n_estimators_<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\"> trees, &quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">          <\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;test accuracy <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">gb.score(X_te, y_te)<\/span><span style=\"color: #569CD6\">:.3f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>learning_rate=1.0: stopped at 21 trees, test accuracy 0.904\nlearning_rate=0.1: stopped at 54 trees, test accuracy 0.936<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">learning_rate=1.0: stopped at 21 trees, test accuracy 0.904<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">learning_rate=0.1: stopped at 54 trees, test accuracy 0.936<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">With learning rate 1.0, training stopped after 21 trees at 90.4% test accuracy; with 0.1 it used 54 trees and reached 93.6%. A common recipe is a small learning rate (0.01 to 0.1), a high tree limit, and early stopping on a validation set.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-86\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q86<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">86. What makes XGBoost different from classic gradient boosting?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Regularised objective:<\/strong> it adds penalties on the number of leaves (<code>gamma<\/code>) and the leaf weights (<code>lambda<\/code>, <code>alpha<\/code>), which reduces overfitting.<\/li>\n\n\n\n<li><strong>Second-order optimisation:<\/strong> it uses both the gradient and the Hessian (curvature) of the loss to choose splits and leaf values, which is more accurate per tree.<\/li>\n\n\n\n<li><strong>Sparsity-aware splits:<\/strong> each split learns a default direction for missing values.<\/li>\n\n\n\n<li><strong>Speed:<\/strong> histogram-based split finding, parallel tree building, cache-aware data layout, GPU support and out-of-core training.<\/li>\n\n\n\n<li>Row and column subsampling, and built-in cross-validation and early stopping.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-87\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Trees &#038; ensembles\"><span class=\"cd-pill\">Q87<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Trees &amp; ensembles<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">87. How do LightGBM, XGBoost and CatBoost compare?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><\/th><th>XGBoost<\/th><th>LightGBM<\/th><th>CatBoost<\/th><\/tr><\/thead><tbody><tr><td>Tree growth<\/td><td>Level by level (depth-wise) by default<\/td><td>Leaf by leaf: grows the best leaf first<\/td><td>Symmetric (oblivious) trees<\/td><\/tr><tr><td>Speed on large data<\/td><td>Fast<\/td><td>Usually fastest<\/td><td>Slower to train, fast to predict<\/td><\/tr><tr><td>Categorical features<\/td><td>Needs encoding (native support is newer)<\/td><td>Native support<\/td><td>Best native support, with ordered target statistics<\/td><\/tr><tr><td>Overfitting risk<\/td><td>Medium<\/td><td>Higher on small data; limit num_leaves<\/td><td>Lower; good defaults<\/td><\/tr><tr><td>Good choice when<\/td><td>You want a mature, widely used default<\/td><td>Data is very large<\/td><td>Many categorical features, little tuning time<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">All three are close in accuracy after tuning. In practice, try whichever fits your data, and spend the saved time on features.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-88\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q88<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">88. How do SHAP and LIME explain a model&#8217;s predictions?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SHAP<\/strong> (SHapley Additive exPlanations) uses Shapley values from game theory: each feature gets a share of the difference between this prediction and the average prediction, and the shares add up exactly to that difference. TreeSHAP computes them exactly and quickly for tree models. You get local explanations (&#8220;why was this loan rejected?&#8221;) and global ones (average absolute SHAP per feature).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>LIME<\/strong> builds a simple, interpretable model, usually a linear one, around a single prediction by perturbing the input and watching how the output changes. It is model-agnostic and fast, but its explanations can change from run to run and depend on how the neighbourhood is defined. SHAP is more consistent and is the usual choice today; both explain the model, not the real world, so correlated features can still mislead.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-89\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q89<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">89. How do you find and reduce bias (unfairness) in a model?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Models learn whatever patterns are in the data, including historical discrimination, and proxy features (such as pin code standing in for community or income) can bring it back even after you drop sensitive columns.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Measure:<\/strong> compare metrics across groups: selection rate (demographic parity), true positive rate (equal opportunity), false positive rate, and calibration by group.<\/li>\n\n\n\n<li><strong>Before training:<\/strong> fix sampling and labelling problems, reweight under-represented groups, remove clear proxies.<\/li>\n\n\n\n<li><strong>During training:<\/strong> fairness constraints or regularisation (for example with Fairlearn).<\/li>\n\n\n\n<li><strong>After training:<\/strong> group-specific thresholds where the law and policy allow.<\/li>\n\n\n\n<li>Document the choices, because some fairness definitions cannot all be satisfied at once.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-90\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Model evaluation\"><span class=\"cd-pill\">Q90<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Model evaluation<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">90. How do you choose the right metric for a business problem?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Start from the decision the model supports and the cost of each kind of mistake, not from the most familiar metric. For a fraud model, a missed fraud might cost \u20b920,000 and a false alarm \u20b9200 of review time. Then you can write the expected cost for each threshold and pick the cheapest one, instead of optimising accuracy or AUC.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ranking problems (which leads to call first): precision@k, recall@k, NDCG.<\/li>\n\n\n\n<li>Probability-based decisions: log loss, Brier score, calibration.<\/li>\n\n\n\n<li>Regression with big costly errors: RMSE; with outliers: MAE; for relative errors: MAPE (careful near zero).<\/li>\n\n\n\n<li>Keep one primary metric and a few guardrail metrics, such as latency or false positive rate.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-91\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q91<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">91. What is a transformer, and why did it replace RNNs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A transformer is a neural network architecture built around <strong>self-attention<\/strong> (next question) instead of recurrence. Each layer lets every token look at every other token directly, then passes the result through a small feed-forward network, with residual connections and layer normalisation around both. Positional encodings add word-order information, since attention by itself ignores order.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It processes all tokens in parallel, so it trains much faster on GPUs than an RNN, which must go step by step.<\/li>\n\n\n\n<li>Any two tokens are one step apart, so long-range dependencies are easy to learn.<\/li>\n\n\n\n<li>It scales very well with data and compute, which made large language models possible.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Encoder-only transformers (BERT) are used for understanding tasks like classification, decoder-only ones (GPT, Claude, Llama) for text generation, and encoder-decoder ones (T5) for translation and summarisation. The original paper is &#8220;Attention Is All You Need&#8221; (2017).<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-92\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q92<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">92. How does self-attention work?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each token&#8217;s embedding is multiplied by three learned matrices to get a <strong>query<\/strong> (what am I looking for?), a <strong>key<\/strong> (what do I contain?) and a <strong>value<\/strong> (what do I pass on?). The attention weights are softmax(QK\u1d40 \/ \u221ad), and each token&#8217;s output is the weighted sum of all the values. Dividing by \u221ad keeps the dot products from growing so large that softmax saturates.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\n\ndef softmax(z):\n    e = np.exp(z - z.max(axis=-1, keepdims=True))\n    return e \/ e.sum(axis=-1, keepdims=True)\n\nrng = np.random.default_rng(0)\nx = rng.normal(size=(3, 4))                  # 3 tokens, each a 4-number embedding\nWq, Wk, Wv = (rng.normal(size=(4, 4)) for _ in range(3))\n\nQ, K, V = x @ Wq, x @ Wk, x @ Wv\nweights = softmax(Q @ K.T \/ np.sqrt(K.shape&#91;1&#93;))   # how much each token looks at the others\noutput = weights @ V\n\nprint(\"Attention weights (each row sums to 1):\")\nprint(weights.round(3))\nprint(\"Output shape:\", output.shape)<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">softmax<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">z<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    e = np.exp(z - z.max(<\/span><span style=\"color: #9CDCFE\">axis<\/span><span style=\"color: #D4D4D4\">=-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">keepdims<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> e \/ e.sum(<\/span><span style=\"color: #9CDCFE\">axis<\/span><span style=\"color: #D4D4D4\">=-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">keepdims<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">rng = np.random.default_rng(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">x = rng.normal(<\/span><span style=\"color: #9CDCFE\">size<\/span><span style=\"color: #D4D4D4\">=(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">))                  <\/span><span style=\"color: #6A9955\"># 3 tokens, each a 4-number embedding<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Wq, Wk, Wv = (rng.normal(<\/span><span style=\"color: #9CDCFE\">size<\/span><span style=\"color: #D4D4D4\">=(<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">)) <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Q, K, V = x @ Wq, x @ Wk, x @ Wv<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">weights = softmax(Q @ K.T \/ np.sqrt(K.shape&#91;<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">&#93;))   <\/span><span style=\"color: #6A9955\"># how much each token looks at the others<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">output = weights @ V<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Attention weights (each row sums to 1):&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(weights.round(<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;Output shape:&quot;<\/span><span style=\"color: #D4D4D4\">, output.shape)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>Attention weights (each row sums to 1):\n[&#91;0.384 0.3   0.315&#93;\n &#91;0.321 0.206 0.473&#93;\n &#91;0.053 0.008 0.939&#93;]\nOutput shape: (3, 4)<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Attention weights (each row sums to 1):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">[&#91;0.384 0.3   0.315&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;0.321 0.206 0.473&#93;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> &#91;0.053 0.008 0.939&#93;]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Output shape: (3, 4)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Each row shows how much one token attends to each of the three tokens, and each row sums to 1. <strong>Multi-head attention<\/strong> runs several of these in parallel with different matrices, so different heads can track different relationships. In decoder models a causal mask stops a token from looking at future tokens. The cost grows with the square of the sequence length, which is why long context windows are expensive.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-93\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q93<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">93. How are large language models trained?<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Pre-training:<\/strong> a decoder-only transformer learns to predict the next token over a huge text corpus. This self-supervised step is where most knowledge and ability come from, and it costs the most compute.<\/li>\n\n\n\n<li><strong>Supervised fine-tuning (SFT):<\/strong> the model is trained on curated examples of prompts and good responses, so it learns to follow instructions and hold a conversation.<\/li>\n\n\n\n<li><strong>Preference tuning:<\/strong> humans (or a model) compare responses, and the model is trained to prefer the better ones, with RLHF (a reward model plus reinforcement learning such as PPO) or simpler methods like DPO. This improves helpfulness and safety.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Inference is autoregressive: the model generates one token at a time, each time feeding its own output back in, using a sampling strategy (question 97). Techniques like quantisation and KV caching make this cheaper and faster.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-94\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q94<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">94. When would you use prompt engineering, RAG or fine-tuning?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>What it changes<\/th><th>Use it when<\/th><\/tr><\/thead><tbody><tr><td>Prompt engineering<\/td><td>Only the input: instructions, examples (few-shot), output format<\/td><td>Always start here; cheap and fast to iterate<\/td><\/tr><tr><td>RAG (retrieval-augmented generation)<\/td><td>Adds relevant documents to the prompt at query time<\/td><td>The model needs private, large or frequently changing knowledge, and answers must cite sources<\/td><\/tr><tr><td>Fine-tuning<\/td><td>The model&#8217;s weights, using your examples<\/td><td>You need a consistent style or format, a narrow task done cheaply by a smaller model, or behaviour prompts cannot get<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A common mistake is fine-tuning to add knowledge. Facts learned that way are hard to update and easy to hallucinate, so RAG is usually better for knowledge, and fine-tuning for behaviour. Many production systems combine all three.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-95\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q95<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">95. How does a RAG pipeline work, and what are embeddings and vector databases for?<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Ingest:<\/strong> split documents into chunks (for example a few hundred tokens with some overlap).<\/li>\n\n\n\n<li><strong>Embed:<\/strong> turn each chunk into a vector with an embedding model, so chunks with similar meaning get similar vectors.<\/li>\n\n\n\n<li><strong>Store<\/strong> the vectors in a vector database or index (FAISS, pgvector, Pinecone, Chroma) that supports fast approximate nearest-neighbour search.<\/li>\n\n\n\n<li><strong>Retrieve:<\/strong> embed the user&#8217;s question and fetch the most similar chunks, often combined with keyword search (hybrid) and a re-ranking model.<\/li>\n\n\n\n<li><strong>Generate:<\/strong> put the retrieved chunks into the prompt and ask the LLM to answer only from them, with citations.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Most RAG failures are retrieval failures, so evaluate retrieval on its own (recall@k for known question and document pairs) as well as the final answers.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-96\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q96<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">96. What is hallucination, and how do you evaluate LLM outputs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A hallucination is fluent, confident output that is false or not supported by the given sources, such as an invented citation or a wrong figure. It happens because the model generates likely-sounding text, not checked facts.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Reduce it:<\/strong> ground answers with RAG, tell the model to say &#8220;I don&#8217;t know&#8221; when the context lacks the answer, ask for citations, lower the temperature for factual tasks, and use structured outputs.<\/li>\n\n\n\n<li><strong>Evaluate:<\/strong> build a test set of real questions with reference answers; measure faithfulness to sources, answer correctness and relevance; use human review plus &#8220;LLM as a judge&#8221; scoring with a clear rubric, checked against human labels.<\/li>\n\n\n\n<li>Track these metrics over time, like any other model, because prompts, models and documents change.<\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<div id=\"q-97\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q97<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">97. What are tokens, temperature and top-p in LLMs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Tokens<\/strong> are the pieces of text a model reads and writes: whole words, parts of words or punctuation, produced by a tokenizer such as BPE. Context limits, speed and API pricing are all counted in tokens. For the next token, the model outputs a score (logit) for every token in its vocabulary.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>import numpy as np\n\nlogits = np.array(&#91;2.0, 1.0, 0.5, -1.0&#93;)      # model scores for 4 possible next words\nwords = &#91;\"Surat\", \"Mumbai\", \"Pune\", \"Paris\"&#93;\n\nfor T in &#91;0.5, 1.0, 2.0&#93;:\n    p = np.exp(logits \/ T) \/ np.exp(logits \/ T).sum()\n    print(f\"T={T}: \" + \", \".join(f\"{w} {q:.2f}\" for w, q in zip(words, p)))<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> numpy <\/span><span style=\"color: #C586C0\">as<\/span><span style=\"color: #D4D4D4\"> np<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">logits = np.array(&#91;<\/span><span style=\"color: #B5CEA8\">2.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1.0<\/span><span style=\"color: #D4D4D4\">&#93;)      <\/span><span style=\"color: #6A9955\"># model scores for 4 possible next words<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">words = &#91;<\/span><span style=\"color: #CE9178\">&quot;Surat&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Mumbai&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Pune&quot;<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;Paris&quot;<\/span><span style=\"color: #D4D4D4\">&#93;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> T <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> &#91;<\/span><span style=\"color: #B5CEA8\">0.5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1.0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">2.0<\/span><span style=\"color: #D4D4D4\">&#93;:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    p = np.exp(logits \/ T) \/ np.exp(logits \/ T).sum()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;T=<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">T<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">: &quot;<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #CE9178\">&quot;, &quot;<\/span><span style=\"color: #D4D4D4\">.join(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">w<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\"> <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">q<\/span><span style=\"color: #569CD6\">:.2f}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> w, q <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">zip<\/span><span style=\"color: #D4D4D4\">(words, p)))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><pre class=\"code-block-pro-copy-button-pre\" aria-hidden=\"true\"><textarea class=\"code-block-pro-copy-button-textarea\" tabindex=\"-1\" aria-hidden=\"true\" readonly>T=0.5: Surat 0.84, Mumbai 0.11, Pune 0.04, Paris 0.00\nT=1.0: Surat 0.61, Mumbai 0.22, Pune 0.14, Paris 0.03\nT=2.0: Surat 0.43, Mumbai 0.26, Pune 0.21, Paris 0.10<\/textarea><\/pre><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">T=0.5: Surat 0.84, Mumbai 0.11, Pune 0.04, Paris 0.00<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">T=1.0: Surat 0.61, Mumbai 0.22, Pune 0.14, Paris 0.03<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">T=2.0: Surat 0.43, Mumbai 0.26, Pune 0.21, Paris 0.10<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Temperature<\/strong> divides the logits before softmax: below 1 makes the top choice more likely (more predictable output), above 1 flattens the distribution (more varied, more random). <strong>Top-p<\/strong> (nucleus sampling) samples only from the smallest set of tokens whose probabilities add up to p, such as 0.9, and <strong>top-k<\/strong> keeps only the k most likely tokens. Use low temperature for extraction and code, and higher for brainstorming.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-98\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"GenAI &#038; LLMs\"><span class=\"cd-pill\">Q98<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">GenAI &amp; LLMs<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">98. What are LoRA and parameter-efficient fine-tuning?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Fully fine-tuning a model with billions of parameters needs a lot of GPU memory and stores a full copy per task. <strong>Parameter-efficient fine-tuning (PEFT)<\/strong> freezes the original weights and trains only a small number of new ones.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>LoRA<\/strong> (low-rank adaptation) adds two small matrices A and B next to selected weight matrices, so the update is \u0394W = BA with a low rank r (such as 8 or 16). Often well under 1% of the parameters are trained, and the result is close to full fine-tuning. <strong>QLoRA<\/strong> also loads the frozen base model in 4-bit precision, so large models can be fine-tuned on a single GPU. The small adapters can be swapped per task or merged into the base weights for serving.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-99\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"Data &#038; features\"><span class=\"cd-pill\">Q99<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">Data &amp; features<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">99. How do you handle categorical features with thousands of categories?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">One-hot encoding a feature like user ID, product ID or pin code creates thousands of sparse columns. Better options:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Target encoding:<\/strong> replace each category with a smoothed average of the target for it. It must be computed out of fold (inside cross-validation), or each row&#8217;s own label leaks into its feature. scikit-learn&#8217;s <code>TargetEncoder<\/code> does the cross-fitting for you.<\/li>\n\n\n\n<li><strong>Frequency or count encoding<\/strong>, and grouping rare categories into &#8220;other&#8221;.<\/li>\n\n\n\n<li><strong>Hashing<\/strong> categories into a fixed number of buckets.<\/li>\n\n\n\n<li><strong>Learned embeddings<\/strong> in a neural network.<\/li>\n\n\n\n<li>Models with native categorical handling: CatBoost and LightGBM.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Also plan for categories that appear only after deployment, and make sure the encoding has a sensible default for them.<\/p>\n<\/div><\/div>\n\n\n\n<div id=\"q-100\" class=\"wp-block-group cdai cd-q\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div class=\"cd-q-meta\" data-level=\"Experienced\" data-topic=\"ML in production\"><span class=\"cd-pill\">Q100<\/span><span class=\"cd-pill cd-lv-Experienced\">Experienced<\/span><span class=\"cd-pill\">ML in production<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading cd-q-title\">100. How would you design a fraud detection system for card transactions?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Requirements:<\/strong> a decision within about 100 milliseconds per transaction, extremely imbalanced labels (well under 1% fraud), labels that arrive late (chargebacks take weeks), and fraudsters who adapt.<\/li>\n\n\n\n<li><strong>Features:<\/strong> transaction amount and merchant category, plus velocity features computed in real time from a feature store (number of transactions in the last hour, distance from the last location, amount compared with the card&#8217;s usual spending), device and IP signals.<\/li>\n\n\n\n<li><strong>Model:<\/strong> gradient-boosted trees as the main model, with business rules for known patterns, plus an anomaly detector for new kinds of fraud. Train with time-based validation.<\/li>\n\n\n\n<li><strong>Decision:<\/strong> calibrated probabilities feed a cost-based policy: approve, ask for OTP verification, send to manual review, or block.<\/li>\n\n\n\n<li><strong>Evaluate and monitor:<\/strong> PR AUC and recall at a fixed false positive rate, money saved, customer friction, drift, and retraining as new labels arrive. Watch for the feedback loop where blocked transactions never get labels.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In design questions, interviewers care more about this structure and the trade-offs you name than about the exact algorithm.<\/p>\n<\/div><\/div>\n\n\n\n<h2 id=\"ml-quiz\" class=\"wp-block-heading\">Machine learning quiz: test yourself<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Ten multiple-choice questions from across this page. Eight or more right means you are in good shape for a machine learning interview.<\/p>\n\n\n\n<div class=\"cdai cd-mlq-quiz\"><span class=\"cd-tag\">Quiz<\/span><h4 class=\"cd-h\">10 machine learning MCQs<\/h4><div class=\"cd-qz-body\"><p class=\"cd-sub\">About three minutes.<\/p><button type=\"button\" class=\"cd-btn cd-primary cd-qz-start\">Start the quiz<\/button><\/div><\/div>\n\n\n\n<h2 id=\"ml-interview-questions-pdf\" class=\"wp-block-heading\">Download all 100 machine learning interview questions as a PDF<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF has the same 100 machine learning interview questions and answers, with every code example and its output, in a clean 42-page printable format with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.<\/p>\n\n\n\n<div class=\"cdai\" style=\"display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between\"><div style=\"min-width:0\"><span class=\"cd-tag\">Free PDF<\/span><h4 class=\"cd-h\">100 Machine Learning Interview Questions and Answers<\/h4><p class=\"cd-sub\" style=\"margin:0\">42 pages \u00b7 Freshers, intermediate and experienced \u00b7 30 Python examples<\/p><\/div><a class=\"cd-btn cd-dl\" href=\"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/11\/machine-learning-interview-questions-code-and-debug.pdf\" download>Download PDF<\/a><\/div>\n\n\n\n<h2 id=\"faq\" class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What machine learning questions are asked in interviews for freshers?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Freshers are most often asked about the types of machine learning, overfitting and underfitting, the bias-variance tradeoff, train and test splits, how linear regression, logistic regression, decision trees, KNN and k-means work, and evaluation metrics such as precision, recall, F1 and ROC AUC. Questions 1 to 40 on this page cover them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How should I prepare for a machine learning interview?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Revise the core concepts with your own examples, practise coding a model end to end in scikit-learn, know the common comparisons (precision vs recall, L1 vs L2, bagging vs boosting), and prepare one project you can explain in depth, including the metric you chose and why. For experienced roles, also revise deployment, monitoring and LLM topics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Are deep learning and LLM questions asked in machine learning interviews?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, increasingly. Most ML interviews still focus on core machine learning, but expect a few questions on neural networks, backpropagation and, for many roles today, transformers, RAG, fine-tuning and evaluating LLM outputs. Questions 39, 40, 69 to 75 and 91 to 98 cover these.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Which algorithms should I know for a data science interview?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Linear and logistic regression, decision trees, random forests, gradient boosting (XGBoost or LightGBM), KNN, Naive Bayes, SVM, k-means and PCA. For each, know how it works, its main hyperparameters, when to use it and its weaknesses.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Do I need to know the maths for a machine learning interview?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You need the intuition and a few key formulas: gradient descent, the loss functions (MSE and log loss), precision, recall and F1, Gini impurity and entropy, and the bias-variance idea. Research and senior roles may go deeper into linear algebra, probability and optimisation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I download these machine learning interview questions as a PDF?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. All 100 questions and answers, with every code example and its output, are in a free 42-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.<\/p>\n\n\n\n<script type=\"application\/ld+json\">{\"@context\": \"https:\/\/schema.org\", \"@type\": \"FAQPage\", \"mainEntity\": [{\"@type\": \"Question\", \"name\": \"What machine learning questions are asked in interviews for freshers?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Freshers are most often asked about the types of machine learning, overfitting and underfitting, the bias-variance tradeoff, train and test splits, how linear regression, logistic regression, decision trees, KNN and k-means work, and evaluation metrics such as precision, recall, F1 and ROC AUC. Questions 1 to 40 on this page cover them.\"}}, {\"@type\": \"Question\", \"name\": \"How should I prepare for a machine learning interview?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Revise the core concepts with your own examples, practise coding a model end to end in scikit-learn, know the common comparisons (precision vs recall, L1 vs L2, bagging vs boosting), and prepare one project you can explain in depth, including the metric you chose and why. For experienced roles, also revise deployment, monitoring and LLM topics.\"}}, {\"@type\": \"Question\", \"name\": \"Are deep learning and LLM questions asked in machine learning interviews?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Yes, increasingly. Most ML interviews still focus on core machine learning, but expect a few questions on neural networks, backpropagation and, for many roles today, transformers, RAG, fine-tuning and evaluating LLM outputs. Questions 39, 40, 69 to 75 and 91 to 98 cover these.\"}}, {\"@type\": \"Question\", \"name\": \"Which algorithms should I know for a data science interview?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Linear and logistic regression, decision trees, random forests, gradient boosting (XGBoost or LightGBM), KNN, Naive Bayes, SVM, k-means and PCA. For each, know how it works, its main hyperparameters, when to use it and its weaknesses.\"}}, {\"@type\": \"Question\", \"name\": \"Do I need to know the maths for a machine learning interview?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"You need the intuition and a few key formulas: gradient descent, the loss functions (MSE and log loss), precision, recall and F1, Gini impurity and entropy, and the bias-variance idea. Research and senior roles may go deeper into linear algebra, probability and optimisation.\"}}, {\"@type\": \"Question\", \"name\": \"Can I download these machine learning interview questions as a PDF?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Yes. All 100 questions and answers, with every code example and its output, are in a free 42-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.\"}}]}<\/script>\n\n\n\n<h2 id=\"next-steps\" class=\"wp-block-heading\">Next steps<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Work through one level at a time and press &#8220;Mark as done&#8221; on each of the machine learning interview questions once you can answer it out loud without looking. Then go deeper with our interactive guides to <a href=\"https:\/\/codeanddebug.in\/blog\/linear-regression-in-machine-learning\/\">linear regression<\/a>, <a href=\"https:\/\/codeanddebug.in\/blog\/logistic-regression-in-machine-learning\/\">logistic regression<\/a>, <a href=\"https:\/\/codeanddebug.in\/blog\/decision-tree-in-machine-learning\/\">decision trees<\/a>, <a href=\"https:\/\/codeanddebug.in\/blog\/support-vector-machine-in-machine-learning\/\">SVM<\/a>, <a href=\"https:\/\/codeanddebug.in\/blog\/k-means-clustering\/\">k-means clustering<\/a> and the <a href=\"https:\/\/codeanddebug.in\/blog\/confusion-matrix-in-machine-learning\/\">confusion matrix<\/a>. For the coding round, revise with our <a href=\"https:\/\/codeanddebug.in\/blog\/python-interview-questions\/\">100 Python interview questions<\/a> and <a href=\"https:\/\/codeanddebug.in\/blog\/sql-interview-questions\/\">100 SQL interview questions<\/a>. All the best for your interview.<\/p>\n\n\n\n<script src=\"data:text\/javascript;charset=utf-8;base64,KGZ1bmN0aW9uICgpIHsKICAidXNlIHN0cmljdCI7CiAgZnVuY3Rpb24gJChzLCByKSB7IHJldHVybiAociB8fCBkb2N1bWVudCkucXVlcnlTZWxlY3RvcihzKTsgfQogIGZ1bmN0aW9uICQkKHMsIHIpIHsgcmV0dXJuIEFycmF5LnByb3RvdHlwZS5zbGljZS5jYWxsKChyIHx8IGRvY3VtZW50KS5xdWVyeVNlbGVjdG9yQWxsKHMpKTsgfQogIGZ1bmN0aW9uIGVsKHRhZywgY2xzLCBodG1sKSB7IHZhciBlID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCh0YWcpOyBpZiAoY2xzKSBlLmNsYXNzTmFtZSA9IGNsczsgaWYgKGh0bWwgIT0gbnVsbCkgZS5pbm5lckhUTUwgPSBodG1sOyByZXR1cm4gZTsgfQogIGZ1bmN0aW9uIGVzYyhzKSB7IHJldHVybiBTdHJpbmcocykucmVwbGFjZSgvJi9nLCAiJmFtcDsiKS5yZXBsYWNlKC88L2csICImbHQ7IikucmVwbGFjZSgvPi9nLCAiJmd0OyIpOyB9CiAgZnVuY3Rpb24gc3RvcmUoaywgdikgeyB0cnkgeyBpZiAodiA9PT0gdW5kZWZpbmVkKSByZXR1cm4gSlNPTi5wYXJzZShsb2NhbFN0b3JhZ2UuZ2V0SXRlbSgiY2RtbHFfIiArIGspKTsgbG9jYWxTdG9yYWdlLnNldEl0ZW0oImNkbWxxXyIgKyBrLCBKU09OLnN0cmluZ2lmeSh2KSk7IH0gY2F0Y2ggKGUpIHsgcmV0dXJuIG51bGw7IH0gfQogIGZ1bmN0aW9uIGNzcyhlLCBuKSB7IHJldHVybiBnZXRDb21wdXRlZFN0eWxlKGUpLmdldFByb3BlcnR5VmFsdWUobikudHJpbSgpOyB9Ci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gKGIuY2xhc3NMaXN0LmNvbnRhaW5zKCJjZC1xei1vcHQiKSkgewogICAgICAgIHZhciBxID0gUVpbaV0sIGsgPSArYi5kYXRhc2V0LmssIG9rID0gayA9PT0gcVsyXTsgaWYgKG9rKSBzY29yZSsrOwogICAgICAgICQkKCIuY2QtcXotb3B0IiwgYm9keSkuZm9yRWFjaChmdW5jdGlvbiAobykgeyBvLmRpc2FibGVkID0gdHJ1ZTsgdmFyIGtrID0gK28uZGF0YXNldC5rOyBpZiAoa2sgPT09IHFbMl0pIG8uY2xhc3NMaXN0LmFkZCgiY2QtcmlnaHQiKTsgZWxzZSBpZiAoa2sgPT09IGspIG8uY2xhc3NMaXN0LmFkZCgiY2Qtd3JvbmciKTsgfSk7CiAgICAgICAgJCgiLmNkLXF6LWZiIiwgYm9keSkuaW5uZXJIVE1MID0gJzxkaXYgY2xhc3M9ImNkLWZlZWRiYWNrICcgKyAob2sgPyAiY2Qtb2siIDogImNkLW5vIikgKyAnIj48Yj4nICsgKG9rID8gIkNvcnJlY3QuIiA6ICJOb3QgcXVpdGUuIikgKyAiPC9iPiAiICsgZXNjKHFbM10pICsgJzwvZGl2PjxidXR0b24gdHlwZT0iYnV0dG9uIiBjbGFzcz0iY2QtYnRuIGNkLXByaW1hcnkgY2QtcXotbmV4dCIgc3R5bGU9Im1hcmdpbi10b3A6MTJweCI+JyArIChpID09PSBRWi5sZW5ndGggLSAxID8gIlNlZSB5b3VyIHNjb3JlIiA6ICJOZXh0IHF1ZXN0aW9uIikgKyAiPC9idXR0b24+IjsKICAgICAgfQogICAgfSk7CiAgfSk7Cn0pKCk7Cg==\"><\/script>\n","protected":false},"excerpt":{"rendered":"<p>The 100 machine learning interview questions asked most often, with clear answers for freshers, intermediate and experienced candidates, 30 tested Python examples, four interactive tools, a quiz and a free PDF.<\/p>\n","protected":false},"author":1,"featured_media":1246,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[54,47],"tags":[57],"class_list":["post-1247","post","type-post","status-publish","format-standard","has-post-thumbnail","category-interview-questions","category-ai-machine-learning","tag-machine-learning"],"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2026\/11\/machine-learning-interview-questions.jpg","author_info":{"display_name":"Anirudh Khurana","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1247","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=1247"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1247\/revisions"}],"predecessor-version":[{"id":1248,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1247\/revisions\/1248"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/1246"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=1247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=1247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=1247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}