code
stringlengths
2.5k
6.36M
kind
stringclasses
2 values
parsed_code
stringlengths
0
404k
quality_prob
float64
0
0.98
learning_prob
float64
0.03
1
``` import pandas as pd ``` ### Generate a brief statistic summary for corresponding data * Sort daily gain/loss for January of 2018 and store the result back to a .csv file ``` FILE = r"C:\Users\pavan\Desktop\SP500 (1).csv" data = pd.read_csv(FILE) data.shape data.columns data.head() data['Gain'] = data.Close - dat...
github_jupyter
import pandas as pd FILE = r"C:\Users\pavan\Desktop\SP500 (1).csv" data = pd.read_csv(FILE) data.shape data.columns data.head() data['Gain'] = data.Close - data.Open data.head() data['Date'] = pd.to_datetime(data.Date) data.loc[data.Date.dt.year==2018,].sort_values(['Gain'],ascending=False).to_csv("./2018_Gain_Loss.cs...
0.113801
0.90291
``` import keras keras.__version__ ``` # 5.2 - Using convnets with small datasets This notebook contains the code sample found in Chapter 5, Section 2 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more conte...
github_jupyter
import keras keras.__version__ import os, shutil # The path to the directory where the original # dataset was uncompressed original_dataset_dir = '/Users/fchollet/Downloads/kaggle_original_data' # The directory where we will # store our smaller dataset base_dir = '/Users/fchollet/Downloads/cats_and_dogs_small' os.mkd...
0.528533
0.980205
# Qiskit Pulseで高エネルギー状態へアクセスする ほとんどの量子アルゴリズム/アプリケーションでは、$|0\rangle$と$|1\rangle$によって張られた2次元空間で計算が実行されます。ただし、IBMのハードウェアでは、通常は使用されない、より高いエネルギー状態も存在します。このセクションでは、Qiskit Pulseを使ってこれらの状態を探索することにフォーカスを当てます。特に、$|2\rangle$ 状態を励起し、$|0\rangle$、$|1\rangle$、$|2\rangle$の状態を分類するための識別器を作成する方法を示します。 このノートブックを読む前に、[前の章](./calibrating-...
github_jupyter
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.signal import find_peaks from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import train_test_split import qiskit.pulse as pulse import qiskit.pulse.library as pulse_lib f...
0.473414
0.957873
# Inaugural Project - Housing demand and taxation ### - *Mathilde Pilgaard, Klara Krogh Hammerum, Louise Albæk Jensen og Oluf Kelkjær* A given household can spend cash $m$ on either housing or consumption $c$. Quality of housing, $h$, grants household utility and has the cost $p_{h}$ which is subject to progressive tax...
github_jupyter
# Importing relevant packages from scipy import optimize import numpy as np par1 = {'m':0.5, 'phi':0.3, 'epsilon': 0.5, 'r': 0.03, 'tau_g': 0.012, 'tau_p': 0.004, 'p_bar': 3 } # Creating utility function def u_func(c, h, phi): return c**(1-phi)*h**phi # Creating o...
0.591959
0.938857
# Introduction This notebook shows how to run a strategy against feeds from the Binance crypto exchange using the **roboquant** algo-trading framework. <img src="https://upload.wikimedia.org/wikipedia/commons/1/12/Binance_logo.svg" alt="Binance" width="400"/> Roboquant includes a dedicated module for crypto trading...
github_jupyter
%use @http://roboquant.org/roboquant-crypto.json Welcome() feed.retrieve("BTCBUSD", "ETHBUSD", interval = Interval.FIVE_MINUTES, timeframe = tf, limit = 250) val feed = BinanceHistoricFeed() val tf = Timeframe.past(500.days) feed.retrieve("BTCBUSD", "ETHBUSD", timeframe = tf) feed.timeframe for (asset in feed.assets...
0.709019
0.985608
``` import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/ubuntu/mesolitica-tpu.json' import string char_vocabs = [''] + list(string.ascii_lowercase + string.digits) + [' '] sr = 16000 maxlen = 18 maxlen_subwords = 100 minlen_text = 1 global_count = 0 from google.cloud import storage import numpy as np impor...
github_jupyter
import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/ubuntu/mesolitica-tpu.json' import string char_vocabs = [''] + list(string.ascii_lowercase + string.digits) + [' '] sr = 16000 maxlen = 18 maxlen_subwords = 100 minlen_text = 1 global_count = 0 from google.cloud import storage import numpy as np import si...
0.311846
0.178025
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); </script> # `GiRaFFE_NRPy` C code library: Conservative-to-Primitive ...
github_jupyter
par.initialize_param(par.glb_param(type="bool", module=thismodule, parname="enforce_orthogonality_StildeD_BtildeU", defaultval=True)) par.initialize_param(par.glb_param(type="bool", module=thismodule, parname="enforce_speed_limit_StildeD", defaultval=True)) par.initialize_param(par.glb_param(type="bool", module=thismod...
0.540681
0.932944
# Computing Galactic Orbits of Stars with Gala ## Authors Adrian Price-Whelan, Stephanie T. Douglas ## Learning Goals * Query the Gaia data release 2 catalog to retrieve data for a sample of well-measured, nearby stars * Define high-mass and low-mass stellar samples using color-magnitude selections * Calculate orbits...
github_jupyter
# astropy imports import astropy.coordinates as coord from astropy.table import QTable import astropy.units as u from astroquery.gaia import Gaia # Third-party imports import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np %matplotlib inline # gala imports import gala.coordinates as gc import gal...
0.673621
0.991836
# Running PARC for clustering analysis of Covid-19 scRNA cells ### Introduction Parc is a fast clustering algorithm designed to effectively cluster heterogeneity in large single cell data. We show how PARC enables downstream analysis on the recent dataset published by [Liao. et al (2020)](https://www.nature.com/articl...
github_jupyter
import matplotlib.pyplot as plt import warnings from numba.errors import NumbaPerformanceWarning import numpy as np import pandas as pd import scanpy as sc import parc import harmonypy as hm datadir = "/home/shobi/Thesis/Data/Covid/GSE145926_RAW/" file_batches = ['GSM4475051_C148_filtered_feature_bc_matrix.h5','GSM447...
0.31363
0.88642
# Diversificación y fuentes de riesgo en un portafolio II - Una ilustración con mercados internacionales. <img style="float: right; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/5/5f/Map_International_Markets.jpg" width="500px" height="300px" /> > Entonces, la clase pasada vimos cómo...
github_jupyter
# Importamos pandas y numpy import pandas as pd import numpy as np # Resumen en base anual de rendimientos esperados y volatilidades annual_ret_summ = pd.DataFrame(columns=['EU', 'RU', 'Francia', 'Alemania', 'Japon'], index=['Media', 'Volatilidad']) annual_ret_summ.loc['Media'] = np.array([0.1355, 0.1589, 0.1519, 0.143...
0.303113
0.987129
<div style="width: 100%; overflow: hidden;"> <div style="width: 150px; float: left;"> <img src="https://raw.githubusercontent.com/DataForScience/Networks/master/data/D4Sci_logo_ball.png" alt="Data For Science, Inc" align="left" border="0" width=150px> </div> <div style="float: left; margin-left: 10px;"> <h1>Tra...
github_jupyter
from collections import Counter from pprint import pprint import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import openpyxl import watermark %load_ext watermark %matplotlib inline %watermark -n -v -m -g -iv plt.style.use('./d4sci.mplstyle') book = openpyxl.Workbook() boo...
0.274643
0.969498
``` #Importing the required libraries import pandas as pd ``` ## Dynamic Asset Allocation or Balanced Advantage Fund These mutual funds invest in both Stocks and Debt/Bonds. Allocation between debt and socks can vary as per market conditions. ## Exctracting Dynamic Asset Allocation or Balanced Advantage Mutual Fund'...
github_jupyter
#Importing the required libraries import pandas as pd daa_lump_sum_rtn = pd.read_html( "https://www.moneycontrol.com/mutual-funds/performance-tracker/returns/dynamic-asset-allocation-or-balanced-advantage.html") df1 = pd.DataFrame(daa_lump_sum_rtn[0]) #Renaming historical returns column names df1.rename({'1W': '1W...
0.466846
0.866698
# Produce Eastern Hydro Profile Using Multiple Data Sources Following data sources are used to generate eastern_hydro_v3.csv * EIA monthly net generation for conventional hydro plants from Form 923 * Hourly total hydro generation profiles of 4 Independent System Operators (ISO): ISONE, NYISO, PJM and SWPP in 2016 * Ho...
github_jupyter
import json import pytz import pandas as pd from tqdm import tqdm from collections import defaultdict from timezonefinder import TimezoneFinder from powersimdata.input.grid import Grid from powersimdata.network.usa_tamu.constants.zones import (interconnect2loadzone, ...
0.451568
0.872728
# Functions One of the core principles of any programming language is, **"Don't Repeat Yourself"**. If you have an action that should occur many times, you can define that action once and then call that code whenever you need to carry out that action. We are already repeating ourselves in our code, so this is a goo...
github_jupyter
# Let's define a function. def function_name(argument_1, argument_2): # Do whatever we want this function to do, # using argument_1 and argument_2 # Use function_name to call the function. function_name(value_1, value_2) print("2+2 is equal to: ", 2+2) print("3+2 is equal to: ", 3+2) print("3+3 is equal to: ...
0.444565
0.974629
<a href="https://colab.research.google.com/github/BaiganKing/DS-Unit-2-Kaggle-Challenge/blob/master/module1/assignment_kaggle_challenge_1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science, Unit 2: Predictive Modeling # Kagg...
github_jupyter
train['functional'] = (train['status_group']=='functional').astype(int) # Reduce cardinality for NEIGHBORHOOD feature ... # Get a list of the top 10 neighborhoods top10 = train['NEIGHBORHOOD'].value_counts()[:10].index # At locations where the neighborhood is NOT in the top 10, # replace the neighborhood with 'OTHER...
0.385375
0.974797
# Imports ``` import math import pandas as pd import pennylane as qml import time from keras.datasets import mnist from matplotlib import pyplot as plt from pennylane import numpy as np from pennylane.templates import AmplitudeEmbedding, AngleEmbedding from pennylane.templates.subroutines import ArbitraryUnitary from...
github_jupyter
import math import pandas as pd import pennylane as qml import time from keras.datasets import mnist from matplotlib import pyplot as plt from pennylane import numpy as np from pennylane.templates import AmplitudeEmbedding, AngleEmbedding from pennylane.templates.subroutines import ArbitraryUnitary from sklearn.decomp...
0.549157
0.879665
# cMLP Lagged VAR Demo - In this notebook, we train a cMLP model on linear VAR data with lagged interactions. - After examining the Granger causality discovery, we train a debiased model using only the discovered interactions. ``` import torch import numpy as np import matplotlib.pyplot as plt from synthetic import s...
github_jupyter
import torch import numpy as np import matplotlib.pyplot as plt from synthetic import simulate_lorenz_96 from models.cmlp import cMLP, cMLPSparse, train_model_ista, train_unregularized # For GPU acceleration device = torch.device('cuda') # Simulate data p = 10 X_np, GC = simulate_lorenz_96(p=p, F=5, T=1000, delta_t=1) ...
0.715821
0.895294
# Predict phonon DoS for new materials and evaluate their specific heat capacities - `ComprehensiveEvaluation`: the function that evaluate phonon DoS and heat capacities with the input `*.cif` file - `AtomEmbeddingAndSumLastLayer`: the model function ``` import glob import torch import torch_geometric import torch_sc...
github_jupyter
import glob import torch import torch_geometric import torch_scatter import e3nn from e3nn import rs, o3 from e3nn.point.data_helpers import DataPeriodicNeighbors from e3nn.networks import GatedConvParityNetwork from e3nn.kernel_mod import Kernel from e3nn.point.message_passing import Convolution import pymatgen from...
0.413004
0.808823
# Deep Deterministic Policy Gradients (DDPG) --- In this notebook, we train DDPG with OpenAI Gym's Pendulum-v0 environment. ### 1. Import the Necessary Packages ``` import gym import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline from ddpg_agen...
github_jupyter
import gym import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline from ddpg_agent import Agent env = gym.make('Pendulum-v1') env.seed(2) agent = Agent(state_size=3, action_size=1, random_seed=2) def ddpg(n_episodes=1000, max_t=300, print_every=1...
0.454472
0.936401
``` import pandas as pd import numpy as np df = pd.read_csv('./data/in_micro_PERSONS_PerthOnly_2011.csv') df.rename(columns={ 'AREAENUM':'sample_geog', "ABSHID":'serialno' },inplace=True) zonecol = 'sample_geog' df.columns df def produce_one_marginal(col, df): gdf = pd.DataFrame(df[[zonecol,col]]) gdf ...
github_jupyter
import pandas as pd import numpy as np df = pd.read_csv('./data/in_micro_PERSONS_PerthOnly_2011.csv') df.rename(columns={ 'AREAENUM':'sample_geog', "ABSHID":'serialno' },inplace=True) zonecol = 'sample_geog' df.columns df def produce_one_marginal(col, df): gdf = pd.DataFrame(df[[zonecol,col]]) gdf = gd...
0.132739
0.210604
# Titanic's data analysis and machine learning ## By Jérémy P. Schneider As someone new in this field, I decided to take my first challenge with the Titanic dataset from Kaggle (https://www.kaggle.com/c/titanic) ## My OS For this work I used a computer with : * Windows 7 * Intel(R) Core(TM) i5-2500K CPU @ 3.3...
github_jupyter
import time import pandas as pd import matplotlib.pyplot as plt import math import seaborn as sns import numpy as np from sklearn import svm from sklearn.preprocessing import MinMaxScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection ...
0.242475
0.945801
``` import matplotlib.pyplot as plt import matplotlib.ticker as mtick import numpy as np import os import pandas as pd import math %matplotlib inline # Load data from filesystem df = pd.read_csv('/kaggle/input/survey_results_public.csv', delimiter=',', nrows = None) df.dataframeName = 'survey_results_public.csv' pand...
github_jupyter
import matplotlib.pyplot as plt import matplotlib.ticker as mtick import numpy as np import os import pandas as pd import math %matplotlib inline # Load data from filesystem df = pd.read_csv('/kaggle/input/survey_results_public.csv', delimiter=',', nrows = None) df.dataframeName = 'survey_results_public.csv' pandasVe...
0.788217
0.689423
<a href="https://colab.research.google.com/github/aly202012/Teaching/blob/master/Copy_of_dataexploration.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64] print(data) impor...
github_jupyter
data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64] print(data) import numpy as np grades = np.array(data) print(grades) # حدثت مضاعفه للبيانات الاصليه من حيث العدد print (type(data),'x 2:', data * 2) print('---') # تم تطبيق عمليه حسابيه علي القيم الموجوده وبالتالي تضاعفت الارقام من حيث ال...
0.187207
0.810028
<div align="right" style="text-align:right"><i>Peter Norvig<br>May 2015</i></div> # When Cheryl Met Eve: A Birthday Story The *Cheryl's Birthday* logic puzzle [made the rounds](https://www.google.com/webhp?#q=cheryl%27s+birthday), and I wrote [code](Cheryl.ipynb) that solves it. In that notebook I said that one rea...
github_jupyter
# Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. # Cheryl gave them a list of 10 possible dates: dates = ['May 15', 'May 16', 'May 19', 'June 17', 'June 18', 'July 14', 'July 16', 'August 14', 'August 15', 'August 17'] def month(date): ...
0.621196
0.921145
<title>Learn Quantum Computation using Qiskit</title> <div class="preface-top"> <div class="preface-checker-pattern"></div> <div class="preface-summary"> <aside class="preface-summary-image"><img src="images/preface_illustration_2.svg"></aside> <div class="preface-summary-text"> <p> Greetings from th...
github_jupyter
# Click 'try', then 'run' to see the output, # you can change the code and run it again. print("This code works!") from qiskit import QuantumCircuit qc = QuantumCircuit(2) # Create circuit with 2 qubits qc.h(0) # Do H-gate on q0 qc.cx(0,1) # Do CNOT on q1 controlled by q0 qc.measure_all() qc.draw()
0.302288
0.92912
``` # install keras, tensorflow and tflearn # (1) Importing dependency import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten,\ Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization import numpy as np np.random.seed(1000) # (2) Get Data i...
github_jupyter
# install keras, tensorflow and tflearn # (1) Importing dependency import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten,\ Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization import numpy as np np.random.seed(1000) # (2) Get Data impor...
0.91282
0.697879
``` #使用seaborn %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_context("paper",font_scale=1.5,rc={'figure.dpi':300}) sns.set_style("ticks") # 风格选择包括:"white", "dark", "whitegrid", "darkgrid", "ticks" sns.set_style({'font.sans-serif': ['SimHei', 'C...
github_jupyter
#使用seaborn %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_context("paper",font_scale=1.5,rc={'figure.dpi':300}) sns.set_style("ticks") # 风格选择包括:"white", "dark", "whitegrid", "darkgrid", "ticks" sns.set_style({'font.sans-serif': ['SimHei', 'Calib...
0.219505
0.237267
# Lesson 3 Exercise 1: Three Queries Three Tables <img src="images/cassandralogo.png" width="250" height="250"> ### Walk through the basics of creating a table in Apache Cassandra, inserting rows of data, and doing a simple CQL query to validate the information. You will practice Denormalization, and the concept of 1 ...
github_jupyter
import cassandra from cassandra.cluster import Cluster try: cluster = Cluster(['127.0.0.1']) #If you have a locally installed Apache Cassandra instance session = cluster.connect() except Exception as e: print(e) try: session.execute(""" CREATE KEYSPACE IF NOT EXISTS udacity WITH REPLICATION ...
0.187579
0.902695
``` import pandas as pd import numpy as np import requests import bs4 as bs import urllib.request ``` ## Extracting features of 2020 movies from Wikipedia ``` link = "https://en.wikipedia.org/wiki/List_of_American_films_of_2020" source = urllib.request.urlopen(link).read() soup = bs.BeautifulSoup(source,'lxml') table...
github_jupyter
import pandas as pd import numpy as np import requests import bs4 as bs import urllib.request link = "https://en.wikipedia.org/wiki/List_of_American_films_of_2020" source = urllib.request.urlopen(link).read() soup = bs.BeautifulSoup(source,'lxml') tables = soup.find_all('table',class_='wikitable sortable') len(tables)...
0.208098
0.413773
# Everything is object in Python # 1 Pass through arguments in constructor ``` class Passthrough: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) pt = Passthrough(name="Zhaokang", age=35) pt.name ``` # 2 Inheritance > The order of base class defined...
github_jupyter
class Passthrough: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) pt = Passthrough(name="Zhaokang", age=35) pt.name class Base: # pass def __init__(self, name, **kwargs): print(name) print(kwargs) class Derived(Base): ...
0.682574
0.647032
``` %load_ext autoreload %autoreload 2 # default_exp pod.client ``` # Pod Client ``` # export from pyintegrators.data.itembase import Edge, ItemBase from pyintegrators.indexers.facerecognition.photo import resize from pyintegrators.data.schema import * from pyintegrators.imports import * from hashlib import sha256 # ...
github_jupyter
%load_ext autoreload %autoreload 2 # default_exp pod.client # export from pyintegrators.data.itembase import Edge, ItemBase from pyintegrators.indexers.facerecognition.photo import resize from pyintegrators.data.schema import * from pyintegrators.imports import * from hashlib import sha256 # export DEFAULT_POD_ADDRESS...
0.240329
0.400544
We left off with the disturbing realization that even though we are satisfied the requirements of the sampling theorem, we still have errors in our approximating formula. We can resolve this by examining the Whittaker interpolating functions which are used to reconstruct the signal from its samples. ``` %pylab inline...
github_jupyter
%pylab inline from __future__ import division t = linspace(-5,5,300) # redefine this here for convenience fig,ax = subplots() fs=5.0 ax.plot(t,sinc(fs * t)) ax.grid() ax.annotate('This keeps going...', xy=(-4,0), xytext=(-5+.1,0.5), arrowprops={'facecolor':'green','shrink':0.05},f...
0.622574
0.986218
<h1 align='center'>WebScraping TripAdvisor</h1> --- El código a continuación tiene por objetivo extraer la **[información solicitada](https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-win64.zip "Word en Google Drive")**, desde la página de **[TripAdvisor](https://www.tripadvisor.cl/...
github_jupyter
%%capture --no-display import warnings warnings.filterwarnings('ignore') import os print(f'Si es la primera vez que corre este programa, por favor abra la terminal PowerShell de Anaconda' + f' e ingrese el siguiente comando: "\033[4mpip install -r {os.getcwd()}\\requirements.txt\033[4m"') import time import p...
0.220091
0.844601
# Rates calculation This notebooks demonstrates basic rates calculation method. We say "basic" because we have also implemented a PyTorch module for rates calculation that can work on GPU. ``` import sys import numpy as np import pandas as pd from datetime import timedelta sys.path.append('..') from deepfield impor...
github_jupyter
import sys import numpy as np import pandas as pd from datetime import timedelta sys.path.append('..') from deepfield import Field model = Field('../open_data/norne_simplified/norne_simplified.data').load() (model.wells .drop_incomplete() .get_wellblocks(model.grid) .drop_outside() .apply_perforations() .calcu...
0.198841
0.839767
``` %matplotlib inline ``` # Pyplot tutorial An introduction to the pyplot interface. Intro to pyplot =============== :mod:`matplotlib.pyplot` is a collection of command style functions that make matplotlib work like MATLAB. Each ``pyplot`` function makes some change to a figure: e.g., creates a figure, creates a...
github_jupyter
%matplotlib inline import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show() plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis([0, 6, 0, 20]) plt.show() import numpy as np # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2)...
0.741487
0.987017
In this notebook, we will use a multi-layer perceptron to develop time series forecasting models. The dataset used for the examples of this notebook is on air pollution measured by concentration of particulate matter (PM) of diameter less than or equal to 2.5 micrometers. There are other variables such as air pressure,...
github_jupyter
from __future__ import print_function import os import sys import pandas as pd import numpy as np %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import datetime #set current working directory os.chdir('D:/Practical Time Series') #Read the dataset into a pandas.DataFrame df = pd.read_csv('...
0.628635
0.982757
``` # %load setup.py import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.ticker as mtick from itertools import product %run helpers.ipynb params_suffstat = pd.read_csv('output/params_suffstat.csv') params_sim = pd.read_csv('output/params_sim.csv') params_full = pd.concat([params_suf...
github_jupyter
# %load setup.py import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.ticker as mtick from itertools import product %run helpers.ipynb params_suffstat = pd.read_csv('output/params_suffstat.csv') params_sim = pd.read_csv('output/params_sim.csv') params_full = pd.concat([params_suffsta...
0.527803
0.551815
``` import clustertools as ctools import numpy as np from astropy.table import QTable import matplotlib.pyplot as plt ``` # Loading and Advancing **Loading** To manually load a snapshot of a cluster, simply read in the file via your preferred method, declare a StarCluster with the appropriate units and origin, and a...
github_jupyter
import clustertools as ctools import numpy as np from astropy.table import QTable import matplotlib.pyplot as plt m,x,y,z,vx,vy,vz=np.loadtxt('00000.dat',unpack=True) cluster=ctools.StarCluster(units='pckms',origin='cluster') cluster.add_stars(x,y,z,vx,vy,vz,m) ctools.starplot(cluster) cluster.analyze() print('Total...
0.556159
0.896523
``` import torch import numpy as np from torch import nn, optim import pandas as pd from sklearn.preprocessing import StandardScaler, RobustScaler from sklearn.model_selection import StratifiedKFold import torch.nn.functional as F import torchvision from sklearn.metrics import accuracy_score, confusion_matrix,f1_score...
github_jupyter
import torch import numpy as np from torch import nn, optim import pandas as pd from sklearn.preprocessing import StandardScaler, RobustScaler from sklearn.model_selection import StratifiedKFold import torch.nn.functional as F import torchvision from sklearn.metrics import accuracy_score, confusion_matrix,f1_score, pr...
0.867148
0.692408
# Text Generation with LSTM Recurrent neural networks are also known for their ability to generate text. As a result, the output of the neural network can be free-form text. In this section, we will see how to train an LSTM can on a textual document, such as classic literature, and learn to output new text that app...
github_jupyter
from tensorflow.keras.callbacks import LambdaCallback from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.utils import get_file import numpy as np import random import sys ...
0.625896
0.992349
# スキーム確認ツール for Navis(I1,I2,I3,I4,A26) #### excelの全シートを読み込んでDFに格納 新しいフロートの生データ(テキスト版)からJAMSTECのデコード用DBに登録用のフィールドが存在するかを判定する ``` import os import pandas as pd import re import termcolor import Levenshtein # レーベンシュタイン距離ライブラリにある、ジャロ・ウインクラー距離を計算するのに使う # jaro_dist = Levenshtein.jaro_winkler(srt1 , str2) navis_excel = pd....
github_jupyter
import os import pandas as pd import re import termcolor import Levenshtein # レーベンシュタイン距離ライブラリにある、ジャロ・ウインクラー距離を計算するのに使う # jaro_dist = Levenshtein.jaro_winkler(srt1 , str2) navis_excel = pd.read_excel('Navis.xlsx' , sheet_name=None) # sheet_name=Noneで全てのシート読み込む def jaro_dist(str1,str2): return Levenshtein.jaro_win...
0.043437
0.80567
# Source contributions ``` import pickle import numpy as np import netCDF4 as nc import pandas as pd from calendar import monthrange %matplotlib inline ``` ###### Parameters: ``` # domain dimensions: imin, imax = 1479, 2179 jmin, jmax = 159, 799 isize = imax-imin jsize = jmax-jmin # Mn model result folders: folder...
github_jupyter
import pickle import numpy as np import netCDF4 as nc import pandas as pd from calendar import monthrange %matplotlib inline # domain dimensions: imin, imax = 1479, 2179 jmin, jmax = 159, 799 isize = imax-imin jsize = jmax-jmin # Mn model result folders: folder_ref = '/data/brogalla/run_storage/Mn-reference-202...
0.323594
0.668124
# Traveling Salesman Problem ## Objective and Prerequisites In this notebook, you will learn how to: 1. Formulate the Traveling Salesman Problem (TSP) as a MIP model. 2. Use lazy constraints to identify solutions of the TSP problem that are infeasible. This modeling example is at the advanced level, where we assume ...
github_jupyter
import json # Read capital names and coordinates from json file capitals_json = json.load(open('capitals.json')) capitals = [] coordinates = {} for state in capitals_json: if state not in ['AK', 'HI']: capital = capitals_json[state]['capital'] capitals.append(capital) coordinates[capital] = (floa...
0.504883
0.983391
## Deep Learning Challenge ### Loading the CIFAR10 data The data can be loaded directly from keras (`keras.datasets.cifar10`). ```python cifar10 = keras.datasets.cifar10 (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() ``` ``` from tensorflow.keras.models import Sequential from tensorfl...
github_jupyter
cifar10 = keras.datasets.cifar10 (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Convolution2D from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers import Flatten from tensorflow.k...
0.912974
0.976602
## Exploring `Series` and `DataFrame` Objects ### Working with pandas *Curtis Miller* Let's create some `Series`. ``` import pandas as pd from pandas import Series, DataFrame import numpy as np ser1 = Series([1, 2, 3, 4]) ser2 = Series(['a', 'b', 'c']) print(ser1) print(ser2) # Create a pandas Index idx = pd.Index(["...
github_jupyter
import pandas as pd from pandas import Series, DataFrame import numpy as np ser1 = Series([1, 2, 3, 4]) ser2 = Series(['a', 'b', 'c']) print(ser1) print(ser2) # Create a pandas Index idx = pd.Index(["New York", "Los Angeles", "Chicago", "Houston", "Philadelphia", "Phoenix", "San Antonio", ...
0.457621
0.938969
# R: Impact of 401(k) on Financial Wealth In this real-data example, we illustrate how the [DoubleML](https://docs.doubleml.org/stable/index.html) package can be used to estimate the effect of 401(k) eligibility and participation on accumulated assets. The 401(k) data set has been analyzed in several studies, among ot...
github_jupyter
# Load required packages for this tutorial library(DoubleML) library(mlr3) library(mlr3learners) library(data.table) library(ggplot2) # suppress messages during fitting lgr::get_logger("mlr3")$set_threshold("warn") # load data as a data.table data = fetch_401k(return_type = "data.table", instrument = TRUE) dim(data)...
0.792986
0.984351
# Create a Local Docker Image In this section, we will create an IoT Edge module, a Docker container image with an HTTP web server that has a scoring REST endpoint. ## Get Global Variables ``` import sys sys.path.append('../../../common') from env_variables import * ``` ## Create Web Application & Inference Server f...
github_jupyter
import sys sys.path.append('../../../common') from env_variables import * %%writefile $lvaExtensionPath/app.py import threading import cv2 import numpy as np import io import onnxruntime import json import logging import linecache import sys from score import MLModel, PrintGetExceptionDetails from flask import Flask, ...
0.171616
0.461077
## Heat flow estimation from aerial radiometric measurements. In this notebook we are concerned with the image processing of radiometric maps from Nova Scotia https://novascotia.ca/natr/meb/download/dp163.asp and the subsequent estimate of heat flow following the equations in Beamish and Busby (2016). ### About the d...
github_jupyter
""" If the colourmap matches all or part of the colour wheel or hue circle, we can decompose the image to HSV and use H as a proxy for the data. """ from io import BytesIO import matplotlib.pyplot as plt import numpy as np from PIL import Image import requests from skimage.color import rgb2hsv import glob def heat_equ...
0.845209
0.972934
# Distirbuted Training of Mask-RCNN in Amazon SageMaker using EFS This notebook is a step-by-step tutorial on distributed tranining of [Mask R-CNN](https://arxiv.org/abs/1703.06870) implemented in [TensorFlow](https://www.tensorflow.org/) framework. Mask R-CNN is also referred to as heavy weight object detection model...
github_jupyter
aws_region = # <aws-region> s3_bucket = # <your-s3_bucket> !cat ./prepare-s3-bucket.sh %%time !./prepare-s3-bucket.sh {s3_bucket} !cat ./prepare-efs.sh %%time !./prepare-efs.sh {s3_bucket} !cat ./container/build_tools/build_and_push.sh %%time ! ./container/build_tools/build_and_push.sh {aws_region} tensorpack_i...
0.452536
0.966663
# Analyzing a PAC I'm trying to understand the spending habits of the Microsoft PAC since I work there. The following is primarily based on the code from [this workbook](https://github.com/boblannon/blogpost_fec-api-howto/blob/master/fec_api.ipynb) from [Bob Lannon](https://github.com/boblannon) that explains how to us...
github_jupyter
%pylab inline import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import numpy as np import pandas as pd import requests import os import json from copy import deepcopy import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s') logging.getLogger("requests").setLevel(logging.ERROR...
0.195786
0.832985
# VacationPy ---- #### Note * Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing. * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think throug...
github_jupyter
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import gmaps import os # Import API key from api_keys import g_key csvpath = '../WeatherPy/output_data/cities.csv' cities_df = pd.read_csv(csvpath) cities_df['Max Temp'] = cities_df['Max Temp']*9/5 -459.67...
0.677581
0.844216
``` %matplotlib inline import datetime as dt import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from alphamind.api import * from PyFin.api import * plt.style.use('ggplot') engine = SqlEngine('postgres+psycopg2://postgres:A12345678!@10.63.6.220/alp...
github_jupyter
%matplotlib inline import datetime as dt import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from alphamind.api import * from PyFin.api import * plt.style.use('ggplot') engine = SqlEngine('postgres+psycopg2://postgres:A12345678!@10.63.6.220/alpha')...
0.5144
0.600423
# Iris species classification. **Problem statement** - Given _Sepal Length_ ,_Sepal width_, _Petal length_ and _Petal width_ classify each instance into one of **Iris-setosa, Iris-versicolor or Iris-virginica** species using Machine learning Classification algorithms. ## Importing the required libraries. ``` impor...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, f1_score, confusion_matrix, classification_report from sklearn.tree import DecisionTr...
0.758153
0.939526
## 实体链指比赛方案分享 ### 1. **任务与难点介绍** 面向中文短文本的实体链指,简称 EL(Entity Linking),是NLP、知识图谱领域的基础任务之一,即对于给定的一个中文短文本(如搜索 Query、微博、对话内容、文章/视频/图片的标题等),EL将其中的实体与给定知识库中对应的实体进行关联。 此次任务的输入输出定义如下: 输入:中文短文本以及该短文本中的实体集合。 输出:输出文本此中文短文本的实体链指结果。每个结果包含:实体 mention、在中文短文本中的位置偏移、其在给定知识库中的 id,如果为 NIL 情况,需要再给出实体的上位概念类型。 传统的实体链指任务主要是针对长文档,长文档拥有在写的上下文信息...
github_jupyter
## 环境配置:基于PaddlePaddle 1.8.4开发(python 3.7), 使用单块V100(32G)训练 ## 各个文件的作用: ### eval.py 官方提供的评估脚本 ### post_matching.py 实体消歧模型后处理,对每个实体选取概率最大的一个作为kb_id(若小于一个阈值,则取NIL)(单模) ### main_nil.py 实体分类模型的推理代码,对实体消歧模型预测为NIL的实体预测其类别 ### post_nil.py 实体分类模型的后处理代码,生成提交文件(单模) ### utils.py 定义各种训练,推理过程中需要的函数等 ### main_matching.py 实...
0.196094
0.63576
<a href="https://colab.research.google.com/github/szoha/test/blob/master/Copy_of_astho_ubaid.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Introduction In this notebook, we implement [YOLOv4](https://arxiv.org/pdf/2004.10934.pdf) for training o...
github_jupyter
!git clone https://github.com/roboflow-ai/pytorch-YOLOv4.git %cd /content/pytorch-YOLOv4 !pip install -r requirements.txt # download yolov4 weights that have already been converted to PyTorch !gdown https://drive.google.com/uc?id=1fcbR0bWzYfIEdLJPzOsn4R5mlvR6IQyA # REPLACE this link with your Roboflow dataset (export ...
0.425605
0.973215
``` import requests import simplejson as json import pandas as pd import numpy as np import os import json import math from openpyxl import load_workbook notebook_path = os.path.abspath("OLS matching.ipynb") # Path to config file config_path = os.path.join(os.path.dirname(notebook_path), "Data/config.json") # Path to...
github_jupyter
import requests import simplejson as json import pandas as pd import numpy as np import os import json import math from openpyxl import load_workbook notebook_path = os.path.abspath("OLS matching.ipynb") # Path to config file config_path = os.path.join(os.path.dirname(notebook_path), "Data/config.json") # Path to asc...
0.469277
0.216239
# CSCE 5290 - Final Project ## Pre-trained model evaluation (BART, T5) Dan Waters (danwaters@my.unt.edu) ``` !pip install transformers from transformers import pipeline summarizer = pipeline("summarization") # Get the data (not the one with the start tokens) !gdown --id 17u3TvSpRq17mFVJ1pEKf6D9fYgBFj4lI import pandas ...
github_jupyter
!pip install transformers from transformers import pipeline summarizer = pipeline("summarization") # Get the data (not the one with the start tokens) !gdown --id 17u3TvSpRq17mFVJ1pEKf6D9fYgBFj4lI import pandas as pd cnn_df = pd.read_csv('cnn_cleaned_test_10k.csv') cnn_df = cnn_df[['text', 'summary']] cnn_df.head(5) art...
0.443841
0.752581
``` import numpy as np import scipy.stats as stats from matplotlib import pyplot as plt x = np.arange(0, 1, 0.01) uno = np.full(x.shape,1) low = np.full(x.shape,0.01) ph = 0.5 #plt.rcParams['figure.dpi'] = 72 plt.rcParams['figure.figsize'] = [10, 10] plt.xticks([0,1 / 6, 0.25, 3/8, 0.5, 5/8, 0.75, 5/6,1]) plt.plot(...
github_jupyter
import numpy as np import scipy.stats as stats from matplotlib import pyplot as plt x = np.arange(0, 1, 0.01) uno = np.full(x.shape,1) low = np.full(x.shape,0.01) ph = 0.5 #plt.rcParams['figure.dpi'] = 72 plt.rcParams['figure.figsize'] = [10, 10] plt.xticks([0,1 / 6, 0.25, 3/8, 0.5, 5/8, 0.75, 5/6,1]) plt.plot(x,un...
0.411111
0.725041
<h1 style="text-align:center">Deep Learning </h1> <h1 style="text-align:center"> Lab Session 2 - 3 Hours </h1> <h1 style="text-align:center"> Convolutional Neural Network (CNN) for Handwritten Digits Recognition</h1> <b> Student 1:</b> CANALE <b> Student 2:</b> ELLENA The aim of this session is to practice with...
github_jupyter
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test =...
0.832509
0.985608
This notebook is part of the `nbsphinx` documentation: https://nbsphinx.readthedocs.io/. # Code Cells ## Code, Output, Streams An empty code cell: Two empty lines: ``` ``` Leading/trailing empty lines: ``` # 2 empty lines before, 1 after ``` A simple output: ``` 6 * 7 ``` The standard output stream: ``` pr...
github_jupyter
``` Leading/trailing empty lines: A simple output: The standard output stream: Normal output + standard output The standard error stream is highlighted and displayed just below the code cell. The standard output stream comes afterwards (with no special highlighting). Finally, the "normal" output is display...
0.779574
0.949389
**This notebook is an exercise in the [Introduction to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/machine-learning-competitions).** --- # Introduction In this exercise, you will create and submit ...
github_jupyter
# Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.machine_learning.ex7 import * # Set up filepaths import os if not os.path.exists("../input/train.csv"): os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv") os.symlink("../input/home-dat...
0.640299
0.955527
# Inverse Kinematics Optimization The previous doc explained features and how they define objectives of a constrained optimization problem. Here we show how to use this to solve IK optimization problems. At the bottom there is more general text explaining the basic concepts. ## Demo of features in Inverse Kinematics...
github_jupyter
import sys sys.path.append('../../lib') #rai/lib') import numpy as np import libry as ry C = ry.Config() C.addFile('../../../rai-robotModels/pr2/pr2.g') C.addFile('../../../rai-robotModels/objects/kitchen.g') C.view() goal = C.addFrame("goal") goal.setShape(ry.ST.sphere, [.05]) goal.setColor([.5,1,1]) goal.setPosition...
0.337749
0.95594
# ml lab6 ``` import numpy as np import matplotlib.pyplot as plt import scipy.io ``` ### 1. read data ``` data = scipy.io.loadmat('data/ex6data1.mat') X = data['X'] X.shape ``` ### 2. random init centroids ``` def rand_centroids(X, K): rand_indices = np.arange(len(X)) np.random.shuffle(rand_indices) c...
github_jupyter
import numpy as np import matplotlib.pyplot as plt import scipy.io data = scipy.io.loadmat('data/ex6data1.mat') X = data['X'] X.shape def rand_centroids(X, K): rand_indices = np.arange(len(X)) np.random.shuffle(rand_indices) centroids = X[rand_indices][:K] return centroids rand_centroids(X, 3) def ...
0.430147
0.918663
# Pandoc Markdown Syntax Pandoc supports a large number of input file formats for processing (including markdown, reStructuredText, textile, HTML, DocBook, LaTeX, MediaWiki markup, TWiki markup, OPML, Emacs Org-Mode, Txt2Tags, Microsoft Word docx, LibreOffice ODT, EPUB, or Haddock markup) into a vast number of output ...
github_jupyter
3**4 % title % author(s) (separated by semicolons) % date (treated as a text string) --- title: title author: author(s) (separated by semicolons) date: date (treated as a text string) ... # Level One ## Level Two ### Level Three ... ###### Level Six A Level One Header ================== A Level Two Header --------...
0.915427
0.982757
``` import torch import torch.optim as optim import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import numpy as np import time import dataset.dataset as dataset import datasplit.datasplit as datasplit import model.models as models import trainer.trainer as trainer import...
github_jupyter
import torch import torch.optim as optim import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import numpy as np import time import dataset.dataset as dataset import datasplit.datasplit as datasplit import model.models as models import trainer.trainer as trainer import uti...
0.494629
0.624752
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file...
github_jupyter
# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
0.628407
0.400867
# Practical Deep Learning for Coders, v3 # 00_notebook_tutorial **Important note:** You should always work on a duplicate of the course notebook. On the page you used to open this, tick the box next to the name of the notebook and click duplicate to easily create a new version of this notebook.<br> You will get error...
github_jupyter
1+1 3/2 # Import necessary libraries from fastai.vision import * import matplotlib.pyplot as plt from PIL import Image a = 1 b = a + 1 c = b + a + 1 d = c + b + a + 1 a, b, c ,d plt.plot([a,b,c,d]) plt.show() Image.open('images/notebook_tutorial/cat_example.jpg') from fastai import* from fastai.vision import * ?I...
0.243642
0.916969
``` import numpy %matplotlib notebook import matplotlib.pyplot import scipy.interpolate import scipy.integrate import pynverse ``` # Arc Length Reparameterization ## Overview To have control over the speed and acceleration of an object along a path, the path should be parameterized on distance. It is much easier to ...
github_jupyter
import numpy %matplotlib notebook import matplotlib.pyplot import scipy.interpolate import scipy.integrate import pynverse l_a = lambda t: numpy.array([[3 + 0 * t], [0 + 1 * t]]) l_b = lambda t: numpy.array([[1 - 1 * t], [3 + 0 * t]]) fig, ax = matplotlib.pyplot.subplots() t_a = t_b = numpy.linspace(0, 1, 100) ax.p...
0.518059
0.981275
``` import os import pickle import pandas as pd import numpy as np from PIL import Image from keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input from keras.utils import to_categorical from keras.preprocessing import image EMOTIONS = [ "angry", "calm", "disgust", "fear", ...
github_jupyter
import os import pickle import pandas as pd import numpy as np from PIL import Image from keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input from keras.utils import to_categorical from keras.preprocessing import image EMOTIONS = [ "angry", "calm", "disgust", "fear", ...
0.50952
0.379148
# XGBoost Ranklib is a relatively old library and doesn't have the wide spread use that XGBoost does. Ranklib is still under active development, but the fork of the project OSC created reflects an older version. The ES-LTR plugin is designed to work with XGBoost model format. This notebook starts with the `classic` t...
github_jupyter
import ltr.judgments as judge df = [j for j in judge.judgments_from_file(open('data/classic-training.txt'))] df = judge.judgments_to_dataframe(df) df import pandas as pd import xgboost as xgb from matplotlib.pylab import rcParams rcParams['figure.figsize'] = 50,150 df = df[['grade', 'features0']] features = df[['feat...
0.26341
0.924005
# Survival Analysis in Python Chapter 1 Allen B. Downey [MIT License](https://en.wikipedia.org/wiki/MIT_License) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style='white') import ...
github_jupyter
# Configure Jupyter so figures appear in the notebook %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style='white') import utils from utils import decorate from empyrical_dist import Pmf, Cdf Dataset from: V.J. Menon and D.C. Agrawal, Re...
0.796055
0.892609
<a href="https://colab.research.google.com/github/jaya-shankar/education-impact/blob/jaya-shankar/randomForest.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !rm -rf education-impact !rm education-impact !git clone https://github.com/jaya-shank...
github_jupyter
!rm -rf education-impact !rm education-impact !git clone https://github.com/jaya-shankar/education-impact.git !pip install tensorflow_decision_forests !pip install wurlitzer root = "education-impact/" datasets_path = { "infant_mortality" : root+ "datasets/Infant_Mortality_Rate.csv", ...
0.455199
0.904566
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20,20) import os,time from glob import glob from PIL import Image from sklearn import neighbors import re df = pd.read_csv('flags_url.csv') def read_flag(countrycode='IN',file='', res=(128,64)): countrycod...
github_jupyter
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20,20) import os,time from glob import glob from PIL import Image from sklearn import neighbors import re df = pd.read_csv('flags_url.csv') def read_flag(countrycode='IN',file='', res=(128,64)): countrycode = ...
0.158891
0.365145
# Aggregated model - class - test set: 3 domain features ## Table of contents 1. [Linear Regression](#LinearRegression) 2. [MLP (Dense)](#MLP) 3. [AE combined latent](#AE_combined) 4. [AE OTU latent](#AE_latentOTU) ``` import sys sys.path.append('../../Src/') from data import * from train_2 import * from transfer_lea...
github_jupyter
import sys sys.path.append('../../Src/') from data import * from train_2 import * from transfer_learning import * from test_functions import * from layers import * from utils import * from loss import * from metric import * from results import * import tensorflow as tf import tensorflow.keras as keras from tensorflow.k...
0.361277
0.873215
``` class ContosoSIS(BaseOEAModule): def __init__(self, oea, source_folder='contoso_sis', pseudonymize = True): BaseOEAModule.__init__(self, oea, source_folder, pseudonymize) self.schemas['studentattendance'] = [['id', 'string', 'no-op'], ['student_id', 's...
github_jupyter
class ContosoSIS(BaseOEAModule): def __init__(self, oea, source_folder='contoso_sis', pseudonymize = True): BaseOEAModule.__init__(self, oea, source_folder, pseudonymize) self.schemas['studentattendance'] = [['id', 'string', 'no-op'], ['student_id', 'strin...
0.278453
0.238107
# Solve a Generalized Assignment Problem using Lagrangian relaxation This tutorial includes data and information that you need to set up decision optimization engines and build mathematical programming models to solve a Generalized Assignment Problem using Lagrangian relaxation. When you finish this tutorial, you'll...
github_jupyter
import sys try: import docplex.mp except: raise Exception('Please install docplex. See https://pypi.org/project/docplex/') try: import cplex except: raise Exception('Please install CPLEX. See https://pypi.org/project/cplex/') B = [15, 15, 15] C = [ [ 6, 10, 1], [12, 12, 5], [15, 4, 3], ...
0.342022
0.985454
# 项目:全美枪支数据分析 ## 目录 <ul> <li><a href="#intro">简介</a></li> <li><a href="#wrangling">数据整理</a></li> <li><a href="#eda">探索性数据分析</a></li> <li><a href="#conclusions">结论</a></li> </ul> <a id='intro'></a> ## 简介 > 该数据来自联邦调查局 (FBI) 的全国即时犯罪背景调查系统 (NICS)。NICS 用于确定潜在买家是否有资格购买枪支或爆炸物。枪支店可以进入这个系统,以确保每位客户没有犯罪记录或符合资格购买。该数据已经收纳了来自 cen...
github_jupyter
# 用这个框对你计划使用的所有数据包进行设置 # 导入语句。 import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 加载数据并打印几行。进行这几项操作,来检查数据 # 类型,以及是否有缺失数据或错误数据的情况。 df_gun = pd.read_excel('gun_data.xlsx') df_census = pd.read_csv('U.S. Census Data.csv') #分析枪支持有数据 df_gun.info() df_gun.fillna(0, inplace=True...
0.282394
0.842831
# Covid-19 status in Chile > Covid-19 overview in Chile - toc: true - badges: true - comments: true - author: Alonso Silva Allende - categories: [jupyter] - image: images/Chile-total-confirmed-cases.png ``` #hide import numpy as np import pandas as pd import altair as alt #hide from IPython.display import display_htm...
github_jupyter
#hide import numpy as np import pandas as pd import altair as alt #hide from IPython.display import display_html, HTML #hide update_date = pd.to_datetime('today') - pd.offsets.Hour(19) today = update_date.strftime('%Y-%m-%d') today #hide date_one_week_ago = (update_date - pd.offsets.Day(7)).strftime('%Y-%m-%d') date_on...
0.236957
0.645176
``` %load_ext autoreload %autoreload 2 from GPy.models import GPRegression from GPy.kern import Matern52, Exponential from summit.utils.models import GPyModel, ModelGroup from summit.utils.dataset import DataSet from GPy.inference.optimization import Adam, RProp, Optimizer from scipydirect import minimize as direct imp...
github_jupyter
%load_ext autoreload %autoreload 2 from GPy.models import GPRegression from GPy.kern import Matern52, Exponential from summit.utils.models import GPyModel, ModelGroup from summit.utils.dataset import DataSet from GPy.inference.optimization import Adam, RProp, Optimizer from scipydirect import minimize as direct import ...
0.735642
0.689155
# The Inference Button: Bayesian GLMs made easy with PyMC3 Author: Thomas Wiecki This tutorial appeared as a post in a small series on Bayesian GLMs on my blog: 1. [The Inference Button: Bayesian GLMs made easy with PyMC3](http://twiecki.github.com/blog/2013/08/12/bayesian-glms-1/) 2. [This world is far from Nor...
github_jupyter
%matplotlib inline from pymc3 import * import numpy as np import matplotlib.pyplot as plt size = 200 true_intercept = 1 true_slope = 2 x = np.linspace(0, 1, size) # y = a + b*x true_regression_line = true_intercept + true_slope * x # add noise y = true_regression_line + np.random.normal(scale=.5, size=size) data ...
0.77373
0.974067
# Simulations with Model Violations: Aperiodic In this set of simulations, we will test power spectrum parameterization performance across power spectra which violate model assumptions, specifically in the aperiodic component. In particular, we will explore the influence of simulating data and fitting with aperiodic ...
github_jupyter
%matplotlib inline from os.path import join as pjoin import numpy as np import matplotlib.pyplot as plt from scipy.stats import spearmanr, mode from fooof import FOOOF, FOOOFGroup, fit_fooof_3d from fooof.plts import plot_spectrum from fooof.sim import gen_power_spectrum, gen_group_power_spectra from fooof.sim.utils ...
0.687
0.98652
``` import pandas as pd import itertools from sklearn.metrics import confusion_matrix from tqdm import tqdm tqdm.pandas() ``` # Summary ABCD Face recognition models are regular convolutional neural networks models. They represent face photos as vectors. We find the distance between these two vectors to compare tw...
github_jupyter
import pandas as pd import itertools from sklearn.metrics import confusion_matrix from tqdm import tqdm tqdm.pandas() # Ref: https://github.com/serengil/deepface/tree/master/tests/dataset idendities = { "Angelina": ["img1.jpg", "img2.jpg", "img4.jpg", "img5.jpg", "img6.jpg", "img7.jpg", "img10.jpg", "img11.jpg"], ...
0.324985
0.878419
## Dependencies ``` !pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git import warnings, glob from tensorflow.keras import Sequential, Model import efficientnet.tfkeras as efn from cassava_scripts import * seed = 0 seed_everything(seed) warnings.filterwarnings('ig...
github_jupyter
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git import warnings, glob from tensorflow.keras import Sequential, Model import efficientnet.tfkeras as efn from cassava_scripts import * seed = 0 seed_everything(seed) warnings.filterwarnings('ignore') # TPU or GPU ...
0.553264
0.547343
<a href="https://colab.research.google.com/github/nsstnaka/machine_learning_handson/blob/master/stock_price_prediction_with_rnn.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ディープラーニングによる株価予測 直近50営業日の4本値+出来高をもとに、終値を予想します。 ## 前準備 ライブラリのimport ...
github_jupyter
import pandas as pd import pandas_datareader as pdr import numpy as np import tensorflow as tf import seaborn as sns import matplotlib.pyplot as plt tf.__version__ df = pdr.data.DataReader('^DJI', 'yahoo', '2017-04-01', '2020-03-31') # '^DJI'の部分を変えると違う株価を拾える(例:AAPL, GOOG) df.reset_index(inplace=True) # 後続処理のためインデック...
0.558809
0.976625
# Preliminary XGBoost This notebook outlines preliminary work done to tune the XGBoost classifier. **The results in this notebook are superceeded by those in `xgb_tuning.ipynb` for the purposes of the report.** This notebook does however show comparable results for gradient boosting and explores a broader design space....
github_jupyter
import matplotlib.pyplot as plt from sklearn.metrics import roc_curve from sklearn.metrics import auc from itertools import cycle from sklearn.metrics import RocCurveDisplay classes = ['anger', 'fear', 'joy', 'love', 'sadness', 'surprise'] def plot_mc_roc(Y_test_bin, Y_test_proba, n_classes, title='ROC Curve'): ...
0.63375
0.917635
# Modern Data Science **(Module 11: Data Analytics (IV))** --- - Materials in this module include resources collected from various open-source online repositories. - You are free to use, change and distribute this package. Prepared by and for **Student Members** | 2006-2018 [TULIP Lab](http://www.tulip.org.au), Aus...
github_jupyter
from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt %matplotlib inline diabetes = load_diabetes() diabetes_X = diabetes.data[:, None, 2] LinReg = LinearRegression() from sklearn.model_selection import train_test_split X_trainset, X_testset...
0.708313
0.991546
# Single Layer Perceptron ``` import numpy as np class Perceptron(object): def __init__(self, input_size, lr = 1, epochs = 10): self.W = np.zeros(input_size + 1) self.epochs = epochs self.lr = lr def activation_fn(self, x): return 1 if x >= 0 else 0 def predict(self, x): z = self.W.T.dot(...
github_jupyter
import numpy as np class Perceptron(object): def __init__(self, input_size, lr = 1, epochs = 10): self.W = np.zeros(input_size + 1) self.epochs = epochs self.lr = lr def activation_fn(self, x): return 1 if x >= 0 else 0 def predict(self, x): z = self.W.T.dot(x) a = self.activation_fn(z...
0.70416
0.913754
## Evaluating HPO Space of SVD algorithm This notebook contains evaluation of RMSE of SVD models at Movielens datasets using different numbers of factors and regularization constants. Initial setup: imports and working dir ``` import os while not os.path.exists('.gitmodules'): os.chdir('..') from typing import ...
github_jupyter
import os while not os.path.exists('.gitmodules'): os.chdir('..') from typing import Dict import matplotlib.pyplot as plt import pandas as pd from parameters import get_env_parameters from util.hpo_space_eval_utils import eval_svd_hpo_space, visualize_hpo_space from util.datasets import MOVIELENS_100K, MOVIELENS...
0.5144
0.832134
``` %matplotlib inline ``` ImageContainer object ===================== This tutorial shows how to use `squidpy.im.ImageContainer` to interact with image structured data. The ImageContainer is the central object in Squidpy containing the high resolution images. It wraps `xarray.Dataset` and provides different croppin...
github_jupyter
%matplotlib inline import squidpy as sq import numpy as np arr = np.ones((100, 100, 3)) arr[40:60, 40:60] = [0, 0.7, 1] print(arr.shape) img = sq.im.ImageContainer(arr, layer="img1") img arr1 = arr.transpose(2, 0, 1) print(arr1.shape) img = sq.im.ImageContainer(arr1, dims=("channels", "y", "x"), layer="img1") img ...
0.272508
0.990642
## 1. Import Libraries ``` import psycopg2 import pandas as pd import numpy as np import xgboost as xgb import tensorflow as tf from functools import reduce from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImpu...
github_jupyter
import psycopg2 import pandas as pd import numpy as np import xgboost as xgb import tensorflow as tf from functools import reduce from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessi...
0.234582
0.616878
<a href="https://colab.research.google.com/github/yukinaga/ai_programming/blob/main/lecture_05/01_gradient_decent.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # 勾配降下法 勾配降下法では、関数の傾き(勾配)に基づき関数を最小化します。 ディープラーニングにおいて、出力と正解の誤差を最小化するために使われます。 ## 勾配降...
github_jupyter
import numpy as np import matplotlib.pyplot as plt def my_func(x): # 最小値を求める関数 return x**2 - 2*x def grad_func(x): # 導関数 return 2*x - 2 eta = 0.1 # 学習係数 x = 4.0 # xに初期値を設定 record_x = [] # xの記録 record_y = [] # yの記録 for i in range(20): # 20回xを更新する y = my_func(x) record_x.append(x) record_y.a...
0.209551
0.976669
<a href="https://colab.research.google.com/github/amita-kapoor/UO-Artificial-Intelligence-Cloud-and-Edge-Implementations/blob/master/Excercise_Classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Classification Exercises For these exer...
github_jupyter
import tensorflow as tf import numpy as np from tensorflow import keras def built_model(input_shape, n_hidden, nb_classes, optimizer='SGD'): ''' The function builds a fully connected neural network with two hidden layers Arguments: input_shape: The number of inputs to the neural network n_hidden: Number of h...
0.886972
0.993029
<a href="https://colab.research.google.com/github/aletcher/impossibility-global-convergence/blob/master/impossibility_global_convergence.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Accompanying code for the paper: [On the Impossibility of Global...
github_jupyter
import numpy as np import torch import matplotlib.pyplot as plt import seaborn as sns plt.style.use('seaborn-darkgrid') #@markdown Plotting function. def plot_param(th, algo, start=0): fig, ax = plt.subplots(nrows=2, ncols=5, figsize=(20, 8)) ax = ax.flatten() for i, algo in enumerate(algos): ax[i].set_xlim(-...
0.550849
0.945951
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from statsmodels.graphics.tsaplots import plot_pacf from statsmodels.graphics.tsaplots import plot_acf from matplotlib.pyplot import figure from sklearn.metrics import f1_score from sklearn.metrics import confusion_matrix d...
github_jupyter
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from statsmodels.graphics.tsaplots import plot_pacf from statsmodels.graphics.tsaplots import plot_acf from matplotlib.pyplot import figure from sklearn.metrics import f1_score from sklearn.metrics import confusion_matrix def v...
0.527803
0.800926
<img src="../img/logo_amds.png" alt="Logo" style="width: 128px;"/> # AmsterdamUMCdb - Freely Accessible ICU Database version 1.0.2 March 2020 Copyright &copy; 2003-2020 Amsterdam UMC - Amsterdam Medical Data Science # <a id='freetextitems'></a>freetextitems table The *freetextitems* table contains all observations...
github_jupyter
%matplotlib inline import amsterdamumcdb import psycopg2 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib as mpl import io from IPython.display import display, HTML, Markdown #matplotlib settings for image size #needs to be in a different...
0.36557
0.848282
<a href="https://colab.research.google.com/github/maxigaarp/Gestion-De-Datos-en-R/blob/main/Tarea1_V2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> En las clases de gestión de datos hemos aprendido acerca de la eficiencia de bases de datos, modelo...
github_jupyter
#rendim2017 <- read.csv("http://datos.mineduc.cl/datasets/180324-rendimiento-escolar-ano-2017.download/",row.names=NULL, sep=";") #rendim2018 <- read.csv("http://datos.mineduc.cl/datasets/189328-rendimiento-escolar-ano-2018.download/",row.names=NULL, sep=";") ## Hay un problema descargando directamente los datos desde...
0.258981
0.934455
``` %matplotlib inline %run ../setup/nb_setup ``` # Orbits 3: Orbits in Triaxial Potentials Author(s): Adrian Price-Whelan ## Learning goals In this tutorial, we will introduce triaxial potential models, and explore the additional complexity that this brings to the landscape of orbits, as compared to orbits in axi...
github_jupyter
%matplotlib inline %run ../setup/nb_setup from astropy.constants import G import astropy.units as u from IPython.display import HTML import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import gala.dynamics as gd import gala.integrate as gi import gala.p...
0.601477
0.993235
<a href="https://qworld.net" target="_blank" align="left"><img src="../qworld/images/header.jpg" align="left"></a> $ \newcommand{\bra}[1]{\langle #1|} $ $ \newcommand{\ket}[1]{|#1\rangle} $ $ \newcommand{\braket}[2]{\langle #1|#2\rangle} $ $ \newcommand{\dot}[2]{ #1 \cdot #2} $ $ \newcommand{\biginner}[2]{\left\langle...
github_jupyter
from random import randrange from math import sin,cos, pi # randomly pick an angle random_angle = randrange(360) print("random angle is",random_angle) # pick angle in radian rotation_angle = random_angle/360*2*pi # the quantum state quantum_state = [ cos(rotation_angle) , sin (rotation_angle) ] the_expected_number_...
0.705278
0.988734
``` import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from joblib import dump from src.mo...
github_jupyter
import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from joblib import dump from src.models...
0.312055
0.685818
# Create your own fake fMRI results With this short jupyter notebook, you can create your own fake fMRI results. The only thing that you have to do is to specify the fake clusters that you want to create under **Targets**. After that you can run the whole notebook, either by using SHIFT+ENTER for each cell, or by sele...
github_jupyter
# Target: Location, radius, intensity target = [([150, 105, 80], 20, 1.), ([30, 105, 80], 25, -1.), ([65, 30, 75], 30, -1.2), ([115, 30, 75], 30, 1.2)] %pylab inline import numpy as np import nibabel as nb from nilearn.plotting import plot_stat_map, plot_glass_brain, cm from nilearn.image...
0.761361
0.873107