Return ndarray normalized by length, i.e. eucledian norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / nump
(data, axis=None, out=None)
| 1841 | |
| 1842 | |
| 1843 | def unit_vector(data, axis=None, out=None): |
| 1844 | """Return ndarray normalized by length, i.e. eucledian norm, along axis. |
| 1845 | |
| 1846 | >>> v0 = numpy.random.random(3) |
| 1847 | >>> v1 = unit_vector(v0) |
| 1848 | >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) |
| 1849 | True |
| 1850 | >>> v0 = numpy.random.rand(5, 4, 3) |
| 1851 | >>> v1 = unit_vector(v0, axis=-1) |
| 1852 | >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) |
| 1853 | >>> numpy.allclose(v1, v2) |
| 1854 | True |
| 1855 | >>> v1 = unit_vector(v0, axis=1) |
| 1856 | >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) |
| 1857 | >>> numpy.allclose(v1, v2) |
| 1858 | True |
| 1859 | >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float64) |
| 1860 | >>> unit_vector(v0, axis=1, out=v1) |
| 1861 | >>> numpy.allclose(v1, v2) |
| 1862 | True |
| 1863 | >>> list(unit_vector([])) |
| 1864 | [] |
| 1865 | >>> list(unit_vector([1.0])) |
| 1866 | [1.0] |
| 1867 | |
| 1868 | """ |
| 1869 | if out is None: |
| 1870 | data = numpy.array(data, dtype=numpy.float64, copy=True) |
| 1871 | if data.ndim == 1: |
| 1872 | data /= math.sqrt(numpy.dot(data, data)) |
| 1873 | return data |
| 1874 | else: |
| 1875 | if out is not data: |
| 1876 | out[:] = numpy.array(data, copy=False) |
| 1877 | data = out |
| 1878 | length = numpy.atleast_1d(numpy.sum(data*data, axis)) |
| 1879 | numpy.sqrt(length, length) |
| 1880 | if axis is not None: |
| 1881 | length = numpy.expand_dims(length, axis) |
| 1882 | data /= length |
| 1883 | if out is None: |
| 1884 | return data |
| 1885 | |
| 1886 | |
| 1887 | def random_vector(size): |
no outgoing calls
no test coverage detected