Начнем с кода

Используется набор данных Стекло. Классификационный набор данных На основе содержания различных элементов, присутствующих в нем, решается, для какой цели следует использовать стекло

#Data Preprocessing Part
#Data Visualisation, Data Analysis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("glass.csv")
print("\nThe Number of Rows and Columns in Dataset : ",df.shape)
print(df)
print("\nThe Number of Rows in Dataset : ",df.shape[0])
#print(df)
#Displaying the Presence of Null Data using Heat Map
print("Heat Map to display the NULL values present in the Dataset\n")
sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis')
#sns.pairplot(df,hue='Type')
nameList = []
for i in df:
    nameList.append(i)
print("The Columns in dataset and their datatypes\n",df.dtypes)
print("\nThe Number of Rows in Dataset : ",df.shape[0])
#To check the Null Data Present in the Dataset
print("\nChecking the Presence of Null Data")
print(df.isnull())
#To Check total Number of Null Data Points in Each Columns
print("\nTotal Number of Null Data Values in Each Column \n",df.isnull().sum())

#To Check total Number of Null Data Points in Each Columns
print("\nTotal Number of Null Data Values in Each Column \n",df.isnull().sum())

#Removing all the Null values present in the Dataset
# making new data frame with dropped NA values
df = df.dropna(axis = 0, how ='any')
#Describing the dataset Statistical Analysis
df.describe()

#Showing the Number different types of Glass
sns.countplot(x='Type',data=df)

#Outlier Detection and removal from all the features
for i in df:
    factor = 3
    upper_lim = df[i].mean () + df[i].std () * factor
    lower_lim = df[i].mean () - df[i].std () * factor
    df = df[(df[i] < upper_lim) & (df[i] > lower_lim)]
    #print(df)
    plt.figure(figsize=(12, 7))
    sns.boxplot(x='Type',y=i,data=df,palette='winter')
print("\nThe Number of Rows in Dataset : ",df.shape[0])

Тип стекла: По номеру

1 зданиеwindowsfloatобработанный

2 зданияокнанеплавающиеобработанные

3 транспортное средствоокнапоплавокобработанный

4 автомобиляокнане плавучиеобработанные

5 контейнеров

6 посуда

7 фар

#To Check total Number of Null Data Points in Each Columns
typeList = df.Type.unique()
print("The Following are the Types of Glasses Present in the Dataset")
print(typeList)

Ниже приведены типы очков, представленные в наборе данных [1 2 3 5 6 7]

#***********This Logistic Regression is applied after Removing the Outliers ********************
#Performing Logistic Regression
df = new_df
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
#print(df)
X_train, X_test, y_train, y_test = train_test_split(df.drop('Type',axis=1), df['Type'], test_size=0.30,random_state=101)
logmodel = LogisticRegression()
logmodel.fit(X_train,y_train)
predictions = logmodel.predict(X_test)
print("\nThe Size of Test Dataset is : ",X_test.shape[0])
accuracy=confusion_matrix(y_test,predictions)
accuracy=confusion_matrix(y_test,predictions)
print("The Confusion Matrix is : \n", accuracy)
accuracy=accuracy_score(y_test,predictions)
print("The Accuracy of Prediction is : ",accuracy)
accuracy
print("\n\tThe F1 Score : ",f1_score(y_test, y_pred,average='micro'))

В заключение, для такого типа набора данных использование KNN лучше, чем использование логистической регрессии, поскольку размер набора данных невелик, поэтому его выполнение не займет много времени.