Skip to content

Instantly share code, notes, and snippets.

@rjpower
Last active July 6, 2016 20:47
Show Gist options
  • Select an option

  • Save rjpower/7fac36d6f892438e62de4533b5bfef25 to your computer and use it in GitHub Desktop.

Select an option

Save rjpower/7fac36d6f892438e62de4533b5bfef25 to your computer and use it in GitHub Desktop.
fizzbuzz w/ maxout dense
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"import keras\n",
"from keras.layers import Dense, MaxoutDense\n",
"from keras.models import Sequential\n",
"from keras.utils import np_utils\n",
"from __future__ import print_function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"N = 10000\n",
"\n",
"def _encode(num):\n",
" digits = [np_utils.to_categorical(c, 10) for c in '%04d' % num]\n",
" return np.hstack(digits)[0]\n",
" \n",
"\n",
"def _fizzdata():\n",
" while True:\n",
" batch_x = []\n",
" batch_y = []\n",
"\n",
" idx = np.arange(N)\n",
" np.random.shuffle(idx)\n",
" for i in idx:\n",
" batch_x.append(_encode(i))\n",
" if i % 15 == 0: batch_y.append(np.asarray([0, 0, 0, 1]))\n",
" elif i % 5 == 0: batch_y.append(np.asarray([0, 0, 1, 0]))\n",
" elif i % 3 == 0: batch_y.append(np.asarray([0, 1, 0, 0]))\n",
" else: batch_y.append(np.asarray([1, 0, 0, 0]))\n",
"\n",
" if len(batch_x) >= 32:\n",
" yield np.asarray(batch_x), np.asarray(batch_y)\n",
" batch_x = []\n",
" batch_y = []\n",
"\n",
" yield np.asarray(batch_x), np.asarray(batch_y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"scrolled": false
},
"outputs": [],
"source": [
"def model():\n",
" m = Sequential()\n",
" m.add(MaxoutDense(20, input_shape=(40,)))\n",
" m.add(Dense(4, activation='softmax'))\n",
" m.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n",
" return m\n",
"\n",
"training_model = model()\n",
"training_model.summary()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for i in range(500):\n",
" training_model.fit_generator(_fizzdata(), samples_per_epoch=N, verbose=1 if i % 10 == 0 else 5, nb_epoch=1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment