Skip to content

Instantly share code, notes, and snippets.

@mjbommar
Created January 25, 2015 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjbommar/51332a44020aa040a252 to your computer and use it in GitHub Desktop.
Save mjbommar/51332a44020aa040a252 to your computer and use it in GitHub Desktop.
Simple column-sum normalization using vectorized numpy methods
Display the source blob
Display the rendered blob
Raw
{"nbformat_minor": 0, "cells": [{"execution_count": 29, "cell_type": "code", "source": "import numpy\nimport scipy", "outputs": [], "metadata": {"collapsed": true, "trusted": true}}, {"execution_count": 30, "cell_type": "code", "source": "# Get a random matrix\nX = numpy.random.randint(0, 2, size=(5,5))\nX = X.astype(numpy.float64)\nX", "outputs": [{"execution_count": 30, "output_type": "execute_result", "data": {"text/plain": "array([[ 0., 0., 0., 0., 0.],\n [ 1., 0., 1., 0., 0.],\n [ 1., 0., 0., 1., 1.],\n [ 1., 0., 0., 1., 0.],\n [ 0., 1., 1., 1., 1.]])"}, "metadata": {}}], "metadata": {"collapsed": false, "trusted": true}}, {"execution_count": 31, "cell_type": "code", "source": "# Get the column sums\ncol_sums = X.sum(axis=0)\ncol_sums", "outputs": [{"execution_count": 31, "output_type": "execute_result", "data": {"text/plain": "array([ 3., 1., 2., 3., 2.])"}, "metadata": {}}], "metadata": {"collapsed": false, "trusted": true}}, {"execution_count": 32, "cell_type": "code", "source": "# Normalize the matrix by dividing each cell by the sum of cells in its column\nY = X / col_sums[numpy.newaxis, :]\nprint(Y)", "outputs": [{"output_type": "stream", "name": "stdout", "text": "[[ 0. 0. 0. 0. 0. ]\n [ 0.33333333 0. 0.5 0. 0. ]\n [ 0.33333333 0. 0. 0.33333333 0.5 ]\n [ 0.33333333 0. 0. 0.33333333 0. ]\n [ 0. 1. 0.5 0.33333333 0.5 ]]\n"}], "metadata": {"collapsed": false, "trusted": true}}], "nbformat": 4, "metadata": {"kernelspec": {"display_name": "IPython (Python 2)", "name": "python2"}, "language_info": {"mimetype": "text/x-python", "nbconvert_exporter": "python", "version": "2.7.3", "name": "python", "file_extension": ".py", "pygments_lexer": "ipython2", "codemirror_mode": {"version": 2, "name": "ipython"}}, "signature": "sha256:c47c58dd53fc3b2f3d855ff38a5251d35d0e85331fbffaf2c783fb9b0347902e"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment