repo_name stringlengths 6 67 | path stringlengths 5 185 | copies stringlengths 1 3 | size stringlengths 4 6 | content stringlengths 1.02k 962k | license stringclasses 15
values |
|---|---|---|---|---|---|
keflavich/scikit-image | doc/examples/plot_adapt_rgb.py | 4 | 4109 | """
=========================================
Adapting gray-scale filters to RGB images
=========================================
There are many filters that are designed to work with gray-scale images but not
with color images. To simplify the process of creating functions that can adapt
to RGB images, scikit-image p... | bsd-3-clause |
trungnt13/scikit-learn | examples/plot_digits_pipe.py | 250 | 1809 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Pipelining: chaining a PCA and a logistic regression
=========================================================
The PCA does an unsupervised dimensionality reduction, while the logistic
regression does the predictio... | bsd-3-clause |
nomadcube/scikit-learn | sklearn/datasets/tests/test_20news.py | 280 | 3045 | """Test the 20news downloader, if the data is available."""
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import SkipTest
from sklearn import datasets
def test_20news():
try:
data = dat... | bsd-3-clause |
stefan-balke/librosa | librosa/core/dtw.py | 1 | 11796 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Sequence Alignment with Dynamic Time Warping."""
import numpy as np
from scipy.spatial.distance import cdist
from ..util.decorators import optional_jit
from ..util.exceptions import ParameterError
__all__ = ['dtw', 'fill_off_diagonal']
def fill_off_diagonal(x, radius... | isc |
jjx02230808/project0223 | sklearn/neural_network/tests/test_mlp.py | 46 | 18585 | """
Testing for Multi-layer Perceptron module (sklearn.neural_network)
"""
# Author: Issam H. Laradji
# Licence: BSD 3 clause
import sys
import warnings
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_equal
from sklearn.datasets import load_digits, load_boston
from sklearn.datasets i... | bsd-3-clause |
pianomania/scikit-learn | examples/applications/plot_out_of_core_classification.py | 51 | 13651 | """
======================================================
Out-of-core classification of text documents
======================================================
This is an example showing how scikit-learn can be used for classification
using an out-of-core approach: learning from data that doesn't fit into main
memory. ... | bsd-3-clause |
cdawei/shogun | examples/undocumented/python_modular/graphical/metric_lmnn_objective.py | 26 | 2350 | #!/usr/bin/env python
def load_compressed_features(fname_features):
try:
import gzip
import numpy
except ImportError:
print 'Error importing gzip and/or numpy modules. Please, verify their installation.'
import sys
sys.exit(0)
# load features from a gz compressed file
file_features = gzip.GzipFile(fname... | gpl-3.0 |
jjx02230808/project0223 | examples/ensemble/plot_voting_probas.py | 316 | 2824 | """
===========================================================
Plot class probabilities calculated by the VotingClassifier
===========================================================
Plot the class probabilities of the first sample in a toy dataset
predicted by three different classifiers and averaged by the
`VotingC... | bsd-3-clause |
karstenw/nodebox-pyobjc | examples/Extended Application/matplotlib/examples/pyplots/whats_new_98_4_fancy.py | 1 | 2644 | """
======================
Whats New 0.98.4 Fancy
======================
"""
import matplotlib.patches as mpatch
import matplotlib.pyplot as plt
# nodebox section
if __name__ == '__builtin__':
# were in nodebox
import os
import tempfile
W = 800
inset = 20
size(W, 600)
plt.cla()
plt.clf... | mit |
DGrady/pandas | pandas/util/testing.py | 1 | 92648 | from __future__ import division
# pylint: disable-msg=W0402
import re
import string
import sys
import tempfile
import warnings
import inspect
import os
import subprocess
import locale
import traceback
from datetime import datetime
from functools import wraps, partial
from contextlib import contextmanager
from distuti... | bsd-3-clause |
burakbayramli/dersblog | algs/algs_175_ocr/tf/test5.py | 2 | 1496 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
w = 128; h = 64
# junk image, only one
dataset = np.zeros((10,w,h,1))
pool_size = 1
num_filters = 16
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_va... | gpl-3.0 |
anntzer/scikit-learn | examples/mixture/plot_gmm_sin.py | 19 | 6100 | """
=================================
Gaussian Mixture Model Sine Curve
=================================
This example demonstrates the behavior of Gaussian mixture models fit on data
that was not sampled from a mixture of Gaussian random variables. The dataset
is formed by 100 points loosely spaced following a noisy ... | bsd-3-clause |
EnSpec/SpecDAL | specdal/operators/proximal_join.py | 1 | 2806 | import pandas as pd
import numpy as np
import warnings
import logging as logging
logging.basicConfig(level=logging.WARNING,
format="%(levelname)s:%(name)s:%(message)s\n")
def get_column_types(df):
'''
Returns a tuple (wvl_cols, meta_cols), given a dataframe.
Notes
-----
Wavelength colu... | mit |
TomAugspurger/pandas | pandas/tests/arithmetic/test_numeric.py | 1 | 46627 | # Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
# Specifically for numeric dtypes
from collections import abc
from decimal import Decimal
from itertools import combinations
import operator
from typing import Any, List
import numpy as np
import pytest
import pandas as pd
f... | bsd-3-clause |
rahuldhote/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | 341 | 2620 | """
Testing for Clustering methods
"""
import numpy as np
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.cluster.affinity_propagation_ import AffinityPropagation
from sklearn.cluster.affinity_propagatio... | bsd-3-clause |
gclenaghan/scikit-learn | examples/applications/plot_prediction_latency.py | 234 | 11277 | """
==================
Prediction Latency
==================
This is an example showing the prediction latency of various scikit-learn
estimators.
The goal is to measure the latency one can expect when doing predictions
either in bulk or atomic (i.e. one by one) mode.
The plots represent the distribution of the pred... | bsd-3-clause |
pprett/scikit-learn | sklearn/linear_model/tests/test_logistic.py | 7 | 47843 | import numpy as np
import scipy.sparse as sp
from scipy import linalg, optimize, sparse
from sklearn.datasets import load_iris, make_classification
from sklearn.metrics import log_loss
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import compute_cl... | bsd-3-clause |
akionakamura/scikit-learn | benchmarks/bench_plot_svd.py | 325 | 2899 | """Benchmarks of Singular Value Decomposition (Exact and Approximate)
The data is mostly low rank but is a fat infinite tail.
"""
import gc
from time import time
import numpy as np
from collections import defaultdict
from scipy.linalg import svd
from sklearn.utils.extmath import randomized_svd
from sklearn.datasets.s... | bsd-3-clause |
cactusbin/nyt | matplotlib/examples/animation/old_animation/histogram_tkagg.py | 3 | 1847 | """
This example shows how to use a path patch to draw a bunch of
rectangles for an animated histogram
"""
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # do this before importing pylab
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
fig, ax = plt.sub... | unlicense |
crichardson17/starburst_atlas | SFH_comparison/data/Geneva_inst_Rot/Geneva_inst_Rot_0/fullgrid/peaks_reader.py | 1 | 5057 | import csv
import matplotlib.pyplot as plt
from numpy import *
import scipy.interpolate
import math
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib.patches as patches
from matplotlib.path import Path
import os
# ---------------------------------------------------... | gpl-2.0 |
Irsan88/SeqTools | DataProcessing/roda/branches/irna/bin/scripts/plotHomHetRegions.py | 6 | 1692 | import sys
import matplotlib.pyplot as plt
vcfIn = open(sys.argv[1], 'r')
positions = {}
allChroms = []
lengthContigs = {}
for line in vcfIn:
if line[0] == '#':
if line[0:8] == '##contig':
line = line.rstrip().split(',')
chrom = line[0].split('=')[-1]
length = line[1].split('=')[-1]
lengthContigs[chro... | gpl-2.0 |
jgabriellima/mining | mining/test/test_mining_utils.py | 7 | 4972 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from datetime import date, datetime
from decimal import Decimal
from pandas import tslib, DataFrame
from mining.utils import slugfy
from mining.utils._pandas import fix_type, fix_render, df_generate
class df_slugfy_test(unittest.TestCase):
def test_g... | mit |
rexshihaoren/scikit-learn | sklearn/tests/test_naive_bayes.py | 142 | 17496 | import pickle
from io import BytesIO
import numpy as np
import scipy.sparse
from sklearn.datasets import load_digits, load_iris
from sklearn.cross_validation import cross_val_score, train_test_split
from sklearn.externals.six.moves import zip
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.te... | bsd-3-clause |
cjratcliff/variational-dropout | nets.py | 1 | 8268 | from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.core import Dropout
from la... | gpl-3.0 |
necromuralist/student_intervention | student_intervention/preparing_data.py | 1 | 3505 |
# python standard library
import pickle
# third party
import pandas
from sklearn.cross_validation import train_test_split
# this code
from common import (student_data, feature_map, TrainTestData,
train_test_path, RANDOM_STATE)
# Extract feature (X) and target (y) columns
feature_columns = list(s... | mit |
lancezlin/ml_template_py | lib/python2.7/site-packages/matplotlib/_cm.py | 4 | 93997 | """
Nothing here but dictionaries for generating LinearSegmentedColormaps,
and a dictionary of these dictionaries.
Documentation for each is in pyplot.colormaps()
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
_binary_data = {
... | mit |
JsNoNo/scikit-learn | examples/cluster/plot_agglomerative_clustering_metrics.py | 402 | 4492 | """
Agglomerative clustering with different metrics
===============================================
Demonstrates the effect of different metrics on the hierarchical clustering.
The example is engineered to show the effect of the choice of different
metrics. It is applied to waveforms, which can be seen as
high-dimens... | bsd-3-clause |
vortex-ape/scikit-learn | examples/model_selection/plot_validation_curve.py | 141 | 1931 | """
==========================
Plotting Validation Curves
==========================
In this plot you can see the training scores and validation scores of an SVM
for different values of the kernel parameter gamma. For very low values of
gamma, you can see that both the training score and the validation score are
low. ... | bsd-3-clause |
mrustl/flopy | flopy/utils/datafile.py | 1 | 17018 | """
Module to read MODFLOW output files. The module contains shared
abstract classes that should not be directly accessed.
"""
from __future__ import print_function
import os
import numpy as np
import flopy.utils
class Header(object):
"""
The header class is an abstract base class to create hea... | bsd-3-clause |
apriha/lineage | tests/test_individual.py | 1 | 2743 | """
MIT License
Copyright (c) 2017 Andrew Riha
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... | gpl-3.0 |
azmainamin/cats_v_dogs_neural_networks | prepare_data.py | 1 | 7672 | import cPickle as pickle
import numpy as np
import timeit
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv2d
import matplotlib.pyplot as plt
from matplotlib import cm
from sys import version_info
import os
from PIL import Image
import gc
CAT = f... | gpl-3.0 |
JanetMatsen/meta4_bins_janalysis | network/network.py | 1 | 3545 | #!/usr/bin/env python2.7
'''
Co-occurence network from expression data.
'''
import os
import pickle
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import pandas as pd
import readline
from rpy2.robjects.packages import importr
from rpy2.robjects.vecto... | bsd-2-clause |
Borillion/mplh5canvas | setup.py | 4 | 1650 | #!/usr/bin/env python
from setuptools import setup, find_packages
from distutils.version import LooseVersion
import os
os.environ['MPLCONFIGDIR'] = "."
# temporarily redirect configuration directory
# to prevent matplotlib import testing for
# writeable directory outside of sandbox
from matplotlib import __version__... | bsd-3-clause |
Srisai85/scikit-learn | sklearn/datasets/base.py | 196 | 18554 | """
Base IO code for all datasets
"""
# Copyright (c) 2007 David Cournapeau <cournape@gmail.com>
# 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr>
# 2010 Olivier Grisel <olivier.grisel@ensta.org>
# License: BSD 3 clause
import os
import csv
import shutil
from os import environ
from os.pa... | bsd-3-clause |
wrichert/BuildingMachineLearningSystemsWithPython | ch05/PosTagFreqVectorizer.py | 27 | 9486 | # This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
import re
from operator import itemgetter
from collections import Mapping
import scipy.sparse as sp
f... | mit |
victorbergelin/scikit-learn | examples/preprocessing/plot_function_transformer.py | 161 | 1949 | """
=========================================================
Using FunctionTransformer to select columns
=========================================================
Shows how to use a function transformer in a pipeline. If you know your
dataset's first principle component is irrelevant for a classification task,
you ca... | bsd-3-clause |
alexsavio/scikit-learn | sklearn/utils/tests/test_class_weight.py | 50 | 13151 | import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_blobs
from sklearn.utils.class_weight import compute_class_weight
from sklearn.utils.class_weight import compute_sample_weight
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testin... | bsd-3-clause |
RobertABT/heightmap | build/matplotlib/lib/matplotlib/tests/test_simplification.py | 2 | 7078 | from __future__ import print_function
import numpy as np
import matplotlib
from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup
import matplotlib.pyplot as plt
from pylab import *
import numpy as np
from matplotlib import patches, path, transforms
from nose.tools import raises
import i... | mit |
epfl-lts2/pygsp | pygsp/graphs/ring.py | 1 | 2870 | # -*- coding: utf-8 -*-
import numpy as np
from scipy import sparse
from . import Graph # prevent circular import in Python < 3.5
class Ring(Graph):
r"""K-regular ring graph.
A signal on the ring graph is akin to a 1-dimensional periodic signal in
classical signal processing.
On the ring graph, t... | bsd-3-clause |
RedPointyJackson/tfg | study_cases/dieharder/plot.py | 1 | 1126 | #!/usr/bin/env python3
def cm2inch(value):
return value/2.54
import matplotlib.pyplot as plt
import pandas as pd
import seaborn.apionly as sns
plt.style.use('custom')
failcolor = '#C44E52'
passcolor = '#55A868'
warncolor = '#FFA574'
df = pd.read_csv('data.csv')
fig = plt.figure(figsize=(cm2inch(15),cm2inch(6)... | mit |
droundy/deft | papers/water-saft/figs/density-compare.py | 1 | 1705 | #!/usr/bin/env python
#need this to run without xserver
import matplotlib
matplotlib.use('Agg')
import math
import matplotlib.pyplot as pyplot
import numpy
import pylab
from matplotlib.patches import Ellipse
nm = 18.8972613
gpermL=4.9388942e-3/0.996782051315 # conversion from atomic units to mass density
grey = '#9... | gpl-2.0 |
JohnGriffiths/nipype | nipype/algorithms/misc.py | 9 | 51269 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
'''
Miscellaneous algorithms
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname(os.path.realpath(__file__))
>>> datadir = os.path.realpath(... | bsd-3-clause |
direvius/bfg | bfg/aggregator.py | 1 | 6997 | '''
Data aggregation facilities.
'''
import threading as th
import queue
import multiprocessing as mp
from .module_exceptions import ConfigurationError
from .util import FactoryBase
from .guns.base import Sample
from .util import q_to_dict
import asyncio
import time
from dateutil import tz
import numpy as np
import pa... | mit |
GDSA-SED/Projecte-SED-2013 | complementary_evaluation/single_evaluation.py | 1 | 7329 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as SQL
import numpy as np
import matplotlib.pyplot as pl
nom = raw_input("Introdueixi el nom del fitxer que conte els resultats de les imatges clasificades (escrigui exit per sortir):")
if nom != "exit":
fitxer = open(nom, 'r') #Obrim el fitxer de dades ... | gpl-3.0 |
quheng/scikit-learn | sklearn/utils/arpack.py | 265 | 64837 | """
This contains a copy of the future version of
scipy.sparse.linalg.eigen.arpack.eigsh
It's an upgraded wrapper of the ARPACK library which
allows the use of shift-invert mode for symmetric matrices.
Find a few eigenvectors and eigenvalues of a matrix.
Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/
"""
#... | bsd-3-clause |
liesbethvanherpe/NeuroM | examples/plot_somas.py | 5 | 2927 | #!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fol... | bsd-3-clause |
wimmuskee/readability-score | readability_score/textanalyzer.py | 1 | 6194 | # -*- coding: utf-8 -*-
"""
This class contains the main text analyzer used in all
the calculators.
Wim Muskee, 2012-2017
wimmuskee@gmail.com
License: GPL-2
"""
from __future__ import division
from sys import version_info
import warnings
import re
import os
with warnings.catch_warnings():
# catch NLTK warning, f... | gpl-2.0 |
hsogo/psychopy_tobii_controller | samples/utility_sample01.py | 1 | 2464 | import matplotlib.pyplot as plt
import numpy as np
# import utility
import psychopy_tobii_controller.utility as util
import psychopy_tobii_controller.constants as const
# Load data file using load_data().
# Return values are two list objects.
# The first one is gaze data, and the other is event data.
gaze_data, event... | gpl-3.0 |
pratapvardhan/pandas | pandas/tests/scalar/timedelta/test_construction.py | 6 | 8805 | # -*- coding: utf-8 -*-
from datetime import timedelta
import pytest
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas import Timedelta
def test_construction():
expected = np.timedelta64(10, 'D').astype('m8[ns]').view('i8')
assert Timedelta(10, unit='d').value == expected
... | bsd-3-clause |
rs2/pandas | pandas/tests/arrays/masked/test_arrow_compat.py | 2 | 1505 | import pytest
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_EA_INT_DTYPES]
arrays += [pd.array([True, False, True, None], dtype="boolean")]
@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arr... | bsd-3-clause |
q1ang/scikit-learn | sklearn/linear_model/setup.py | 146 | 1713 | import os
from os.path import join
import numpy
from sklearn._build_utils import get_blas_info
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('linear_model', parent_package, top_path)
cblas_libs, blas_info = get_blas_info... | bsd-3-clause |
michaelbrundage/vowpal_wabbit | python/vowpalwabbit/sklearn_vw.py | 7 | 20683 | # -*- coding: utf-8 -*-
# pylint: unused-argument, invalid-name, too-many-arguments, too-many-locals
"""
Utilities to support integration of Vowpal Wabbit and scikit-learn
"""
import numpy as np
import re
import io
from scipy.sparse import csr_matrix
from sklearn.base import BaseEstimator, RegressorMixin
from sklear... | bsd-3-clause |
wanggang3333/scikit-learn | sklearn/ensemble/__init__.py | 217 | 1307 | """
The :mod:`sklearn.ensemble` module includes ensemble-based methods for
classification and regression.
"""
from .base import BaseEnsemble
from .forest import RandomForestClassifier
from .forest import RandomForestRegressor
from .forest import RandomTreesEmbedding
from .forest import ExtraTreesClassifier
from .fores... | bsd-3-clause |
cogmission/nupic | examples/opf/clients/hotgym/anomaly/one_gym/run.py | 34 | 4938 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... | agpl-3.0 |
btabibian/scikit-learn | examples/ensemble/plot_adaboost_twoclass.py | 347 | 3268 | """
==================
Two-class AdaBoost
==================
This example fits an AdaBoosted decision stump on a non-linearly separable
classification dataset composed of two "Gaussian quantiles" clusters
(see :func:`sklearn.datasets.make_gaussian_quantiles`) and plots the decision
boundary and decision scores. The di... | bsd-3-clause |
valexandersaulys/prudential_insurance_kaggle | venv/lib/python2.7/site-packages/pandas/tseries/tests/test_period.py | 9 | 153010 | """Tests suite for Period handling.
Parts derived from scikits.timeseries code, original authors:
- Pierre Gerard-Marchant & Matt Knox
- pierregm_at_uga_dot_edu - mattknow_ca_at_hotmail_dot_com
"""
from datetime import datetime, date, timedelta
from numpy.ma.testutils import assert_equal
from pandas import Timesta... | gpl-2.0 |
sergpolly/Thermal_adapt_scripts | retrieve_essential_genbanks.py | 1 | 2578 | import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
from Bio.Alphabet import IUPAC
import numpy as np
import pandas as pd
# path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER/ftp.ncbi.nih.gov/refseq/release/bacteria/genbank')
path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER_REL... | mit |
shangwuhencc/scikit-learn | sklearn/decomposition/tests/test_kernel_pca.py | 57 | 8062 | import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import (assert_array_almost_equal, assert_less,
assert_equal, assert_not_equal,
assert_raises)
from sklearn.decomposition import PCA, KernelPCA
from sklearn.datasets import mak... | bsd-3-clause |
ctogle/dilapidator | src/dilap/core/plotting.py | 1 | 5799 | from dilap.geometry.vec3 import vec3
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pdb
###############################################################################
# create a mpl 2d axes object
def plot_axes_xy(x = 5,o = (0,0),f = None,aspect = None):
if f is None:ax = plt.fi... | mit |
nchikkam/tdd | code/msp.py | 1 | 1520 | import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
def minimum_spanning_tree(X, copy_X=True):
"""X are edge weights of fully connected graph"""
if copy_X:
X = X.copy()
if X.shape[0] != X.shape[1]:
raise ValueError("X needs to be square ... | mit |
anntzer/scikit-learn | benchmarks/bench_plot_ward.py | 14 | 1277 | """
Benchmark scikit-learn's Ward implement compared to SciPy's
"""
import time
import numpy as np
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
ward = AgglomerativeClustering(n_clusters=3, linkage='ward')
n_samples = np.logspace(.5, 3, 9)
n... | bsd-3-clause |
UNR-AERIAL/scikit-learn | examples/missing_values.py | 233 | 3056 | """
======================================================
Imputing missing values before building an estimator
======================================================
This example shows that imputing the missing values can give better results
than discarding the samples containing any missing value.
Imputing does not ... | bsd-3-clause |
joshzarrabi/e-mission-server | emission/storage/timeseries/builtin_timeseries.py | 1 | 5212 | import logging
import pandas as pd
import pymongo
import emission.core.get_database as edb
import emission.storage.timeseries.abstract_timeseries as esta
class BuiltinTimeSeries(esta.TimeSeries):
def __init__(self, user_id):
super(BuiltinTimeSeries, self).__init__(user_id)
self.key_query = lambda(... | bsd-3-clause |
rishikksh20/scikit-learn | benchmarks/bench_tree.py | 131 | 3647 | """
To run this, you'll need to have installed.
* scikit-learn
Does two benchmarks
First, we fix a training set, increase the number of
samples to classify and plot number of classified samples as a
function of time.
In the second benchmark, we increase the number of dimensions of the
training set, classify a sam... | bsd-3-clause |
diogo149/CauseEffectPairsPaper | configs/categorical_kmeans10_none.py | 1 | 7424 | import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.p... | mit |
zak-k/cartopy | lib/cartopy/crs.py | 1 | 70157 | # (C) British Crown Copyright 2011 - 2017, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... | lgpl-3.0 |
jamescorsini/evaluator | portfolio_value.py | 1 | 10234 | # portfolio_value.py
'''
Software used:
http://wiki.quantsoftware.org/index.php?title=QSTK_License
Created on October 16, 2014
Updated on October 29, 2014
@author: James Corsini
@summary: Takes buy and sell data in csv format and outputs the portfolio's
value. Should be used in conjunction with portfolio_analyze.py t... | mit |
fzalkow/scikit-learn | doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py | 254 | 2005 | """Build a language detector model
The goal of this exercise is to train a linear classifier on text features
that represent sequences of up to 3 consecutive characters so as to be
recognize natural languages by using the frequencies of short character
sequences as 'fingerprints'.
"""
# Author: Olivier Grisel <olivie... | bsd-3-clause |
ngoix/OCRF | examples/manifold/plot_swissroll.py | 330 | 1446 | """
===================================
Swiss Roll reduction with LLE
===================================
An illustration of Swiss Roll reduction
with locally linear embedding
"""
# Author: Fabian Pedregosa -- <fabian.pedregosa@inria.fr>
# License: BSD 3 clause (C) INRIA 2011
print(__doc__)
import matplotlib.pyplot... | bsd-3-clause |
massmutual/scikit-learn | benchmarks/bench_plot_nmf.py | 90 | 5742 | """
Benchmarks of Non-Negative Matrix Factorization
"""
from __future__ import print_function
from collections import defaultdict
import gc
from time import time
import numpy as np
from scipy.linalg import norm
from sklearn.decomposition.nmf import NMF, _initialize_nmf
from sklearn.datasets.samples_generator import... | bsd-3-clause |
JPFrancoia/scikit-learn | examples/cluster/plot_face_segmentation.py | 71 | 2839 | """
===================================================
Segmenting the picture of a raccoon face in regions
===================================================
This example uses :ref:`spectral_clustering` on a graph created from
voxel-to-voxel difference on an image to break this image into multiple
partly-homogeneous... | bsd-3-clause |
vibhorag/scikit-learn | examples/exercises/plot_iris_exercise.py | 323 | 1602 | """
================================
SVM Exercise
================================
A tutorial exercise for using different SVM kernels.
This exercise is used in the :ref:`using_kernels_tut` part of the
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
"""
print(__doc__)
import numpy as np
i... | bsd-3-clause |
matz-e/lobster | lobster/commands/plot.py | 1 | 60092 | # vim: fileencoding=utf-8
from collections import defaultdict, Counter
from cycler import cycler
from datetime import datetime
import glob
import gzip
import itertools
import jinja2
import logging
import multiprocessing
import os
import pickle
import shutil
import sqlite3
import signal
import time
import re
import str... | mit |
ethertricity/bluesky | bluesky/traffic/performance/nap/coeff.py | 1 | 5989 | ''' NAP performance library. '''
import os
import json
import numpy as np
import pandas as pd
from bluesky import settings
settings.set_variable_defaults(perf_path_nap="data/performance/NAP")
# nap_path = os.path.dirname(os.path.realpath(__file__)) \
# + '/../../../../data/performance/NAP/'
ENG_TF = 1
ENG_... | gpl-3.0 |
marcsans/cnn-physics-perception | phy/lib/python2.7/site-packages/sklearn/gaussian_process/gpc.py | 13 | 31632 | """Gaussian processes classification."""
# Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
#
# License: BSD 3 clause
import warnings
from operator import itemgetter
import numpy as np
from scipy.linalg import cholesky, cho_solve, solve
from scipy.optimize import fmin_l_bfgs_b
from scipy.special import erf... | mit |
dmnfarrell/epitopepredict | epitopepredict/config.py | 2 | 5239 | #!/usr/bin/env python
"""
epitopepredict config
Created March 2016
Copyright (C) Damien Farrell
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the Lic... | apache-2.0 |
GuessWhoSamFoo/pandas | pandas/tests/reshape/test_reshape.py | 1 | 25038 | # -*- coding: utf-8 -*-
# pylint: disable-msg=W0612,E1101
from collections import OrderedDict
import numpy as np
from numpy import nan
import pytest
from pandas.compat import u
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
from pandas import Categorical, DataFrame, Index, Series, get_d... | bsd-3-clause |
Midafi/scikit-image | skimage/viewer/plugins/overlayplugin.py | 40 | 3615 | from warnings import warn
from ...util.dtype import dtype_range
from .base import Plugin
from ..utils import ClearColormap, update_axes_image
import six
from ..._shared.version_requirements import is_installed
__all__ = ['OverlayPlugin']
class OverlayPlugin(Plugin):
"""Plugin for ImageViewer that displays an ... | bsd-3-clause |
dmitru/rankpy | rankpy/analysis/lambdamart.py | 1 | 3256 | # This file is part of RankPy.
#
# RankPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RankPy is distributed in the hope ... | gpl-3.0 |
Sentient07/scikit-learn | examples/plot_digits_pipe.py | 65 | 1652 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Pipelining: chaining a PCA and a logistic regression
=========================================================
The PCA does an unsupervised dimensionality reduction, while the logistic
regression does the predictio... | bsd-3-clause |
OceanPARCELS/parcels | parcels/plotting.py | 1 | 15740 | from datetime import datetime
from datetime import timedelta as delta
import numpy as np
from parcels.field import Field
from parcels.field import VectorField
from parcels.grid import CurvilinearGrid
from parcels.grid import GridCode
from parcels.tools.statuscodes import TimeExtrapolationError
from parcels.tools.logg... | mit |
pymango/pymango | misc/python/mango/application/shale.py | 1 | 9724 | __doc__ = \
"""
======================================================================
Multi-modal shale CT imaging analysis (:mod:`mango.application.shale`)
======================================================================
.. currentmodule:: mango.application.shale
Analysis of shale dry, dry-after, Iodine-stain... | bsd-2-clause |
B3AU/waveTree | sklearn/mixture/gmm.py | 5 | 27249 | """
Gaussian Mixture Models.
This implementation corresponds to frequentist (non-Bayesian) formulation
of Gaussian Mixture Models.
"""
# Author: Ron Weiss <ronweiss@gmail.com>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Bertrand Thirion <bertrand.thirion@inria.fr>
import numpy as np
from ..base... | bsd-3-clause |
herilalaina/scikit-learn | examples/model_selection/plot_multi_metric_evaluation.py | 29 | 3755 | """
============================================================================
Demonstration of multi-metric evaluation on cross_val_score and GridSearchCV
============================================================================
Multiple metric parameter search can be done by setting the ``scoring``
parameter to... | bsd-3-clause |
shusenl/scikit-learn | sklearn/tests/test_isotonic.py | 230 | 11087 | import numpy as np
import pickle
from sklearn.isotonic import (check_increasing, isotonic_regression,
IsotonicRegression)
from sklearn.utils.testing import (assert_raises, assert_array_equal,
assert_true, assert_false, assert_equal,
... | bsd-3-clause |
rsivapr/scikit-learn | benchmarks/bench_glm.py | 297 | 1493 | """
A comparison of different methods in GLM
Data comes from a random square matrix.
"""
from datetime import datetime
import numpy as np
from sklearn import linear_model
from sklearn.utils.bench import total_seconds
if __name__ == '__main__':
import pylab as pl
n_iter = 40
time_ridge = np.empty(n_it... | bsd-3-clause |
vshtanko/scikit-learn | examples/gaussian_process/plot_gp_regression.py | 253 | 4054 | #!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
=========================================================
Gaussian Processes regression: basic introductory example
=========================================================
A simple one-dimensional regression exercise computed in two different ways:
1. A noise-free cas... | bsd-3-clause |
weinbe58/QuSpin | docs/downloads/8ebdaf354c80ef927ecd6a3597c6b0f6/example5.py | 3 | 4756 | from __future__ import print_function, division
import sys,os
# line 4 and line 5 below are for development purposes and can be removed
qspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,qspin_path)
#####################################################################
# example... | bsd-3-clause |
jwiggins/scikit-image | doc/examples/xx_applications/plot_morphology.py | 6 | 8329 | """
=======================
Morphological Filtering
=======================
Morphological image processing is a collection of non-linear operations related
to the shape or morphology of features in an image, such as boundaries,
skeletons, etc. In any given technique, we probe an image with a small shape or
template ca... | bsd-3-clause |
linebp/pandas | doc/sphinxext/ipython_sphinxext/ipython_directive.py | 1 | 37844 | # -*- coding: utf-8 -*-
"""
Sphinx directive to support embedded IPython code.
This directive allows pasting of entire interactive IPython sessions, prompts
and all, and their code will actually get re-executed at doc build time, with
all prompts renumbered sequentially. It also allows you to input code as a pure
pyth... | bsd-3-clause |
DGrady/pandas | pandas/plotting/_style.py | 11 | 8329 | # being a bit too dynamic
# pylint: disable=E1101
from __future__ import division
import warnings
from contextlib import contextmanager
import re
import numpy as np
from pandas.core.dtypes.common import is_list_like
from pandas.compat import range, lrange, lmap
import pandas.compat as compat
from pandas.plotting._co... | bsd-3-clause |
cybernet14/scikit-learn | sklearn/svm/classes.py | 126 | 40114 | import warnings
import numpy as np
from .base import _fit_liblinear, BaseSVC, BaseLibSVM
from ..base import BaseEstimator, RegressorMixin
from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \
LinearModel
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils import check_X... | bsd-3-clause |
BigDataforYou/movie_recommendation_workshop_1 | big_data_4_you_demo_1/venv/lib/python2.7/site-packages/pandas/tests/test_groupby.py | 1 | 249119 | # -*- coding: utf-8 -*-
from __future__ import print_function
import nose
from datetime import datetime
from numpy import nan
from pandas import date_range, bdate_range, Timestamp
from pandas.core.index import Index, MultiIndex, CategoricalIndex
from pandas.core.api import Categorical, DataFrame
from pandas.core.grou... | mit |
DiracInstitute/kbmod | analysis/trajectoryFiltering.py | 1 | 8204 | from sklearn.cluster import DBSCAN
import numpy as np
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
if r == 0: return 1
numer = reduce(op.mul, range(n, n-r, -1))
denom = reduce(op.mul, range(1, r+1))
return numer//denom
def maximum_expected_detections(im_count, ... | bsd-2-clause |
DANA-Laboratory/CoolProp | wrappers/Python/CoolProp/GUI/CoolPropGUI.py | 4 | 17019 | import wx
import wx.grid
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as WXCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as WXToolbar
import matplotlib as mpl
import CoolProp as CP
from CoolProp.Plots.Plots import Ph, Ts
from CoolProp.Plots import PsychChart
import numpy a... | mit |
ywcui1990/nupic | external/linux32/lib/python2.6/site-packages/matplotlib/numerix/__init__.py | 69 | 5473 | """
numerix imports either Numeric or numarray based on various selectors.
0. If the value "--numpy","--numarray" or "--Numeric" is specified on the
command line, then numerix imports the specified
array package.
1. The value of numerix in matplotlibrc: either Numeric or numarray
2. If none of the above is... | agpl-3.0 |
abimannans/scikit-learn | examples/gaussian_process/gp_diabetes_dataset.py | 223 | 1976 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
========================================================================
Gaussian Processes regression: goodness-of-fit on the 'diabetes' dataset
========================================================================
In this example, we fit a Gaussian Process model onto... | bsd-3-clause |
RPGOne/Skynet | scikit-learn-c604ac39ad0e5b066d964df3e8f31ba7ebda1e0e/examples/cluster/plot_segmentation_toy.py | 258 | 3336 | """
===========================================
Spectral clustering for image segmentation
===========================================
In this example, an image with connected circles is generated and
spectral clustering is used to separate the circles.
In these settings, the :ref:`spectral_clustering` approach solve... | bsd-3-clause |
sfcta/synthpop | demos/sfcta/synthesize_sfcta.py | 2 | 4155 |
# coding: utf-8
from sfcta_starter import SFCTAStarter
from sfcta_starter_hh import SFCTAStarterHouseholds
from sfcta_starter_gq import SFCTAStarterGroupQuarters
from synthpop.synthesizer import synthesize_all, enable_logging
import pandas as pd
import argparse
import os
import re
import sys
if __name__=='__main__'... | bsd-3-clause |
huongttlan/statsmodels | statsmodels/regression/tests/test_lme.py | 19 | 25081 | import warnings
import numpy as np
import pandas as pd
from statsmodels.regression.mixed_linear_model import MixedLM, MixedLMParams
from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
dec, assert_)
from . import lme_r_results
from statsmodels.base import _penalties ... | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.