Spaces:
Sleeping
Sleeping
File size: 354,715 Bytes
83fd221 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "LPPvT9ymC3IT"
},
"source": [
"# Problem Statement"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qGihLYlPigGF"
},
"source": [
"## Business Context"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pcYVQzSbllJN"
},
"source": [
"In modern manufacturing, predictive maintenance plays a critical role in ensuring equipment availability and minimizing unplanned downtime. Unexpected machine failures can cause significant delays and financial losses. A manufacturing company is working to enhance the efficiency and reliability of its predictive maintenance system by leveraging operational and sensor data collected from machine tools. This data includes variables such as air temperature, process temperature, rotational speed, torque, tool wear, and failure indicators.\n",
"\n",
"While the company has developed a machine learning model to predict failures, the current process for data handling, model training, and deployment is manual and time-consumingβrequiring engineers to rerun notebooks each time new data becomes available. This introduces inefficiencies and delays in responding to potential failures.\n",
"\n",
"To address this, there is a clear need for an MLOps pipeline that can seamlessly handle data registration, preprocessing, model training with tuning, and deployment. Such a pipeline would enable real-time integration of new data, reduce manual effort, and support timely, data-driven maintenance decisionsβultimately improving production reliability and reducing operational costs."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LN0KWTL4i2B-"
},
"source": [
"## Objective"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XupSlU6QlmDQ"
},
"source": [
"As an MLOps engineer, you have to design and implement a comprehensive CI/CD pipeline integrated with MLflow for continuous machine learning experimentation tracking. This pipeline will automate critical tasks including data registration, preprocessing, model training with hyperparameter tuning, and deployment to production. The objective is to streamline the entire machine learning workflow, allowing for automated execution of each component whenever new data is ingested, thereby minimizing manual intervention, enhancing operational efficiency, and ensuring robust tracking of experiments and model artifacts through MLflow. This will facilitate better collaboration among team members, faster iterations, and more reliable deployment of machine learning models into production environments."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cuC5FGgnEmSF"
},
"source": [
"## Pre-requisites"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XEuuy1fIEmSF"
},
"source": [
"This project deploys everything on **GitHub Actions** (the ML pipeline) and **Streamlit Community Cloud** (the live app). No Hugging Face and no Codespaces are used.\n",
"\n",
"**1. Create a Personal Access Token (PAT)**\n",
"- GitHub β **Settings** β **Developer settings** β **Personal access tokens** β **Tokens (classic)**\n",
"- **Generate new token (classic)** and enable these scopes:\n",
" - `repo` (push code + let the pipeline commit the trained model back)\n",
" - `workflow` (push the Actions workflow file)\n",
"- Copy the token.\n",
"\n",
"**2. Store the token in Colab secrets**\n",
"- In Colab, click the **key icon** (left sidebar) β **Add new secret**\n",
"- Name: **GH_TOKEN** (must match `COLAB_SECRET_NAME` in the config cell below)\n",
"- Value: paste your token, and toggle **Notebook access** on.\n",
"\n",
"**3. Create a Streamlit Community Cloud account**\n",
"- Go to **https://share.streamlit.io** and sign in with the **same GitHub account** so it can access your repo. You'll deploy the app from there at the very end (see the last section).\n",
"\n",
"**4. Get an ngrok authtoken (for local MLflow experimentation)**\n",
"- Go to **https://dashboard.ngrok.com/authtokens**, sign up/sign in, and copy your authtoken.\n",
"- You'll paste this into the MLflow/ngrok cell later, in the **Experimentation and Tracking (Development Environment)** section."
]
},
{
"cell_type": "markdown",
"source": [
"##Installing and Importing Necessary Libraries"
],
"metadata": {
"id": "hoTSxB0eV3jf"
}
},
{
"cell_type": "code",
"source": [
"!pip install -q PyGithub==2.9.1\n",
"!pip install mlflow==3.0.1 pyngrok==7.2.12 -q"
],
"metadata": {
"id": "sGegY4MmVi_A"
},
"execution_count": 112,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Note:**\n",
"\n",
"- After running the above cell, kindly restart the notebook kernel (for Jupyter Notebook) or runtime (for Google Colab) and run all cells sequentially from the next cell.\n",
"\n",
"- On executing the above line of code, you might see a warning regarding package dependencies. This error message can be ignored as the above code ensures that all necessary libraries and their dependencies are maintained to successfully execute the code in this notebook."
],
"metadata": {
"id": "ai3Z1xkFV80E"
}
},
{
"cell_type": "code",
"source": [
"import os\n",
"from github import Github, GithubException\n",
"\n",
"from pyngrok import ngrok\n",
"import subprocess\n",
"import mlflow\n",
"\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.compose import make_column_transformer\n",
"from sklearn.pipeline import make_pipeline\n",
"import xgboost as xgb\n",
"from sklearn.model_selection import GridSearchCV\n",
"from sklearn.metrics import classification_report\n",
"import joblib"
],
"metadata": {
"id": "U54adAhfVsWz"
},
"execution_count": 2,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "NoWqvBRDEmSG"
},
"source": [
"## Configuration"
]
},
{
"cell_type": "code",
"metadata": {
"id": "pOQH9MPAEmSG"
},
"execution_count": null,
"outputs": [],
"source": [
"# Edit these three values, then run every cell top to bottom.\n",
"GITHUB_USERNAME = \"Swetha1929\" # Your GitHub username\n",
"REPO_NAME = \"https://github.com/Swetha1929/predictive-maintenance-mlops\" # Repository name\n",
"COLAB_SECRET_NAME = \"GITHUB_TOKEN\" # Name of the secret in Colab\n",
"\n",
"REPO = f\"{GITHUB_USERNAME}/{REPO_NAME}\"\n",
"BRANCH = \"main\""
]
},
{
"cell_type": "markdown",
"source": [
"### Secrets in Colab"
],
"metadata": {
"id": "Xv4xyPs-YzOh"
}
},
{
"cell_type": "markdown",
"source": [
"**Secrets** in Google Colab provide a secure way to store sensitive information such as API keys, access tokens, and passwords. Instead of hardcoding these values in your notebook, you can save them as secrets and access them securely whenever needed."
],
"metadata": {
"id": "ZTn9QfuPFtMP"
}
},
{
"cell_type": "markdown",
"source": [
"1. In the left pane of Google Colab, click the fifth icon, which looks like a key."
],
"metadata": {
"id": "UcXbMr9-Y2b4"
}
},
{
"cell_type": "markdown",
"source": [
""
],
"metadata": {
"id": "O4nzux__Yuns"
}
},
{
"cell_type": "markdown",
"source": [
"2. Then, click **+ Add new secret**. In the **Name** field, enter a name to identify the GitHub Personal Access Token, for example, **Gittoken**. In the **Value** field, paste the token. Once done, close the **Secrets** window. We will access this token programmatically later."
],
"metadata": {
"id": "_GbLKduqY9-c"
}
},
{
"cell_type": "markdown",
"source": [
""
],
"metadata": {
"id": "RkJ6WU2sZJ-S"
}
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "alv74F-cEmSH",
"outputId": "fd4567ca-47d4-4cd4-90cf-cee3c6e7b1bf"
},
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Token loaded.\n"
]
}
],
"source": [
"COLAB_SECRET_NAME = \"GITHUB_TOKEN\"\n",
"\n",
"import os\n",
"from google.colab import userdata\n",
"\n",
"os.environ[\"GH_TOKEN\"] = userdata.get(COLAB_SECRET_NAME)\n",
"print(\"Token loaded.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0LbSu_p2jYfe"
},
"source": [
"# Model Building"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9DtS3gNDjBbR"
},
"source": [
"## Data Registration"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"id": "9R55s4cdrqYW"
},
"outputs": [],
"source": [
"os.makedirs(\"week_3_mls/data\", exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WxXiD9ZXxodF"
},
"source": [
"Once the **data** folder created after executing the above cell, please upload the **machine-failure-prediction.csv** in to the folder"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {
"id": "oAyK_beOrqYW"
},
"outputs": [],
"source": [
"# Create a folder for storing the model building files\n",
"os.makedirs(\"/content/week_3_mls/model_building\", exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OzqvKufQrqYW"
},
"source": [
"1. **Imports Libraries**: Brings in `pandas` to read and validate the dataset.\n",
"2. **Loads the Raw Dataset**: Reads the CSV that was uploaded into `week_3_mls/data/`.\n",
"3. **Validates Columns**: Checks that all the expected columns are present before treating the dataset as \"registered\".\n",
"4. **Reports a Summary**: Prints the row/column counts and the class balance of the target column.\n",
"\n",
"This keeps \"registration\" lightweight and file-based: the CSV lives in the GitHub repo itself, so there's no external dataset store to manage."
]
},
{
"cell_type": "code",
"execution_count": 149,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "BDU0DQGErqYW",
"outputId": "6be8224d-d088-479f-e5d1-d615cd94dcba"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dataset registered successfully.\n",
"Rows: 10000\n",
"Columns: 14\n",
"Columns: ['UDI', 'Product ID', 'Type', 'Air temperature [K]', 'Process temperature [K]', 'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]', 'Machine failure', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']\n",
"\n",
"Target distribution:\n",
"Machine failure\n",
"0 9661\n",
"1 339\n",
"Name: count, dtype: int64\n",
"\n",
"Dataset saved at: /content/week_3_mls/data/machine-failure-prediction.csv\n"
]
}
],
"source": [
"from pathlib import Path\n",
"import pandas as pd\n",
"\n",
"# -----------------------------\n",
"# Paths\n",
"# -----------------------------\n",
"# BASE_DIR = Path(__file__).resolve().parent\n",
"# In Colab, __file__ is not defined. We use an explicit path based on the\n",
"# directory where this script (data_register.py) would be written.\n",
"BASE_DIR = Path(\"/content/week_3_mls/model_building\")\n",
"DATA_PATH = BASE_DIR.parent / \"data\" / \"machine-failure-prediction.csv\"\n",
"\n",
"# -----------------------------\n",
"# Load dataset\n",
"# -----------------------------\n",
"if not DATA_PATH.exists():\n",
" raise FileNotFoundError(f\"Dataset not found at: {DATA_PATH}\")\n",
"\n",
"df = pd.read_csv(DATA_PATH)\n",
"df.columns = df.columns.str.strip()\n",
"\n",
"# -----------------------------\n",
"# Validate columns\n",
"# -----------------------------\n",
"expected_columns = [\n",
" \"UDI\", \"Product ID\", \"Type\", \"Air temperature [K]\",\n",
" \"Process temperature [K]\", \"Rotational speed [rpm]\",\n",
" \"Torque [Nm]\", \"Tool wear [min]\", \"Machine failure\",\n",
" \"TWF\", \"HDF\", \"PWF\", \"OSF\", \"RNF\"\n",
"]\n",
"\n",
"missing = [col for col in expected_columns if col not in df.columns]\n",
"if missing:\n",
" raise ValueError(f\"Dataset is missing expected columns: {missing}\")\n",
"\n",
"# -----------------------------\n",
"# Basic info\n",
"# -----------------------------\n",
"print(\"Dataset registered successfully.\")\n",
"print(f\"Rows: {df.shape[0]}\")\n",
"print(f\"Columns: {df.shape[1]}\")\n",
"print(\"Columns:\", df.columns.tolist())\n",
"print(\"\\nTarget distribution:\")\n",
"print(df[\"Machine failure\"].value_counts())\n",
"\n",
"# -----------------------------\n",
"# Save cleaned dataset back\n",
"# -----------------------------\n",
"DATA_PATH.parent.mkdir(parents=True, exist_ok=True)\n",
"df.to_csv(DATA_PATH, index=False)\n",
"\n",
"print(f\"\\nDataset saved at: {DATA_PATH}\")"
]
},
{
"cell_type": "code",
"source": [
"df.columns"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1Gu5l832tlnw",
"outputId": "72f9c3e4-74a5-444c-d75d-15c02f4684aa"
},
"execution_count": 116,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Index(['UDI', 'Product ID', 'Type', 'Air temperature [K]',\n",
" 'Process temperature [K]', 'Rotational speed [rpm]', 'Torque [Nm]',\n",
" 'Tool wear [min]', 'Machine failure', 'TWF', 'HDF', 'PWF', 'OSF',\n",
" 'RNF'],\n",
" dtype='object')"
]
},
"metadata": {},
"execution_count": 116
}
]
},
{
"cell_type": "code",
"source": [
"import pandas as pd\n",
"\n",
"df = pd.read_csv('/content/week_3_mls/data/machine-failure-prediction.csv')\n",
"df.columns = df.columns.str.strip() # Strip whitespace from column names\n",
"print(\"DataFrame Columns after stripping whitespace:\", df.columns.tolist())\n",
"\n",
"# Validate that the expected columns are present before registering it\n",
"expected_columns = [\n",
" \"UDI\", \"Type\", \"Air temperature [K]\", \"Process temperature [K]\",\n",
" \"Rotational speed [rpm]\", \"Torque [Nm]\", \"Tool wear [min]\", \"Machine failure\"\n",
"]\n",
"missing = [c for c in expected_columns if c not in df.columns]\n",
"if missing:\n",
" raise ValueError(f\"Dataset is missing expected columns: {missing}\")\n",
"\n",
"print(\"Dataset registered successfully.\")\n",
"print(f\"Rows: {df.shape[0]}, Columns: {df.shape[1]}\")\n",
"print(\"Columns:\", list(df.columns))\n",
"print(\"Failure distribution:\")\n",
"print(df[\"Machine failure\"].value_counts())"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yQabtyHnstre",
"outputId": "a49ff5e4-159a-4152-f371-b151c9b62606"
},
"execution_count": 117,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"DataFrame Columns after stripping whitespace: ['UDI', 'Product ID', 'Type', 'Air temperature [K]', 'Process temperature [K]', 'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]', 'Machine failure', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']\n",
"Dataset registered successfully.\n",
"Rows: 10000, Columns: 14\n",
"Columns: ['UDI', 'Product ID', 'Type', 'Air temperature [K]', 'Process temperature [K]', 'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]', 'Machine failure', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']\n",
"Failure distribution:\n",
"Machine failure\n",
"0 9661\n",
"1 339\n",
"Name: count, dtype: int64\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hh2TjRG5WJ4Z"
},
"source": [
"## Data Preparation"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kHWdLAZCrqYW"
},
"source": [
"1. **Imports Necessary Libraries**: Brings in `pandas` and `train_test_split`.\n",
"2. **Dataset Loading**: Reads the registered CSV from `week_3_mls/data/`.\n",
"3. **Data Preparation**: Drops the `UDI` identifier column and splits features/target into train and test sets (stratified on `Failure` to preserve the class imbalance).\n",
"4. **Saving Prepared Data**: Writes `Xtrain.csv`, `Xtest.csv`, `ytrain.csv`, and `ytest.csv` to disk, which the GitHub Actions workflow passes to the next job as an artifact.\n",
"\n",
"**Note:** `Type` is kept as raw H/L/M strings here. It's one-hot-encoded later, inside the model pipeline, not label-encoded, so training and the deployed app stay consistent."
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "6mwk_9rsrqYW",
"outputId": "cfa47120-8574-4bc2-8215-2b34613013bc"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Data preparation completed successfully.\n",
"Saved files: Xtrain.csv, Xtest.csv, ytrain.csv, ytest.csv\n"
]
}
],
"source": [
"from pathlib import Path\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# Replace Path(__file__).resolve().parent with the absolute path\n",
"# where this script would conceptually reside if it were a file.\n",
"# In the context of writing to 'week_3_mls/model_building/prep.py',\n",
"# its base directory is '/content/week_3_mls/model_building'.\n",
"BASE_DIR = Path(\"/content/week_3_mls/model_building\")\n",
"DATA_PATH = BASE_DIR.parent / \"data\" / \"machine-failure-prediction.csv\"\n",
"\n",
"if not DATA_PATH.exists():\n",
" raise FileNotFoundError(f\"Dataset not found at: {DATA_PATH}\")\n",
"\n",
"df = pd.read_csv(DATA_PATH)\n",
"df.columns = df.columns.str.strip()\n",
"\n",
"TARGET_COL = \"Machine failure\"\n",
"if TARGET_COL not in df.columns:\n",
" raise ValueError(\n",
" f\"Target column '{TARGET_COL}' not found. Available columns: {df.columns.tolist()}\"\n",
" )\n",
"\n",
"X = df.drop(columns=[TARGET_COL])\n",
"y = df[TARGET_COL]\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(\n",
" X, y, test_size=0.2, random_state=42, stratify=y\n",
")\n",
"\n",
"X_train.to_csv(\"Xtrain.csv\", index=False)\n",
"X_test.to_csv(\"Xtest.csv\", index=False)\n",
"y_train.to_csv(\"ytrain.csv\", index=False)\n",
"y_test.to_csv(\"ytest.csv\", index=False)\n",
"\n",
"print(\"Data preparation completed successfully.\")\n",
"print(\"Saved files: Xtrain.csv, Xtest.csv, ytrain.csv, ytest.csv\")"
]
},
{
"cell_type": "code",
"source": [
"df"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 424
},
"id": "c53UXntcsGqD",
"outputId": "84c89c6a-a357-4392-ac41-91e04f88b3bf"
},
"execution_count": 121,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
" UDI Product ID Type Air temperature [K] Process temperature [K] \\\n",
"0 1 M14860 M 298.1 308.6 \n",
"1 2 L47181 L 298.2 308.7 \n",
"2 3 L47182 L 298.1 308.5 \n",
"3 4 L47183 L 298.2 308.6 \n",
"4 5 L47184 L 298.2 308.7 \n",
"... ... ... ... ... ... \n",
"9995 9996 M24855 M 298.8 308.4 \n",
"9996 9997 H39410 H 298.9 308.4 \n",
"9997 9998 M24857 M 299.0 308.6 \n",
"9998 9999 H39412 H 299.0 308.7 \n",
"9999 10000 M24859 M 299.0 308.7 \n",
"\n",
" Rotational speed [rpm] Torque [Nm] Tool wear [min] Machine failure \\\n",
"0 1551 42.8 0 0 \n",
"1 1408 46.3 3 0 \n",
"2 1498 49.4 5 0 \n",
"3 1433 39.5 7 0 \n",
"4 1408 40.0 9 0 \n",
"... ... ... ... ... \n",
"9995 1604 29.5 14 0 \n",
"9996 1632 31.8 17 0 \n",
"9997 1645 33.4 22 0 \n",
"9998 1408 48.5 25 0 \n",
"9999 1500 40.2 30 0 \n",
"\n",
" TWF HDF PWF OSF RNF \n",
"0 0 0 0 0 0 \n",
"1 0 0 0 0 0 \n",
"2 0 0 0 0 0 \n",
"3 0 0 0 0 0 \n",
"4 0 0 0 0 0 \n",
"... ... ... ... ... ... \n",
"9995 0 0 0 0 0 \n",
"9996 0 0 0 0 0 \n",
"9997 0 0 0 0 0 \n",
"9998 0 0 0 0 0 \n",
"9999 0 0 0 0 0 \n",
"\n",
"[10000 rows x 14 columns]"
],
"text/html": [
"\n",
" <div id=\"df-16ef2210-ff5c-473a-90d5-360889bf2cbd\" class=\"colab-df-container\">\n",
" <div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>UDI</th>\n",
" <th>Product ID</th>\n",
" <th>Type</th>\n",
" <th>Air temperature [K]</th>\n",
" <th>Process temperature [K]</th>\n",
" <th>Rotational speed [rpm]</th>\n",
" <th>Torque [Nm]</th>\n",
" <th>Tool wear [min]</th>\n",
" <th>Machine failure</th>\n",
" <th>TWF</th>\n",
" <th>HDF</th>\n",
" <th>PWF</th>\n",
" <th>OSF</th>\n",
" <th>RNF</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1</td>\n",
" <td>M14860</td>\n",
" <td>M</td>\n",
" <td>298.1</td>\n",
" <td>308.6</td>\n",
" <td>1551</td>\n",
" <td>42.8</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" <td>L47181</td>\n",
" <td>L</td>\n",
" <td>298.2</td>\n",
" <td>308.7</td>\n",
" <td>1408</td>\n",
" <td>46.3</td>\n",
" <td>3</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>3</td>\n",
" <td>L47182</td>\n",
" <td>L</td>\n",
" <td>298.1</td>\n",
" <td>308.5</td>\n",
" <td>1498</td>\n",
" <td>49.4</td>\n",
" <td>5</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4</td>\n",
" <td>L47183</td>\n",
" <td>L</td>\n",
" <td>298.2</td>\n",
" <td>308.6</td>\n",
" <td>1433</td>\n",
" <td>39.5</td>\n",
" <td>7</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5</td>\n",
" <td>L47184</td>\n",
" <td>L</td>\n",
" <td>298.2</td>\n",
" <td>308.7</td>\n",
" <td>1408</td>\n",
" <td>40.0</td>\n",
" <td>9</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9995</th>\n",
" <td>9996</td>\n",
" <td>M24855</td>\n",
" <td>M</td>\n",
" <td>298.8</td>\n",
" <td>308.4</td>\n",
" <td>1604</td>\n",
" <td>29.5</td>\n",
" <td>14</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9996</th>\n",
" <td>9997</td>\n",
" <td>H39410</td>\n",
" <td>H</td>\n",
" <td>298.9</td>\n",
" <td>308.4</td>\n",
" <td>1632</td>\n",
" <td>31.8</td>\n",
" <td>17</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9997</th>\n",
" <td>9998</td>\n",
" <td>M24857</td>\n",
" <td>M</td>\n",
" <td>299.0</td>\n",
" <td>308.6</td>\n",
" <td>1645</td>\n",
" <td>33.4</td>\n",
" <td>22</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9998</th>\n",
" <td>9999</td>\n",
" <td>H39412</td>\n",
" <td>H</td>\n",
" <td>299.0</td>\n",
" <td>308.7</td>\n",
" <td>1408</td>\n",
" <td>48.5</td>\n",
" <td>25</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9999</th>\n",
" <td>10000</td>\n",
" <td>M24859</td>\n",
" <td>M</td>\n",
" <td>299.0</td>\n",
" <td>308.7</td>\n",
" <td>1500</td>\n",
" <td>40.2</td>\n",
" <td>30</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>10000 rows Γ 14 columns</p>\n",
"</div>\n",
" <div class=\"colab-df-buttons\">\n",
"\n",
" <div class=\"colab-df-container\">\n",
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-16ef2210-ff5c-473a-90d5-360889bf2cbd')\"\n",
" title=\"Convert this dataframe to an interactive table.\"\n",
" style=\"display:none;\">\n",
"\n",
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
" </svg>\n",
" </button>\n",
"\n",
" <style>\n",
" .colab-df-container {\n",
" display:flex;\n",
" gap: 12px;\n",
" }\n",
"\n",
" .colab-df-convert {\n",
" background-color: #E8F0FE;\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: #1967D2;\n",
" height: 32px;\n",
" padding: 0 0 0 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-convert:hover {\n",
" background-color: #E2EBFA;\n",
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: #174EA6;\n",
" }\n",
"\n",
" .colab-df-buttons div {\n",
" margin-bottom: 4px;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert {\n",
" background-color: #3B4455;\n",
" fill: #D2E3FC;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert:hover {\n",
" background-color: #434B5C;\n",
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
" fill: #FFFFFF;\n",
" }\n",
" </style>\n",
"\n",
" <script>\n",
" const buttonEl =\n",
" document.querySelector('#df-16ef2210-ff5c-473a-90d5-360889bf2cbd button.colab-df-convert');\n",
" buttonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
"\n",
" async function convertToInteractive(key) {\n",
" const element = document.querySelector('#df-16ef2210-ff5c-473a-90d5-360889bf2cbd');\n",
" const dataTable =\n",
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
" [key], {});\n",
" if (!dataTable) return;\n",
"\n",
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
" + ' to learn more about interactive tables.';\n",
" element.innerHTML = '';\n",
" dataTable['output_type'] = 'display_data';\n",
" await google.colab.output.renderOutput(dataTable, element);\n",
" const docLink = document.createElement('div');\n",
" docLink.innerHTML = docLinkHtml;\n",
" element.appendChild(docLink);\n",
" }\n",
" </script>\n",
" </div>\n",
"\n",
"\n",
" <div id=\"id_65f928d9-b74e-47f9-bea7-b5ac0a4e41c3\">\n",
" <style>\n",
" .colab-df-generate {\n",
" background-color: #E8F0FE;\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: #1967D2;\n",
" height: 32px;\n",
" padding: 0 0 0 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-generate:hover {\n",
" background-color: #E2EBFA;\n",
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: #174EA6;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-generate {\n",
" background-color: #3B4455;\n",
" fill: #D2E3FC;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-generate:hover {\n",
" background-color: #434B5C;\n",
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
" fill: #FFFFFF;\n",
" }\n",
" </style>\n",
" <button class=\"colab-df-generate\" onclick=\"generateWithVariable('df')\"\n",
" title=\"Generate code using this dataframe.\"\n",
" style=\"display:none;\">\n",
"\n",
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
" width=\"24px\">\n",
" <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
" </svg>\n",
" </button>\n",
" <script>\n",
" (() => {\n",
" const buttonEl =\n",
" document.querySelector('#id_65f928d9-b74e-47f9-bea7-b5ac0a4e41c3 button.colab-df-generate');\n",
" buttonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
"\n",
" buttonEl.onclick = () => {\n",
" google.colab.notebook.generateWithVariable('df');\n",
" }\n",
" })();\n",
" </script>\n",
" </div>\n",
"\n",
" </div>\n",
" </div>\n"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "dataframe",
"variable_name": "df",
"summary": "{\n \"name\": \"df\",\n \"rows\": 10000,\n \"fields\": [\n {\n \"column\": \"UDI\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2886,\n \"min\": 1,\n \"max\": 10000,\n \"num_unique_values\": 10000,\n \"samples\": [\n 6253,\n 4685,\n 1732\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Product ID\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 10000,\n \"samples\": [\n \"L53432\",\n \"M19544\",\n \"M16591\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Type\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"M\",\n \"L\",\n \"H\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Air temperature [K]\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 2.0002586829157574,\n \"min\": 295.3,\n \"max\": 304.5,\n \"num_unique_values\": 93,\n \"samples\": [\n 299.3,\n 296.9,\n 300.8\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Process temperature [K]\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1.4837342191657419,\n \"min\": 305.7,\n \"max\": 313.8,\n \"num_unique_values\": 82,\n \"samples\": [\n 307.2,\n 308.6,\n 310.1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Rotational speed [rpm]\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 179,\n \"min\": 1168,\n \"max\": 2886,\n \"num_unique_values\": 941,\n \"samples\": [\n 1274,\n 1576,\n 2010\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Torque [Nm]\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 9.968933725121401,\n \"min\": 3.8,\n \"max\": 76.6,\n \"num_unique_values\": 577,\n \"samples\": [\n 36.1,\n 65.9,\n 12.6\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Tool wear [min]\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 63,\n \"min\": 0,\n \"max\": 253,\n \"num_unique_values\": 246,\n \"samples\": [\n 93,\n 14,\n 215\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Machine failure\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"TWF\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"HDF\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"PWF\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"OSF\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"RNF\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 0,\n \"max\": 1,\n \"num_unique_values\": 2,\n \"samples\": [\n 1,\n 0\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
}
},
"metadata": {},
"execution_count": 121
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eZZKnLkLjeM4"
},
"source": [
"## Model Training"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "G7nMvH4vtnLQ"
},
"source": [
"\n",
"1. **Set Ngrok Authentication**: Authenticates Ngrok using a personal token to enable secure tunneling from local to public network.\n",
"\n",
"2. **Launch MLflow UI**: Starts the MLflow Tracking UI as a background process on local port 5000 for experiment visualization and tracking.\n",
"\n",
"3. **Create Public Tunnel**: Uses Ngrok to expose the local MLflow UI to the internet, generating a public URL that can be accessed remotely.\n",
"\n",
"4. **Display Public URL**: Prints the Ngrok-generated URL, allowing users to open and interact with the MLflow UI in their browser."
]
},
{
"cell_type": "code",
"metadata": {
"id": "PzE083BHJhx1",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "76bd0420-f1da-478a-8abf-ec25620cf56a"
},
"execution_count": 129,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"2026/07/31 18:12:05 INFO mlflow.tracking.fluent: Experiment with name 'mlops-training-experiment' does not exist. Creating a new experiment.\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"MLflow started.\n"
]
}
],
"source": [
"import subprocess\n",
"import time\n",
"import mlflow\n",
"\n",
"process = subprocess.Popen(\n",
" [\"mlflow\", \"ui\", \"--host\", \"0.0.0.0\", \"--port\", \"5000\"],\n",
" stdout=subprocess.DEVNULL,\n",
" stderr=subprocess.DEVNULL\n",
")\n",
"\n",
"time.sleep(5)\n",
"\n",
"mlflow.set_tracking_uri(\"http://127.0.0.1:5000\")\n",
"mlflow.set_experiment(\"mlops-training-experiment\")\n",
"\n",
"print(\"MLflow started.\")"
]
},
{
"cell_type": "code",
"metadata": {
"id": "3EnwkJHmK7Ax",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "da70d44d-3a33-4abc-8f3b-79098ff50f08"
},
"execution_count": 131,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<Experiment: artifact_location='mlflow-artifacts:/876009104830794530', creation_time=1785521525692, experiment_id='876009104830794530', last_update_time=1785521525692, lifecycle_stage='active', name='mlops-training-experiment', tags={}>"
]
},
"metadata": {},
"execution_count": 131
}
],
"source": [
"# Set the tracking URL for MLflow\n",
"mlflow.set_experiment(\"mlops-training-experiment\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HnqCGXq6rqYX"
},
"source": [
"1. **Imports Necessary Libraries**: Essential libraries for data manipulation, model training, evaluation, and experiment tracking are brought in.\n",
"2. **Data Loading**: The registered dataset is read directly from `week_3_mls/data/`.\n",
"3. **Feature Definition**: Numerical and categorical features are defined, detailing the characteristics of each.\n",
"4. **Class Weight Calculation**: Class weights are calculated to address the imbalance in the target variable, improving model training effectiveness.\n",
"5. **Preprocessing Steps**: Preprocessing is set up using a column transformer that scales numerical features and one-hot-encodes the categorical `Type` feature.\n",
"6. **Model Definition**: An XGBoost classifier is defined with the calculated class weight.\n",
"7. **Experimentation Tracking**: MLflow logs each parameter combination tested during grid search as a nested run, so every trial can be compared side by side in the MLflow UI.\n",
"8. **Prediction and Evaluation**: Predictions are made on both training and test datasets (using a custom classification threshold), and classification reports are generated to evaluate performance.\n",
"9. **Model Storage**: The best model is saved locally with joblib, ready to be committed by the pipeline and served by the Streamlit app."
]
},
{
"cell_type": "code",
"execution_count": 156,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "9xPJaYf2rqYX",
"outputId": "633a580c-eff4-4230-a8a3-2353227fa8c1"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"π View run trial_1 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/8f7ec3472cb04bf3b786e3e192f15e21\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 1/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_2 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/b29e1762b65c431b88079bf4789505a9\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 2/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_3 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/a782359bff7c4a878c81cee6085caf0d\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 3/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_4 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/31721225db944c4a9532136ff6b24448\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 4/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_5 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/05cc699023984ce0b923f62a7ff874b1\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 5/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_6 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/59fc767f8f9e4a4aa31e1e598ec04662\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 6/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_7 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/cd4e25d2733e4ff586b5b6014b26418e\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 7/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_8 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/67534d7a1b454830bd4c089b1fd7296d\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 8/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_9 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/50b19e299800413ea5e58b59895ee120\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 9/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_10 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/09d0263ae3484c71889097d3723a49e9\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 10/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_11 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/0e6c54b1898e414db334f0ea68d29b49\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 11/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_12 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/3c7e22d6972f4545b87c30ed2cdbdf15\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 12/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_13 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/17897031174f4a048740311882f96788\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 13/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_14 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/e57bbd7fa1ca494f91210bf13b4a0cf6\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 14/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_15 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/6a82970d588140fdbc84fa88322fb7bd\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 15/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_16 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/49b266e1fb794a2a8e7f6b9e9bc7f6c3\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 16/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_17 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/d19a1eec8dd4420f9430199efdd13275\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 17/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_18 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/02eb3f3bb00342b0ad967be461bb52d3\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 18/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_19 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/7d38a0477dc0469bb7958a4ce6cfbad7\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 19/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_20 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/75fd4344e2514b5497ad8c4119544f6c\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 20/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_21 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/d040eaf3b3cc45d88ed3f7c50fd0d295\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 21/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_22 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/f107e9e31c5f446eb25ede79341b1525\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 22/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_23 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/124f530077b94b80bc20edd45c87b55c\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 23/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_24 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/784191cfbaa4423cb381de1c58f792f8\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 24/30 - Recall: 0.9559 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 3, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_25 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/446143408db34b3abf8c0f2c8c3c5a04\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 25/30 - Recall: 0.9265 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_26 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/d2c6bb81e2444f14a5b1537efe97b8c2\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 26/30 - Recall: 0.9265 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.6}\n",
"π View run trial_27 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/e8e79ac00159420eae097c1fcbf61f44\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 27/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 0.8}\n",
"π View run trial_28 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/9c6fa3aa5a73432dbe3257ac799fc64e\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 28/30 - Recall: 0.9412 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 50, 'xgbclassifier__reg_lambda': 1.0}\n",
"π View run trial_29 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/41c77c4f9c064ee09a01597b1bd542e8\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 29/30 - Recall: 0.9118 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.4}\n",
"π View run trial_30 at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/1e831da91df14dcd90bbc134b09d1e0f\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n",
"Trial 30/30 - Recall: 0.9118 - Params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 4, 'xgbclassifier__n_estimators': 75, 'xgbclassifier__reg_lambda': 0.6}\n",
"\n",
"Best params: {'xgbclassifier__learning_rate': 0.01, 'xgbclassifier__max_depth': 2, 'xgbclassifier__n_estimators': 100, 'xgbclassifier__reg_lambda': 0.4}\n",
"Best test recall: 0.9558823529411765\n",
"\n",
"Final Test Classification Report:\n",
" precision recall f1-score support\n",
"\n",
" 0 1.00 0.91 0.95 1932\n",
" 1 0.27 0.91 0.41 68\n",
"\n",
" accuracy 0.91 2000\n",
" macro avg 0.63 0.91 0.68 2000\n",
"weighted avg 0.97 0.91 0.93 2000\n",
"\n",
"\n",
"Model saved to week_3_mls/deployment/best_machine_failure_model_v1.joblib\n",
"π View run xgb_grid_search at: http://127.0.0.1:5000/#/experiments/876009104830794530/runs/56bfe72036a74017a0d684b29dce2b38\n",
"π§ͺ View experiment at: http://127.0.0.1:5000/#/experiments/876009104830794530\n"
]
}
],
"source": [
"import pandas as pd\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.compose import make_column_transformer\n",
"from sklearn.pipeline import make_pipeline\n",
"from sklearn.model_selection import GridSearchCV, ParameterGrid\n",
"from sklearn.metrics import classification_report\n",
"import xgboost as xgb\n",
"import joblib\n",
"import mlflow\n",
"\n",
"# If you are running in GitHub Actions with a local MLflow server,\n",
"# uncomment the next line:\n",
"# mlflow.set_tracking_uri(\"http://localhost:5000\")\n",
"\n",
"mlflow.set_experiment(\"mlops-training-experiment\")\n",
"\n",
"# -----------------------------\n",
"# Load train/test splits\n",
"# -----------------------------\n",
"Xtrain = pd.read_csv(\"Xtrain.csv\")\n",
"Xtest = pd.read_csv(\"Xtest.csv\")\n",
"ytrain = pd.read_csv(\"ytrain.csv\").squeeze()\n",
"ytest = pd.read_csv(\"ytest.csv\").squeeze()\n",
"\n",
"Xtrain.columns = Xtrain.columns.str.strip()\n",
"Xtest.columns = Xtest.columns.str.strip()\n",
"\n",
"# -----------------------------\n",
"# Features\n",
"# -----------------------------\n",
"numeric_features = [\n",
" \"Air temperature [K]\",\n",
" \"Process temperature [K]\",\n",
" \"Rotational speed [rpm]\",\n",
" \"Torque [Nm]\",\n",
" \"Tool wear [min]\"\n",
"]\n",
"categorical_features = [\"Type\"]\n",
"\n",
"# -----------------------------\n",
"# Handle class imbalance\n",
"# -----------------------------\n",
"class_weight = ytrain.value_counts()[0] / ytrain.value_counts()[1]\n",
"\n",
"# -----------------------------\n",
"# Preprocessing\n",
"# -----------------------------\n",
"preprocessor = make_column_transformer(\n",
" (StandardScaler(), numeric_features),\n",
" (OneHotEncoder(handle_unknown=\"ignore\"), categorical_features)\n",
")\n",
"\n",
"# -----------------------------\n",
"# Base model\n",
"# -----------------------------\n",
"xgb_model = xgb.XGBClassifier(\n",
" scale_pos_weight=class_weight,\n",
" random_state=42,\n",
" eval_metric=\"logloss\",\n",
" tree_method=\"hist\"\n",
")\n",
"\n",
"# -----------------------------\n",
"# Hyperparameter grid\n",
"# Create 30 combinations\n",
"# -----------------------------\n",
"full_grid = {\n",
" \"xgbclassifier__n_estimators\": [50, 75, 100],\n",
" \"xgbclassifier__max_depth\": [2, 3, 4],\n",
" \"xgbclassifier__learning_rate\": [0.01, 0.05, 0.1],\n",
" \"xgbclassifier__reg_lambda\": [0.4, 0.6, 0.8, 1.0]\n",
"}\n",
"\n",
"param_list = list(ParameterGrid(full_grid))[:30]\n",
"\n",
"# -----------------------------\n",
"# Pipeline\n",
"# -----------------------------\n",
"model_pipeline = make_pipeline(preprocessor, xgb_model)\n",
"\n",
"# -----------------------------\n",
"# Main MLflow run\n",
"# -----------------------------\n",
"with mlflow.start_run(run_name=\"xgb_grid_search\"):\n",
"\n",
" best_score = -1\n",
" best_params = None\n",
" best_model = None\n",
" best_threshold = 0.45\n",
"\n",
" for i, params in enumerate(param_list):\n",
" # Update model params\n",
" model_pipeline.set_params(**params)\n",
"\n",
" # Fit model\n",
" model_pipeline.fit(Xtrain, ytrain)\n",
"\n",
" # Predict on validation/test set\n",
" y_pred_test_proba = model_pipeline.predict_proba(Xtest)[:, 1]\n",
" y_pred_test = (y_pred_test_proba >= best_threshold).astype(int)\n",
"\n",
" # Metrics\n",
" test_report = classification_report(ytest, y_pred_test, output_dict=True)\n",
" recall_score = test_report[\"1\"][\"recall\"]\n",
"\n",
" # Log each param set as a nested MLflow run\n",
" with mlflow.start_run(run_name=f\"trial_{i+1}\", nested=True):\n",
" mlflow.log_params(params)\n",
" mlflow.log_metric(\"test_accuracy\", test_report[\"accuracy\"])\n",
" mlflow.log_metric(\"test_precision\", test_report[\"1\"][\"precision\"])\n",
" mlflow.log_metric(\"test_recall\", test_report[\"1\"][\"recall\"])\n",
" mlflow.log_metric(\"test_f1-score\", test_report[\"1\"][\"f1-score\"])\n",
"\n",
" print(f\"Trial {i+1}/30 - Recall: {recall_score:.4f} - Params: {params}\")\n",
"\n",
" # Keep best model\n",
" if recall_score > best_score:\n",
" best_score = recall_score\n",
" best_params = params\n",
" best_model = model_pipeline\n",
"\n",
" # -------------------------\n",
" # Log best params\n",
" # -------------------------\n",
" mlflow.log_params(best_params)\n",
" mlflow.log_metric(\"best_test_recall\", best_score)\n",
"\n",
" print(\"\\nBest params:\", best_params)\n",
" print(\"Best test recall:\", best_score)\n",
"\n",
" # -------------------------\n",
" # Final evaluation\n",
" # -------------------------\n",
" threshold = 0.45\n",
"\n",
" y_pred_train_proba = best_model.predict_proba(Xtrain)[:, 1]\n",
" y_pred_train = (y_pred_train_proba >= threshold).astype(int)\n",
"\n",
" y_pred_test_proba = best_model.predict_proba(Xtest)[:, 1]\n",
" y_pred_test = (y_pred_test_proba >= threshold).astype(int)\n",
"\n",
" train_report = classification_report(ytrain, y_pred_train, output_dict=True)\n",
" test_report = classification_report(ytest, y_pred_test, output_dict=True)\n",
"\n",
" print(\"\\nFinal Test Classification Report:\")\n",
" print(classification_report(ytest, y_pred_test))\n",
"\n",
" mlflow.log_metrics({\n",
" \"train_accuracy\": train_report[\"accuracy\"],\n",
" \"train_precision\": train_report[\"1\"][\"precision\"],\n",
" \"train_recall\": train_report[\"1\"][\"recall\"],\n",
" \"train_f1-score\": train_report[\"1\"][\"f1-score\"],\n",
" \"test_accuracy\": test_report[\"accuracy\"],\n",
" \"test_precision\": test_report[\"1\"][\"precision\"],\n",
" \"test_recall\": test_report[\"1\"][\"recall\"],\n",
" \"test_f1-score\": test_report[\"1\"][\"f1-score\"]\n",
" })\n",
"\n",
" # -------------------------\n",
" # Save model\n",
" # -------------------------\n",
" model_path = \"week_3_mls/deployment/best_machine_failure_model_v1.joblib\"\n",
" joblib.dump(best_model, model_path)\n",
" mlflow.log_artifact(model_path, artifact_path=\"model\")\n",
"\n",
" print(f\"\\nModel saved to {model_path}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ABqaxuW5TvRW"
},
"source": [
"- As we can see, all the experiments conducted during hyperparameter tuning are being logged by MLflow.\n",
"- Upon clicking the links in the output of the above code cell, we can check the tracking on MLflow."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LCH6DuM-T_DA"
},
"source": [
"Now that we've tested the experimentation tracking with MLflow in a development environment, let's convert this to the required script for production environment usage."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oV__RG6dOgYW"
},
"source": [
"### Experimentation and Tracking (Production Environment)"
]
},
{
"cell_type": "code",
"execution_count": 146,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "owM3g9lVrqYZ",
"outputId": "47324741-c75a-44ac-994c-79b32f2fa523"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting week_3_mls/model_building/train.py\n"
]
}
],
"source": [
"%%writefile week_3_mls/model_building/train.py\n",
"import pandas as pd\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.compose import make_column_transformer\n",
"from sklearn.pipeline import make_pipeline\n",
"from sklearn.model_selection import GridSearchCV\n",
"from sklearn.metrics import classification_report\n",
"import xgboost as xgb\n",
"import joblib\n",
"import mlflow\n",
"\n",
"mlflow.set_experiment(\"mlops-training-experiment\")\n",
"\n",
"Xtrain = pd.read_csv(\"Xtrain.csv\")\n",
"Xtest = pd.read_csv(\"Xtest.csv\")\n",
"ytrain = pd.read_csv(\"ytrain.csv\").squeeze()\n",
"ytest = pd.read_csv(\"ytest.csv\").squeeze()\n",
"\n",
"Xtrain.columns = Xtrain.columns.str.strip()\n",
"Xtest.columns = Xtest.columns.str.strip()\n",
"\n",
"numeric_features = [\n",
" \"Air temperature [K]\",\n",
" \"Process temperature [K]\",\n",
" \"Rotational speed [rpm]\",\n",
" \"Torque [Nm]\",\n",
" \"Tool wear [min]\"\n",
"]\n",
"categorical_features = [\"Type\"]\n",
"\n",
"class_weight = ytrain.value_counts()[0] / ytrain.value_counts()[1]\n",
"\n",
"preprocessor = make_column_transformer(\n",
" (StandardScaler(), numeric_features),\n",
" (OneHotEncoder(handle_unknown=\"ignore\"), categorical_features)\n",
")\n",
"\n",
"xgb_model = xgb.XGBClassifier(\n",
" scale_pos_weight=class_weight,\n",
" random_state=42,\n",
" eval_metric=\"logloss\",\n",
" tree_method=\"hist\"\n",
")\n",
"\n",
"param_grid = {\n",
" \"xgbclassifier__n_estimators\": [50, 100],\n",
" \"xgbclassifier__max_depth\": [2, 3],\n",
" \"xgbclassifier__learning_rate\": [0.05, 0.1],\n",
"}\n",
"\n",
"model_pipeline = make_pipeline(preprocessor, xgb_model)\n",
"\n",
"with mlflow.start_run():\n",
" grid_search = GridSearchCV(\n",
" model_pipeline,\n",
" param_grid,\n",
" cv=3,\n",
" scoring=\"recall\",\n",
" n_jobs=-1\n",
" )\n",
" grid_search.fit(Xtrain, ytrain)\n",
"\n",
" mlflow.log_params(grid_search.best_params_)\n",
"\n",
" best_model = grid_search.best_estimator_\n",
" print(\"Best params:\", grid_search.best_params_)\n",
"\n",
" threshold = 0.45\n",
" y_pred_train = (best_model.predict_proba(Xtrain)[:, 1] >= threshold).astype(int)\n",
" y_pred_test = (best_model.predict_proba(Xtest)[:, 1] >= threshold).astype(int)\n",
"\n",
" train_report = classification_report(ytrain, y_pred_train, output_dict=True)\n",
" test_report = classification_report(ytest, y_pred_test, output_dict=True)\n",
"\n",
" print(classification_report(ytest, y_pred_test))\n",
"\n",
" mlflow.log_metrics({\n",
" \"train_accuracy\": train_report[\"accuracy\"],\n",
" \"train_precision\": train_report[\"1\"][\"precision\"],\n",
" \"train_recall\": train_report[\"1\"][\"recall\"],\n",
" \"train_f1-score\": train_report[\"1\"][\"f1-score\"],\n",
" \"test_accuracy\": test_report[\"accuracy\"],\n",
" \"test_precision\": test_report[\"1\"][\"precision\"],\n",
" \"test_recall\": test_report[\"1\"][\"recall\"],\n",
" \"test_f1-score\": test_report[\"1\"][\"f1-score\"]\n",
" })\n",
"\n",
" model_path = \"week_3_mls/deployment/best_machine_failure_model_v1.joblib\"\n",
" joblib.dump(best_model, model_path)\n",
" mlflow.log_artifact(model_path, artifact_path=\"model\")\n",
" print(f\"Model saved to {model_path}\")"
]
},
{
"cell_type": "code",
"source": [
"%%writefile week_3_mls/model_building/prep.py\n",
"\n",
"from pathlib import Path\n",
"import pandas as pd\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# -----------------------------\n",
"# Paths\n",
"# -----------------------------\n",
"BASE_DIR = Path(__file__).resolve().parent\n",
"DATA_PATH = BASE_DIR.parent / \"data\" / \"machine-failure-prediction.csv\"\n",
"\n",
"# -----------------------------\n",
"# Load dataset\n",
"# -----------------------------\n",
"if not DATA_PATH.exists():\n",
" raise FileNotFoundError(f\"Dataset not found at: {DATA_PATH}\")\n",
"\n",
"df = pd.read_csv(DATA_PATH)\n",
"df.columns = df.columns.str.strip()\n",
"\n",
"print(\"Dataset loaded successfully.\")\n",
"print(\"Shape:\", df.shape)\n",
"\n",
"# -----------------------------\n",
"# Drop unnecessary columns\n",
"# -----------------------------\n",
"drop_cols = [\"UDI\", \"Product ID\", \"TWF\", \"HDF\", \"PWF\", \"OSF\", \"RNF\"]\n",
"\n",
"existing_cols = [c for c in drop_cols if c in df.columns]\n",
"df = df.drop(columns=existing_cols)\n",
"\n",
"# -----------------------------\n",
"# Target\n",
"# -----------------------------\n",
"TARGET_COL = \"Machine failure\"\n",
"\n",
"if TARGET_COL not in df.columns:\n",
" raise ValueError(\n",
" f\"Target column '{TARGET_COL}' not found. \"\n",
" f\"Available columns: {df.columns.tolist()}\"\n",
" )\n",
"\n",
"X = df.drop(columns=[TARGET_COL])\n",
"y = df[TARGET_COL]\n",
"\n",
"# -----------------------------\n",
"# Train/Test Split\n",
"# -----------------------------\n",
"Xtrain, Xtest, ytrain, ytest = train_test_split(\n",
" X,\n",
" y,\n",
" test_size=0.20,\n",
" random_state=42,\n",
" stratify=y\n",
")\n",
"\n",
"# -----------------------------\n",
"# Save splits\n",
"# -----------------------------\n",
"Xtrain.to_csv(\"Xtrain.csv\", index=False)\n",
"Xtest.to_csv(\"Xtest.csv\", index=False)\n",
"ytrain.to_csv(\"ytrain.csv\", index=False)\n",
"ytest.to_csv(\"ytest.csv\", index=False)\n",
"\n",
"print(\"Data preparation completed successfully.\")\n",
"print(f\"Training samples : {len(Xtrain)}\")\n",
"print(f\"Testing samples : {len(Xtest)}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZLLI5Ql7goZ1",
"outputId": "54ab693f-9371-4f90-a758-e13edc6bc0d6"
},
"execution_count": 151,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting week_3_mls/model_building/prep.py\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0McYCZzkji5I"
},
"source": [
"# Deployment"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4roQt1bFrqYa"
},
"source": [
"## Streamlit App"
]
},
{
"cell_type": "code",
"execution_count": 134,
"metadata": {
"id": "sSXNru68rqYa"
},
"outputs": [],
"source": [
"os.makedirs(\"week_3_mls/deployment\", exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7RR6I3ePrqYb"
},
"source": [
"This application provides an interactive tool for machine failure prediction, predicting whether a machine is likely to fail based on its operational parameters. It loads the model that the GitHub Actions pipeline trained and committed into the repo, collects user inputs, makes predictions, and displays the results in a simple interface. Streamlit Community Cloud runs this file directly from the repo, so there's nothing to configure beyond pointing it at `week_3_mls/deployment/app.py` when you deploy at the end."
]
},
{
"cell_type": "code",
"execution_count": 135,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "gLOCkgotrqYb",
"outputId": "9af8f813-8515-4b43-d847-a2f0a1fa1886"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting week_3_mls/deployment/app.py\n"
]
}
],
"source": [
"%%writefile week_3_mls/deployment/app.py\n",
"\n",
"import os\n",
"import streamlit as st\n",
"import pandas as pd\n",
"import joblib\n",
"\n",
"# -----------------------------\n",
"# Load trained model\n",
"# -----------------------------\n",
"model_path = os.path.join(\n",
" os.path.dirname(__file__),\n",
" \"best_machine_failure_model_v1.joblib\"\n",
")\n",
"\n",
"model = joblib.load(model_path)\n",
"\n",
"# -----------------------------\n",
"# Streamlit page configuration\n",
"# -----------------------------\n",
"st.set_page_config(\n",
" page_title=\"Machine Failure Prediction\",\n",
" page_icon=\"βοΈ\",\n",
" layout=\"centered\"\n",
")\n",
"\n",
"st.title(\"βοΈ Machine Failure Prediction\")\n",
"st.write(\n",
" \"\"\"\n",
" Enter the machine operating parameters below to predict\n",
" whether the machine is likely to fail.\n",
" \"\"\"\n",
")\n",
"\n",
"# -----------------------------\n",
"# User Inputs\n",
"# -----------------------------\n",
"machine_type = st.selectbox(\n",
" \"Machine Type\",\n",
" [\"H\", \"L\", \"M\"]\n",
")\n",
"\n",
"air_temp = st.number_input(\n",
" \"Air Temperature (K)\",\n",
" min_value=250.0,\n",
" max_value=400.0,\n",
" value=298.0,\n",
" step=0.1\n",
")\n",
"\n",
"process_temp = st.number_input(\n",
" \"Process Temperature (K)\",\n",
" min_value=250.0,\n",
" max_value=500.0,\n",
" value=308.0,\n",
" step=0.1\n",
")\n",
"\n",
"rot_speed = st.number_input(\n",
" \"Rotational Speed (rpm)\",\n",
" min_value=0,\n",
" max_value=3000,\n",
" value=1500,\n",
" step=1\n",
")\n",
"\n",
"torque = st.number_input(\n",
" \"Torque (Nm)\",\n",
" min_value=0.0,\n",
" max_value=100.0,\n",
" value=40.0,\n",
" step=0.1\n",
")\n",
"\n",
"tool_wear = st.number_input(\n",
" \"Tool Wear (min)\",\n",
" min_value=0,\n",
" max_value=300,\n",
" value=10,\n",
" step=1\n",
")\n",
"\n",
"# -----------------------------\n",
"# Prediction\n",
"# -----------------------------\n",
"if st.button(\"Predict Machine Failure\"):\n",
"\n",
" input_df = pd.DataFrame({\n",
" \"Type\": [machine_type],\n",
" \"Air temperature [K]\": [air_temp],\n",
" \"Process temperature [K]\": [process_temp],\n",
" \"Rotational speed [rpm]\": [rot_speed],\n",
" \"Torque [Nm]\": [torque],\n",
" \"Tool wear [min]\": [tool_wear]\n",
" })\n",
"\n",
" prediction = model.predict(input_df)[0]\n",
"\n",
" # Only calculate probability if the model supports it\n",
" probability = None\n",
" if hasattr(model, \"predict_proba\"):\n",
" probability = model.predict_proba(input_df)[0][1]\n",
"\n",
" st.subheader(\"Prediction Result\")\n",
"\n",
" if prediction == 1:\n",
" st.error(\"β Machine Failure Predicted\")\n",
" else:\n",
" st.success(\"β
No Machine Failure Predicted\")\n",
"\n",
" if probability is not None:\n",
" st.write(f\"**Failure Probability:** {probability:.2%}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gw5Uyox_rqYb"
},
"source": [
"## App Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 137,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "cUz77AcOrqYb",
"outputId": "4d34a7bb-3359-4151-d99e-add6dc4bed50"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting week_3_mls/deployment/requirements.txt\n"
]
}
],
"source": [
"%%writefile week_3_mls/deployment/requirements.txt\n",
"streamlit==1.43.2\n",
"pandas==2.2.2\n",
"numpy==2.2.3\n",
"scikit-learn==1.6.0\n",
"xgboost==2.1.4\n",
"joblib==1.5.1"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PuCgAW2hktli"
},
"source": [
"# Create and Automate MLOps Pipeline with GitHub Action Workflows using CI/CD"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yo_xWLLvkqSC"
},
"source": [
"## Action Workflow YAML File"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ICEDG3zwkLh2"
},
"source": [
"* A YAML file is a simple, human-readable file used to store configuration settings.\n",
"* YAML stands for Yet Another Markup Language or YAML Ain't Markup Language (a recursive acronym).\n",
"* It uses indentation (spaces) to show structure, like folders inside folders.\n",
"* Each line contains a key and a value, making it easy to organize data.\n",
"* YAML is often used in automation tools, cloud setups, and app settings."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_oH3zSIIrqYb"
},
"source": [
"Three jobs run in sequence β **Register Dataset β Data Preparation β Model Training (with MLflow tracking)** β then the trained model is committed back into the repo so Streamlit Community Cloud can serve it.\n",
"\n",
"**Important:** GitHub only picks up workflow files from `.github/workflows/` at the repo **root** β not nested inside `week_3_mls/`. The cell below creates that folder at the top level, alongside `week_3_mls/`."
]
},
{
"cell_type": "code",
"execution_count": 138,
"metadata": {
"id": "qZiLae0QrqYb"
},
"outputs": [],
"source": [
"os.makedirs(\".github/workflows\", exist_ok=True)"
]
},
{
"cell_type": "code",
"execution_count": 140,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JDX-bDMmrqYc",
"outputId": "f576bb35-18e4-4757-c53d-c4a80350d685"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting .github/workflows/pipeline.yml\n"
]
}
],
"source": [
"%%writefile .github/workflows/pipeline.yml\n",
"name: Week 3 MLS CI/CD Pipeline\n",
"\n",
"on:\n",
" push:\n",
" branches:\n",
" - main\n",
" workflow_dispatch:\n",
"\n",
"permissions:\n",
" contents: write\n",
"\n",
"jobs:\n",
" register-dataset:\n",
" name: Register Dataset\n",
" runs-on: ubuntu-latest\n",
"\n",
" steps:\n",
" - name: Checkout Repository\n",
" uses: actions/checkout@v4\n",
"\n",
" - name: Setup Python\n",
" uses: actions/setup-python@v5\n",
" with:\n",
" python-version: \"3.11\"\n",
"\n",
" - name: Install Dependencies\n",
" run: |\n",
" python -m pip install --upgrade pip\n",
" pip install -r week_3_mls/requirements.txt\n",
"\n",
" - name: Register Dataset\n",
" run: python week_3_mls/model_building/data_register.py\n",
"\n",
" - name: Upload Registered Dataset\n",
" uses: actions/upload-artifact@v4\n",
" with:\n",
" name: registered-data\n",
" path: week_3_mls/data/machine-failure-prediction.csv\n",
"\n",
" data-preparation:\n",
" name: Data Preparation\n",
" needs: register-dataset\n",
" runs-on: ubuntu-latest\n",
"\n",
" steps:\n",
" - name: Checkout Repository\n",
" uses: actions/checkout@v4\n",
"\n",
" - name: Setup Python\n",
" uses: actions/setup-python@v5\n",
" with:\n",
" python-version: \"3.11\"\n",
"\n",
" - name: Install Dependencies\n",
" run: |\n",
" python -m pip install --upgrade pip\n",
" pip install -r week_3_mls/requirements.txt\n",
"\n",
" - name: Prepare Data\n",
" run: python week_3_mls/model_building/prep.py\n",
"\n",
" - name: Upload Train/Test Splits\n",
" uses: actions/upload-artifact@v4\n",
" with:\n",
" name: data-splits\n",
" path: |\n",
" Xtrain.csv\n",
" Xtest.csv\n",
" ytrain.csv\n",
" ytest.csv\n",
"\n",
" model-training:\n",
" name: Model Training\n",
" needs: data-preparation\n",
" runs-on: ubuntu-latest\n",
"\n",
" steps:\n",
" - name: Checkout Repository\n",
" uses: actions/checkout@v4\n",
"\n",
" - name: Setup Python\n",
" uses: actions/setup-python@v5\n",
" with:\n",
" python-version: \"3.11\"\n",
"\n",
" - name: Install Dependencies\n",
" run: |\n",
" python -m pip install --upgrade pip\n",
" pip install -r week_3_mls/requirements.txt\n",
"\n",
" - name: Start MLflow Tracking Server\n",
" run: |\n",
" nohup mlflow ui --host 0.0.0.0 --port 5000 &\n",
" sleep 5\n",
"\n",
" - name: Download Train/Test Splits\n",
" uses: actions/download-artifact@v4\n",
" with:\n",
" name: data-splits\n",
"\n",
" - name: Train Model\n",
" run: python week_3_mls/model_building/train.py\n",
"\n",
" - name: Commit Trained Model\n",
" run: |\n",
" git config user.name \"github-actions[bot]\"\n",
" git config user.email \"github-actions[bot]@users.noreply.github.com\"\n",
"\n",
" git add week_3_mls/deployment/best_machine_failure_model_v1.joblib\n",
"\n",
" git diff --cached --quiet || git commit -m \"Add trained model [skip ci]\"\n",
" git push"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4sMZOH8jrqYc"
},
"source": [
"**Note:** The cells above already created `.github/workflows/pipeline.yml` locally. There's nothing to copy-paste manually β the push step later in this notebook will upload it to your repo along with the rest of the project."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PvEUJ-t5kdxH"
},
"source": [
"## Requirements file for the Github Actions Workflow"
]
},
{
"cell_type": "code",
"execution_count": 141,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "bEr0Lly9rqYc",
"outputId": "3fb98058-257b-48b1-dcb4-a8a91abade33"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Overwriting week_3_mls/requirements.txt\n"
]
}
],
"source": [
"%%writefile week_3_mls/requirements.txt\n",
"pandas==2.2.2\n",
"numpy==2.2.3\n",
"scikit-learn==1.6.0\n",
"xgboost==2.1.4\n",
"joblib==1.5.1\n",
"mlflow==3.0.1\n",
"streamlit==1.43.2\n",
"PyGithub==2.3.0"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BA6mP-Ebkm3O"
},
"source": [
"## Github Authentication and Push Files"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "T1cH6gpOrqYc"
},
"source": [
"We already created a GitHub PAT and stored it in Colab secrets during the **Prerequisites** step above (as `GITHUB_TOKEN`), and loaded it into `GH_TOKEN` in the **Configuration** section. The cell below uses that token (via `PyGithub`) to create the repo if needed and push every file β no manual `git clone`/`git push`, and no token hardcoded in this notebook."
]
},
{
"cell_type": "code",
"source": [
"import os\n",
"os.makedirs(\"week_3_mls/model_building\", exist_ok=True)\n",
"os.makedirs(\"week_3_mls/data\", exist_ok=True)"
],
"metadata": {
"id": "kuDxUMgO8xP7"
},
"execution_count": 142,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "4cc3a423"
},
"source": [
"# Edit these three values, then run every cell top to bottom.\n",
"GITHUB_USERNAME = \"Swetha1929\" # Your GitHub username\n",
"REPO_NAME = \"predictive-maintenance-mlops\" # Repository name\n",
"COLAB_SECRET_NAME = \"GITHUB_TOKEN\" # Name of the secret in Colab\n",
"\n",
"REPO = f\"{GITHUB_USERNAME}/{REPO_NAME}\"\n",
"BRANCH = \"main\""
],
"execution_count": 143,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import pandas as pd\n",
"import os\n",
"\n",
"# Dataset path\n",
"CSV_PATH = \"/content/week_3_mls/data/machine-failure-prediction.csv\"\n",
"\n",
"# Ensure data directory exists\n",
"os.makedirs(\"/content/week_3_mls/data\", exist_ok=True)\n",
"\n",
"# Check dataset exists\n",
"if not os.path.exists(CSV_PATH):\n",
" raise FileNotFoundError(\n",
" f\"Dataset not found at {CSV_PATH}. \"\n",
" \"Please upload machine-failure-prediction.csv into week_3_mls/data.\"\n",
" )\n",
"\n",
"# Load dataset\n",
"df = pd.read_csv(CSV_PATH)\n",
"\n",
"# Remove any extra spaces from column names\n",
"df.columns = df.columns.str.strip()\n",
"\n",
"print(\"Dataset loaded successfully.\")\n",
"print(f\"Path: {CSV_PATH}\")\n",
"print(f\"Shape: {df.shape}\")\n",
"\n",
"print(\"\\nColumns:\")\n",
"print(df.columns.tolist())\n",
"\n",
"print(\"\\nFirst 5 rows:\")\n",
"print(df.head())\n",
"\n",
"print(\"\\nMissing Values:\")\n",
"print(df.isnull().sum())\n",
"\n",
"print(\"\\nTarget Distribution:\")\n",
"print(df[\"Machine failure\"].value_counts())\n",
"\n",
"# Save the validated dataset\n",
"df.to_csv(CSV_PATH, index=False)\n",
"\n",
"print(\"\\nDataset registered successfully.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "tJcezWODOV1N",
"outputId": "556a1c8b-bb62-4071-eb60-b43c728689a1"
},
"execution_count": 144,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dataset loaded successfully.\n",
"Path: /content/week_3_mls/data/machine-failure-prediction.csv\n",
"Shape: (10000, 14)\n",
"\n",
"Columns:\n",
"['UDI', 'Product ID', 'Type', 'Air temperature [K]', 'Process temperature [K]', 'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]', 'Machine failure', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']\n",
"\n",
"First 5 rows:\n",
" UDI Product ID Type Air temperature [K] Process temperature [K] \\\n",
"0 1 M14860 M 298.1 308.6 \n",
"1 2 L47181 L 298.2 308.7 \n",
"2 3 L47182 L 298.1 308.5 \n",
"3 4 L47183 L 298.2 308.6 \n",
"4 5 L47184 L 298.2 308.7 \n",
"\n",
" Rotational speed [rpm] Torque [Nm] Tool wear [min] Machine failure TWF \\\n",
"0 1551 42.8 0 0 0 \n",
"1 1408 46.3 3 0 0 \n",
"2 1498 49.4 5 0 0 \n",
"3 1433 39.5 7 0 0 \n",
"4 1408 40.0 9 0 0 \n",
"\n",
" HDF PWF OSF RNF \n",
"0 0 0 0 0 \n",
"1 0 0 0 0 \n",
"2 0 0 0 0 \n",
"3 0 0 0 0 \n",
"4 0 0 0 0 \n",
"\n",
"Missing Values:\n",
"UDI 0\n",
"Product ID 0\n",
"Type 0\n",
"Air temperature [K] 0\n",
"Process temperature [K] 0\n",
"Rotational speed [rpm] 0\n",
"Torque [Nm] 0\n",
"Tool wear [min] 0\n",
"Machine failure 0\n",
"TWF 0\n",
"HDF 0\n",
"PWF 0\n",
"OSF 0\n",
"RNF 0\n",
"dtype: int64\n",
"\n",
"Target Distribution:\n",
"Machine failure\n",
"0 9661\n",
"1 339\n",
"Name: count, dtype: int64\n",
"\n",
"Dataset registered successfully.\n"
]
}
]
},
{
"cell_type": "code",
"execution_count": 145,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "F4BrFFPTrqYc",
"outputId": "f1714171-815c-4166-95d4-44343c35b8ee"
},
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/tmp/ipykernel_1044/4257184302.py:35: DeprecationWarning: Argument login_or_token is deprecated, please use auth=github.Auth.Token(...) instead\n",
" gh = Github(os.environ[\"GH_TOKEN\"])\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"Repo already exists: Swetha1929/predictive-maintenance-mlops\n",
"updated week_3_mls/requirements.txt\n",
"updated week_3_mls/data/machine-failure-prediction.csv\n",
"added week_3_mls/deployment/best_machine_failure_model_v1.joblib\n",
"updated week_3_mls/deployment/app.py\n",
"updated week_3_mls/deployment/requirements.txt\n",
"updated week_3_mls/model_building/prep.py\n",
"updated week_3_mls/model_building/train.py\n",
"updated week_3_mls/model_building/data_register.py\n",
"updated .github/workflows/pipeline.yml\n",
"\n",
"Verifying repo layout...\n",
" ok week_3_mls/requirements.txt\n",
" ok week_3_mls/model_building/data_register.py\n",
" ok week_3_mls/model_building/prep.py\n",
" ok week_3_mls/model_building/train.py\n",
" ok week_3_mls/data/machine-failure-prediction.csv\n",
" ok .github/workflows/pipeline.yml\n",
" ok week_3_mls/deployment/app.py\n",
" ok week_3_mls/deployment/requirements.txt\n",
"\n",
"All files pushed.\n"
]
}
],
"source": [
"import os\n",
"from pathlib import Path\n",
"from github import Github, GithubException\n",
"\n",
"# -----------------------------\n",
"# Paths\n",
"# -----------------------------\n",
"ROOT = Path(\"/content\")\n",
"PROJECT_DIR = ROOT / \"week_3_mls\"\n",
"DATA_DIR = PROJECT_DIR / \"data\"\n",
"\n",
"LEGACY_CSV = PROJECT_DIR / \"machine failure.csv\"\n",
"TARGET_CSV = DATA_DIR / \"machine-failure-prediction.csv\"\n",
"\n",
"# -----------------------------\n",
"# Make sure folders exist\n",
"# -----------------------------\n",
"DATA_DIR.mkdir(parents=True, exist_ok=True)\n",
"\n",
"# -----------------------------\n",
"# Move/rename dataset if needed\n",
"# -----------------------------\n",
"if LEGACY_CSV.exists() and not TARGET_CSV.exists():\n",
" LEGACY_CSV.replace(TARGET_CSV)\n",
" print(f\"Moved dataset to: {TARGET_CSV}\")\n",
"\n",
"assert TARGET_CSV.exists(), (\n",
" f\"{TARGET_CSV} not found. Place the dataset in week_3_mls/data/ \"\n",
" \"and name it machine-failure-prediction.csv before running this cell.\"\n",
")\n",
"\n",
"# -----------------------------\n",
"# Connect to GitHub\n",
"# -----------------------------\n",
"gh = Github(os.environ[\"GH_TOKEN\"])\n",
"user = gh.get_user()\n",
"\n",
"try:\n",
" repo = gh.get_repo(REPO)\n",
" print(\"Repo already exists:\", repo.full_name)\n",
"except GithubException:\n",
" repo = user.create_repo(\n",
" REPO_NAME,\n",
" private=False,\n",
" auto_init=True,\n",
" )\n",
" print(\"Repo created:\", repo.full_name)\n",
"\n",
"# -----------------------------\n",
"# Push local folders to repo\n",
"# -----------------------------\n",
"def push_folder(local_dir):\n",
" for root, _, files in os.walk(local_dir):\n",
" for fname in files:\n",
" local_path = os.path.join(root, fname)\n",
" repo_path = local_path # keep same relative path in GitHub\n",
" content = open(local_path, \"rb\").read()\n",
"\n",
" try:\n",
" sha = repo.get_contents(repo_path, ref=BRANCH).sha\n",
" repo.update_file(\n",
" repo_path,\n",
" f\"update {repo_path}\",\n",
" content,\n",
" sha,\n",
" branch=BRANCH,\n",
" )\n",
" print(\"updated\", repo_path)\n",
" except GithubException:\n",
" repo.create_file(\n",
" repo_path,\n",
" f\"add {repo_path}\",\n",
" content,\n",
" branch=BRANCH,\n",
" )\n",
" print(\"added \", repo_path)\n",
"\n",
"push_folder(\"week_3_mls\")\n",
"push_folder(\".github\")\n",
"\n",
"# -----------------------------\n",
"# Verify repo layout\n",
"# -----------------------------\n",
"print(\"\\nVerifying repo layout...\")\n",
"required = [\n",
" \"week_3_mls/requirements.txt\",\n",
" \"week_3_mls/model_building/data_register.py\",\n",
" \"week_3_mls/model_building/prep.py\",\n",
" \"week_3_mls/model_building/train.py\",\n",
" \"week_3_mls/data/machine-failure-prediction.csv\",\n",
" \".github/workflows/pipeline.yml\",\n",
" \"week_3_mls/deployment/app.py\",\n",
" \"week_3_mls/deployment/requirements.txt\",\n",
"]\n",
"\n",
"all_ok = True\n",
"for f in required:\n",
" try:\n",
" repo.get_contents(f, ref=BRANCH)\n",
" print(\" ok \", f)\n",
" except GithubException:\n",
" print(\" MISSING \", f)\n",
" all_ok = False\n",
"\n",
"print(\"\\nAll files pushed.\" if all_ok else \"\\nSome files are missing - check the list above.\")"
]
},
{
"cell_type": "code",
"source": [
"from github import Github\n",
"import os\n",
"\n",
"# GitHub connection\n",
"gh = Github(os.environ[\"GH_TOKEN\"])\n",
"repo = gh.get_repo(REPO)\n",
"\n",
"# File to push\n",
"file_path = \"week_3_mls/model_building/train.py\"\n",
"\n",
"# Read local file\n",
"with open(file_path, \"rb\") as f:\n",
" content = f.read()\n",
"\n",
"try:\n",
" # Update existing file\n",
" file = repo.get_contents(file_path, ref=BRANCH)\n",
" repo.update_file(\n",
" path=file_path,\n",
" message=\"Update train.py\",\n",
" content=content,\n",
" sha=file.sha,\n",
" branch=BRANCH\n",
" )\n",
" print(\"β
train.py updated successfully.\")\n",
"\n",
"except Exception:\n",
" # Create file if it doesn't exist\n",
" repo.create_file(\n",
" path=file_path,\n",
" message=\"Add train.py\",\n",
" content=content,\n",
" branch=BRANCH\n",
" )\n",
" print(\"β
train.py created successfully.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "_fdMrG73eThz",
"outputId": "4fc4345d-e411-4768-a80c-8f007125e1c6"
},
"execution_count": 147,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/tmp/ipykernel_1044/793259524.py:5: DeprecationWarning: Argument login_or_token is deprecated, please use auth=github.Auth.Token(...) instead\n",
" gh = Github(os.environ[\"GH_TOKEN\"])\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"β
train.py updated successfully.\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"from github import Github\n",
"import os\n",
"\n",
"# Connect to GitHub\n",
"gh = Github(os.environ[\"GH_TOKEN\"])\n",
"repo = gh.get_repo(REPO)\n",
"\n",
"# File to update\n",
"file_path = \"week_3_mls/model_building/data_register.py\"\n",
"\n",
"# Read the local file\n",
"with open(file_path, \"rb\") as f:\n",
" content = f.read()\n",
"\n",
"try:\n",
" # Update if it already exists\n",
" file = repo.get_contents(file_path, ref=BRANCH)\n",
"\n",
" repo.update_file(\n",
" path=file_path,\n",
" message=\"Update data_register.py\",\n",
" content=content,\n",
" sha=file.sha,\n",
" branch=BRANCH\n",
" )\n",
"\n",
" print(\"β
data_register.py updated successfully.\")\n",
"\n",
"except Exception:\n",
" # Create if it doesn't exist\n",
" repo.create_file(\n",
" path=file_path,\n",
" message=\"Add data_register.py\",\n",
" content=content,\n",
" branch=BRANCH\n",
" )\n",
"\n",
" print(\"β
data_register.py created successfully.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "FFiLXwvVfqjG",
"outputId": "51b6fdea-f5a9-453f-8af7-d29ebb9c7c61"
},
"execution_count": 150,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/tmp/ipykernel_1044/1283134696.py:5: DeprecationWarning: Argument login_or_token is deprecated, please use auth=github.Auth.Token(...) instead\n",
" gh = Github(os.environ[\"GH_TOKEN\"])\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"β
data_register.py updated successfully.\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"from github import Github\n",
"import os\n",
"\n",
"gh = Github(os.environ[\"GH_TOKEN\"])\n",
"repo = gh.get_repo(REPO)\n",
"\n",
"file_path = \"week_3_mls/model_building/prep.py\"\n",
"\n",
"with open(file_path, \"rb\") as f:\n",
" content = f.read()\n",
"\n",
"try:\n",
" file = repo.get_contents(file_path, ref=BRANCH)\n",
"\n",
" repo.update_file(\n",
" path=file_path,\n",
" message=\"Update prep.py\",\n",
" content=content,\n",
" sha=file.sha,\n",
" branch=BRANCH\n",
" )\n",
"\n",
" print(\"β
prep.py updated successfully.\")\n",
"\n",
"except Exception:\n",
" repo.create_file(\n",
" path=file_path,\n",
" message=\"Add prep.py\",\n",
" content=content,\n",
" branch=BRANCH\n",
" )\n",
"\n",
" print(\"β
prep.py created successfully.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "fxDWGf7AgOUI",
"outputId": "d0d9ab59-ef3e-4bee-c224-e0383624e5e6"
},
"execution_count": 152,
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"/tmp/ipykernel_1044/2163703070.py:4: DeprecationWarning: Argument login_or_token is deprecated, please use auth=github.Auth.Token(...) instead\n",
" gh = Github(os.environ[\"GH_TOKEN\"])\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"β
prep.py updated successfully.\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EHl1Wm1CrqYc"
},
"source": [
"# Run the Pipeline, then Deploy on Streamlit Community Cloud\n",
"\n",
"## 1. Run the GitHub Actions pipeline\n",
"After the push above finishes, open your repo β **Actions** tab. Select **Week 3 MLS CI/CD Pipeline**\n",
"β **Run workflow** β **Run workflow** (it will also run automatically on every push to `main`).\n",
"\n",
"You'll see three jobs run in order: **Register Dataset β Data Preparation β Model Training**.\n",
"The **Model Training** job starts a local MLflow server, runs the hyperparameter search while logging\n",
"every trial to it, and finishes by committing the trained model to\n",
"`week_3_mls/deployment/best_machine_failure_model_v1.joblib` on `main`.\n",
"\n",
"## 2. Deploy the app on Streamlit Community Cloud\n",
"1. Go to **https://share.streamlit.io** and sign in with the GitHub account that owns the repo.\n",
"2. Click **Create app**\n",
"3. Fill in:\n",
" - **Repository:** `your-username/Machine_Failure_Prediction`\n",
" - **Branch:** `main`\n",
" - **Main file path:** `week_3_mls/deployment/app.py`\n",
"4. Open **Advanced settings** and set **Python version** to **3.11** (this matches the version that\n",
" trained the model in GitHub Actions, so the saved `.joblib` loads cleanly).\n",
"5. Click **Deploy**.\n",
"\n",
"Streamlit installs dependencies from `week_3_mls/deployment/requirements.txt` (it sits next to\n",
"`app.py`, so it takes precedence) and launches your app at a public `β¦streamlit.app` URL.\n",
"\n",
"**Note:**\n",
"* Refer to the Model Deployment via Streamlit and GitHub guide to set up Streamlit Community Cloud deployment.\n",
"* Refer to the GitHub Account and Token Guide to create and configure your GitHub Personal Access Token (PAT)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fN8j9-3nW8G9"
},
"source": [
"<font size=6 color=\"navyblue\">Power Ahead!</font>\n",
"___"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} |