The Wayback Machine - https://web.archive.org/web/20240827045216/https://www.geeksforgeeks.org/ml-kaggle-breast-cancer-wisconsin-diagnosis-using-knn/
Open In App

ML | Kaggle Breast Cancer Wisconsin Diagnosis using KNN and Cross Validation

Last Updated : 22 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dataset :
It is given by Kaggle from UCI Machine Learning Repository, in one of its challenges. It is a dataset of Breast Cancer patients with Malignant and Benign tumor.
K-nearest neighbour algorithm is used to predict whether is patient is having cancer (Malignant tumour) or not (Benign tumour).

Implementation of KNN algorithm for classification.

Code : Importing Libraries




# performing linear algebra
import numpy as np 
  
# data processing
import pandas as pd
  
# visualisation
import matplotlib.pyplot as plt


Code : Loading dataset




df = pd.read_csv("..\\breast-cancer-wisconsin-data\\data.csv")
  
print (data.head)


Output :

Code: Data Info




df.info()


Output :

RangeIndex: 569 entries, 0 to 568
Data columns (total 33 columns):
id                         569 non-null int64
diagnosis                  569 non-null object
radius_mean                569 non-null float64
texture_mean               569 non-null float64
perimeter_mean             569 non-null float64
area_mean                  569 non-null float64
smoothness_mean            569 non-null float64
compactness_mean           569 non-null float64
concavity_mean             569 non-null float64
concave points_mean        569 non-null float64
symmetry_mean              569 non-null float64
fractal_dimension_mean     569 non-null float64
radius_se                  569 non-null float64
texture_se                 569 non-null float64
perimeter_se               569 non-null float64
area_se                    569 non-null float64
smoothness_se              569 non-null float64
compactness_se             569 non-null float64
concavity_se               569 non-null float64
concave points_se          569 non-null float64
symmetry_se                569 non-null float64
fractal_dimension_se       569 non-null float64
radius_worst               569 non-null float64
texture_worst              569 non-null float64
perimeter_worst            569 non-null float64
area_worst                 569 non-null float64
smoothness_worst           569 non-null float64
compactness_worst          569 non-null float64
concavity_worst            569 non-null float64
concave points_worst       569 non-null float64
symmetry_worst             569 non-null float64
fractal_dimension_worst    569 non-null float64
Unnamed: 32                0 non-null float64
dtypes: float64(31), int64(1), object(1)
memory usage: 146.8+ KB

Code: We are dropping columns – ‘id’ and ‘Unnamed: 32’ as they have no role in prediction




df.drop(['Unnamed: 32', 'id'], axis = 1)
print(df.shape)


Output:

(569, 31)

Code: Converting the diagnosis value of M and B to a numerical value where M (Malignant) = 1 and B (Benign) = 0




def diagnosis_value(diagnosis):
    if diagnosis == 'M':
        return 1
    else:
        return 0
  
df['diagnosis'] = df['diagnosis'].apply(diagnosis_value)


Code :




sns.lmplot(x = 'radius_mean', y = 'texture_mean', hue = 'diagnosis', data = df)


Output:


Code :




sns.lmplot(x ='smoothness_mean', y = 'compactness_mean', 
           data = df, hue = 'diagnosis')


Output:

Code : Input and Output data




X = np.array(df.iloc[:, 1:])
y = np.array(df['diagnosis'])


Code : Splitting data to training and testing




from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size = 0.33, random_state = 42)


Code : Using Sklearn




knn = KNeighborsClassifier(n_neighbors = 13)
knn.fit(X_train, y_train)


Output:

KNeighborsClassifier(algorithm='auto', leaf_size=30, 
             metric='minkowski', metric_params=None, 
             n_jobs=None, n_neighbors=13, p=2, 
             weights='uniform')

Code : Prediction Score




knn.score(X_test, y_test)


Output:

0.9627659574468085

Code : Performing Cross Validation




neighbors = []
cv_scores = []
  
from sklearn.model_selection import cross_val_score
# perform 10 fold cross validation
for k in range(1, 51, 2):
    neighbors.append(k)
    knn = KNeighborsClassifier(n_neighbors = k)
    scores = cross_val_score(
        knn, X_train, y_train, cv = 10, scoring = 'accuracy')
    cv_scores.append(scores.mean())


Code : Misclassification error versus k




MSE = [1-x for x in cv_scores]
  
# determining the best k
optimal_k = neighbors[MSE.index(min(MSE))]
print('The optimal number of neighbors is % d ' % optimal_k)
  
# plot misclassification error versus k
plt.figure(figsize = (10, 6))
plt.plot(neighbors, MSE)
plt.xlabel('Number of neighbors')
plt.ylabel('Misclassification Error')
plt.show()


Output:

The optimal number of neighbors is 13 



Previous Article
Next Article

Similar Reads

ML | Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression
Dataset:It is given by Kaggle from UCI Machine Learning Repository, in one of its challenge. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. Logistic Regression is used to predict whether the given patient is having Malignant or Benign tumor based on the attributes in the given dataset. Code : Loading Libraries C/C++ Code
5 min read
Breast Cancer Wisconsin (Diagnostic) Dataset
The Breast Cancer Wisconsin (Diagnostic) dataset is a renowned collection of data used extensively in machine learning and medical research. Originating from digitized images of fine needle aspirates (FNA) of breast masses, this dataset facilitates the analysis of cell nuclei characteristics to aid in the diagnosis of breast cancer. In this article
6 min read
Breast Cancer predictions using catboost
CatBoost is a gradient boosting algorithm that deals with the categorical features during the training process. In the article, we are going to perform prediction analysis on breast cancer dataset using CatBoost. Breast Cancer Detection using CatBoost We aim to provide a comprehensive pipeline for training a CatBoostClassifier model on the Breast C
7 min read
Leukaemia Cell Classification For Paediatric Cancer Diagnosis
In the world of children's cancer, especially leukaemia, our focus is on using the latest technology to help battle pediatric cancer. We are using deep learning techniques to build a model that will increase the precision with which medical professionals identify childhood leukaemia. Leukaemia Cell Classification For Paediatric Cancer DiagnosisWhat
11 min read
Healthcare Diagnosis in R
Healthcare diagnosis, the process of identifying diseases or conditions in individuals, plays a pivotal role in healthcare decision-making and patient management. With the advancement of technology and the availability of large healthcare datasets, data-driven approaches have become increasingly important in aiding healthcare professionals in makin
8 min read
Cross-Validation Using K-Fold With Scikit-Learn
Cross-validation involves repeatedly splitting data into training and testing sets to evaluate the performance of a machine-learning model. One of the most commonly used cross-validation techniques is K-Fold Cross-Validation. In this article, we will explore the implementation of K-Fold Cross-Validation using Scikit-Learn, a popular Python machine-
12 min read
Cross-validation and Hyperparameter tuning of LightGBM Model
In a variety of industries, including finance, healthcare, and marketing, machine learning models have become essential for resolving challenging real-world issues. Gradient boosting techniques have become incredibly popular among the myriad of machine learning algorithms due to their remarkable prediction performance. Due to its speed and effectiv
14 min read
CatBoost Cross-Validation and Hyperparameter Tuning
CatBoost is a powerful gradient-boosting algorithm of machine learning that is very popular for its effective capability to handle categorial features of both classification and regression tasks. To maximize the potential of CatBoost, it's essential to fine-tune its hyperparameters which can be done by Cross-validation. Cross-validation is a crucia
11 min read
What is the Difference Between Cross Validation and Train Validate Test?
Answer: Cross-validation involves partitioning a dataset into multiple subsets for training and validation, iteratively switching the validation set, while train-validate-test is a simpler approach with a single split into training and validation sets, leaving a separate test set for final model evaluation.Cross Validation:Cross-validation is a tec
2 min read
Mastering Generalized Cross-Validation (GCV): Theory, Applications, and Best Practices
Generalized Cross-Validation (GCV) is a statistical method used to estimate the prediction error of a model, particularly in the context of linear regression and regularization techniques like ridge regression. It is an extension of the traditional cross-validation method, designed to be rotation-invariant and computationally efficient. In this art
15 min read
Why an Increasing Validation Loss and Validation Accuracy Signifies Overfitting?
Answer: An increasing validation loss and accuracy plateau or decline in deep learning signify overfitting, where the model performs well on training data but fails to generalize to new, unseen data.An increasing validation loss and plateau or decline in validation accuracy indicate overfitting in a deep learning model. Overfitting occurs when a mo
2 min read
Stratified K Fold Cross Validation
In machine learning, When we want to train our ML model we split our entire dataset into training_set and test_set using train_test_split() class present in sklearn. Then we train our model on training_set and test our model on test_set. The problems that we are going to face in this method are: Whenever we change the random_state parameter present
4 min read
LOOCV (Leave One Out Cross-Validation) in R Programming
LOOCV(Leave One Out Cross-Validation) is a type of cross-validation approach in which each observation is considered as the validation set and the rest (N-1) observations are considered as the training set. In LOOCV, fitting of the model is done and predicting using one observation validation set. Furthermore, repeating this for N times for each ob
4 min read
Receiver Operating Characteristic (ROC) with Cross Validation in Scikit Learn
In this article, we will implement ROC with Cross-Validation in Scikit Learn. Before we jump into the code, let's first understand why we need ROC curve and Cross-Validation in Machine Learning model predictions. Receiver Operating Characteristic Curve (ROC Curve) To understand the ROC curve one must be familiar with terminologies such as True Posi
3 min read
Recursive Feature Elimination with Cross-Validation in Scikit Learn
In this article, we will earn how to implement recursive feature elimination with cross-validation using scikit learn package in Python. What is Recursive Feature Elimination (RFE)? Recursive Feature Elimination (RFE) is a feature selection algorithm that is used to select a subset of the most relevant features from a dataset. It is a recursive pro
5 min read
Cross-validation on Digits Dataset in Scikit-learn
In this article, we will discuss cross-validation and its use on digit datasets. Further, we will see the code implementation using a digits dataset. What is Cross-Validation?Cross Validation on the Digits Dataset will allow us to choose the best parameters avoiding overfitting over the training dataset. It is a procedure of experimentation of hit
5 min read
Time Series Cross-Validation
In this article, we delve into the concept of Time Series Cross-Validation (TSCV), a powerful technique for robust model evaluation in time series analysis. We'll explore its significance, implementation, and best practices, along with providing insightful code examples for clarity. What is Cross Validation?Cross-validation is a crucial technique i
4 min read
How to Choose a Classifier After Cross-Validation?
Answer: After cross-validation, choose the classifier with the highest average performance metric (e.g., accuracy, precision, recall) on the validation folds.After conducting cross-validation, which involves splitting the dataset into multiple subsets, training the classifier on a portion of the data, and evaluating its performance on the remaining
2 min read
Cross Validation on a Dataset with Factors in R
Cross-validation is a widely used technique in machine learning and statistical modeling to assess how well a model generalizes to new data. When working with datasets containing factors (categorical variables), it's essential to handle them appropriately during cross-validation to ensure unbiased performance estimation. In this article, we'll expl
4 min read
How to Deal with Factors with Rare Levels in Cross-Validation in R
Cross-validation is a vital technique for evaluating model performance in machine learning. However, traditional cross-validation approaches may lead to biased or unreliable results when dealing with factors (categorical variables) that contain rare levels. In this guide, we'll explore strategies for effectively dealing with factors with rare level
4 min read
Cross-Validation vs. Bootstrapping
When developing machine learning models, it's crucial to assess their performance accurately. Cross-validation and bootstrapping are two fundamental techniques used for this purpose. They help estimate how well a model will generalize to an independent dataset, thereby guiding decisions on model selection and parameter tuning. Although both methods
7 min read
SVM with Cross Validation in R
Support Vector Machine (SVM) is a powerful and versatile machine learning model used for classification and regression tasks. In this article, we'll go through the steps to implement an SVM with cross-validation in R using the caret package. Cross Validation in RCross-validation involves splitting the data into multiple parts (folds), training the
4 min read
Cross Validation function for logistic regression in R
Cross-validation is a technique for assessing the performance of a machine-learning model. It helps in understanding how the model generalizes to an independent dataset, thereby ensuring that the model is neither overfitted nor underfitted. This article will guide you through creating a cross-validation function for logistic regression in R, a comm
3 min read
How to interpret cross validation output from cv.kknn (kknn package)
Cross-validation is a resampling procedure used to evaluate machine learning models on a limited data sample. The most common type is k-fold cross-validation, where the dataset is divided into k subsets (folds). The model is trained on k-1 of these folds and validated on the remaining one. This process is repeated k times, with each fold being used
3 min read
How to perform 10 fold cross validation with LibSVM in R?
Support Vector Machines (SVM) are a powerful tool for classification and regression tasks. LibSVM is a widely used library that implements SVM, and it can be accessed in R with the e1071 package. Cross-validation, particularly 10-fold cross-validation, is an essential technique for assessing the performance and generalizability of a model. This art
5 min read
Cross Validation in Machine Learning
In machine learning, we couldn't fit the model on the training data and can't say that the model will work accurately for the real data. For this, we must assure that our model got the correct patterns from the data, and it is not getting up too much noise. For this purpose, we use the cross-validation technique. In this article, we'll delve into t
8 min read
Creating Custom Cross-Validation Generators in Scikit-learn
Cross-validation is a fundamental technique in machine learning used to assess the performance and generalizability of models. Scikit-learn, a popular Python library, provides several built-in cross-validation methods, such as K-Fold, Stratified K-Fold, and Time Series Split. However, there are scenarios where these standard methods may not be suff
6 min read
ML | Cancer cell classification using Scikit-learn
Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let's classify cancer cells based on their features, and identifying them if they are 'malignant' or 'benign'. We will be using
10 min read
Lung Cancer Detection using Convolutional Neural Network (CNN)
Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify normal lung tissues from c
8 min read
Skin Cancer Detection using TensorFlow
In this article, we will learn how to implement a Skin Cancer Detection model using Tensorflow. We will use a dataset that contains images for the two categories that are malignant or benign. We will use the transfer learning technique to achieve better results in less amount of training. We will use EfficientNet architecture as the backbone of our
5 min read