repo_name
stringlengths
7
90
path
stringlengths
5
191
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
976
581k
license
stringclasses
15 values
chebee7i/twitter
scripts/rates.py
1
2320
""" Plot tweet rates. """ import operator from collections import OrderedDict import twitterproj import json import matplotlib.pyplot as plt import numpy as np import seaborn def user_rates(ax=None): if ax is None: ax = plt.gca() rates = twitterproj.tweet_rates__users() import json with open(...
unlicense
rishikksh20/scikit-learn
benchmarks/bench_plot_neighbors.py
101
6469
""" Plot the scaling of the nearest neighbors algorithms with k, D, and N """ from time import time import numpy as np import matplotlib.pyplot as plt from matplotlib import ticker from sklearn import neighbors, datasets def get_data(N, D, dataset='dense'): if dataset == 'dense': np.random.seed(0) ...
bsd-3-clause
nasa/CrisisMappingToolkit
bin/lake_measure.py
1
25777
# ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache #...
apache-2.0
pmelchior/shear-stacking-tests
shear_stacking.py
2
16172
import numpy as np from math import pi, sqrt import os, fitsio def skyAngle(ra, dec, ra_ref, dec_ref): # CAUTION: this needs to be a pseudo-Cartesian coordinate frame # (not pure RA/DEC), otherwise angles are skewed return np.arctan2(dec-dec_ref, (ra-ra_ref)*np.cos(dec*pi/180)) def skyDistance(ra, dec, ra...
mit
awanke/bokeh
bokeh/charts/builder/line_builder.py
43
5360
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the Line class which lets you build your Line charts just passing the arguments to the Chart class and calling the proper functions. """ #-----------------------------------------------------------------...
bsd-3-clause
vidalalcala/ml-tools
mltools/metrics.py
1
4159
import sklearn.metrics import numpy as np import xgboost import pandas as pd import rpy2.robjects.packages as packages import rpy2.robjects.pandas2ri as pandas2ri import matplotlib matplotlib.use('Agg') import matplotlib.backends.backend_pdf as backend_pdf import seaborn # R import and interfaces p_roc = packages.impo...
mit
joshloyal/scikit-learn
sklearn/tree/tests/test_tree.py
12
60577
""" Testing for the tree module (sklearn.tree). """ import copy import pickle from functools import partial from itertools import product import struct import numpy as np from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from sklearn.random_projection import s...
bsd-3-clause
billy-inn/scikit-learn
doc/sphinxext/numpy_ext/docscrape_sphinx.py
408
8061
import re import inspect import textwrap import pydoc from .docscrape import NumpyDocString from .docscrape import FunctionDoc from .docscrape import ClassDoc class SphinxDocString(NumpyDocString): def __init__(self, docstring, config=None): config = {} if config is None else config self.use_plots...
bsd-3-clause
mikebenfield/scikit-learn
examples/classification/plot_lda_qda.py
32
5381
""" ==================================================================== Linear and Quadratic Discriminant Analysis with covariance ellipsoid ==================================================================== This example plots the covariance ellipsoids of each class and decision boundary learned by LDA and QDA. The...
bsd-3-clause
dsullivan7/scikit-learn
sklearn/feature_selection/tests/test_base.py
170
3666
import numpy as np from scipy import sparse as sp from nose.tools import assert_raises, assert_equal from numpy.testing import assert_array_equal from sklearn.base import BaseEstimator from sklearn.feature_selection.base import SelectorMixin from sklearn.utils import check_array class StepSelector(SelectorMixin, Ba...
bsd-3-clause
sinhrks/japandas
doc/source/conf.py
1
8760
# -*- coding: utf-8 -*- # # japandas documentation build configuration file, created by # sphinx-quickstart on Sun Feb 8 19:30:56 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
bsd-3-clause
holsety/tushare
tushare/datayes/future.py
17
1740
# -*- coding:utf-8 -*- """ 通联数据 Created on 2015/08/24 @author: Jimmy Liu @group : waditu @contact: jimmysoa@sina.cn """ from pandas.compat import StringIO import pandas as pd from tushare.util import vars as vs from tushare.util.common import Client from tushare.util import upass as up class Future(): def _...
bsd-3-clause
ngoix/OCRF
sklearn/gaussian_process/tests/test_kernels.py
24
11602
"""Testing for kernels for Gaussian processes.""" # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # Licence: BSD 3 clause from collections import Hashable from sklearn.externals.funcsigs import signature import numpy as np from sklearn.gaussian_process.kernels import _approx_fprime from sklearn.metrics...
bsd-3-clause
jorik041/scikit-learn
examples/text/document_classification_20newsgroups.py
222
10500
""" ====================================================== Classification of text documents using sparse features ====================================================== This is an example showing how scikit-learn can be used to classify documents by topics using a bag-of-words approach. This example uses a scipy.spars...
bsd-3-clause
FreeSchoolHackers/data_hacking
data_hacking/simple_stats/simple_stats.py
6
7475
# Contingency Table, Two-way table, Joint Distribution, G-Scores # Going off the reservation here, just couldn't find the right functionality elsewhere # References: http://en.wikipedia.org/wiki/Contingency_table # http://en.wikipedia.org/wiki/G_test (Wikipedia) # http://udel.edu/~mcdonald/stath...
mit
fbagirov/scikit-learn
examples/mixture/plot_gmm_classifier.py
250
3918
""" ================== GMM classification ================== Demonstration of Gaussian mixture models for classification. See :ref:`gmm` for more information on the estimator. Plots predicted labels on both training and held out test data using a variety of GMM classifiers on the iris dataset. Compares GMMs with sp...
bsd-3-clause
MyRookie/SentimentAnalyse
venv/lib/python2.7/site-packages/nltk/draw/dispersion.py
3
1802
# Natural Language Toolkit: Dispersion Plots # # Copyright (C) 2001-2015 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ A utility for displaying lexical dispersion. """ def dispersion_plot(text, words, ignore_case=False, t...
mit
roman-dvorak/SolarForecast
tools/rename.py
1
13299
#!/usr/bin/python import os import datetime import time import ftplib import ConfigParser from datetime import datetime import numpy as np import matplotlib.pyplot as plt import operator from scipy.interpolate import interp1d from array import array import subprocess import Image import pyfits arrA = [] arrB = [] ...
gpl-3.0
calliope-project/calliope
calliope/time/clustering.py
1
17528
""" Copyright (C) since 2013 Calliope contributors listed in AUTHORS. Licensed under the Apache 2.0 License (see LICENSE file). clustering.py ~~~~~~~~~~~~~ Functions to cluster data along the time dimension. """ import numpy as np import pandas as pd import xarray as xr from sklearn.metrics import mean_squared_erro...
apache-2.0
466152112/scikit-learn
sklearn/datasets/tests/test_lfw.py
230
7880
"""This test for the LFW require medium-size data dowloading and processing If the data has not been already downloaded by running the examples, the tests won't run (skipped). If the test are run, the first execution will be long (typically a bit more than a couple of minutes) but as the dataset loader is leveraging ...
bsd-3-clause
carrillo/scikit-learn
examples/classification/plot_digits_classification.py
289
2397
""" ================================ Recognizing hand-written digits ================================ An example showing how the scikit-learn can be used to recognize images of hand-written digits. This example is commented in the :ref:`tutorial section of the user manual <introduction>`. """ print(__doc__) # Autho...
bsd-3-clause
Connexions/cnx-mathml2svg
tests.py
2
9765
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import os import unittest from pyramid import httpexceptions from pyramid import testing as pyramid_testin...
agpl-3.0
d00d/quantNotebooks
Notebooks/strategies/from quantopian.algorithm import attach_pipeline,.py
1
4644
from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import CustomFactor, SimpleMovingAverage from quantopian.pipeline.data import morningstar import pandas as pd import n...
unlicense
beepee14/scikit-learn
sklearn/preprocessing/tests/test_data.py
71
38516
import warnings import numpy as np import numpy.linalg as la from scipy import sparse from distutils.version import LooseVersion from sklearn.utils.testing import assert_almost_equal, clean_warning_registry from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal...
bsd-3-clause
simmimourya1/cyvlfeat
cyvlfeat/sift/plotsiftdescriptor.py
1
7655
import math import numpy as np from numpy import newaxis from numpy import matlib from matplotlib import collections as mc from matplotlib import pyplot as plt from cyvlfeat.utils import utils as utils def plotsiftdescriptor(d, f=None, magnification=3.0, num_spatial_bins=4, num_orientation_bins=8, max_value=0): r...
bsd-2-clause
lo-co/atm-py
atmPy/for_removal/miniSASP/miniSASP.py
6
46804
# -*- coding: utf-8 -*- """ Created on Thu Mar 19 21:23:22 2015 @author: htelg """ import warnings import numpy as np import pandas as pd import pylab as plt from scipy import stats from atmPy.tools import array_tools, plt_tools from atmPy.tools import math_linear_algebra as mla # from scipy impor...
mit
RayMick/scikit-learn
sklearn/cluster/setup.py
263
1449
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD 3 clause 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 cblas_libs, blas_info = ...
bsd-3-clause
rs2/pandas
pandas/tests/series/methods/test_isin.py
2
2751
import numpy as np import pytest import pandas as pd from pandas import Series, date_range import pandas._testing as tm class TestSeriesIsIn: def test_isin(self): s = Series(["A", "B", "C", "a", "B", "B", "A", "C"]) result = s.isin(["A", "C"]) expected = Series([True, False, True, False,...
bsd-3-clause
kraemerd17/kraemerd17.github.io
static/files/brownian/brownian.py
1
1492
# tools for numerical computation and basic plotting import numpy as np from scipy.stats import gaussian_kde import matplotlib.pyplot as plt # seaborn is for improving the aesthetic of matplotlib's default # plotting it's also a pretty powerful statistical plotting # library, which we do not take advantage of here ...
mit
terrycojones/dark-matter
dark/graphics.py
2
37967
import os from copy import deepcopy from stat import S_ISDIR from math import ceil from collections import defaultdict from time import ctime, time from textwrap import fill try: import matplotlib if not os.environ.get('DISPLAY'): # Use non-interactive Agg backend matplotlib.use('Agg') impo...
mit
scenarios/tensorflow
tensorflow/examples/learn/iris.py
19
1651
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
apache-2.0
ClimbsRocks/scikit-learn
examples/feature_selection/plot_f_test_vs_mi.py
75
1647
""" =========================================== Comparison of F-test and mutual information =========================================== This example illustrates the differences between univariate F-test statistics and mutual information. We consider 3 features x_1, x_2, x_3 distributed uniformly over [0, 1], the targ...
bsd-3-clause
BeiLuoShiMen/nupic
examples/opf/clients/hotgym/anomaly/one_gym/nupic_anomaly_output.py
49
9450
# ---------------------------------------------------------------------- # 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 apply: # # This progra...
agpl-3.0
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/pandas/core/groupby.py
3
146721
import types from functools import wraps import numpy as np import datetime import collections import warnings import copy from textwrap import dedent from pandas.compat import ( zip, range, lzip, callable, map ) from pandas import compat from pandas.compat.numpy import function as nv, _np_version_under1p8 fr...
mit
thunderhoser/GewitterGefahr
gewittergefahr/scripts/find_normalization_params_test.py
1
13957
"""Unit tests for find_normalization_params.py.""" import copy import unittest import numpy import pandas from gewittergefahr.deep_learning import deep_learning_utils as dl_utils from gewittergefahr.scripts import find_normalization_params as find_norm_params TOLERANCE = 1e-6 # The following constants are used to te...
mit
anurag313/scikit-learn
sklearn/neighbors/tests/test_ball_tree.py
159
10196
import pickle import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.neighbors.ball_tree import (BallTree, NeighborsHeap, simultaneous_sort, kernel_norm, nodeheap_sort, DTYPE, ITYPE) from sklearn.neighbors.dis...
bsd-3-clause
ashutoshvt/psi4
psi4/driver/diatomic.py
1
11372
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
lgpl-3.0
yavalvas/yav_com
build/matplotlib/examples/event_handling/lasso_demo.py
9
2365
""" Show how to use a lasso to select a set of points and get the indices of the selected points. A callback is used to change the color of the selected points This is currently a proof-of-concept implementation (though it is usable as is). There will be some refinement of the API. """ from matplotlib.widgets import...
mit
Windy-Ground/scikit-learn
examples/linear_model/plot_sgd_weighted_samples.py
344
1458
""" ===================== SGD: Weighted samples ===================== Plot decision function of a weighted dataset, where the size of points is proportional to its weight. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # we create 20 points np.random.seed(0) X ...
bsd-3-clause
astropy/astropy
astropy/visualization/wcsaxes/tests/test_grid_paths.py
6
1050
import numpy as np import pytest from matplotlib.lines import Path from astropy.visualization.wcsaxes.grid_paths import get_lon_lat_path @pytest.mark.parametrize('step_in_degrees', [10, 1, 0.01]) def test_round_trip_visibility(step_in_degrees): zero = np.zeros(100) # The pixel values are irrelevant for this...
bsd-3-clause
SMTorg/smt
smt/problems/tests/test_problem_examples.py
3
7369
import unittest import matplotlib import matplotlib.pyplot matplotlib.use("Agg") matplotlib.pyplot.switch_backend("Agg") class Test(unittest.TestCase): def test_cantilever_beam(self): import numpy as np import matplotlib.pyplot as plt from smt.problems import CantileverBeam ndi...
bsd-3-clause
JsNoNo/scikit-learn
sklearn/linear_model/tests/test_least_angle.py
98
20870
from nose.tools import assert_equal import numpy as np from scipy import linalg from sklearn.cross_validation import train_test_split from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_less from sklearn.utils.testing impor...
bsd-3-clause
SylvioL/PHYMOBAT
Precision_moba.py
1
8682
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of PHYMOBAT 1.2. # Copyright 2016 Sylvio Laventure (IRSTEA - UMR TETIS) # # PHYMOBAT 1.2 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, eit...
gpl-3.0
simontorres/bravo
gui/gui_con_pdm_play.py
1
7734
#import sys import matplotlib matplotlib.use('QT4Agg') from matplotlib.widgets import Button import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import UnivariateSpline from matplotlib.widgets import MultiCursor import os import argparse from astropy.stats import LombScargle def get_args(argu...
gpl-3.0
chris-chris/tensorflow
tensorflow/contrib/learn/python/learn/tests/dataframe/in_memory_source_test.py
62
3960
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
apache-2.0
kthyng/tracpy
tracpy/tools.py
1
18989
""" Tools for dealing with drifter stuff. Functions include: * interpolate2d * interpolate3d * find_final * convert_indices * check_points * seed """ import numpy as np from scipy import ndimage import time import matplotlib.tri as mtri # from matplotlib.mlab import Path, find from matplotlib.path import Path def ...
mit
louispotok/pandas
pandas/tests/indexes/timedeltas/test_construction.py
3
3568
import pytest import numpy as np from datetime import timedelta import pandas as pd import pandas.util.testing as tm from pandas import TimedeltaIndex, timedelta_range, to_timedelta class TestTimedeltaIndex(object): def test_construction_base_constructor(self): arr = [pd.Timedelta('1 days'), pd.NaT, pd...
bsd-3-clause
heyfaraday/CMB_test
planck_viewer.py
1
1097
import matplotlib.pyplot as plt import numpy as np import healpy as hp map_I = hp.read_map('data/COM_CMB_IQU-smica_1024_R2.02_full.fits') hp.mollview(map_I, norm='hist', min=-0.1, max=0.1, xsize=2000) plt.show() map_Q = hp.read_map('data/COM_CMB_IQU-smica_1024_R2.02_full.fits', field=1) hp.mollview(map_Q, norm='hist...
mit
kaichogami/scikit-learn
sklearn/ensemble/tests/test_bagging.py
34
25693
""" Testing for the bagging ensemble module (sklearn.ensemble.bagging). """ # Author: Gilles Louppe # License: BSD 3 clause import numpy as np from sklearn.base import BaseEstimator from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.te...
bsd-3-clause
oscarbranson/latools
Supplement/comparison_tools/plots_zircon.py
1
2913
import re import numpy as np import matplotlib.pyplot as plt from scipy import stats from .stats import fmt_RSS from .plots import rangecalcx, bland_altman, get_panel_bounds def fmt_el(el): e = re.match('.*?([A-z]+).*?', el).groups()[0] m = re.match('.*?([0-9]+).*?', el).groups()[0] return e + m def bland...
mit
ankurankan/scikit-learn
examples/classification/plot_classification_probability.py
242
2624
""" =============================== Plot classification probability =============================== Plot the classification probability for different classifiers. We use a 3 class dataset, and we classify it with a Support Vector classifier, L1 and L2 penalized logistic regression with either a One-Vs-Rest or multinom...
bsd-3-clause
captiosus/treadmill
treadmill/reports.py
1
10706
"""Handles reports over scheduler data.""" from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import time import datetime import itertools import logging import fnmatch import numpy as np import pandas as pd import six...
apache-2.0
oaklandanalytics/cutting_board
scripts/fetch_buildings.py
1
1841
import geopandas as gpd import osmnx import time import sys import numpy as np args = sys.argv[1:] juris = args[0] # this is nasty - these are cities without building footprints in OSM # that crashes osmnx (at the time of this writing) - so we switch to a # city that doesn't crash and the joins will fail in the next ...
bsd-3-clause
kedz/cuttsum
trec2014/python/cuttsum/salience.py
1
18804
import os import re import gzip import pandas as pd from cuttsum.data import get_resource_manager, MultiProcessWorker from cuttsum.misc import ProgressBar import random import GPy import numpy as np from collections import defaultdict import multiprocessing import signal import sys import Queue from sklearn.preprocessi...
apache-2.0
nguyentu1602/statsmodels
statsmodels/sandbox/nonparametric/kde2.py
34
3158
# -*- coding: utf-8 -*- from __future__ import print_function from statsmodels.compat.python import lzip, zip import numpy as np from . import kernels #TODO: should this be a function? class KDE(object): """ Kernel Density Estimator Parameters ---------- x : array-like N-dimensional array...
bsd-3-clause
jeffschulte/protein
pyplots/single-image-creation.py
2
3203
from __future__ import division import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os import sys import time import file_loader as load import Image import math import re f_shape = sys.argv[1] f_param1 = sys.argv[2] f_param2 = sys.argv[3] f_param3 = sys.argv[4] f_param4 =...
mit
jreback/pandas
pandas/tests/arrays/categorical/test_algos.py
6
2589
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("ordered", [True, False]) @pytest.mark.parametrize("categories", [["b", "a", "c"], ["a", "b", "c", "d"]]) def test_factorize(categories, ordered): cat = pd.Categorical( ["b", "b", "a", "c", None], c...
bsd-3-clause
jeepsterboy/waveletanalysis
wavelets_bams/tests/test_wavelets.py
1
10164
from __future__ import division from nose.tools import * import numpy.testing as npt import numpy as np import scipy.signal from scipy.io import wavfile import matplotlib.pyplot as plt import wavelets from wavelets import WaveletAnalysis __all__ = ['test_N', 'compare_cwt', 'compare_morlet', 'test_Cd', 't...
mit
andrewcbennett/iris
docs/iris/example_code/General/projections_and_annotations.py
6
5249
""" Plotting in different projections ================================= This example shows how to overlay data and graphics in different projections, demonstrating various features of Iris, Cartopy and matplotlib. We wish to overlay two datasets, defined on different rotated-pole grids. To display both together, we m...
gpl-3.0
gpersistence/tstop
scripts/bar_plot_from_csv.py
1
2145
#TSTOP # #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 License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, ...
gpl-3.0
robbymeals/scikit-learn
examples/linear_model/plot_lasso_coordinate_descent_path.py
254
2639
""" ===================== Lasso and Elastic Net ===================== Lasso and elastic net (L1 and L2 penalisation) implemented using a coordinate descent. The coefficients can be forced to be positive. """ print(__doc__) # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD 3 clause import num...
bsd-3-clause
chenyyx/scikit-learn-doc-zh
examples/en/linear_model/plot_omp.py
385
2263
""" =========================== Orthogonal Matching Pursuit =========================== Using orthogonal matching pursuit for recovering a sparse signal from a noisy measurement encoded with a dictionary """ print(__doc__) import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import OrthogonalM...
gpl-3.0
bnaul/scikit-learn
sklearn/tests/test_isotonic.py
3
18868
import warnings import numpy as np import pickle import copy import pytest from sklearn.isotonic import (check_increasing, isotonic_regression, IsotonicRegression, _make_unique) from sklearn.utils.validation import check_array from sklearn.utils._testing import (assert_raises, assert_al...
bsd-3-clause
ephes/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
wolfiex/ropacode
revamp/ropa_tool.py
1
2766
''' A tool to calculate the fluxes from DSMACC D.Ellis 2016 ''' #functions global specs,reactants xlen = lambda x: xrange(len(x)) def getcoef (x): # '''gets specie coefficients from data''' try: return int(re.sub(r'([\.\d]*)\s*\D[\d\D]*', r'\1', x)) except: return 1 #assume coeff are Z+ def getspec (x)...
cc0-1.0
amandersillinois/landlab
landlab/components/chi_index/channel_chi.py
3
27201
# -*- coding: utf-8 -*- """Created March 2016. @author: dejh """ import numpy as np from landlab import Component, RasterModelGrid try: from itertools import izip except ImportError: izip = zip class ChiFinder(Component): """Calculate Chi Indices. This component calculates chi indices, sensu Per...
mit
ml-playground/data-science-from-scratch
code/nearest_neighbors.py
57
7357
from __future__ import division from collections import Counter from linear_algebra import distance from statistics import mean import math, random import matplotlib.pyplot as plt def raw_majority_vote(labels): votes = Counter(labels) winner, _ = votes.most_common(1)[0] return winner def majority_vote(lab...
unlicense
Fireblend/chromium-crosswalk
chrome/test/data/nacl/gdb_rsp.py
99
2431
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This file is based on gdb_rsp.py file from NaCl repository. import re import socket import time def RspChecksum(data): checksum = 0 for char in ...
bsd-3-clause
glouppe/scikit-learn
sklearn/gaussian_process/tests/test_kernels.py
23
11813
"""Testing for kernels for Gaussian processes.""" # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # Licence: BSD 3 clause from collections import Hashable from sklearn.externals.funcsigs import signature import numpy as np from scipy.optimize import approx_fprime from sklearn.metrics.pairwise \ imp...
bsd-3-clause
zhoulingjun/zipline
zipline/finance/trading.py
15
19380
# # Copyright 2014 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
apache-2.0
hainm/statsmodels
statsmodels/sandbox/distributions/examples/matchdist.py
33
9822
'''given a 1D sample of observation, find a matching distribution * estimate maximum likelihood paramater for each distribution * rank estimated distribution by Kolmogorov-Smirnov and Anderson-Darling test statistics Author: Josef Pktd License: Simplified BSD original December 2008 TODO: * refactor to result clas...
bsd-3-clause
AlexRobson/scikit-learn
sklearn/setup.py
225
2856
import os from os.path import join import warnings def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError import numpy libraries = [] if os.name == 'posix': libraries.appe...
bsd-3-clause
tonysyu/mpltools
mpltools/sphinx/plot2rst.py
2
20147
""" Generate reStructuredText example from python files. Generate the rst files for the examples by iterating over the python example files. Files that generate images should start with 'plot'. To generate your own examples, add ``'mpltools.sphinx.plot2rst'`` to the list of ``extensions`` in your Sphinx configuration...
bsd-3-clause
siutanwong/scikit-learn
examples/exercises/plot_cv_digits.py
232
1206
""" ============================================= Cross-validation on Digits Dataset Exercise ============================================= A tutorial exercise using Cross-validation with an SVM on the Digits dataset. This exercise is used in the :ref:`cv_generators_tut` part of the :ref:`model_selection_tut` section...
bsd-3-clause
tody411/ImageViewerFramework
ivf/batch/segmentation.py
1
4213
# -*- coding: utf-8 -*- ## @package ivf.batch.segmentation # # ivf.batch.segmentation utility package. # @author tody # @date 2016/02/15 import numpy as np import cv2 import matplotlib.pyplot as plt from PyQt4.QtGui import * from PyQt4.QtCore import * import sys import os from ivf.batch.batch import ...
mit
bigdataelephants/scikit-learn
examples/manifold/plot_manifold_sphere.py
258
5101
#!/usr/bin/python # -*- coding: utf-8 -*- """ ============================================= Manifold Learning methods on a severed sphere ============================================= An application of the different :ref:`manifold` techniques on a spherical data-set. Here one can see the use of dimensionality reducti...
bsd-3-clause
edux300/research
script_full_images_view.py
1
16557
# -*- coding: utf-8 -*- """ Created on Thu Aug 10 13:22:54 2017 @author: eduardo """ from matplotlib import pyplot as plt import dicom as dcm import pickle as pkl import read_inbreast as readin import scipy import scipy.ndimage import cnn_models as models import tensorflow as tf import numpy as np import utils as ut ...
apache-2.0
bigfootproject/OSMEF
data_processing/graphs/jain.py
1
1315
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import json data = json.load(open("../../osmef/data.json")) N = 6 MS = 10 #xpoints = (1, 5, 10, 20, 30, 50) xpoints = (1, 5, 10, 15, 20, 25, 30, 35, 40, 50) def calc_jain(values): return (sum(values)**2)/(len(values)*sum(values**2)) fig = pl...
apache-2.0
buncem/deep-learning
image-classification/helper.py
155
5631
import pickle import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import LabelBinarizer def _load_label_names(): """ Load the label names from file """ return ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] def load_cfar10_batch(ci...
mit
dopplershift/MetPy
tests/plots/test_declarative.py
1
41498
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test the simplified plotting interface.""" from datetime import datetime, timedelta from io import BytesIO import warnings import matplotlib import numpy as np import pandas ...
bsd-3-clause
shenzebang/scikit-learn
sklearn/utils/tests/test_sparsefuncs.py
157
13799
import numpy as np import scipy.sparse as sp from scipy import linalg from numpy.testing import assert_array_almost_equal, assert_array_equal from sklearn.datasets import make_classification from sklearn.utils.sparsefuncs import (mean_variance_axis, inplace_column_scale, ...
bsd-3-clause
muxiaobai/CourseExercises
python/kaggle/competition/house-price/house_price.py
1
8403
# coding: utf-8 # # 房价预测案例 # # ## Step 1: 检视源数据集 # In[5]: import numpy as np import pandas as pd # #### 读入数据 # # * 一般来说源数据的index那一栏没什么用,我们可以用来作为我们pandas dataframe的index。这样之后要是检索起来也省事儿。 # # * 有人的地方就有鄙视链。跟知乎一样。Kaggle的也是个处处呵呵的危险地带。Kaggle上默认把数据放在*input*文件夹下。所以我们没事儿写个教程什么的,也可以依据这个convention来,显得自己很有逼格。。 # In[6]: ...
gpl-2.0
arashzamani/lstm_nlg_ver1
test_cases/embedding_al1.py
1
3778
import collections import operator import numpy import random import sys from keras.layers import Dense, Activation, Dropout, Embedding, LSTM, Input from keras.layers.recurrent import GRU from keras.models import Sequential from keras.wrappers.scikit_learn import KerasRegressor from keras.utils import np_utils from sk...
gpl-3.0
CVML/scikit-learn
sklearn/qda.py
140
7682
""" Quadratic Discriminant Analysis """ # Author: Matthieu Perrot <matthieu.perrot@gmail.com> # # License: BSD 3 clause import warnings import numpy as np from .base import BaseEstimator, ClassifierMixin from .externals.six.moves import xrange from .utils import check_array, check_X_y from .utils.validation import ...
bsd-3-clause
akionakamura/scikit-learn
examples/decomposition/plot_kernel_pca.py
353
2011
""" ========== Kernel PCA ========== This example shows that Kernel PCA is able to find a projection of the data that makes data linearly separable. """ print(__doc__) # Authors: Mathieu Blondel # Andreas Mueller # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.decomp...
bsd-3-clause
anntzer/scikit-learn
sklearn/feature_selection/tests/test_chi2.py
19
2987
""" Tests for chi2, currently the only feature selection function designed specifically to work with sparse matrices. """ import warnings import numpy as np import pytest from scipy.sparse import coo_matrix, csr_matrix import scipy.stats from sklearn.feature_selection import SelectKBest, chi2 from sklearn.feature_se...
bsd-3-clause
amolkahat/pandas
pandas/plotting/_core.py
2
128319
# being a bit too dynamic # pylint: disable=E1101 from __future__ import division import warnings import re from collections import namedtuple from distutils.version import LooseVersion import numpy as np from pandas.util._decorators import cache_readonly, Appender from pandas.compat import range, lrange, map, zip, ...
bsd-3-clause
jkorell/PTVS
Python/Product/Analyzer/BuiltinScraperTests.py
18
18954
# ############################################################################ # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution....
apache-2.0
rohit21122012/DCASE2013
runs/2016/baseline64/task1_scene_classification.py
6
34635
#!/usr/bin/env python # -*- coding: utf-8 -*- # # DCASE 2016::Acoustic Scene Classification / Baseline System from src.ui import * from src.general import * from src.files import * from src.features import * from src.dataset import * from src.evaluation import * import numpy import csv import argparse import textwra...
mit
hbar/python-BeamDynamicsTools
applications/Trajectory-BFieldRippleStudy.py
1
7085
import sys sys.path.append('../lib/') from BeamDynamicsTools import * import pylab as pl import matplotlib as mpl # Define array of injection angles # (x,y,z) = (1.798m, -0.052m, 0.243m) # alpha = 12.6 degrees (X-Z plane) # beta = 8.0 degrees (X-Y plane) alpha0 = 12.6 beta0 = 8.0 alpha = alpha0/180.0*pi; beta = bet...
mit
kaichogami/scikit-learn
examples/tree/unveil_tree_structure.py
67
4824
""" ========================================= Understanding the decision tree structure ========================================= The decision tree structure can be analysed to gain further insight on the relation between the features and the target to predict. In this example, we show how to retrieve: - the binary t...
bsd-3-clause
joshloyal/scikit-learn
examples/applications/svm_gui.py
124
11251
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create neg...
bsd-3-clause
saiwing-yeung/scikit-learn
examples/ensemble/plot_gradient_boosting_quantile.py
392
2114
""" ===================================================== Prediction Intervals for Gradient Boosting Regression ===================================================== This example shows how quantile regression can be used to create prediction intervals. """ import numpy as np import matplotlib.pyplot as plt from skle...
bsd-3-clause
StartupsPoleEmploi/labonneboite
labonneboite/scripts/impact_retour_emploi/make_report.py
1
12252
import numpy import pandas as pd from labonneboite.conf import settings from labonneboite.importer import util as import_util from labonneboite.importer.jobs.common import logger from labonneboite.importer import settings as importer_settings from labonneboite.scripts.impact_retour_emploi.google_sheets_report import G...
agpl-3.0
davidgbe/scikit-learn
examples/plot_kernel_ridge_regression.py
230
6222
""" ============================================= Comparison of kernel ridge regression and SVR ============================================= Both kernel ridge regression (KRR) and SVR learn a non-linear function by employing the kernel trick, i.e., they learn a linear function in the space induced by the respective k...
bsd-3-clause
q1ang/seaborn
examples/elaborate_violinplot.py
30
1055
""" Violinplot from a wide-form dataset =================================== _thumb: .6, .45 """ import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid") # Load the example dataset of brain network correlations df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) # Pull out a...
bsd-3-clause
ulikoehler/cv_algorithms
cv_algorithms/neighbours.py
1
6843
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Thinning algorithms """ import numpy as np from ._ffi import * from ._checks import * import enum __all__ = ["binary_neighbours", "Neighbours", "Direction"] _ffi.cdef(''' int binary_neighbours(uint8_t* dst, const uint8_t* src, int width, int height); ''') def binary...
apache-2.0
gevero/deap
examples/coev/coop_evol.py
12
6361
# This file is part of DEAP. # # DEAP 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. # # DEAP is distributed ...
lgpl-3.0
aleksandr-bakanov/astropy
astropy/visualization/wcsaxes/axislabels.py
4
5905
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from matplotlib import rcParams from matplotlib.text import Text import matplotlib.transforms as mtransforms from .frame import RectangularFrame class AxisLabels(Text): def __init__(self, frame, minpad=1, *args, **kwargs): ...
bsd-3-clause
Clyde-fare/scikit-learn
examples/cluster/plot_ward_structured_vs_unstructured.py
320
3369
""" =========================================================== Hierarchical clustering: structured vs unstructured ward =========================================================== Example builds a swiss roll dataset and runs hierarchical clustering on their position. For more information, see :ref:`hierarchical_clus...
bsd-3-clause