{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is an academic exercise. The purpose of this notebook is check how LogisticRegression performs when it comes to image classification.\n\nAny advice is extremely welcome.","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport zipfile\nimport cv2\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\n\ntraining_images_folder = '/train/train'\ntest_images_folder = '/test/test1'\n\nimage_size = 32\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as train_zip:\n    train_zip.extractall('/train')\n    \nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as test_zip:\n    test_zip.extractall('/test')\n\nprint('Files extracted')\nprint(\"Training files:\",len(os.listdir(training_images_folder)))\nprint(\"Test files:\",len(os.listdir(test_images_folder)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Read categories to get the y array\ntrain_files = os.listdir(training_images_folder)\ncategories = []\nfor img in train_files: \n    categories.append(img.split('.')[0])\ny = np.array(categories)\nprint(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_image_arr(path):\n        img = cv2.imread(path, cv2.COLOR_BGR2GRAY) \n        img = cv2.resize(img, (image_size, image_size)).reshape(1,-1)\n        return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_features_count(path):\n        img = cv2.imread(path, cv2.COLOR_BGR2GRAY) \n        img = cv2.resize(img, (image_size, image_size)).reshape(-1,1)\n        return len(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features_count = get_features_count(training_images_folder + '/' + train_files[0])\nprint('Features count: ',features_count)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create the X array\nX = np.ones((1,features_count), int)\nadvance = 0\n\nfor x in train_files:\n    X = np.append(X,get_image_arr(training_images_folder + '/' + x),axis = 0)\n\nprint('X traing array generated',X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = np.delete(X, (0), axis=0)\n\nprint('X shape:',X.shape)\nprint('y shape:',y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n\nprint('X Train shape:',X_train.shape)\nprint('X Test shape:',X_test.shape)\nprint('Y Train shape:',y_train.shape)\nprint('Y Test shape:',y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Scale data\ntrain_scaler = preprocessing.RobustScaler().fit(X_train)\nx_scaled = train_scaler.transform(X_train)\n\ntest_scaler = preprocessing.RobustScaler().fit(X_test)\ntest_scaled = test_scaler.transform(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_model = LogisticRegression(max_iter=2000)\nimages_model.fit(x_scaled, y_train)\n\ny_prima = images_model.predict(test_scaled)\nprint(y_prima)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Statistics \nprint(classification_report(y_test, y_prima))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Accuracy\naccuracy_score(y_test, y_prima)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#confusion matrix\ndisp = plot_confusion_matrix(images_model, X_train, y_train,\n                             cmap=plt.cm.Blues,\n                             normalize=None)\nplt.show()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}