{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\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 20GB 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":"# **Preprocessing Data**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",'r') as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"> **Load library**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport skimage.io as io\nimport random\nfrom skimage.transform import resize\nfrom tqdm import tqdm\nimport pandas as pd\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = '/kaggle/working/train/'\nf_l = os.listdir(path)\nlen(f_l)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Sampling due to cpu overload"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = random.sample(f_l, int(len(f_l)/10))\nsample_image = random.choice(sample)\nimage = io.imread(path + sample_image)\n%matplotlib notebook\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"> **Image resize & Cats and Dogs file classification**"},{"metadata":{"trusted":true},"cell_type":"code","source":"target = []\nimg_l = []\nfor file in tqdm(sample):\n    img = io.imread(path+file)\n    img = resize(img, (150, 150, 3))\n    img_l.append(img)\n    \n    if 'cat' in file:\n        target.append(1)\n    elif 'dog' in file:\n        target.append(0)\n        \ndf_image=pd.DataFrame(\n    {\"filename\":sample,\n    \"target\":target}\n)\ntarget = pd.Series(target)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib notebook\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib notebook\ndf_image['target'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Data Dimension Reduction**"},{"metadata":{"trusted":true},"cell_type":"code","source":"retrain = []\nfor i in range(len(img_l)):\n    retrain.append(img_l[i].reshape(150*150*3))\npixel = []\nfor i in range(150*150*3):\n    pixel.append('pixel_{}'.format(i))\ndf = pd.DataFrame(retrain, columns=pixel)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Modeling & Scoring**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\nimport numpy as np\n\nk_fold = KFold(n_splits=5, shuffle = True, random_state = 45)\n\nscores = np.zeros(5)\nfor i, (tr_idx, te_idx) in enumerate(k_fold.split(df)):\n    X_train, y_train = df.iloc[tr_idx], target.iloc[tr_idx]\n    x_test, y_test = df.iloc[te_idx], target.iloc[te_idx]\n    \n    clf = RandomForestClassifier()\n    clf.fit(X_train, y_train)\n    predict = clf.predict(x_test)\n    score = accuracy_score(y_test, predict)\n    print(score)\n    scores[i] = score\n\nprint(round(np.mean(score)*100, 2))","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}