Skip to content

Instantly share code, notes, and snippets.

@amir-rahnama
Last active November 30, 2018 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amir-rahnama/b1d6583c25d5c0cf6003161fb2a3b97d to your computer and use it in GitHub Desktop.
Save amir-rahnama/b1d6583c25d5c0cf6003161fb2a3b97d to your computer and use it in GitHub Desktop.
An implementation of KNN based on Numpy and Pandas
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from __future__ import division"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"X_train = pd.read_csv('./glass_train.txt')\n",
"X_test = pd.read_csv('./glass_test.txt')\n",
"\n",
"y_train = X_train['CLASS']\n",
"X_train = X_train.drop(['CLASS', 'ID'], axis=1)\n",
"\n",
"y_test = X_test['CLASS']\n",
"X_test = X_test.drop(['CLASS', 'ID'], axis=1)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"x_train_mean = X_train.mean()\n",
"x_train_std = X_train.std()\n",
"\n",
"x_train_max = X_train.max()\n",
"x_train_min = X_train.min()\n",
"\n",
"# X_train = (X_train - x_train_mean) / (x_train_mean - x_train_std)\n",
"# X_test = (X_test - x_train_mean) / (x_train_mean - x_train_std)\n",
"\n",
"X_train = (X_train - x_train_min) / (x_train_max - x_train_min)\n",
"X_test = (X_test - x_train_min) / (x_train_max - x_train_min)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"y_train = pd.get_dummies(y_train).astype(int)\n",
"y_test = pd.get_dummies(y_test).astype(int)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"k = 1"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"from collections import Counter\n",
"\n",
"def predict(data, labels, t_instance, k=5):\n",
" dist = np.sqrt(np.sum(np.power(t_instance.values - data.values, 2), axis=1))\n",
" \n",
" top_k = np.argsort(dist)[:k]\n",
" top_classes = labels.iloc[top_k]\n",
" \n",
" unique, count = np.unique(top_classes.values, return_counts=True, axis=0)\n",
" inde = np.argmax(count)\n",
" \n",
" return unique[inde]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"predictions = np.zeros((107, 6), dtype=int)\n",
"data = X_train.copy()\n",
"labels = y_train.copy()\n",
"last = data.shape[0]\n",
"\n",
"for index, row in X_test.iterrows():\n",
" predicted_class = predict(data, labels, row, k)\n",
" predictions[index, :] = predicted_class"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"result = (predictions == y_test.values).all(axis=1)\n",
"correct = result[result == True]\n",
"incorrect = result[result == False]\n",
"accuracy = len(correct)/len(result)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.7476635514018691"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Sklearn's implementation"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.neighbors import KNeighborsClassifier\n",
"from sklearn.metrics import accuracy_score\n",
"\n",
"neigh = KNeighborsClassifier(n_neighbors=k)\n",
"\n",
"neigh.fit(X_train, y_train)\n",
"\n",
"pred_sklearn = neigh.predict(X_test)\n",
"score = accuracy_score(y_test, pred_sklearn)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.7476635514018691"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"score"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python (tf)",
"language": "python",
"name": "tf"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment