# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/Pratik180198/Breast_Cancer-Prediction/blob/main/Breast_Cancer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="oMBbtAcQcJ-C"
import pandas as pd
import numpy as np
from sklearn import datasets

# + colab={"base_uri": "https://localhost:8080/"} id="lZbI5I9dckGQ" outputId="8215ca05-5d91-49c3-c861-985fff1f2a41"
cancer_dataset=datasets.load_breast_cancer()
print(cancer_dataset)

# + colab={"base_uri": "https://localhost:8080/", "height": 258} id="WaBiBiXWdPUA" outputId="b1a6f0a2-f1cd-4340-bdef-aa65fc2f56bb"
#Load the dataset in pandas Dataframe
cancer_df=pd.DataFrame(cancer_dataset.data,columns=cancer_dataset.feature_names)
cancer_df.head()

# + colab={"base_uri": "https://localhost:8080/", "height": 258} id="SpijK_v2eC7R" outputId="fb27cde1-bd27-43ac-d107-2bd4a9c54021"
#Adding the target variable as class which is 'malignant', 'benign'
cancer_df['class']=cancer_dataset.target
cancer_df.head()

# + colab={"base_uri": "https://localhost:8080/"} id="WEz4AhO8ecSC" outputId="13955f22-3866-41f7-ed27-e7eea1a8d755"
cancer_df.shape

# + colab={"base_uri": "https://localhost:8080/"} id="VVFkiwbWehx7" outputId="b49c1af2-399e-42c0-9d3a-0e8eb5b23753"
#checking null values
cancer_df.isnull().sum()

# + colab={"base_uri": "https://localhost:8080/", "height": 351} id="q3-OefOvnvqg" outputId="65a8da80-0cad-481d-e702-e24191ff08ed"
cancer_df.describe()

# + colab={"base_uri": "https://localhost:8080/"} id="vvLJkPtqoBSW" outputId="450883e4-0f25-4891-c351-34178df4f57e"
cancer_df['class'].value_counts()

# + colab={"base_uri": "https://localhost:8080/", "height": 196} id="ZOUlnx1tn4Ow" outputId="06765b8d-44ff-4a46-e0a6-bde154ffb267"
cancer_df.groupby('class').mean()

# + [markdown] id="JrDoqYenqLPs"
# **0** = **Malignant**
# **1** = **Benign**

# + id="iRZ5JkfiqcLG"
X=cancer_df.iloc[:,:-1]
y=cancer_df.iloc[:,-1]

# + id="j87uSTQUrqrj"
# doing train-test split for training our data model

# + id="o4Tb6TLyr3L1"
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,stratify=y,random_state=42)

# + [markdown] id="uWfpPqzqtkWg"
# Here we are using 90% of data to trained the model and 10% of data to test the model. Stratify is used for having equal amount of ratio present in both for training and testing in which having equal amount of data in training will provide to make the model as generalize. Random state is used for having same number of random values when you run again the code.

# + colab={"base_uri": "https://localhost:8080/"} id="ZG5mE36qsdhx" outputId="7897bf2f-058c-4e33-e97c-58ee0ba9d0d1"
print(X_train.shape,X_test.shape)

# + colab={"base_uri": "https://localhost:8080/"} id="UyZYLJ3lszZU" outputId="b81d5851-dae3-4b01-9d41-1043e1ef6124"
print(y_train.mean(),y_test.mean())

# + id="aiPAEdfKzz5-"
# performing Standardization
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
X_train_scaler=scaler.fit_transform(X_train)
X_test_scaler=scaler.transform(X_test)

# + id="tfX8AtpzvE0S"
# Using Logistic Regression
from sklearn.linear_model import LogisticRegression
Logistic_classifier=LogisticRegression()

# + colab={"base_uri": "https://localhost:8080/"} id="qyYBd6ETzRwQ" outputId="d6b3cee6-3581-46eb-b611-8360098344ad"
# fit the model on training data
Logistic_classifier.fit(X_train_scaler,y_train)

# + colab={"base_uri": "https://localhost:8080/"} id="bSh08-Cm0zgk" outputId="15b74e94-ee08-4355-ddea-98aed2808ad5"
# Evaluatin the model on train and test data
predictions_training = Logistic_classifier.predict(X_train_scaler)

from sklearn.metrics import accuracy_score
accuracy_training = accuracy_score(y_train,predictions_training)
print('Accuracy on Training dataset: ',accuracy_training)

predictions_testing = Logistic_classifier.predict(X_test_scaler)
accuracy_testing = accuracy_score(y_test,predictions_testing)
print('Accuracy on Testing dataset: ',accuracy_testing)


# + colab={"base_uri": "https://localhost:8080/"} id="NRUoYNia24hX" outputId="30d10115-65d5-4384-b80c-bb42833ee432"
# showing the confusion metrics and classification report
from sklearn.metrics import confusion_matrix, classification_report
confusion_mat=confusion_matrix(y_test,predictions_testing)
classification_rep=classification_report(y_test,predictions_testing)
print(confusion_mat)
print(classification_rep)

# + id="I3ZBUjnO2paD"
# Using KNN
from sklearn.neighbors import KNeighborsClassifier
knn=KNeighborsClassifier(n_neighbors=5)

# + colab={"base_uri": "https://localhost:8080/"} id="lbFH1QkN4e0B" outputId="e6626936-d921-4705-f0f7-67e9ba78205c"
# fit the model using KNN
knn.fit(X_train_scaler,y_train)

# + colab={"base_uri": "https://localhost:8080/"} id="paC6xhiK4vx7" outputId="dc5cd35e-34ac-467f-b065-299eb8c31c6a"
# Evaluatin the model on train and test data
predictions_training_knn = knn.predict(X_train_scaler)

accuracy_training_knn = accuracy_score(y_train,predictions_training_knn)
print('Accuracy on Training dataset: ',accuracy_training_knn)

predictions_testing_knn = knn.predict(X_test_scaler)
accuracy_testing_knn = accuracy_score(y_test,predictions_testing_knn)
print('Accuracy on Testing dataset: ',accuracy_testing_knn)

# + colab={"base_uri": "https://localhost:8080/"} id="9dwSEsejWAno" outputId="eb7e7ff2-f83a-4b6f-b132-ce1ec03010f6"
# showing the confusion metrics and classification report
from sklearn.metrics import confusion_matrix, classification_report
confusion_mat=confusion_matrix(y_test,predictions_testing_knn)
classification_rep=classification_report(y_test,predictions_testing_knn)
print(confusion_mat)
print(classification_rep)

# + colab={"base_uri": "https://localhost:8080/", "height": 421} id="obtAcnJ__0Eu" outputId="888097b0-d1b7-4809-fc20-139eb834bb08"
# to select the k value
import matplotlib.pyplot as plt
error_rate = []

# Will take some time
for i in range(1,40):
    knn = KNeighborsClassifier(n_neighbors=i)
    knn.fit(X_train_scaler,y_train)
    pred_i = knn.predict(X_test_scaler)
    error_rate.append(np.mean(pred_i != y_test))

plt.figure(figsize=(10,6))
plt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', marker='o',
         markerfacecolor='red', markersize=10)
plt.title('Error Rate vs. K Value')
plt.xlabel('K')
plt.ylabel('Error Rate')

# + id="jDZjCBqg5SQT"
# using SVM
from sklearn.svm import SVC
support_vector_classifier=SVC()

# + colab={"base_uri": "https://localhost:8080/"} id="PnBvw1gS5pIz" outputId="e526a106-5a8b-411a-b380-f1a286b94a75"
# fit the model using svc
support_vector_classifier.fit(X_train_scaler,y_train)

# + colab={"base_uri": "https://localhost:8080/"} id="MoDlYK_i5y99" outputId="b472b9ec-e9e1-4a17-a351-7f9c9676ddf7"
# Evaluatin the model on train and test data
predictions_training_svc = support_vector_classifier.predict(X_train_scaler)

accuracy_training_svc = accuracy_score(y_train,predictions_training_svc)
print('Accuracy on Training dataset: ',accuracy_training_svc)

predictions_testing_svc = support_vector_classifier.predict(X_test_scaler)
accuracy_testing_svc = accuracy_score(y_test,predictions_testing_svc)
print('Accuracy on Testing dataset: ',accuracy_testing_svc)

# + colab={"base_uri": "https://localhost:8080/"} id="qEPGowS4Wx6q" outputId="cafe48db-1bfc-4a1e-a2cc-b73963971bc0"
# showing the confusion metrics and classification report
from sklearn.metrics import confusion_matrix, classification_report
confusion_mat=confusion_matrix(y_test,predictions_testing_svc)
classification_rep=classification_report(y_test,predictions_testing_svc)
print(confusion_mat)
print(classification_rep)

# + colab={"base_uri": "https://localhost:8080/", "height": 483} id="rGDixEcpFWqq" outputId="d1deddbd-4191-4321-f784-34c4b71b15cc"
plt.figure(figsize=(10,8))

x = np.asarray(['Logistic','KNN','SVM'])
y = np.asarray([accuracy_testing,accuracy_testing_knn,accuracy_testing_svc])
plt.bar(x,y,edgecolor='black',color='white')
plt.show()

# + [markdown] id="TSi1gKvZN6cH"
# As we can see SVC works well in all 3 models we had used.

# + colab={"base_uri": "https://localhost:8080/"} id="XqASjnC4OGcW" outputId="cbc04319-d3e8-4e65-e568-2cd9979c4c65"
# Predicting on new dataset

input_values=[17.99,10.38,122.8,1001,0.1184,0.2776,0.3001,0.1471,0.2419,0.07871,1.095,0.9053,8.589,153.4,0.006399,0.04904,0.05373,0.01587,0.03003,0.006193,25.38,17.33,184.6,2019,0.1622,0.6656,0.7119,0.2654,0.4601,0.1189]
input=np.asarray(input_values)
reshape=input.reshape(1,-1)

pred=support_vector_classifier.predict(reshape)[0]
if pred == 0 :
  print('Malignant')
else:
  print("Benign")


StarcoderdataJupyterScriptsDedupFiltered