{
  "source_file": "0930",
  "source_platform": "Hashnode",
  "author": "Wesley Kambale",
  "title_listed": "PCOS Detection Using Machine Learning",
  "keywords": "",
  "domain": "图像处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://kambale.dev/pcos-detection-using-ml",
  "publish_date": "2023-06-08",
  "corpus_stage": "",
  "notes": "",
  "id": "f15d70e5327c",
  "collected_at": "2026-10-02T14:11:34",
  "title": "PCOS Detection Using Machine Learning",
  "body_markdown": "PCOS Detection Using Machine Learning\nBuilding a Polycystic Ovary Syndrome (PCOS) detection model \nusing Machine Learning\nUpdated\nJuly 18, 2023\n•\n6\nmin read\n•\nView as Markdown\nW\nWesley Kambale\nI'm a Machine Learning Engineer passionate about building production-ready ML systems for the African market.\nWith experience in TensorFlow, Keras, and Python-based workflows, I help teams bridge the gap between machine learning research and real-world deployment—especially on resource-constrained devices.\nI'm also a Google Developer Expert in AI. I regularly speak at tech conferences including PyCon Africa, DevFest Kampala, DevFest Nairobi and more and also write technical articles on AI/ML here.\nPart of series\nMachine Learning\nIntroduction\nPolycystic Ovary Syndrome (PCOS) is a common hormonal disorder that affects many women of reproductive age. It is characterized by the presence of multiple cysts in the ovaries, irregular menstrual cycles, and symptoms such as excessive hair growth, acne, and weight gain.\nEarly detection of PCOS is crucial for effective management and treatment of the condition. Machine Learning (ML) techniques can be utilized to build predictive models that can aid in the detection and diagnosis of PCOS. In this article, we will explore the process of PCOS detection using ML and provide code snippets for implementation.\nUnderstanding PCOS Detection\nPCOS detection involves analyzing various factors such as medical history, symptoms, physical examinations, and laboratory tests. ML algorithms can learn patterns and relationships within these factors to predict the likelihood of PCOS. We will use Python and the scikit-learn library, which provides a wide range of ML algorithms and utilities.\nImport the Required Libraries\nWe will need to import essential libraries like Pandas, scikit-learn, and Seaborn, NumPy for numerical computations, and Matplotlib for visualizing the results. Create a new Python script, and import the necessary libraries as shown below:\nimport\npandas\nas\npd\nimport\nnumpy\nas\nnp\nimport\nmatplotlib.pyplot\nas\nplt\n%matplotlib inline\nimport\nseaborn\nas\nsns\nfrom\nsklearn.model_selection\nimport\ntrain_test_split\nfrom\nsklearn.preprocessing\nimport\nStandardScaler\nfrom\nsklearn.ensemble\nimport\nRandomForestClassifier\nfrom\nsklearn.svm\nimport\nSVC\nfrom\nsklearn.metrics\nimport\naccuracy_score, precision_score, recall_score, f1_score\nData Collection\nGather a dataset that includes relevant features and labels. The features can include medical history, symptoms, hormone levels, and other related variables, while the labels indicate whether an individual has been diagnosed with PCOS or not.\nBelow is the dataset that we are going to use in this article:\nLoad the dataset in a Google Colab or Jupyter Notebook environment\n# Load the dataset\npcosData = pd.read_csv(\n'pcos_dataset.csv'\n)\nData Preprocessing\nClean the dataset by handling missing values, normalizing numerical features, and encoding categorical variables.\n# Check for the sum of null values in each column\npcosData.isnull().sum()\nYou will realize that\nMarriage Status\nand\nFast Food\nboth have a null value that need to be cleaned (dropped).\n# Drop all the null values in the dataset\npcosData = pcosData.dropna()\n# Check again for the sum of null values in each column\npcosData.isnull().sum()\nDepending on the dataset that you have, sometimes the data type of the data collected could be\nobject\ninstead of\nint64\nor\nfloat64\n. It is our duty to typecast the data to the right data type for numerical computation and manipulation. The code snippet ensures that we cast the data to numerical values.\nfor\ncolumn\nin\npcosData:\n    columnSeriesObj = pcosData[column]\n    pcosData[column] = pd.to_numeric(pcosData[column], errors=\n'coerce'\n)\nWe can now visualize our data using Seaborn's\npairplot\nfunction. The pairplot function creates a grid of scatterplots and histograms to visualize the pairwise relationships between multiple variables in a dataset. It provides a quick way to explore the correlation and distribution of variables.\nIn our case, we are going to visualize the pairwise relationship between the\nAge\n,\nWeight\n,\nHeight\nand\nBMI\nof the patients to find any correlation between these features.\nsns.pairplot(pcosData.iloc[:,\n1\n:\n5\n])\nTo get more insights into the data we are looking at, we shall plot histograms showing the distribution of\nAge\n,\nWeight\nand\nMarital Status\namong the patients.\ndef\nplot_hist\n(\nvariable\n):\nplt.figure(figsize = (\n9\n,\n3\n))\n    plt.hist(pcosData[variable], bins =\n50\n)\n    plt.xlabel(variable)\n    plt.ylabel(\n\"Frequency\"\n)\n    plt.title(\n\"{} distribution with hist\"\n.format(variable))\n    plt.show()\n\nnumericVar = [\n\" Age (yrs)\"\n,\n\"Weight (Kg)\"\n,\n\"Marraige Status (Yrs)\"\n]\nfor\nn\nin\nnumericVar:\n    plot_hist(n)\nLastly, we shall plot a correlation graph between the features in that dataset. This is important when choosing which features to use when predicting PCOS in patients. As an ML engineer, you need to choose optimal features that will give you the best accuracy in prediction, not just 99%.\ncorr_matrix = pcosData.corr()\nplt.subplots(figsize=(\n30\n,\n10\n))\nsns.heatmap(corr_matrix, annot =\nTrue\n, fmt =\n\".2f\"\n);\nplt.title(\n\"Correlation Between Features\"\n)\nplt.show()\nSplit the dataset into features and labels\nX\nand\nY\nand then split the dataset into training and testing sets.\n# Split the dataset into features and labels\nX = pcosData.iloc[:,\n1\n:\n41\n].values\ny = pcosData.iloc[:,\n0\n].values\n# Split the dataset into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size =\n0.3\n, random_state =\n42\n)\nFeature Selection\nAnalyze the dataset to identify the most informative features. This step helps improve model performance and reduces computational complexity. Techniques such as correlation analysis, feature importance ranking, and domain expertise can aid in feature selection.\n# Normalize the numerical features\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.fit_transform(X_test)\nModel Selection\nChoose an appropriate ML algorithm for PCOS detection. Commonly used algorithms include Logistic Regression, Support Vector Machines (SVM), Random Forest, and Gradient Boosting. Consider the characteristics of the dataset, such as the number of features and the size of the dataset, to make an informed choice. In our case, we are going to use Support Vector Machine (SVM) and Random Forest.\n# Create a Random Forest model\nrf_model = RandomForestClassifier()\n# Create an SVM model\nsvm_model = SVC()\nModel Training\nTrain the selected ML model using the training dataset. During training, the model learns the patterns and relationships between the features and labels. This step involves optimization techniques to find the best set of model parameters.\n# Train the Random Forest model\nrf_model.fit(X_train, y_train)\n# Train the SVM model\nsvm_model.fit(X_train, y_train)\nMake Predictions\nOnce the model is trained and evaluated, it can be used to make predictions on new, unseen data. The model takes in input features related to a specific individual and predicts the probability of that individual having PCOS.\n# Make predictions on the testing set with RF\nrf_pred = rf_model.predict(X_test)\n# Make predictions on the testing set with SVM\nsvm_pred = svm_model.predict(X_test)\nModel Evaluation\nEvaluate the trained model using the testing dataset. Performance metrics such as accuracy, precision, recall, and F1 score can be used to assess the model's performance. Adjust the model's hyperparameters if necessary to improve performance.\n# Evaluate the Random Forest model\nrf_accuracy = accuracy_score(y_test, rf_pred)\nrf_precision = precision_score(y_test, rf_pred)\nrf_recall = recall_score(y_test, rf_pred)\nrf_f1 = f1_score(y_test, rf_pred)\n\nprint(\n\"Random Forest Accuracy:\"\n, rf_accuracy)\nprint(\n\"Random Forest Precision:\"\n, rf_precision)\nprint(\n\"Random Forest Recall:\"\n, rf_recall)\nprint(\n\"Random Forest F1 Score:\"\n, rf_f1)\n# Evaluate the SVM model\nsvm_accuracy = accuracy_score(y_test, svm_pred)\nsvm_precision = precision_score(y_test, svm_pred)\nsvm_recall = recall_score(y_test, svm_pred)\nsvm_f1 = f1_score(y_test, svm_pred)\n\nprint(\n\"SVM Accuracy:\"\n, svm_accuracy)\nprint(\n\"SVM Precision:\"\n, svm_precision)\nprint(\n\"SVM Recall:\"\n, svm_recall)\nprint(\n\"SVM F1 Score:\"\n, svm_f1)\nModel Deployment\nAfter successfully training and evaluating the model, we can deploy it to make PCOS diagnoses on new, unseen data. This could involve integrating the model into a web application, mobile app, or any other suitable platform.\n# Save the trained RF model\nrf_model.save(\n'pcos_rf_model.h5'\n)\n# Save the trained SVM model\nsvm_model.save(\n'pcos_svm_model.h5'\n)\nConclusion\nMachine Learning techniques provide a valuable tool for the detection and diagnosis of Polycystic Ovary Syndrome (PCOS). By leveraging ML algorithms, we can analyze various factors and build predictive models that assist healthcare professionals in identifying PCOS in patients. This article outlined the step-by-step process of PCOS detection using ML and provided code snippets for data preprocessing, model training, and evaluation. Remember to adapt the code to your specific dataset and explore different ML algorithms to find the best approach for PCOS detection.\nResources\nAccess the code snippets in a Google Colab notebook\nhere\n(MIT License).\nAccess the dataset used in this article\nhere\n(MIT License).\nDon't request access\n,\nMake A Copy.\n#\nml\n#\nmachine-learning\n#\ndisease",
  "metadata": {
    "title": "PCOS Detection Using Machine Learning",
    "description": "Building a Polycystic Ovary Syndrome (PCOS) detection model using Machine Learning",
    "keywords": null,
    "author": null,
    "og:title": "PCOS Detection Using Machine Learning",
    "og:description": "Building a Polycystic Ovary Syndrome (PCOS) detection model using Machine Learning",
    "og:url": "https://kambale.dev/pcos-detection-using-ml",
    "og:site_name": "Wesley Kambale",
    "og:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1689701843231/4fe5ecea-59a1-41b0-be88-ff10d7895798.png",
    "og:image:width": "1200",
    "og:image:height": "630",
    "og:type": "article",
    "twitter:card": "summary_large_image",
    "twitter:creator": "https://twitter.com/WesKambale",
    "twitter:title": "PCOS Detection Using Machine Learning",
    "twitter:description": "Building a Polycystic Ovary Syndrome (PCOS) detection model using Machine Learning",
    "twitter:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1689701843231/4fe5ecea-59a1-41b0-be88-ff10d7895798.png",
    "article:published_time": "2023-06-08T15:39:55.765Z",
    "article:modified_time": "2023-07-18T17:37:54.942Z",
    "article:author": "https://kambale.dev/@kambale"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/f15d70e5327c/code/body-000.txt",
      "chars": 378,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-001.txt",
      "chars": 62,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-002.txt",
      "chars": 74,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-003.txt",
      "chars": 151,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-004.txt",
      "chars": 135,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-005.txt",
      "chars": 35,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-006.txt",
      "chars": 335,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-007.txt",
      "chars": 166,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-008.txt",
      "chars": 254,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-009.txt",
      "chars": 127,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-010.txt",
      "chars": 108,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-011.txt",
      "chars": 118,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-012.txt",
      "chars": 166,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-013.txt",
      "chars": 727,
      "language": "text"
    },
    {
      "file": "attachments/f15d70e5327c/code/body-014.txt",
      "chars": 128,
      "language": "text"
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1689701843231/4fe5ecea-59a1-41b0-be88-ff10d7895798.png",
      "bytes": 91769,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/000.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1689701843231/4fe5ecea-59a1-41b0-be88-ff10d7895798.png",
      "alt": "PCOS Detection Using Machine Learning",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686140239497/26e80cc1-ffb9-41a2-acaa-353844e53b0a.png",
      "bytes": 64595,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/002.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686140239497/26e80cc1-ffb9-41a2-acaa-353844e53b0a.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686147471095/5250cfb9-251c-4098-9ce1-e2c3e0690c13.png",
      "bytes": 42847,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/003.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686147471095/5250cfb9-251c-4098-9ce1-e2c3e0690c13.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686149526562/55fce1fd-cc25-4cd8-ac7e-eb181f6146cc.png",
      "bytes": 47121,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/004.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686149526562/55fce1fd-cc25-4cd8-ac7e-eb181f6146cc.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686150710470/a96e4011-f9f9-4c14-b228-4ef13c484a01.png",
      "bytes": 226644,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/005.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686150710470/a96e4011-f9f9-4c14-b228-4ef13c484a01.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686170530207/7f829c1c-20f6-45a4-b342-4ac1c4af9bf5.png",
      "bytes": 40025,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/006.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686170530207/7f829c1c-20f6-45a4-b342-4ac1c4af9bf5.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686151692419/3f18a2de-a979-4b8e-b0a3-641b55755f4a.png",
      "bytes": 777705,
      "reused": true,
      "local_path": "attachments/f15d70e5327c/images/007.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1686151692419/3f18a2de-a979-4b8e-b0a3-641b55755f4a.png",
      "alt": "",
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://kambale.dev/pcos-detection-using-ml.md",
      "label": "View as Markdown",
      "type": "a"
    },
    {
      "href": "https://hashnode.com/@kambale",
      "label": "W",
      "type": "a"
    },
    {
      "href": "https://twitter.com/WesKambale",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://linkedin.com/in/WesKambale",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://kambale.dev/series/ml-series",
      "label": "Part of series Machine Learning",
      "type": "a"
    },
    {
      "href": "https://colab.research.google.com/drive/1D78IygybTGZJ_MYxLDVZ2Yfv3cl_veKQ?usp=sharing",
      "label": "here",
      "type": "a"
    },
    {
      "href": "https://drive.google.com/drive/folders/1BVCpse-Dfa3uyBGCiYUVNjGTBtITvwXH?usp=sharing",
      "label": "here",
      "type": "a"
    },
    {
      "href": "https://kambale.dev/tag/ml",
      "label": "# ml",
      "type": "a"
    },
    {
      "href": "https://kambale.dev/tag/machine-learning",
      "label": "# machine-learning",
      "type": "a"
    },
    {
      "href": "https://kambale.dev/tag/disease",
      "label": "# disease",
      "type": "a"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:50:51Z",
  "source_url": "https://kambale.dev/pcos-detection-using-ml",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 9451,
  "expected_body_images": 7,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/f15d70e5327c/pages/source.html",
  "local_html": "attachments/f15d70e5327c/pages/article.html",
  "body_base_path": "attachments/f15d70e5327c/pages/",
  "body_markdown_path": "attachments/f15d70e5327c/pages/article.md"
}