{"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9345e46525cee5cbd20e5bcde2e4f38c93fd0e9b"},"cell_type":"code","source":"!pip install imutils","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from imutils import paths\nimport cv2\ndef image_to_feature_vector(image, size=(32, 32)):\n  return cv2.resize(image, size).flatten()\n\nimagePaths = list(paths.list_images('../input/train/train/'))\nprint(imagePaths[0])\nX_train = []\ny_train = []\nfor (i, imagePath) in enumerate(imagePaths):\n  image = cv2.imread(imagePath)\n  label = imagePath.split('/')[-1].split('.')[0]\n  pixels = image_to_feature_vector(image)\n  X_train.append(pixels)\n  y_train.append(label)\n  if(i>0 and i%1000==0):\n    print(\"[INFO] processed{}/{}\".format(i, len(imagePaths)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"04bf8137c37079034cbcd11c5c635037d936756e"},"cell_type":"code","source":"imagePaths = list(paths.list_images('../input/test1/test1/'))\nprint(imagePaths[0])\nX_test = []\nid_test = []\nfor (i, imagePath) in enumerate(imagePaths):\n  image = cv2.imread(imagePath)\n  idt = imagePath.split('/')[-1].split('.')[0]\n  pixels = image_to_feature_vector(image)\n  X_test.append(pixels)\n  id_test.append(idt)\n  if(i>0 and i%1000==0):\n    print(\"[INFO] processed{}/{}\".format(i, len(imagePaths)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7e562ebad23813084bfa56d630bf53a41e19eddb"},"cell_type":"code","source":"import numpy as np\nX_train = np.array(X_train)\ny_train = np.array(y_train)\nX_test = np.array(X_test)\n\nlabels = np.zeros((y_train.shape[0], 2))\nfor i in range(0, y_train.shape[0]):\n  label = np.zeros(2)\n  if(y_train[i]=='dog'):\n    label[1]=1.0\n  else:\n    label[0]=1.0\n  labels[i] = label\n\ny_train=labels\n\n# from sklearn.model_selection import train_test_split\n\n# X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"49fc3a8c071ec1c6f38a57dbc698b8e5c9b2e500"},"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nlearning_rate = 0.001\nnum_steps = 200\nbatch_size = 128\ndisplay_step = 10\n\n\nnum_input = 3072\nnum_classes = 2\ndropout = 0.75\n\nX = tf.placeholder(tf.float32, [None, num_input])\nY = tf.placeholder(tf.float32, [None, num_classes])\nkeep_prob = tf.placeholder(tf.float32)\n\ndef conv2d(x, W, b, strides=1):\n  x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n  x = tf.nn.bias_add(x, b)\n  return tf.nn.relu(x)\n\ndef maxpool2d(x, k=2):\n  return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')\ndef conv_net(x, weights, biases, dropout):\n  x = tf.reshape(x, shape=[-1, 32, 32, 3])\n  conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n  conv1 = maxpool2d(conv1, k=2)\n  \n  conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n  conv2 = maxpool2d(conv2, k=2)\n  \n  fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n  fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n  fc1 = tf.nn.dropout(fc1, dropout)\n  \n  out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n  return out\n\nweights = {\n    'wc1': tf.Variable(tf.random_normal([5, 5, 3, 32])),\n    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n    'wd1': tf.Variable(tf.random_normal([8*8*64, 1024])),\n    'out': tf.Variable(tf.random_normal([1024, num_classes]))\n}\nbiases = {\n     'bc1': tf.Variable(tf.random_normal([32])),\n    'bc2': tf.Variable(tf.random_normal([64])),\n    'bd1': tf.Variable(tf.random_normal([1024])),\n    'out': tf.Variable(tf.random_normal([num_classes]))\n}\n\nlogits = conv_net(X, weights, biases, keep_prob)\nprediction = tf.nn.softmax(logits)\n\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain_op = optimizer.minimize(loss_op)\n\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n  sess.run(init)\n  for step in range(1, 250+1):\n    batch_x = X_train[(step-1)*100:step*100]\n    batch_y = y_train[(step-1)*100:step*100]\n    sess.run(train_op, feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.8})\n    if step % display_step == 0 or step == 1:\n      loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y, keep_prob: 1.0})\n      print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n                  \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n                  \"{:.3f}\".format(acc))\n  print(\"Optimization Finished!\")\n  preds = sess.run(prediction, feed_dict={X:X_test, keep_prob:1.0})\n  submit = pd.DataFrame()\n  submit['id']=id_test\n  label = []\n  for i in range(0, preds.shape[0]):\n    for j in range(0, preds.shape[1]):\n      if(preds[i, j]==1):\n        label.append(j)\n  submit['label']= label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c306ea6294fedc00290e88a2331ca97957b7c7f3"},"cell_type":"code","source":"submit.to_csv('submit.csv', index=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"62fd0aee40933902967a5d74455c1728bd69402b"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}