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 |
|---|---|---|---|---|---|
eramirem/astroML | book_figures/chapter5/fig_lutz_kelker.py | 3 | 4551 | """
Eddington-Malmquist & Lutz-Kelker Biases
----------------------------------------
Figure 5.3
An illustration of the Eddington-Malmquist (left) and Lutz-Kelker (right)
biases for mock data sets that simulate upcoming LSST and Gaia surveys
(see text). The left panel shows a bias in photometric calibration when using... | bsd-2-clause |
davidam/python-examples | scikit/plot_unveil_tree_structure.py | 47 | 4852 | """
=========================================
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... | gpl-3.0 |
dmancevo/nlpNet | net_test.py | 2 | 4632 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 15:54:51 2015
@author: Diego
"""
import numpy as np
import matplotlib.pyplot as plt
from nlp_net import word_vec, conv_layer, pool_layer, layer, hinge_loss
def test_word_conv_pool():
l1 = word_vec(word_dim=2)
l2 = conv_layer(word_dim=2, K=(4,0), lrate=1.0, c=... | apache-2.0 |
tobykurien/pi-tracking-telescope | app/playground/opencv_samples/common.py | 5 | 6350 | #!/usr/bin/env python
'''
This module contains some common routines used by other samples.
'''
import numpy as np
import cv2
# built-in modules
import os
import itertools as it
from contextlib import contextmanager
image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm']
class ... | mit |
gotomypc/scikit-learn | examples/ensemble/plot_gradient_boosting_regularization.py | 355 | 2843 | """
================================
Gradient Boosting regularization
================================
Illustration of the effect of different regularization strategies
for Gradient Boosting. The example is taken from Hastie et al 2009.
The loss function used is binomial deviance. Regularization via
shrinkage (``lear... | bsd-3-clause |
hack1nt0/word2vec | baseline.py | 1 | 1127 | __author__ = 'dy'
from gensim.models.word2vec import Word2Vec
import numpy as np
import matplotlib.pyplot as plt
from cs224d.datasets.data_utils import *
dataset = StanfordSentiment()
sentences = dataset.sentences()
model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)
# model.save_word2vec_format("... | apache-2.0 |
sserrot/champion_relationships | venv/share/doc/networkx-2.4/examples/drawing/plot_knuth_miles.py | 1 | 3017 | #!/usr/bin/env python
"""
===========
Knuth Miles
===========
`miles_graph()` returns an undirected graph over the 128 US cities from
the datafile `miles_dat.txt`. The cities each have location and population
data. The edges are labeled with the distance between the two cities.
This example is described in Section 1... | mit |
Technariumas/Marimba | data_analysis/agg_csv_to_csv.py | 1 | 1076 | import sqlite3
import pandas as pd
import os
conn = sqlite3.connect('temp.db') # create a temp db file
data = pd.read_csv('data_full.csv')
sql = data.to_sql('data_data', conn, if_exists='append', index=False) # convert csv to sql
statement = """select time_start, cell_grp AS 'Region',
count(1) AS 'T... | gpl-3.0 |
Richert/BrainNetworks | BasalGanglia/stn_gpe_combined_opt.py | 1 | 14531 | import os
import warnings
import numpy as np
from pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm
from pandas import DataFrame, read_hdf
from copy import deepcopy
class CustomGOA(CGSGeneticAlgorithm):
def eval_fitness(self, target: list, **kwargs):
# define simulation conditions
wor... | apache-2.0 |
mbednarski/Chiron | chiron/es2_discrete.py | 1 | 3375 | from __future__ import print_function, division
import gym
import numpy as np
import matplotlib as plt
import logging
import matplotlib.pyplot as plt
logging.disable(logging.CRITICAL)
np.seterr('raise')
plt.ion()
problem = 'Pendulum-v0'
env = gym.make(problem)
validation_env = gym.make(problem)
validation_env = gym... | gpl-3.0 |
DuCorey/bokeh | bokeh/util/serialization.py | 2 | 11282 | '''
Functions for helping with serialization and deserialization of
Bokeh objects.
Certain NunPy array dtypes can be serialized to a binary format for
performance and efficiency. The list of supported dtypes is:
{binary_array_types}
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(_... | bsd-3-clause |
jayvalentine/CellularAutomata | plotting.py | 1 | 2639 | """
This module provides an easy interface for plotting automata
All code is released under the MIT License and is (C) copyright 2016 Jay Valentine
"""
import matplotlib.pyplot as plt
import math
global_sizes = {
1:10.0,
100:5.0,
1000:1.0,
10000:0.01,
100000:0.005
}
def get_size(x, y):
"""
convenience method ... | mit |
benjaminpope/pysco | pysco/diffract_tools.py | 2 | 7806 | import numpy as np
import matplotlib.pyplot as plt
import pyfits as pf
from scipy.interpolate import RectBivariateSpline as interp
from frebin import *
# from wfirst import *
# from jwstpupil import *
from simpupil import *
import time
from common_tasks import shift_image
from astropy.io import fits
shift = np.fft.... | gpl-3.0 |
kenshay/ImageScripter | ProgramData/SystemFiles/Python/Lib/site-packages/pandas/util/validators.py | 7 | 7837 | """
Module that contains many useful utilities
for validating data or function arguments
"""
from pandas.types.common import is_bool
def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
"""
Checks whether 'args' has length of at most 'compat_args'. Raises
a TypeError if that is not the c... | gpl-3.0 |
kagayakidan/scikit-learn | sklearn/metrics/classification.py | 95 | 67713 | """Metrics to assess performance on classification task given classe prediction
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
the lower the better
"""
# Authors: Alexandre Gramfort <alexandre.gram... | bsd-3-clause |
gotomypc/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 |
rbalda/neural_ocr | env/lib/python2.7/site-packages/matplotlib/testing/jpl_units/UnitDbl.py | 8 | 9360 | #===========================================================================
#
# UnitDbl
#
#===========================================================================
"""UnitDbl module."""
#===========================================================================
# Place all imports after here.
#
from __future__ ... | mit |
vybstat/scikit-learn | examples/cluster/plot_cluster_comparison.py | 246 | 4684 | """
=========================================================
Comparing different clustering algorithms on toy datasets
=========================================================
This example aims at showing characteristics of different
clustering algorithms on datasets that are "interesting"
but still in 2D. The last ... | bsd-3-clause |
tgquintela/WikipediaParserTools | municipios.py | 1 | 2450 |
import wikipedia
import pandas as pd
import numpy as np
from utils import parse_excel_sheet, write_dataframe_to_excel
### Setting and parsing initial data
wikipedia.set_lang('es')
data = parse_excel_sheet('/home/tono/Documents/municipios-espana_2011.xls')
municipios15 = parse_excel_sheet('/home/tono/Documents/15codm... | mit |
manewton/BioReactor-Data-Logging | Project/downloader.py | 1 | 4044 | """
Written By: Kathryn Cogert
For: Winkler Lab/CSE599 Winter Quarter 2016
Purpose: Downloads most recent copy of reactor data.
"""
import pandas as pd
import datetime
from googledriveutils import list_rfiles_by_date, read_from_reactordrive
# TODO: Make more efficient
# Constants
TEN_MINS = datetime.timedelta(minute... | gpl-3.0 |
mayblue9/scikit-learn | examples/linear_model/plot_ols_ridge_variance.py | 387 | 2060 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Ordinary Least Squares and Ridge Regression Variance
=========================================================
Due to the few points in each dimension and the straight
line that linear regression uses to follow thes... | bsd-3-clause |
siutanwong/scikit-learn | sklearn/datasets/mldata.py | 309 | 7838 | """Automatically download MLdata datasets."""
# Copyright (c) 2011 Pietro Berkes
# License: BSD 3 clause
import os
from os.path import join, exists
import re
import numbers
try:
# Python 2
from urllib2 import HTTPError
from urllib2 import quote
from urllib2 import urlopen
except ImportError:
# Pyt... | bsd-3-clause |
jkarnows/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 |
arbuz001/sms-tools | lectures/09-Sound-description/plots-code/k-means.py | 25 | 1714 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import os, sys
from scipy.cluster.vq import vq, kmeans, whiten
from numpy import random
import pickle
n = 30
features = np.hstack((np.array([np.random.normal(-2,1.1,n), np.random.normal(-2,1.1,n)]), np.array([np.random.normal(2,1.5,... | agpl-3.0 |
justacec/bokeh | bokeh/core/compat/mplexporter/tools.py | 75 | 1732 | """
Tools for matplotlib plot exporting
"""
def ipynb_vega_init():
"""Initialize the IPython notebook display elements
This function borrows heavily from the excellent vincent package:
http://github.com/wrobstory/vincent
"""
try:
from IPython.core.display import display, HTML
except I... | bsd-3-clause |
mamhoud/ArDicSenti-Flask | views.py | 1 | 11086 |
from django.shortcuts import render
from django.http import HttpResponse, StreamingHttpResponse
from wsgiref.util import FileWrapper
import nltk
import os, tempfile, zipfile
import sys
from imp import reload
from io import BytesIO
reload(sys)
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem.isri i... | bsd-3-clause |
rvraghav93/scikit-learn | examples/cluster/plot_segmentation_toy.py | 33 | 3442 | """
===========================================
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 |
leofdecarvalho/MachineLearning | 2. Modeling/2. Classification/12. Decision_Tree_Classification/decision_tree_classification.py | 5 | 2725 | # Decision Tree Classification
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into the Training set and Te... | mit |
soylentdeen/BlurryApple | GUI/Demo/Graffiti.py | 1 | 16052 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This is the main file for launching the PyQt app.
Requirements:
You need Python 2 (+ matplotlib, pylab and pyfits modules), Qt4 and PyQt for this to work
Description:
- Graffiti.py is this Python file, must be executable.
Launch the GUI using the command (in terminal):
... | gpl-2.0 |
xubenben/scikit-learn | examples/ensemble/plot_gradient_boosting_regression.py | 227 | 2520 | """
============================
Gradient Boosting regression
============================
Demonstrate Gradient Boosting on the Boston housing dataset.
This example fits a Gradient Boosting model with least squares loss and
500 regression trees of depth 4.
"""
print(__doc__)
# Author: Peter Prettenhofer <peter.prett... | bsd-3-clause |
midnightradio/gensim | gensim/test/test_d2vmodel.py | 2 | 1579 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking D2VTransformer class.
"""
import unittest
import logging
from gensim.sklearn_api import D2VTransformer... | gpl-3.0 |
MostafaGazar/tensorflow | tensorflow/contrib/learn/python/learn/tests/grid_search_test.py | 27 | 2080 | # 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 applica... | apache-2.0 |
rexshihaoren/scikit-learn | sklearn/ensemble/forest.py | 9 | 61610 | """Forest of trees-based ensemble methods
Those methods include random forests and extremely randomized trees.
The module structure is the following:
- The ``BaseForest`` base class implements a common ``fit`` method for all
the estimators in the module. The ``fit`` method of the base ``Forest``
class calls the ... | bsd-3-clause |
daodaoliang/neural-network-animation | matplotlib/stackplot.py | 11 | 3978 | """
Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow
answer:
http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib
(http://stackoverflow.com/users/66549/doug)
"""
from __future__ import (absolute_import, division, print_function,
... | mit |
ilyes14/scikit-learn | sklearn/datasets/tests/test_mldata.py | 384 | 5221 | """Test functionality of mldata fetching utilities."""
import os
import shutil
import tempfile
import scipy as sp
from sklearn import datasets
from sklearn.datasets import mldata_filename, fetch_mldata
from sklearn.utils.testing import assert_in
from sklearn.utils.testing import assert_not_in
from sklearn.utils.test... | bsd-3-clause |
mdeff/ntds_2016 | project/reports/fake_news/lib/exploitation_helper.py | 1 | 2665 | import tensorflow as tf
import numpy as np
import pandas as pd
from tensorflow.contrib import learn
def preprocessing(dataframe):
mask_true = np.array(dataframe.rating == 'mostly true')
mask_false = np.array(dataframe.rating == 'mostly false')
# Extract text and labels
x_text = dataframe.message.fill... | mit |
ssaeger/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | 23 | 11915 | """Testing for Gaussian process regression """
# Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
# Licence: BSD 3 clause
import numpy as np
from scipy.optimize import approx_fprime
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels \
import RBF, Constan... | bsd-3-clause |
rajul/mne-python | mne/viz/montage.py | 13 | 1786 | """Functions to plot EEG sensor montages or digitizer montages
"""
import numpy as np
def plot_montage(montage, scale_factor=1.5, show_names=False, show=True):
"""Plot a montage
Parameters
----------
montage : instance of Montage
The montage to visualize.
scale_factor : float
Dete... | bsd-3-clause |
Neurita/boyle | boyle/storage.py | 1 | 4572 | """
Data storage in different formats helper functions for data persistence.
"""
# coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais V... | bsd-3-clause |
highfei2011/spark | python/pyspark/sql/tests/test_pandas_udf_window.py | 4 | 12837 | #
# 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 |
tbullmann/heuhaufen | publication/classic_loss_function/aggregate.py | 1 | 1871 | import os
import pandas
import numpy as np
import json
def main(test_path='temp/publication/loss_functions/test'):
labels = ['membranes', 'synapses', 'mitochondria']
# concatenate the evaluation and parameters for all runs
dfs = []
for label in labels:
for run in range(1, 6*3+1):
... | mit |
colinsheppard/beam | src/main/python/counts_tools/utils/network_tools.py | 2 | 2394 | from collections import defaultdict
from xml.etree import cElementTree as CET
import geopandas as gpd
import numpy as np
from shapely.geometry import Point
__author__ = 'Andrew A Campbell'
def links_2_counties(net_path, county_path, net_crs={'init' :'epsg:26910'}, county_crs={'init' :'epsg:4326'}):
'''
:p... | gpl-3.0 |
seb-buch/personal-mess | gsblib/show_xvg.py | 1 | 3075 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 12 21:06:51 2015
@author: sebastien
"""
from __future__ import print_function
from argparse import ArgumentDefaultsHelpFormatter
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sys
def populate_parser(parent_parse... | gpl-3.0 |
krlynch/muon_timer | coincidences/coincidence_counter.py | 1 | 10512 | import time
from stream_reader import StreamReader, Requestor
import os
from logger import Logger
import sys
from matplotlib import pyplot as plt
import COUNTER_CONSTS
if len(sys.argv) < 5:
print("Usage: python coincidence_counter.py url1 url2 data_dir logfile")
sys.exit()
urlTop = sys.argv[1]
urlBottom = sy... | gpl-2.0 |
ElinorSun/Ulysses | build/scripts/evaluate_rpe.py | 2 | 17390 | #!/usr/bin/python
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Juergen Sturm, TUM
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must... | gpl-3.0 |
nikitasingh981/scikit-learn | examples/neighbors/plot_species_kde.py | 44 | 4025 | """
================================================
Kernel Density Estimate of Species Distributions
================================================
This shows an example of a neighbors-based query (in particular a kernel
density estimate) on geospatial data, using a Ball Tree built upon the
Haversine distance metric... | bsd-3-clause |
arahuja/scikit-learn | examples/cluster/plot_kmeans_digits.py | 53 | 4524 | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example we compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the gr... | bsd-3-clause |
Aieener/SUS_3D | DATA/GCMC_data_one_specie_model/1E11L_8_64_9.65_2nd_coex/his.py | 1 | 4276 | #Analysis # distribution for the 3-D Rods
#Author: Yuding Ai
#Date: 2015 July 28
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import math
from matplotlib import rc
rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
def his():
N1 = [] # Ver
N2 = [] # Hor... | mit |
richardotis/scipy | scipy/integrate/quadrature.py | 25 | 27849 | from __future__ import division, print_function, absolute_import
__all__ = ['fixed_quad','quadrature','romberg','trapz','simps','romb',
'cumtrapz','newton_cotes']
from scipy.special.orthogonal import p_roots
from scipy.special import gammaln
from numpy import sum, ones, add, diff, isinf, isscalar, \
a... | bsd-3-clause |
toobaz/pandas | pandas/io/parsers.py | 1 | 128169 | """
Module contains tools for processing files into DataFrames or other objects
"""
from collections import defaultdict
import csv
import datetime
from io import StringIO
import re
import sys
from textwrap import fill
from typing import Any, Dict, Set
import warnings
import numpy as np
import pandas._libs.lib as lib... | bsd-3-clause |
FilipDominec/python-meep-utils | plot_cdh.py | 1 | 13044 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
## Import common moduli
import matplotlib, sys, os, time, argparse
import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import c, hbar, pi
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parse... | gpl-2.0 |
ambikeshwar1991/gnuradio | gnuradio-core/src/examples/pfb/synth_to_chan.py | 17 | 3587 | #!/usr/bin/env python
#
# Copyright 2010 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# ... | gpl-3.0 |
alekz112/statsmodels | statsmodels/tsa/vector_ar/util.py | 24 | 6383 | """
Miscellaneous utility code for VAR estimation
"""
from statsmodels.compat.python import range, string_types, asbytes
import numpy as np
import scipy.stats as stats
import scipy.linalg as L
import scipy.linalg.decomp as decomp
import statsmodels.tsa.tsatools as tsa
from scipy.linalg import cholesky
#--------------... | bsd-3-clause |
chugunovyar/factoryForBuild | env/lib/python2.7/site-packages/matplotlib/tests/test_colors.py | 3 | 24671 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import itertools
from distutils.version import LooseVersion as V
from nose.tools import assert_raises, assert_equal, assert_true
try:
# this is not available in nose + py2.6
from nose.tools... | gpl-3.0 |
0asa/scikit-learn | sklearn/utils/tests/test_shortest_path.py | 42 | 2894 | from collections import defaultdict
import numpy as np
from numpy.testing import assert_array_almost_equal
from sklearn.utils.graph import (graph_shortest_path,
single_source_shortest_path_length)
def floyd_warshall_slow(graph, directed=False):
N = graph.shape[0]
#set nonzer... | bsd-3-clause |
quheng/scikit-learn | sklearn/metrics/cluster/bicluster.py | 359 | 2797 | from __future__ import division
import numpy as np
from sklearn.utils.linear_assignment_ import linear_assignment
from sklearn.utils.validation import check_consistent_length, check_array
__all__ = ["consensus_score"]
def _check_rows_and_columns(a, b):
"""Unpacks the row and column arrays and checks their shap... | bsd-3-clause |
zrhans/pythonanywhere | .virtualenvs/django19/lib/python3.4/site-packages/pandas/tseries/timedeltas.py | 9 | 3765 | """
timedelta support tools
"""
import re
import numpy as np
import pandas.tslib as tslib
from pandas import compat
from pandas.core.common import (ABCSeries, is_integer_dtype,
is_timedelta64_dtype, is_list_like,
isnull, _ensure_object, ABCIndexClass)
fro... | apache-2.0 |
dingocuster/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | 114 | 25281 | # Authors: Olivier Grisel <olivier.grisel@ensta.org>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# License: BSD 3 clause
from sys import version_info
import numpy as np
from scipy import interpolate, sparse
from copy import deepcopy
from sklearn.datasets import load_boston
from sklearn.utils.testing ... | bsd-3-clause |
manipopopo/tensorflow | tensorflow/contrib/learn/__init__.py | 17 | 2736 | # 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 applica... | apache-2.0 |
zdary/intellij-community | python/helpers/pycharm_display/datalore/display/supported_data_type.py | 14 | 2135 | import json
from abc import abstractmethod
from datetime import datetime
try:
import numpy
except ImportError:
numpy = None
try:
import pandas
except ImportError:
pandas = None
# Parameter 'value' can also be pandas.DataFrame
def _standardize_dict(value):
result = {}
for k, v in value.items(... | apache-2.0 |
rfinn/LCS | python/LCSsimulate-infall-paper1.py | 2 | 5346 | #!/usr/bin/env python
'''
USAGE
- from within ipython
%run ~/Dropbox/pythonCode/LCSsimulate-infall.py
t = run_sim(tmax=0,drdt_step=0.05,nrandom=1000)
t = run_sim(tmax=1,drdt_step=0.05,nrandom=1000)
t = run_sim(tmax=2,drdt_step=0.05,nrandom=1000)
t = run_sim(tmax=3,drdt_step=0.05,nrandom=1000)
t = run_sim(tmax=4,drd... | gpl-3.0 |
schwallie2/alive_rescue | config.py | 1 | 5542 | import pandas as pd
from string import ascii_uppercase
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from secret import *
pd.set_option('display.height', 1000)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
def... | gpl-3.0 |
pizzathief/scipy | scipy/spatial/_spherical_voronoi.py | 7 | 13695 | """
Spherical Voronoi Code
.. versionadded:: 0.18.0
"""
#
# Copyright (C) Tyler Reddy, Ross Hemsley, Edd Edmondson,
# Nikolai Nowaczyk, Joe Pitt-Francis, 2015.
#
# Distributed under the same BSD license as SciPy.
#
import warnings
import numpy as np
import scipy
from . import _voronoi
from scipy.spat... | bsd-3-clause |
cosmir/dev-set-builder | scripts/max_inst.py | 1 | 1912 | #!/usr/bin/env python
# coding: utf8
'''Obtain the most likely k instruments on a dataset
subset and group excerpts by instrument similarity
'''
import argparse
import numpy as np
import pandas as pd
import sys
def params(args):
parser = argparse.ArgumentParser(description='Obtain the most likely instruments on... | mit |
idlead/scikit-learn | sklearn/datasets/mlcomp.py | 289 | 3855 | # Copyright (c) 2010 Olivier Grisel <olivier.grisel@ensta.org>
# License: BSD 3 clause
"""Glue code to load http://mlcomp.org data as a scikit.learn dataset"""
import os
import numbers
from sklearn.datasets.base import load_files
def _load_document_classification(dataset_path, metadata, set_=None, **kwargs):
if ... | bsd-3-clause |
herberthamaral/mestrado | MD/segunda-aula-pratica/main.py | 1 | 4642 | # encoding: utf-8
from itertools import cycle
import sys, math, random
import matplotlib.pyplot as plt
import numpy as np
from dataset import load_dataset
# euclidean distance
ed = lambda p1,p2: math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
class Cluster(object):
ficou_sem_ponto = False
def __init__(self, po... | apache-2.0 |
costypetrisor/scikit-learn | sklearn/tests/test_base.py | 216 | 7045 | # Author: Gael Varoquaux
# License: BSD 3 clause
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing impo... | bsd-3-clause |
eggplantbren/Oscillations | FitSine/display.py | 1 | 2150 | # Copyright (c) 2009, 2010, 2011, 2012 Brendon J. Brewer.
#
# This file is part of DNest3.
#
# DNest3 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 ... | gpl-3.0 |
rjw57/starman | doc/plotutils.py | 1 | 1979 | # Adapted from
# http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals
from matplotlib.patches import Ellipse
from matplotlib.pylab import *
import numpy as np
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
"""
Plots an `nstd` sigma error ellipse based on the specified ... | mit |
GuessWhoSamFoo/pandas | pandas/core/tools/timedeltas.py | 1 | 6153 | """
timedelta support tools
"""
import numpy as np
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
import pandas as pd
from pandas.core.arrays.timedeltas import sequence_to_t... | bsd-3-clause |
TomAugspurger/pandas | pandas/io/parquet.py | 1 | 10193 | """ parquet compat """
from typing import Any, Dict, Optional
from warnings import catch_warnings
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import (
get_filepath_or_buffer,
get_f... | bsd-3-clause |
josephmisiti/BDA_py_demos | demos_ch10/demo10_1.py | 19 | 4102 | """Bayesian data analysis
Chapter 10, demo 1
Rejection sampling example
"""
from __future__ import division
import numpy as np
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
# edit default plot settings (colours from colorbrewer2.org)
plt.rc('font', size=14)
plt.rc('lines', color='... | gpl-3.0 |
briandconnelly/nicheconstruct | model/Metapopulation.py | 1 | 12109 | # -*- coding: utf-8 -*-
"""Functions for working with Metapopulations"""
import numpy as np
from numpy import bitwise_xor, where
from numpy.random import binomial, multinomial, random_integers
import pandas as pd
from misc import adaptive_colnames
from Topology import random_neighbor
def create_metapopulation(conf... | cc0-1.0 |
savkov/qsutils | src/qsutils.py | 1 | 6613 | # This file is part of qsutils.
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Aleksandar Savkov
#
# 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 lim... | mit |
vighneshbirodkar/scikit-image | doc/examples/color_exposure/plot_regional_maxima.py | 7 | 3653 | """
=========================
Filtering regional maxima
=========================
Here, we use morphological reconstruction to create a background image, which
we can subtract from the original image to isolate bright features (regional
maxima).
First we try reconstruction by dilation starting at the edges of the ima... | bsd-3-clause |
Carmezim/tensorflow | tensorflow/contrib/learn/python/learn/estimators/estimator_test.py | 14 | 46097 | # 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 applica... | apache-2.0 |
neuroidss/nupic | external/linux32/lib/python2.6/site-packages/matplotlib/backends/backend_fltkagg.py | 69 | 20839 | """
A backend for FLTK
Copyright: Gregory Lielens, Free Field Technologies SA and
John D. Hunter 2004
This code is released under the matplotlib license
"""
from __future__ import division
import os, sys, math
import fltk as Fltk
from backend_agg import FigureCanvasAgg
import os.path
import matplotli... | agpl-3.0 |
meghana1995/sympy | sympy/external/tests/test_importtools.py | 91 | 1215 | from sympy.external import import_module
# fixes issue that arose in addressing issue 6533
def test_no_stdlib_collections():
'''
make sure we get the right collections when it is not part of a
larger list
'''
import collections
matplotlib = import_module('matplotlib',
__import__kwargs={... | bsd-3-clause |
nekopuni/adagio | adagio/layers/portfolio.py | 1 | 2096 | import pandas as pd
from .base import BaseBacktestObject
from .engine import Engine
from .longonly import LongOnly
from ..utils.date import data_asfreq
from ..utils.logging import get_logger
from ..utils import keys
logger = get_logger(name=__name__)
class Portfolio(BaseBacktestObject):
""" Layer to bind strate... | mit |
xuzhenqi/gardenia | scripts/rfs_exp.py | 1 | 2343 | import numpy as np
import cv2
import matplotlib.pyplot as plt
from util import get_index, get_index_mean, softmax
from inference import get_preds_single
caffe_root = '../caffe/'
import sys
import random
sys.path.insert(0, caffe_root + 'python')
import caffe
caffe.set_mode_cpu()
mean_file = '../data/train_mean.blob'
... | gpl-3.0 |
Windy-Ground/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 |
vortex-ape/scikit-learn | sklearn/cluster/tests/test_hierarchical.py | 4 | 24228 | """
Several basic tests for hierarchical clustering procedures
"""
# Authors: Vincent Michel, 2010, Gael Varoquaux 2012,
# Matteo Visconti di Oleggio Castello 2014
# License: BSD 3 clause
from tempfile import mkdtemp
import shutil
import pytest
from functools import partial
import numpy as np
from scipy impo... | bsd-3-clause |
zingale/hydro_examples | advection/fv_mol.py | 1 | 5693 | import numpy as np
import matplotlib.pyplot as plt
class FVGrid(object):
def __init__(self, nx, ng, xmin=0.0, xmax=1.0):
self.xmin = xmin
self.xmax = xmax
self.ng = ng
self.nx = nx
# python is zero-based. Make easy intergers to know where the
# real data lives
... | bsd-3-clause |
wathen/PhD | MHD/FEniCS/MHD/Stabilised/Precond/MHDstabtest3D.py | 2 | 11327 | #!/usr/bin/python
# interpolate scalar gradient onto nedelec space
from dolfin import *
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
import numpy as np
#import matplotlib.pylab as plt
import PETScIO as IO
import common
import ... | mit |
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 |
aabadie/scikit-learn | sklearn/linear_model/sag.py | 11 | 11291 | """Solvers for Ridge and LogisticRegression using SAG algorithm"""
# Authors: Tom Dupre la Tour <tom.dupre-la-tour@m4x.org>
#
# License: BSD 3 clause
import numpy as np
import warnings
from ..exceptions import ConvergenceWarning
from ..utils import check_array
from ..utils.extmath import row_norms
from .base import ... | bsd-3-clause |
iancze/EchelleTools | TRESplot.py | 1 | 1654 | #!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(prog="TRESplot.py",
description="You've already run TRESio, now lets plot all the spectra!")
parser.add_argument("file", help="The HDF5 file you want to plot.")
parser.add_argument("--orders", default="all", help="Wh... | bsd-3-clause |
glue-viz/glue-qt | glue/qt/widgets/tests/test_scatter_widget.py | 1 | 9761 | #pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103
from distutils.version import LooseVersion # pylint:disable=W0611
import pytest
from ..scatter_widget import ScatterWidget
from .... import core
from matplotlib import __version__ as mpl_version # pylint:disable=W0611
class TestScatterWidget(object):
def ... | bsd-3-clause |
Udzu/pudzu | dataviz/politics_homicide.py | 1 | 3458 | from pudzu.charts import *
import seaborn as sns
BG = "white"
FONT = calibri
LIMITS = [10, 5, 2, 1, 0]
REDS = treversed(tmap(RGBA, sns.color_palette("Reds", len(LIMITS))))
countries = pd.read_csv("datasets/countries.csv").split_columns(['country', 'organisations', 'tld'], "|").explode('country').set_index("co... | mit |
marcsans/cnn-physics-perception | phy/lib/python2.7/site-packages/sklearn/linear_model/stochastic_gradient.py | 20 | 51086 | # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> (main author)
# Mathieu Blondel (partial_fit support)
#
# License: BSD 3 clause
"""Classification and regression using Stochastic Gradient Descent (SGD)."""
import numpy as np
from abc import ABCMeta, abstractmethod
from ..externals.joblib import ... | mit |
theoryno3/scikit-learn | sklearn/neighbors/tests/test_approximate.py | 142 | 18692 | """
Testing for the approximate neighbor search using
Locality Sensitive Hashing Forest module
(sklearn.neighbors.LSHForest).
"""
# Author: Maheshakya Wijewardena, Joel Nothman
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_a... | bsd-3-clause |
ashhher3/pyDatasets | pydatasets/physionet/challenge2012.py | 2 | 12710 | # -*- coding: utf-8 -*-
"""
@author: dbell
@author: davekale
"""
import re
from datetime import timedelta, datetime
import numpy as np
from pandas import DataFrame, Series
class InvalidChallenge2012DataException(Exception):
def __init__(self, field, err, value, recordid=None):
s = '{0} has invalid {1}:... | apache-2.0 |
bartosh/zipline | zipline/data/bundles/core.py | 5 | 20538 | from collections import namedtuple
import errno
import os
import shutil
import warnings
from contextlib2 import ExitStack
import click
import pandas as pd
from toolz import curry, complement, take
from ..us_equity_pricing import (
BcolzDailyBarReader,
BcolzDailyBarWriter,
SQLiteAdjustmentReader,
SQLit... | apache-2.0 |
samzhang111/scikit-learn | sklearn/gaussian_process/tests/test_kernels.py | 5 | 11736 | """Testing for kernels for Gaussian processes."""
# Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
# Licence: BSD 3 clause
from collections import Hashable
import inspect
import numpy as np
from scipy.optimize import approx_fprime
from sklearn.metrics.pairwise \
import PAIRWISE_KERNEL_FUNCTIONS, euc... | bsd-3-clause |
fmfn/UnbalancedDataset | imblearn/over_sampling/_smote/tests/test_smote_nc.py | 2 | 8627 | """Test the module SMOTENC."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# Dzianis Dudnik
# License: MIT
from collections import Counter
import pytest
import numpy as np
from scipy import sparse
from sklearn.datasets import make_classification
from sklearn.utils._tes... | mit |
shenzebang/scikit-learn | sklearn/metrics/cluster/tests/test_unsupervised.py | 230 | 2823 | import numpy as np
from scipy.sparse import csr_matrix
from sklearn import datasets
from sklearn.metrics.cluster.unsupervised import silhouette_score
from sklearn.metrics import pairwise_distances
from sklearn.utils.testing import assert_false, assert_almost_equal
from sklearn.utils.testing import assert_raises_regexp... | bsd-3-clause |
hainm/scikit-learn | sklearn/preprocessing/__init__.py | 268 | 1319 | """
The :mod:`sklearn.preprocessing` module includes scaling, centering,
normalization, binarization and imputation methods.
"""
from ._function_transformer import FunctionTransformer
from .data import Binarizer
from .data import KernelCenterer
from .data import MinMaxScaler
from .data import MaxAbsScaler
from .data ... | bsd-3-clause |
jwren/intellij-community | python/helpers/pycharm_matplotlib_backend/sitecustomize.py | 10 | 1837 | import os
import sys
import traceback
SHOW_DEBUG_INFO = os.getenv('PYCHARM_DEBUG', 'False').lower() in ['true', '1']
def debug(message):
if SHOW_DEBUG_INFO:
sys.stderr.write(message)
sys.stderr.write("\n")
debug("Executing PyCharm's `sitecustomize`")
modules_list = []
try:
# We want to impo... | apache-2.0 |
msultan/msmbuilder | msmbuilder/tests/test_lumping.py | 6 | 3480 | from __future__ import print_function
import numpy as np
from sklearn.pipeline import Pipeline
from msmbuilder.lumping import PCCA, PCCAPlus
from msmbuilder.msm import MarkovStateModel
random = np.random.RandomState(9)
def _metastable_system():
# Make a simple dataset with four states, where there are 2 obviou... | lgpl-2.1 |
ryandougherty/mwa-capstone | MWA_Tools/build/matplotlib/doc/mpl_examples/pylab_examples/demo_text_path.py | 3 | 4462 |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.image import BboxImage
import numpy as np
from matplotlib.transforms import IdentityTransform
import matplotlib.patches as mpatches
from matplotlib.offsetbox import AnnotationBbox,\
AnchoredOffsetbox, AuxTransformBox
from matplotlib.cbook... | gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.