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
pianomania/scikit-learn
examples/classification/plot_classification_probability.py
138
2871
""" =============================== 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
luo66/scikit-learn
examples/applications/plot_stock_market.py
227
8284
""" ======================================= Visualizing the stock market structure ======================================= This example employs several unsupervised learning techniques to extract the stock market structure from variations in historical quotes. The quantity that we use is the daily variation in quote ...
bsd-3-clause
mrshu/scikit-learn
examples/ensemble/plot_forest_iris.py
2
3013
""" ==================================================================== Plot the decision surfaces of ensembles of trees on the iris dataset ==================================================================== Plot the decision surfaces of forests of randomized trees trained on pairs of features of the iris dataset. ...
bsd-3-clause
vorasagar7/sp17-i524
project/S17-IO-3012/code/bin/benchmark_version_find.py
19
4572
import matplotlib.pyplot as plt import sys import pandas as pd def get_parm(): """retrieves mandatory parameter to program @param: none @type: n/a """ try: return sys.argv[1] except: print ('Must enter file name as parameter') exit() def read_file(filename): """...
apache-2.0
duthchao/kaggle-galaxies
try_convnet_cc_multirotflip_3x69r45_normconstraint.py
7
17800
import numpy as np # import pandas as pd import theano import theano.tensor as T import layers import cc_layers import custom import load_data import realtime_augmentation as ra import time import csv import os import cPickle as pickle from datetime import datetime, timedelta # import matplotlib.pyplot as plt # plt.i...
bsd-3-clause
lnunno/big-data-uber-viz
nunno/process.py
1
7271
''' Requires: * python3 * pandas - pip3 install pandas Created on Aug 28, 2014 @author: lnunno ''' import json import pandas as pd import os data_dir = 'json/' def filter_uber_df(df, time_of_day=None, day_filters=None, night_begin_hour=17, morning_begin_hour=5): ''' Filter the uber dataset with the given p...
mit
anurag313/scikit-learn
sklearn/neural_network/rbm.py
206
12292
"""Restricted Boltzmann Machine """ # Authors: Yann N. Dauphin <dauphiya@iro.umontreal.ca> # Vlad Niculae # Gabriel Synnaeve # Lars Buitinck # License: BSD 3 clause import time import numpy as np import scipy.sparse as sp from ..base import BaseEstimator from ..base import TransformerMixi...
bsd-3-clause
Adai0808/scikit-learn
benchmarks/bench_plot_omp_lars.py
266
4447
"""Benchmarks of orthogonal matching pursuit (:ref:`OMP`) versus least angle regression (:ref:`least_angle_regression`) The input data is mostly low rank but is a fat infinite tail. """ from __future__ import print_function import gc import sys from time import time import numpy as np from sklearn.linear_model impo...
bsd-3-clause
FluidityStokes/fluidity
examples/tides_in_the_Mediterranean_Sea/Med-tides-probe.py
2
6073
#!/usr/bin/env python3 import vtktools import math from numpy import array u=vtktools.vtu("tidesmedsea-flat.vtu") g = open("Med-GEBCO-5m-gauges-fes2004-O1-102", "w") pts=vtktools.arr([ #[-5.3500, 36.1333, -2.00], #[-4.4500, 36.7000, 0.00], #[-3.9167, 35.2500, 0.00], #[-2.4500, 36.8333, 0.00], #[-0.5833, 38.3333, 0....
lgpl-2.1
abhishekgahlot/scikit-learn
sklearn/feature_selection/rfe.py
10
14074
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Vincent Michel <vincent.michel@inria.fr> # Gilles Louppe <g.louppe@gmail.com> # # License: BSD 3 clause """Recursive feature elimination for feature ranking""" import numpy as np from ..utils import check_X_y, safe_sqr from ..base import ...
bsd-3-clause
ashhher3/scikit-learn
examples/ensemble/plot_adaboost_hastie_10_2.py
355
3576
""" ============================= Discrete versus Real AdaBoost ============================= This example is based on Figure 10.2 from Hastie et al 2009 [1] and illustrates the difference in performance between the discrete SAMME [2] boosting algorithm and real SAMME.R boosting algorithm. Both algorithms are evaluate...
bsd-3-clause
smartscheduling/scikit-learn-categorical-tree
examples/ensemble/plot_forest_importances_faces.py
403
1519
""" ================================================= Pixel importances with a parallel forest of trees ================================================= This example shows the use of forests of trees to evaluate the importance of the pixels in an image classification task (faces). The hotter the pixel, the more impor...
bsd-3-clause
olologin/scikit-learn
sklearn/datasets/__init__.py
72
3807
""" The :mod:`sklearn.datasets` module includes utilities to load datasets, including methods to load and fetch popular reference datasets. It also features some artificial data generators. """ from .base import load_diabetes from .base import load_digits from .base import load_files from .base import load_iris from ....
bsd-3-clause
HIPS/pgmult
pgmult/internals/dirichlet.py
1
4440
""" From Matt's dirichlet-truncated-multinomial repo. """ import numpy as np na = np.newaxis import scipy.special from .simplex import proj_to_2D, mesh def _dirichlet_support_check(x,alpha): x = np.array(x,ndmin=2) alpha = np.array(alpha,ndmin=1) assert alpha.ndim == 1 if len(alpha) == 1: a...
mit
msmbuilder/msmbuilder
msmbuilder/tests/test_agglomerative.py
6
4311
import numpy as np from mdtraj.testing import eq from sklearn.base import clone from sklearn.metrics import adjusted_rand_score from msmbuilder.cluster import LandmarkAgglomerative from msmbuilder.example_datasets import AlanineDipeptide random = np.random.RandomState(2) def test_1(): x = [random.randn(10, 2), ...
lgpl-2.1
mne-tools/mne-tools.github.io
stable/_downloads/911f82913fdceaf692d2bd4584358dcd/50_decoding.py
3
17267
r""" =============== Decoding (MVPA) =============== .. include:: ../../links.inc Design philosophy ================= Decoding (a.k.a. MVPA) in MNE largely follows the machine learning API of the scikit-learn package. Each estimator implements ``fit``, ``transform``, ``fit_transform``, and (optionally) ``inverse_tran...
bsd-3-clause
AtsushiSakai/PythonRobotics
SLAM/GraphBasedSLAM/graphslam/edge/edge_odometry.py
1
5422
# Copyright (c) 2020 Jeff Irion and contributors # # This file originated from the `graphslam` package: # # https://github.com/JeffLIrion/python-graphslam r"""A class for odometry edges. """ import numpy as np import matplotlib.pyplot as plt #: The difference that will be used for numerical differentiation EPSI...
mit
gengliangwang/spark
python/pyspark/sql/tests/test_pandas_udf_typehints.py
22
9603
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
apache-2.0
rishikksh20/scikit-learn
sklearn/decomposition/tests/test_nmf.py
28
17934
import numpy as np import scipy.sparse as sp import numbers from scipy import linalg from sklearn.decomposition import NMF, non_negative_factorization from sklearn.decomposition import nmf # For testing internals from scipy.sparse import csc_matrix from sklearn.utils.testing import assert_true from sklearn.utils.te...
bsd-3-clause
huzq/scikit-learn
sklearn/metrics/_plot/confusion_matrix.py
3
9459
from itertools import product import numpy as np from .. import confusion_matrix from ...utils import check_matplotlib_support from ...utils.validation import _deprecate_positional_args from ...base import is_classifier class ConfusionMatrixDisplay: """Confusion Matrix visualization. It is recommend to use...
bsd-3-clause
yonglehou/scikit-learn
sklearn/cross_validation.py
96
58309
""" The :mod:`sklearn.cross_validation` module includes utilities for cross- validation and performance evaluation. """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>, # Gael Varoquaux <gael.varoquaux@normalesup.org>, # Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause from...
bsd-3-clause
nixingyang/Kaggle-Face-Verification
Claims Management/fine_tune.py
1
5007
from sklearn.cross_validation import StratifiedKFold from xgboost.sklearn import XGBClassifier import numpy as np np.random.seed(666) OBJECTIVE = "binary:logistic" EVAL_METRIC = "logloss" SCORING = "log_loss" GET_BEST_SCORE_INDEX = np.argmin CV_FOLD_NUM = 5 def evaluate_estimator(estimator, X_train, Y_train, early_s...
mit
JosmanPS/scikit-learn
benchmarks/bench_plot_parallel_pairwise.py
297
1247
# Author: Mathieu Blondel <mathieu@mblondel.org> # License: BSD 3 clause import time import pylab as pl from sklearn.utils import check_random_state from sklearn.metrics.pairwise import pairwise_distances from sklearn.metrics.pairwise import pairwise_kernels def plot(func): random_state = check_random_state(0) ...
bsd-3-clause
SeldonIO/seldon-server
python/seldon/pipeline/util.py
2
6887
import seldon.fileutil as fu import json import os.path import logging import shutil import unicodecsv import numpy as np import pandas as pd import random import string from sklearn.externals import joblib import logging from seldon.util import DeprecationHelper logger = logging.getLogger(__name__) class PipelineWr...
apache-2.0
kleinrap/policyemergence
mesa/batchrunner.py
2
6206
# -*- coding: utf-8 -*- """ Batchrunner =========== A single class to manage a batch run or parameter sweep of a given model. """ from itertools import product import pandas as pd from tqdm import tqdm class BatchRunner: """ This class is instantiated with a model class, and model parameters associated with...
gpl-3.0
mattilyra/scikit-learn
sklearn/feature_extraction/dict_vectorizer.py
37
12559
# Authors: Lars Buitinck # Dan Blanchard <dblanchard@ets.org> # License: BSD 3 clause from array import array from collections import Mapping from operator import itemgetter import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..externals import six from ..ext...
bsd-3-clause
Reagankm/KnockKnock
venv/lib/python3.4/site-packages/matplotlib/tests/test_text.py
9
12004
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings import numpy as np from numpy.testing import assert_almost_equal from nose.tools import eq_ from matplotlib.transforms import Bbox import matplotlib import matplotlib.pyplot as plt ...
gpl-2.0
Intel-Corporation/tensorflow
tensorflow/contrib/eager/python/examples/rnn_colorbot/rnn_colorbot.py
9
13792
# Copyright 2017 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
coshx/portfolio_optimizer
backend/optimizer/utils.py
1
1412
"""Given ticker symbols and dates, get stock data from Quandl.""" import Quandl import os import pandas as pd def get_data(params): """Return a pandas data frame with adjusted close data. Args: params (dict): a portfolio of form: {'symbols': ['AAPL', 'FB', 'GOOG'], 'start_da...
mit
jayflo/scikit-learn
sklearn/tree/export.py
75
15670
""" This module defines export functions for decision trees. """ # Authors: Gilles Louppe <g.louppe@gmail.com> # Peter Prettenhofer <peter.prettenhofer@gmail.com> # Brian Holt <bdholt1@gmail.com> # Noel Dawe <noel@dawe.me> # Satrajit Gosh <satrajit.ghosh@gmail.com> # Trevor...
bsd-3-clause
grundgruen/powerline
powerline/data/loader_power.py
2
1488
import pandas as pd from math import pow import numpy as np from zipline.data.loader import ensure_treasury_data __author__ = "Warren" INDEX_MAPPING = { '^GSPC': ('treasuries', 'treasury_curves.csv', 'data.treasury.gov'), '^GSPTSE': ('treasuries_can', 'treasury_curves_can.csv', 'bankofcanada.ca'), ...
apache-2.0
Midnighter/pyorganism
scripts/trn_multiprocessing.py
1
12113
#!/usr/bin/env python # -*- coding: utf-8 from __future__ import (absolute_import, unicode_literals) import os import sys import logging import argparse import multiprocessing import random from logging.config import dictConfig from glob import glob from random import choice import numpy as np import networkx as nx...
bsd-3-clause
Ziqi-Li/bknqgis
pandas/asv_bench/benchmarks/packers.py
6
9228
from .pandas_vb_common import * from numpy.random import randint import pandas as pd from collections import OrderedDict from pandas.compat import BytesIO import sqlite3 import os from sqlalchemy import create_engine import numpy as np from random import randrange class _Packers(object): goal_time = 0.2 def _...
gpl-2.0
Akshay0724/scikit-learn
examples/linear_model/plot_lasso_lars.py
363
1080
#!/usr/bin/env python """ ===================== Lasso path using LARS ===================== Computes Lasso Path along the regularization parameter using the LARS algorithm on the diabetes dataset. Each color represents a different feature of the coefficient vector, and this is displayed as a function of the regulariza...
bsd-3-clause
vermouthmjl/scikit-learn
examples/svm/plot_svm_scale_c.py
44
5405
""" ============================================== Scaling the regularization parameter for SVCs ============================================== The following example illustrates the effect of scaling the regularization parameter when using :ref:`svm` for :ref:`classification <svm_classification>`. For SVC classificati...
bsd-3-clause
jreback/pandas
pandas/tests/extension/base/missing.py
4
4515
import numpy as np import pandas as pd import pandas._testing as tm from .base import BaseExtensionTests class BaseMissingTests(BaseExtensionTests): def test_isna(self, data_missing): expected = np.array([True, False]) result = pd.isna(data_missing) tm.assert_numpy_array_equal(result, e...
bsd-3-clause
jwkvam/conex
bowtie/_component.py
1
10278
"""Bowtie abstract component classes. All visual and control components inherit these. """ from typing import Any, Callable, Optional, ClassVar, Tuple # pylint: disable=unused-import from abc import ABCMeta, abstractmethod import string from functools import wraps import json from datetime import datetime, date, tim...
mit
NumCosmo/NumCosmo
examples/example_Vexp.py
1
4506
#!/usr/bin/env python try: import gi gi.require_version('NumCosmo', '1.0') gi.require_version('NumCosmoMath', '1.0') except: pass import math import matplotlib import matplotlib.pyplot as plt import numpy as np from gi.repository import NumCosmo as Nc from gi.repository import NumCosmoMath as Ncm # # Initia...
gpl-3.0
hugobowne/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
wzbozon/scikit-learn
sklearn/utils/tests/test_utils.py
215
8100
import warnings import numpy as np import scipy.sparse as sp from scipy.linalg import pinv2 from itertools import chain from sklearn.utils.testing import (assert_equal, assert_raises, assert_true, assert_almost_equal, assert_array_equal, SkipTest, ...
bsd-3-clause
asoliveira/NumShip
scripts/plot/acel-u-cg-plt.py
1
2317
#!/usr/bin/env python # -*- coding: utf-8 -*- #É adimensional? adi = False #É para salvar as figuras(True|False)? save = True #Caso seja para salvar, qual é o formato desejado? formato = 'jpg' #Caso seja para salvar, qual é o diretório que devo salvar? dircg = 'fig-sen' #Caso seja para salvar, qual é o nome do arquivo...
gpl-3.0
andyraib/data-storage
python_scripts/env/lib/python3.6/site-packages/pandas/tools/tests/test_merge_ordered.py
7
3401
import nose import pandas as pd from pandas import DataFrame, merge_ordered from pandas.util import testing as tm from pandas.util.testing import assert_frame_equal from numpy import nan class TestOrderedMerge(tm.TestCase): def setUp(self): self.left = DataFrame({'key': ['a', 'c', 'e'], ...
apache-2.0
WesleyAC/toybox
learning/mnist.py
1
1356
import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.optimizers import Adam from keras.datasets import mnist from matplotlib import pyplot as plt np.random.s...
mit
Milias/FinancialStuff
Homeworks/hw3/python/plot-data.py
4
3103
#!/bin/python # -*- coding: utf-8 -*- from numpy import * import matplotlib.pyplot as plt f_line = lambda x, a, b: a*(1-x)+b*x def oP_X_plot(name, title, symbol): Xcall = loadtxt('../data/%s_%s_x.txt' % (name, 'call'), delimiter=',') Ycall = loadtxt('../data/%s_%s_mean.txt' % (name, 'call'), delimiter=',...
mit
matthew-tucker/mne-python
mne/preprocessing/tests/test_ica.py
4
23046
from __future__ import print_function # Author: Denis Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import os import os.path as op import warnings from nose.tools import assert_true, assert_raises, assert_equal from copy import ...
bsd-3-clause
ronalcc/zipline
zipline/finance/risk/period.py
17
11952
# # Copyright 2013 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
annayqho/TheCannon
code/lamost/mass_age/cn/xval.py
1
5415
import numpy as np import glob import matplotlib.pyplot as plt import sys import pyfits from TheCannon import dataset from TheCannon import model from TheCannon import lamost from astropy.table import Table from matplotlib.colors import LogNorm from matplotlib import rc rc('font', family='serif') rc('text', usetex=True...
mit
xguse/bokeh
bokeh/util/serialization.py
31
7419
""" Functions for helping with serialization and deserialization of Bokeh objects. """ from __future__ import absolute_import from six import iterkeys is_numpy = None try: import numpy as np is_numpy = True except ImportError: is_numpy = False try: import pandas as pd is_pandas = True except Im...
bsd-3-clause
KennethPierce/pylearnk
pylearn2/cross_validation/tests/test_cross_validation.py
49
6767
""" Tests for cross-validation module. """ import os import tempfile from pylearn2.config import yaml_parse from pylearn2.testing.skip import skip_if_no_sklearn def test_train_cv(): """Test TrainCV class.""" skip_if_no_sklearn() handle, layer0_filename = tempfile.mkstemp() handle, layer1_filename = t...
bsd-3-clause
tacaswell/bokeh
bokeh/charts/_data_adapter.py
43
8802
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the ChartObject class, a minimal prototype class to build more chart types on top of it. It provides the mechanisms to support the shared chained methods. """ #-------------------------------------------...
bsd-3-clause
bzamecnik/sms-tools
lectures/05-Sinusoidal-model/plots-code/spectral-peaks-interpolation.py
1
1107
# matplotlib without any blocking GUI import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np from smst.utils import audio, peaks from smst.models import dft (fs, x) = audio.read_wav('../../../sounds/oboe-A4.wav') N = 512 * 2 M = 511 t = -60 w = np.hamming(M) start = .8 * fs hN = N...
agpl-3.0
aleju/ImageAugmenter
setup.py
2
3821
# pylint: disable=missing-module-docstring import re from pkg_resources import get_distribution, DistributionNotFound from setuptools import setup, find_packages long_description = """A library for image augmentation in machine learning experiments, particularly convolutional neural networks. Supports the augmentatio...
mit
sinhrks/expandas
pandas_ml/skaccessors/test/test_tree.py
2
2127
#!/usr/bin/env python import pytest import sklearn.datasets as datasets import sklearn.tree as tree import pandas_ml as pdml import pandas_ml.util.testing as tm class TestTree(tm.TestCase): def test_objectmapper(self): df = pdml.ModelFrame([]) self.assertIs(df.tree.DecisionTreeCla...
bsd-3-clause
sheabrown/faraday_complexity
final/tmp/cutoff_plots.py
2
8108
from __future__ import print_function from keras.models import Model from keras.layers import Activation, Dense, Dropout, Flatten, Input from keras.layers import concatenate from keras.layers import Conv1D, MaxPooling1D from keras.utils import plot_model from loadData import * import sys from keras.models import model_...
mit
rmatam/Deep-Learning
01.Python/14.pandas.py
1
1044
# -*- coding: utf-8 -*- """ Created on Mon Mar 27 13:59:06 2017 @author: rmatam """ import numpy as np import pandas as pd import os import seaborn as sns s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) s2=pd.Series(np.random.randn(10),index=['a','ab','abc','abcd','abcde','ax','axb'...
apache-2.0
yunque/sms-tools
lectures/05-Sinusoidal-model/plots-code/sine-analysis-synthesis.py
22
1543
import numpy as np import matplotlib.pyplot as plt from scipy.signal import hamming, triang, blackmanharris import sys, os, functools, time from scipy.fftpack import fft, ifft, fftshift sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/')) import dftModel as DFT import ...
agpl-3.0
davidgbe/scikit-learn
sklearn/ensemble/tests/test_forest.py
5
35292
""" Testing for the forest module (sklearn.ensemble.forest). """ # Authors: Gilles Louppe, # Brian Holt, # Andreas Mueller, # Arnaud Joly # License: BSD 3 clause import pickle from collections import defaultdict from itertools import product import numpy as np from scipy.sparse import csr_...
bsd-3-clause
yipenggao/moose
modules/porous_flow/doc/tests/radialinjection.py
5
4190
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np # # The two phase radial injection problem has a similarity solution (r^2/t) # # Read MOOSE simulation data for constant time (tdata) and constant # radial distance (rdata) tdata = np.genfromtxt('../../tests/dirackernels/theis3_line_0016.csv', d...
lgpl-2.1
andaag/scikit-learn
sklearn/calibration.py
137
18876
"""Calibration of predicted probabilities.""" # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Balazs Kegl <balazs.kegl@gmail.com> # Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # Mathieu Blondel <mathieu@mblondel.org> # # License: BSD 3 clause from __future__ impo...
bsd-3-clause
gfyoung/pandas
pandas/tests/groupby/test_nth.py
3
20252
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna import pandas._testing as tm def test_first_last_nth(df): # tests for first / last / nth grouped = df.groupby("A") first = grouped.first() expected = df.loc[[1, 0], ["B", "C",...
bsd-3-clause
Windy-Ground/scikit-learn
examples/svm/plot_oneclass.py
249
2302
""" ========================================== One-class SVM with non-linear kernel (RBF) ========================================== An example using a one-class SVM for novelty detection. :ref:`One-class SVM <svm_outlier_detection>` is an unsupervised algorithm that learns a decision function for novelty detection: ...
bsd-3-clause
nesterione/scikit-learn
examples/model_selection/plot_validation_curve.py
229
1823
""" ========================== 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
nomadcube/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py
221
5517
""" Testing for the gradient boosting loss functions and initial estimators. """ import numpy as np from numpy.testing import assert_array_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_equal from nose.tools import assert_raises from sklearn.utils import check_random_state from ...
bsd-3-clause
Don86/microscopium
tests/test_metrics.py
1
1784
from microscopium import metrics import time import numpy as np import os import pandas as pd from pymongo import MongoClient import subprocess as sp abspath = os.path.dirname(__file__) def string2tuple(string_tuple): # TODO add docstring string_values = string_tuple.split(', ') coords = (int(string_value...
bsd-3-clause
ehocchen/trading-with-python
lib/vixFutures.py
79
4157
# -*- coding: utf-8 -*- """ set of tools for working with VIX futures @author: Jev Kuznetsov Licence: GPL v2 """ import datetime as dt from pandas import * import os import urllib2 #from csvDatabase import HistDataCsv m_codes = dict(zip(range(1,13),['F','G','H','J','K','M','N','Q','U','V','X','Z'])) #m...
bsd-3-clause
nhuntwalker/astroML
book_figures/chapter10/fig_LINEAR_clustering.py
3
9133
""" Clustering of LINEAR data ------------------------- Figure 10.20 ~~~~~~~~~~~~ Unsupervised clustering analysis of periodic variable stars from the LINEAR data set. The top row shows clusters derived using two attributes (g - i and log P) and a mixture of 12 Gaussians. The colorized symbols mark the five most signif...
bsd-2-clause
mblondel/scikit-learn
examples/decomposition/plot_ica_vs_pca.py
43
3343
""" ========================== FastICA on 2D point clouds ========================== This example illustrates visually in the feature space a comparison by results using two different component analysis techniques. :ref:`ICA` vs :ref:`PCA`. Representing ICA in the feature space gives the view of 'geometric ICA': ICA...
bsd-3-clause
poryfly/scikit-learn
examples/model_selection/plot_roc.py
146
3697
""" ======================================= Receiver Operating Characteristic (ROC) ======================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X a...
bsd-3-clause
tmills/neural-assertion
scripts/keras/singletask/assertion_predict.py
1
2097
from keras.models import Sequential, load_model from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD from keras.utils import np_utils #from sklearn.datasets import load_svmlight_file import pickle import sklearn as sk import sklearn.cross_validation import numpy as np import cleartk_io a...
apache-2.0
Aurore54F/MalwareClustering
clustering/utility.py
1
10130
""" Additional functions to cluster/classify JS files, print the predictions, their accuracy… """ import os import logging import pickle # import graphviz # from sklearn import tree from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix import __init__ def classifier_...
gpl-3.0
dansbecker/skflow
examples/multiple_gpu.py
6
1527
# Copyright 2015-present Scikit Flow 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...
apache-2.0
umuzungu/zipline
zipline/data/treasuries_can.py
15
5257
# # Copyright 2013 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
PyroIgnus/ECE1747-A1-SimMud
tools/parse_log.py
1
3306
#!/usr/bin/env python import sys import numpy as np import matplotlib.pyplot as plt # Flag to save graphs automatically or not SAVE_GRAPHS = False def moving_average(data, thread_ids, min_time, max_time, window=5): # Compute moving average running_average_window = window * 1000 time_splits = np.arange(0...
mit
eickenberg/scikit-learn
sklearn/utils/tests/test_validation.py
4
7105
"""Tests for input validation functions""" from tempfile import NamedTemporaryFile import numpy as np from numpy.testing import assert_array_equal import scipy.sparse as sp from nose.tools import assert_raises, assert_true, assert_false, assert_equal from itertools import product from sklearn.utils import as_float_ar...
bsd-3-clause
clawpack/adjoint
paper2_examples/acoustics_2d_ex3/generate_tolplots.py
1
7318
from numpy import * from matplotlib.pyplot import * from pylab import * # Setting up local variables tols = ['1e-0','6e-1','3e-1', '1e-1','6e-2','3e-2', '1e-2','6e-3','3e-3', '1e-3','6e-4','3e-4', '1e-4','6e-5','3e-5', '1e-5'] ## --------------------------------- ## Setting up ...
bsd-2-clause
rspavel/spack
var/spack/repos/builtin/packages/py-opppy/package.py
3
1387
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyOpppy(PythonPackage): """The Output Parse-Plot Python (OPPPY) library is a python based ...
lgpl-2.1
lorenzo-desantis/mne-python
mne/decoding/base.py
6
26547
"""Base class copy from sklearn.base""" # Authors: Gael Varoquaux <gael.varoquaux@normalesup.org> # Romain Trachel <trachelr@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import inspect import warnings import six import numpy as np class BaseE...
bsd-3-clause
michaelhuang/QuantSoftwareToolkit
Legacy/Legacy/names.py
5
1114
import matplotlib.pyplot as plt from pylab import * from qstkutil import DataAccess as da from qstkutil import timeutil as tu from qstkutil import pseries as ps import pandas # Set the list of stocks for us to look at # symbols= list() # symtoplot = 'VZ' # symbols.append(symtoplot) # symbols.append('IBM') ...
bsd-3-clause
joequant/zipline
zipline/examples/dual_moving_average.py
18
2054
#!/usr/bin/env python # # 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 ...
apache-2.0
kjung/scikit-learn
sklearn/cluster/tests/test_k_means.py
41
27789
"""Testing for K-means""" import sys import numpy as np from scipy import sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing i...
bsd-3-clause
frank-tancf/scikit-learn
sklearn/cluster/spectral.py
25
18522
# -*- coding: utf-8 -*- """Algorithms for spectral clustering""" # Author: Gael Varoquaux gael.varoquaux@normalesup.org # Brian Cheung # Wei LI <kuantkid@gmail.com> # License: BSD 3 clause import warnings import numpy as np from ..base import BaseEstimator, ClusterMixin from ..utils import check_rand...
bsd-3-clause
hitszxp/scikit-learn
sklearn/metrics/cluster/supervised.py
17
26843
"""Utilities to evaluate the clustering performance of models Functions named as *_score return a scalar value to maximize: the higher the better. """ # Authors: Olivier Grisel <olivier.grisel@ensta.org> # Wei LI <kuantkid@gmail.com> # Diego Molla <dmolla-aliod@gmail.com> # License: BSD 3 clause fr...
bsd-3-clause
ywcui1990/htmresearch
projects/neural_correlations/EXP5-Bar/NeuCorr_Exp5.py
10
8590
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, 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
arahuja/scikit-learn
examples/manifold/plot_lle_digits.py
181
8510
""" ============================================================================= Manifold learning on handwritten digits: Locally Linear Embedding, Isomap... ============================================================================= An illustration of various embeddings on the digits dataset. The RandomTreesEmbed...
bsd-3-clause
0asa/scikit-learn
sklearn/utils/setup.py
296
2884
import os from os.path import join from sklearn._build_utils import get_blas_info def configuration(parent_package='', top_path=None): import numpy from numpy.distutils.misc_util import Configuration config = Configuration('utils', parent_package, top_path) config.add_subpackage('sparsetools') ...
bsd-3-clause
mne-tools/mne-tools.github.io
0.17/_downloads/afd72e067412c390ceccc64f99255ba2/plot_compute_raw_data_spectrum.py
11
4858
""" ================================================== Compute the power spectral density of raw data ================================================== This script shows how to compute the power spectral density (PSD) of measurements on a raw dataset. It also show the effect of applying SSP to the data to reduce ECG ...
bsd-3-clause
padilha/biclustlib
biclustlib/algorithms/las.py
1
7689
""" biclustlib: A Python library of biclustering algorithms and evaluation measures. Copyright (C) 2017 Victor Alexandre Padilha This file is part of biclustlib. biclustlib is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by...
gpl-3.0
lthurlow/Network-Grapher
proj/external/networkx-1.7/doc/make_gallery.py
12
2477
#!/usr/bin/env python # generate a thumbnail gallery of examples template = """\ {%% extends "layout.html" %%} {%% set title = "Gallery" %%} {%% block body %%} <h3>Click on any image to see source code</h3> <br/> %s {%% endblock %%} """ link_template = """\ <a href="%s"><img src="%s" border="0" alt="%s"/></a> """ ...
mit
dumbringer/ns-3-dev-ndnSIM
src/flow-monitor/examples/wifi-olsr-flowmon.py
108
7439
# -*- Mode: Python; -*- # Copyright (c) 2009 INESC Porto # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation; # # This program is distributed in the hope that it will be useful, #...
gpl-2.0
gsalvatori/tredify
lib/Pie.py
1
1477
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import random from mpl_toolkits.mplot3d import Axes3D from pylab import * class Pie: def __init__(self, dict_, title): figure(1, figsize=(6,6)) self.ax = axes([0.1, 0.1, 0.8, 0.8]) self.dict = dict_ self...
gpl-3.0
bikong2/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
srio/minishadow
minishadow/undulator/source_undulator_input_output.py
1
13362
__authors__ = ["M Sanchez del Rio - ESRF ISDD Advanced Analysis and Modelling"] __license__ = "MIT" __date__ = "12/01/2017" # # load/write files and plot facilities for the undul_phot and undul_cdf shadow3/undulator preprocessors # import numpy import h5py import time class SourceUndulatorInputOutput(object): ...
mit
e-koch/pyspeckit
pyspeckit/spectrum/models/n2hp.py
1
6325
""" =========== N2H+ fitter =========== Reference for line params: Daniel, F., Dubernet, M.-L., Meuwly, M., Cernicharo, J., Pagani, L. 2005, MNRAS 363, 1083 http://www.strw.leidenuniv.nl/~moldata/N2H+.html http://adsabs.harvard.edu/abs/2005MNRAS.363.1083D Does not yet implement: http://adsabs.harvard.edu/abs/2010ApJ...
mit
hsiaoyi0504/scikit-learn
sklearn/feature_extraction/hashing.py
183
6155
# Author: Lars Buitinck <L.J.Buitinck@uva.nl> # License: BSD 3 clause import numbers import numpy as np import scipy.sparse as sp from . import _hashing from ..base import BaseEstimator, TransformerMixin def _iteritems(d): """Like d.iteritems, but accepts any collections.Mapping.""" return d.iteritems() if...
bsd-3-clause
fyffyt/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py
256
2406
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a ...
bsd-3-clause
theoryno3/scikit-learn
sklearn/cluster/__init__.py
364
1228
""" The :mod:`sklearn.cluster` module gathers popular unsupervised clustering algorithms. """ from .spectral import spectral_clustering, SpectralClustering from .mean_shift_ import (mean_shift, MeanShift, estimate_bandwidth, get_bin_seeds) from .affinity_propagation_ import affinity_propagati...
bsd-3-clause
datacommonsorg/data
scripts/india_udise/udise_school_dropout_rate/preprocess.py
1
3271
# Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
apache-2.0
ryscet/pyseries
pyseries/Preprocessing/PrepareData.py
2
23819
""" PrepareData =========== Filter signals using PCA decomposition of their fast-fourier transform #. Identify outliers in fft-transformed signal #. Identify clusters in fft - i.e. signals with simmilar features """ import sys sys.path.insert(0, '/Users/ryszardcetnarski/Desktop/pySeries') import numpy as n...
mit
rbiswas4/simlib
tests/test_simlibCalculation.py
1
4235
""" Test file for calculating simlibs This file reads a couple of lines of opsim outputs and produces a simlib file which is compared for values of skysig and zptavg against a simlib file produced by a different code. """ from __future__ import absolute_import, print_function import os import opsimsummary as oss import...
mit
FilWisher/distributed-project
icarus/examples/offpath-vs-onpath-caching/plotresults.py
4
14558
#!/usr/bin/env python """Plot results read from a result set """ from __future__ import division import os import argparse import collections import logging import numpy as np import matplotlib.pyplot as plt from icarus.util import Settings, Tree, config_logging, step_cdf from icarus.tools import means_confidence_int...
mit