Skip to content

Instantly share code, notes, and snippets.

@notwa
Created May 2, 2020 23:04
Show Gist options
  • Save notwa/51926f4736d5a6ba167ffea205936b2a to your computer and use it in GitHub Desktop.
Save notwa/51926f4736d5a6ba167ffea205936b2a to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"data = np.random.normal(size=(100, 100))"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20 µs ± 59.3 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)\n",
"16.1 µs ± 252 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)\n",
"13 µs ± 1.33 µs per loop (mean ± std. dev. of 10 runs, 100000 loops each)\n"
]
}
],
"source": [
"%timeit -r 10 -n 100000 np.sqrt(np.mean(np.square(data)))\n",
"%timeit -r 10 -n 100000 np.linalg.norm(data.flat, ord=2) / np.sqrt(data.size)\n",
"%timeit -r 10 -n 100000 np.linalg.norm(data.ravel(), ord=2) / np.sqrt(data.size)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"thumbs up!\n"
]
}
],
"source": [
"assert np.allclose(np.sqrt(np.mean(np.square(data))), np.linalg.norm(data.ravel(), ord=2) / np.sqrt(data.size))\n",
"print(\"thumbs up!\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20.8 µs ± 69.1 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)\n",
"21.3 µs ± 92 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)\n"
]
}
],
"source": [
"%timeit -r 10 -n 100000 np.sqrt(np.mean(np.square(data), axis=0))\n",
"%timeit -r 10 -n 100000 np.linalg.norm(data, ord=2, axis=0) / np.sqrt(data.shape[0])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"thumbs up!\n"
]
}
],
"source": [
"assert np.allclose(np.sqrt(np.mean(np.square(data), axis=0)), np.linalg.norm(data, ord=2, axis=0) / np.sqrt(data.shape[0]))\n",
"print(\"thumbs up!\")"
]
}
],
"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.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment