Skip to content

Instantly share code, notes, and snippets.

@sumartoyo
Created October 12, 2016 10:22
Show Gist options
  • Save sumartoyo/edba2eee645457a98fdf046e1b4297e4 to your computer and use it in GitHub Desktop.
Save sumartoyo/edba2eee645457a98fdf046e1b4297e4 to your computer and use it in GitHub Desktop.
Scipy sparse matrix variance and standard deviation
import numpy as np
def vars(a, axis=None):
""" Variance of sparse matrix a
var = mean(a**2) - mean(a)**2
"""
a_squared = a.copy()
a_squared.data **= 2
return a_squared.mean(axis) - np.square(a.mean(axis))
def stds(a, axis=None):
""" Standard deviation of sparse matrix a
std = sqrt(var(a))
"""
return np.sqrt(vars(a, axis))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment