Python numpy.var() Examples

The following are 30 code examples of numpy.var(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: BlurDetection.py    From python-- with GNU General Public License v3.0 10 votes vote down vote up
def _lapulaseDetection(self, imgName):
        """
        :param strdir: 文件所在的目录
        :param name: 文件名称
        :return: 检测模糊后的分数
        """
        # step1: 预处理
        img2gray, reImg = self.preImgOps(imgName)
        # step2: laplacian算子 获取评分
        resLap = cv2.Laplacian(img2gray, cv2.CV_64F)
        score = resLap.var()
        print("Laplacian %s score of given image is %s", str(score))
        # strp3: 绘制图片并保存  不应该写在这里  抽象出来   这是共有的部分
        newImg = self._drawImgFonts(reImg, str(score))
        newDir = self.strDir + "/_lapulaseDetection_/"
        if not os.path.exists(newDir):
            os.makedirs(newDir)
        newPath = newDir + imgName
        # 显示
        cv2.imwrite(newPath, newImg)  # 保存图片
        cv2.imshow(imgName, newImg)
        cv2.waitKey(0)

        # step3: 返回分数
        return score 
Example #2
Source File: BlurDetection.py    From python-- with GNU General Public License v3.0 6 votes vote down vote up
def _Variance(self, imgName):
        """
               灰度方差乘积
               :param imgName:
               :return:
               """
        # step 1 图像的预处理
        img2gray, reImg = self.preImgOps(imgName)
        f = self._imageToMatrix(img2gray)

        # strp3: 绘制图片并保存  不应该写在这里  抽象出来   这是共有的部分
        score = np.var(f)
        newImg = self._drawImgFonts(reImg, str(score))
        newDir = self.strDir + "/_Variance_/"
        if not os.path.exists(newDir):
            os.makedirs(newDir)
        newPath = newDir + imgName
        cv2.imwrite(newPath, newImg)  # 保存图片
        cv2.imshow(imgName, newImg)
        cv2.waitKey(0)
        return score 
Example #3
Source File: running_mean_std.py    From lirpg with MIT License 6 votes vote down vote up
def test_runningmeanstd():
    for (x1, x2, x3) in [
        (np.random.randn(3), np.random.randn(4), np.random.randn(5)),
        (np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
        ]:

        rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])

        x = np.concatenate([x1, x2, x3], axis=0)
        ms1 = [x.mean(axis=0), x.var(axis=0)]
        rms.update(x1)
        rms.update(x2)
        rms.update(x3)
        ms2 = [rms.mean, rms.var]

        assert np.allclose(ms1, ms2) 
Example #4
Source File: running_mean_std.py    From HardRLWithYoutube with MIT License 6 votes vote down vote up
def test_tf_runningmeanstd():
    for (x1, x2, x3) in [
        (np.random.randn(3), np.random.randn(4), np.random.randn(5)),
        (np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
        ]:

        rms = TfRunningMeanStd(epsilon=0.0, shape=x1.shape[1:], scope='running_mean_std' + str(np.random.randint(0, 128)))

        x = np.concatenate([x1, x2, x3], axis=0)
        ms1 = [x.mean(axis=0), x.var(axis=0)]
        rms.update(x1)
        rms.update(x2)
        rms.update(x3)
        ms2 = [rms.mean, rms.var]

        np.testing.assert_allclose(ms1, ms2) 
Example #5
Source File: signal_changepoints.py    From NeuroKit with MIT License 6 votes vote down vote up
def _signal_changepoints_cost_mean(signal):
    """Cost function for a normally distributed signal with a changing mean."""
    i_variance_2 = 1 / (np.var(signal) ** 2)
    cmm = [0.0]
    cmm.extend(np.cumsum(signal))

    cmm2 = [0.0]
    cmm2.extend(np.cumsum(np.abs(signal)))

    def cost(start, end):
        cmm2_diff = cmm2[end] - cmm2[start]
        cmm_diff = pow(cmm[end] - cmm[start], 2)
        i_diff = end - start
        diff = cmm2_diff - cmm_diff
        return (diff / i_diff) * i_variance_2

    return cost 
Example #6
Source File: standard_variance.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def standard_variance(data, period):
    """
    Standard Variance.

    Formula:
    (Ct - AVGt)^2 / N
    """
    check_for_period_error(data, period)
    sv = list(map(
        lambda idx:
        np.var(data[idx+1-period:idx+1], ddof=1),
        range(period-1, len(data))
        ))
    sv = fill_for_noncomputable_vals(data, sv)

    return sv 
Example #7
Source File: node.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def var(self):
        name = "ExpandingVar({})".format(self.name)
        return self.agg(lambda x: np.var(x, ddof=1)).rename(name) 
Example #8
Source File: node.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def std(self, bias: bool = False):
        name = "EWM:SD({},{})".format(self.name, self.alpha)
        return self.var(bias).sqrt().rename(name) 
Example #9
Source File: demos.py    From bayesian_bootstrap with MIT License 5 votes vote down vote up
def plot_var_bootstrap():
    X = np.random.uniform(-1, 1, 100)
    posterior_samples = var(X, 10000)
    sns.distplot(posterior_samples)
    classical_samples = [np.var(resample(X)) for _ in range(10000)]
    sns.distplot(classical_samples)
    plt.show() 
Example #10
Source File: bag_of_characters.py    From sato with Apache License 2.0 5 votes vote down vote up
def extract_bag_of_characters_features(data, n_val):
    
    characters_to_check = [ '['+  c + ']' for c in string.printable if c not in ( '\n', '\\', '\v', '\r', '\t', '^' )] + ['[\\\\]', '[\^]']
    
    f = OrderedDict()

    f['n_values'] = n_val
    data_no_null = data.dropna()
    all_value_features = OrderedDict()

    all_value_features['length'] = data_no_null.apply(len)

    for c in characters_to_check:
        all_value_features['n_{}'.format(c)] = data_no_null.str.count(c)
        
    for value_feature_name, value_features in all_value_features.items():
        f['{}-agg-any'.format(value_feature_name)] = any(value_features)
        f['{}-agg-all'.format(value_feature_name)] = all(value_features)
        f['{}-agg-mean'.format(value_feature_name)] = np.mean(value_features)
        f['{}-agg-var'.format(value_feature_name)] = np.var(value_features)
        f['{}-agg-min'.format(value_feature_name)] = np.min(value_features)
        f['{}-agg-max'.format(value_feature_name)] = np.max(value_features)
        f['{}-agg-median'.format(value_feature_name)] = np.median(value_features)
        f['{}-agg-sum'.format(value_feature_name)] = np.sum(value_features)
        f['{}-agg-kurtosis'.format(value_feature_name)] = kurtosis(value_features)
        f['{}-agg-skewness'.format(value_feature_name)] = skew(value_features)

    n_none = data.size - data_no_null.size - len([ e for e in data if e == ''])
    f['none-agg-has'] = n_none > 0
    f['none-agg-percent'] = n_none / len(data)
    f['none-agg-num'] = n_none
    f['none-agg-all'] = (n_none == len(data))
    #print(len(f))
    return f 
Example #11
Source File: decision_tree_regression.py    From Python-Machine-Learning-By-Example-Second-Edition with MIT License 5 votes vote down vote up
def mse(targets):
    # When the set is empty
    if targets.size == 0:
        return 0
    return np.var(targets) 
Example #12
Source File: common.py    From Jtyoui with MIT License 5 votes vote down vote up
def line_regression_a_b(x: np.array, y: np.array):
    """求解线性回归的a和β值。即y=b+a*x

    :param x: 数据特征值:应该是两维度。即:[[],[],[]]
    :param y: 数据预测值;一维度。即:[]
    :return: a值、和b值
    """
    var = np.var(x, ddof=1)  # 贝塞尔校正,方差
    cov = np.cov(x.transpose(), y)[0][1]  # 协方差
    x_ = np.mean(x)
    y_ = np.mean(y)
    a = cov / var
    b = y_ - a * x_
    return a, b 
Example #13
Source File: test_bootstrap.py    From bayesian_bootstrap with MIT License 5 votes vote down vote up
def test_var_resample(self):
        X = np.random.uniform(-1, 1, 500)
        posterior_samples = bayesian_bootstrap(X, np.var, 10000, 5000, low_mem=True)
        self.assertAlmostEqual(np.mean(posterior_samples), 1/3., delta=0.05)
        X = np.random.uniform(-1, 1, 500)
        posterior_samples = bayesian_bootstrap(X, np.var, 10000, 5000, low_mem=False)
        self.assertAlmostEqual(np.mean(posterior_samples), 1 / 3., delta=0.05) 
Example #14
Source File: test_bootstrap.py    From bayesian_bootstrap with MIT License 5 votes vote down vote up
def test_self_covar(self):
        X = np.random.uniform(-1, 1, 500)
        posterior_samples = covar(X, X, 10000)
        self.assertAlmostEqual(np.mean(posterior_samples), np.var(X), delta=0.05) 
Example #15
Source File: test_bootstrap.py    From bayesian_bootstrap with MIT License 5 votes vote down vote up
def test_variance(self):
        X = np.random.uniform(-1, 1, 500)
        posterior_samples = var(X, 10000)
        self.assertAlmostEqual(np.mean(posterior_samples), 1/3., delta=0.05) 
Example #16
Source File: demos.py    From bayesian_bootstrap with MIT License 5 votes vote down vote up
def plot_var_resample_bootstrap():
    X = np.random.uniform(-1, 1, 100)
    posterior_samples = bayesian_bootstrap(X, np.var, 10000, 500)
    sns.distplot(posterior_samples)
    classical_samples = [np.var(resample(X)) for _ in range(10000)]
    sns.distplot(classical_samples)
    plt.show() 
Example #17
Source File: node.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def var(self, bias: bool = False):
        name = "EWM:Var({},{})".format(self.name, self.alpha)
        return ExponentialWeightedMovingVariance(bias, name)(self, self.inputs[0]) 
Example #18
Source File: node.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def var(self):
        name = "RollingVar({},{})".format(self.name, self.window)
        return self.agg(np.var).rename(name) 
Example #19
Source File: test_nanvar.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_large_epsilon_axis(self):
        a = np.random.random((1000, 5))
        res = np.var(a, axis=0)
        res_dp = nanvar(a, epsilon=1, bounds=(0, 1), axis=0)

        for i in range(res.shape[0]):
            self.assertAlmostEqual(res[i], res_dp[i], delta=0.01) 
Example #20
Source File: test_nanvar.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_large_epsilon(self):
        a = np.random.random(1000)
        res = float(np.var(a))
        res_dp = nanvar(a, epsilon=1, bounds=(0, 1))

        self.assertAlmostEqual(res, res_dp, delta=0.01) 
Example #21
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_accountant(self):
        from diffprivlib.accountant import BudgetAccountant
        acc = BudgetAccountant(1.5, 0)

        a = np.random.random((1000, 5))
        var(a, epsilon=1, bounds=(0, 1), accountant=acc)
        self.assertEqual((1.0, 0), acc.total())

        with acc:
            with self.assertRaises(BudgetError):
                var(a, epsilon=1, bounds=(0, 1)) 
Example #22
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_clipped_output(self):
        a = np.random.random((10,))

        for i in range(100):
            self.assertTrue(0 <= var(a, epsilon=1e-5, bounds=(0, 1)) <= 1) 
Example #23
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_array_like(self):
        self.assertIsNotNone(var([1, 2, 3], bounds=(1, 3)))
        self.assertIsNotNone(var((1, 2, 3), bounds=(1, 3))) 
Example #24
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_large_epsilon_axis(self):
        a = np.random.random((1000, 5))
        res = np.var(a, axis=0)
        res_dp = var(a, epsilon=1, bounds=(0, 1), axis=0)

        for i in range(res.shape[0]):
            self.assertAlmostEqual(res[i], res_dp[i], delta=0.01) 
Example #25
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_large_epsilon(self):
        a = np.random.random(1000)
        res = float(np.var(a))
        res_dp = var(a, epsilon=1, bounds=(0, 1))

        self.assertAlmostEqual(res, res_dp, delta=0.01) 
Example #26
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_missing_bounds(self):
        a = np.array([1, 2, 3])
        with self.assertWarns(PrivacyLeakWarning):
            res = var(a, 1, None)
        self.assertIsNotNone(res) 
Example #27
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_no_bounds(self):
        a = np.array([1, 2, 3])
        with self.assertWarns(PrivacyLeakWarning):
            var(a, epsilon=1) 
Example #28
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_no_epsilon(self):
        a = np.array([1, 2, 3])
        self.assertIsNotNone(var(a, bounds=(0, 1))) 
Example #29
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_no_params(self):
        a = np.array([1, 2, 3])
        with self.assertWarns(PrivacyLeakWarning):
            res = var(a)
        self.assertIsNotNone(res) 
Example #30
Source File: test_var.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_not_none(self):
        mech = var
        self.assertIsNotNone(mech)