Skip to content

Instantly share code, notes, and snippets.

@kanedo
Created March 7, 2018 15:04
Show Gist options
  • Save kanedo/00f96bd3f9ac52746d7d7014f561e8ce to your computer and use it in GitHub Desktop.
Save kanedo/00f96bd3f9ac52746d7d7014f561e8ce to your computer and use it in GitHub Desktop.
use mxnet.nd.gather_nd to create matrix for fertility bias (Cohn et al, 2016)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 470,
"metadata": {},
"outputs": [],
"source": [
"import mxnet as mx\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 471,
"metadata": {},
"outputs": [],
"source": [
"k=1\n",
"n=4"
]
},
{
"cell_type": "code",
"execution_count": 472,
"metadata": {},
"outputs": [],
"source": [
"def create_indices(k, n):\n",
" index_center = mx.nd.zeros((2*k+1, n))\n",
" zeros = mx.nd.zeros((n, 2*k+1))\n",
" for i in range(0,2*k+1):\n",
" value = np.arange(i, i+n)\n",
" index_center[i][:] = value[:]\n",
" index_center= index_center.transpose()\n",
" return mx.nd.stack(zeros, index_center, zeros)"
]
},
{
"cell_type": "code",
"execution_count": 473,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 4, 1)"
]
},
"execution_count": 473,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"attention = mx.ndarray.array([[[1], [2], [3], [4]],[[5], [6], [7], [8]]])\n",
"attention.shape"
]
},
{
"cell_type": "code",
"execution_count": 474,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\n",
"[[[0.]\n",
" [1.]\n",
" [2.]\n",
" [3.]\n",
" [4.]\n",
" [0.]]\n",
"\n",
" [[0.]\n",
" [5.]\n",
" [6.]\n",
" [7.]\n",
" [8.]\n",
" [0.]]]\n",
"<NDArray 2x6x1 @cpu(0)>"
]
},
"execution_count": 474,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# mxnet's padding only works for 4- and 5-dimensional data\n",
"attention_padded = np.pad(attention.asnumpy(), [(0,0), (k,k), (0,0)], \"constant\")\n",
"attention_padded = mx.nd.array(attention_padded)\n",
"attention_padded "
]
},
{
"cell_type": "code",
"execution_count": 475,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\n",
"[[0. 1. 2.]\n",
" [1. 2. 3.]\n",
" [2. 3. 4.]\n",
" [3. 4. 0.]]\n",
"<NDArray 4x3 @cpu(0)>"
]
},
"execution_count": 475,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mx.ndarray.gather_nd(attention_padded, create_indices(k,n))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"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.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment