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
# Cross validation of the potential fit The functions required to run the fit in a Jupyter notebook are imported from the source code, along with matplotlib, and glob. ``` import popoff.fitting_output as fit_out import popoff.cross_validation as cv import matplotlib.pyplot as plt import glob ``` ## Setup of fitting p...
github_jupyter
import popoff.fitting_output as fit_out import popoff.cross_validation as cv import matplotlib.pyplot as plt import glob params = {} params['core_shell'] = { 'Li': False, 'Ni': False, 'O': True } params['charges'] = {'Li': +1.0, 'Ni': +3.0, 'O': {'core': -2.0, ...
0.363534
0.983407
``` import pandas as pd import utils import seaborn as sns import matplotlib.pyplot as plt import random import plotly.express as px random.seed(9000) plt.style.use("seaborn-ticks") plt.rcParams["image.cmap"] = "Set1" plt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.Set1.colors) %matplotlib inline ``` In th...
github_jupyter
import pandas as pd import utils import seaborn as sns import matplotlib.pyplot as plt import random import plotly.express as px random.seed(9000) plt.style.use("seaborn-ticks") plt.rcParams["image.cmap"] = "Set1" plt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.Set1.colors) %matplotlib inline n_samples = 1...
0.427994
0.749145
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: ```javascript [".-","-...","-.-."...
github_jupyter
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Input: words = ["gin", "zen", "gig", "msg"] "gin" -> "--...-." "zen" -> "--...-." "gig" -> "--...--." "msg" -> "--...--." class Solution(object): def u...
0.314366
0.834744
# Support Vector Regression with RobustScaler This Code template is for regression analysis using Support Vector Regressor(SVR) based on the Support Vector Machine algorithm and feature rescaling technique RobustScaler in a pipeline. ### Required Packages ``` import warnings import numpy as np import pandas as pd ...
github_jupyter
import warnings import numpy as np import pandas as pd import seaborn as se import matplotlib.pyplot as plt from sklearn.svm import SVR from sklearn.preprocessing import RobustScaler from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics import r2_score...
0.331877
0.989531
# Root cause analysis (RCA) of latencies in a microservice architecture In this case study, we identify the root causes of "unexpected" observed latencies in cloud services that empower an online shop. We focus on the process of placing an order, which involves different services to make sure that the placed order is ...
github_jupyter
from IPython.display import Image Image('microservice-architecture-dependencies.png', width=500) import pandas as pd normal_data = pd.read_csv("rca_microservice_architecture_latencies.csv") normal_data.head() axes = pd.plotting.scatter_matrix(normal_data, figsize=(10, 10), c='#ff0d57', alpha=0.2, hist_kwds={'color':...
0.658088
0.985594
## Identifiability Test of Linear VAE on Synthetic Dataset ``` %load_ext autoreload %autoreload 2 import torch import torch.nn.functional as F from torch.utils.data import DataLoader, random_split import ltcl import numpy as np from ltcl.datasets.sim_dataset import SimulationDatasetTSTwoSample from ltcl.modules.srnn i...
github_jupyter
%load_ext autoreload %autoreload 2 import torch import torch.nn.functional as F from torch.utils.data import DataLoader, random_split import ltcl import numpy as np from ltcl.datasets.sim_dataset import SimulationDatasetTSTwoSample from ltcl.modules.srnn import SRNNSynthetic from ltcl.tools.utils import load_yaml impor...
0.584983
0.722356
# 5.3 – Open Systems and Enthalpy --- ## 5.3.0 – Learning Objectives By the end of this section you should be able to: 1. Understand the definition of enthalpy. 2. Explain how enthalpy differs from internal energy 3. Look at the steps to solving an enthalpy problem. --- ## 5.3.1 – Introduction ...
github_jupyter
# 5.3 – Open Systems and Enthalpy --- ## 5.3.0 – Learning Objectives By the end of this section you should be able to: 1. Understand the definition of enthalpy. 2. Explain how enthalpy differs from internal energy 3. Look at the steps to solving an enthalpy problem. --- ## 5.3.1 – Introduction ...
0.806358
0.983723
# Ray RLlib Multi-Armed Bandits - A Simple Bandit Example © 2019-2021, Anyscale. All Rights Reserved ![Anyscale Academy](../../images/AnyscaleAcademyLogo.png) Let's explore a very simple contextual bandit example with three arms. We'll run trials using RLlib and [Tune](http://tune.io), Ray's hyperparameter tuning li...
github_jupyter
import gym from gym.spaces import Discrete, Box import numpy as np import random import time import ray class SimpleContextualBandit (gym.Env): def __init__ (self, config=None): self.action_space = Discrete(3) # 3 arms self.observation_space = Box(low=-1., high=1., shape=(2, ), dtype=np.float64...
0.714927
0.983863
``` import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from scipy import signal from scipy.fftpack import fft, ifft import seaborn as sns from obspy.io.segy.segy import _read_segy from las import LASReader from tabulate import tabulate from scipy.optimize import curve_fit import ...
github_jupyter
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from scipy import signal from scipy.fftpack import fft, ifft import seaborn as sns from obspy.io.segy.segy import _read_segy from las import LASReader from tabulate import tabulate from scipy.optimize import curve_fit import pand...
0.356895
0.471162
# Data Preprocessing ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd ``` # Importing the Datasets ``` dataset=pd.read_csv("E:\\Edu\\Data Science and ML\\Machinelearningaz\\Datasets\\Part 2 - Regression\\Section 6 - Polynomial Regression\\Position_Salaries.csv") dataset.head() dataset.plot(...
github_jupyter
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset=pd.read_csv("E:\\Edu\\Data Science and ML\\Machinelearningaz\\Datasets\\Part 2 - Regression\\Section 6 - Polynomial Regression\\Position_Salaries.csv") dataset.head() dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, share...
0.700383
0.977414
<h1> 2. Creating a sampled dataset </h1> This notebook illustrates: <ol> <li> Sampling a BigQuery dataset to create datasets for ML <li> Preprocessing with Pandas </ol> ``` # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.e...
github_jupyter
# change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${B...
0.252384
0.934634
``` import csv, time, requests, json, datetime import hmac import hashlib import sys !{sys.executable} -m pip install websocket-client import websocket import ssl webSocket ='wss://stream.binance.com:9443/ws/xvgbtc@ticker' ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) connect = ws.connect(webSocket) ...
github_jupyter
import csv, time, requests, json, datetime import hmac import hashlib import sys !{sys.executable} -m pip install websocket-client import websocket import ssl webSocket ='wss://stream.binance.com:9443/ws/xvgbtc@ticker' ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) connect = ws.connect(webSocket) binT...
0.158304
0.122052
# Name Data processing by creating a cluster in Cloud Dataproc # Label Cloud Dataproc, cluster, GCP, Cloud Storage, KubeFlow, Pipeline # Summary A Kubeflow Pipeline component to create a cluster in Cloud Dataproc. # Details ## Intended use Use this component at the start of a Kubeflow Pipeline to create a tempora...
github_jupyter
component_op(...).apply(gcp.use_gcp_secret('user-gcp-sa')) ``` * Grant the following types of access to the Kubeflow user service account: * Read access to the Cloud Storage buckets which contains initialization action files. * The role, `roles/dataproc.editor` on the project. ## Detailed descrip...
0.845017
0.944382
# 函数 - 函数可以用来定义可重复代码,组织和简化 - 一般来说一个函数在实际开发中为一个小功能 - 一个类为一个大功能 - 同样函数的长度不要超过一屏 Python中的所有函数实际上都是有返回值(return None), 如果你没有设置return,那么Python将不显示None. 如果你设置return,那么将返回出return这个值. ## 定义一个函数 def function_name(list of parameters): do something ![](../Photo/69.png) - 以前使用的random 或者range 或者print.. 其实都是函数或者类 ``` ...
github_jupyter
def uuu():#r任何函数值都有默认值, print('hello') b='uuu' print(b) import random com=random.randint(0,5) while 1: com = eval(input('')) if com def num(x1,x2,x3): if x1>x2 and x1>x3 result = x1 elif x2>x3 and x2>x1: result = x2 elif x3>x1 and x3>x2: result = x3 num(x1=4,x2=2,x3=10) d...
0.239083
0.761073
# HW3 ### Samir Patel ### DATA 515a ### 4/20/2017 For this homework, you are a data scientist working for Pronto (before the end of their contract with the City of Seattle). Your job is to assist in determining how to do end-of-day adjustments in the number of bikes at stations so that all stations will have enough b...
github_jupyter
import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import numpy as np df = pd.read_csv("2015_trip_data.csv") start_weekday = [pd.to_datetime(x).dayofweek for x in df.starttime] stop_weekday = [pd.to_datetime(x).dayofweek for x in df.stoptime] df['startweekday'] = start_weekday # Creates a new colu...
0.479016
0.962883
``` from source_files import SNOW_DEPTH_DIR, CASI_COLORS from plot_helpers import * from raster_compare.plots import PlotBase from raster_compare.base import RasterFile import math from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection aso_snow_depth = RasterFile( SNOW_DEPTH_...
github_jupyter
from source_files import SNOW_DEPTH_DIR, CASI_COLORS from plot_helpers import * from raster_compare.plots import PlotBase from raster_compare.base import RasterFile import math from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection aso_snow_depth = RasterFile( SNOW_DEPTH_DIR ...
0.60054
0.597079
![Egeria Logo](https://raw.githubusercontent.com/odpi/egeria/master/assets/img/ODPi_Egeria_Logo_color.png) ### ODPi Egeria Hands-On Lab # Welcome to the Understanding Cohort Configuration Lab ## Introduction ODPi Egeria is an open source project that provides open standards and implementation libraries to connect to...
github_jupyter
%run ../common/environment-check.ipynb print (" ") print ('Cohort(s) for cocoMDS1 are [%s]' % ', '.join(map(str, queryServerCohorts(cocoMDS1Name, cocoMDS1PlatformName, cocoMDS1PlatformURL)))) print ('Cohort(s) for cocoMDS2 are [%s]' % ', '.join(map(str, queryServerCohorts(cocoMDS2Name, cocoMDS2PlatformName, cocoMDS2...
0.099563
0.941061
``` import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import seaborn as sns # Matplotlib sns.set() W = 8.27 plt.rcParams.update({ 'figure.figsize': (W, W/(4/3)), 'figure.dpi': 150, 'font.size' : 11, 'axes.labelsize': 11, ...
github_jupyter
import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import seaborn as sns # Matplotlib sns.set() W = 8.27 plt.rcParams.update({ 'figure.figsize': (W, W/(4/3)), 'figure.dpi': 150, 'font.size' : 11, 'axes.labelsize': 11, 'leg...
0.764188
0.559771
# DSCI 525 - Web and Cloud Computing Milestone 2: Your team is planning to migrate to the cloud. AWS gave 400$ (100$ each) to your team to support this. As part of this initiative, your team needs to set up a server in the cloud, a collaborative environment for your team, and later move your data to the cloud. After t...
github_jupyter
import re import os import glob import zipfile import requests from urllib.request import urlretrieve import json import pandas as pd # Necessary metadata article_id = 14226968 # this is the unique identifier of the article on figshare url = f"https://api.figshare.com/v2/articles/{article_id}" headers = {"Content-Typ...
0.238373
0.89774
# Overview of pMuTT's Core Functionality Originally written for Version 1.2.1 Last Updated for Version 1.2.13 ## Topics Covered - Using constants and converting units using the ``constants`` module - Initializing ``StatMech`` objects by specifying all modes and by using ``presets`` dictionary - Initializing empirica...
github_jupyter
from pmutt import constants as c 1.987 print(c.R('kJ/mol/K')) print('Some constants') print('R (J/mol/K) = {}'.format(c.R('J/mol/K'))) print("Avogadro's number = {}\n".format(c.Na)) print('Unit conversions') print('5 kJ/mol --> {} eV/molecule'.format(c.convert_unit(num=5., initial='kJ/mol', final='eV/molecule'))) pr...
0.505859
0.852137
# TabNet: Attentive Interpretable Tabular Learning ## Preparation ``` %%capture !pip install pytorch-tabnet !pip install imblearn !pip install catboost !pip install tab-transformer-pytorch import torch import torch.nn as nn from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score...
github_jupyter
%%capture !pip install pytorch-tabnet !pip install imblearn !pip install catboost !pip install tab-transformer-pytorch import torch import torch.nn as nn from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, accuracy_score, f1_score, confusion_matrix from sklearn.preprocessing ...
0.776453
0.889769
# Human numbers ``` from fastai.text import * bs=64 ``` ## Data ``` path = untar_data(URLs.HUMAN_NUMBERS) path.ls() def readnums(d): return [', '.join(o.strip() for o in open(path/d).readlines())] train_txt = readnums('train.txt'); train_txt[0][:80] valid_txt = readnums('valid.txt'); valid_txt[0][-80:] train = TextL...
github_jupyter
from fastai.text import * bs=64 path = untar_data(URLs.HUMAN_NUMBERS) path.ls() def readnums(d): return [', '.join(o.strip() for o in open(path/d).readlines())] train_txt = readnums('train.txt'); train_txt[0][:80] valid_txt = readnums('valid.txt'); valid_txt[0][-80:] train = TextList(train_txt, path=path) valid = Text...
0.813387
0.770206
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Vectors/us_epa_ecoregions.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_b...
github_jupyter
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import gee...
0.526343
0.961929
``` import keras from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, BatchNormalization, LocallyConnected2D, Permute from keras.layers import Concat...
github_jupyter
import keras from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, BatchNormalization, LocallyConnected2D, Permute from keras.layers import Concatenat...
0.508788
0.410166
# Question formulation Notebook Use of toy dataset and notebook dependencies. ### Notebook Set-up: ``` import re import ast import math import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings from os import path from pyspark.sql import functions as F from pyspark....
github_jupyter
import re import ast import math import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings from os import path from pyspark.sql import functions as F from pyspark.sql.types import IntegerType warnings.filterwarnings('ignore') # warnings.resetwarnings() PWD = !pwd PWD =...
0.497803
0.859664
``` # Import the dependencies import pandas as pd import matplotlib.pyplot as plt import numpy as np from citipy import citipy import requests from config import weather_api_key import sys from datetime import datetime # Create a set of random latitute and longitude combinations. lats = np.random.uniform(low = -90.000...
github_jupyter
# Import the dependencies import pandas as pd import matplotlib.pyplot as plt import numpy as np from citipy import citipy import requests from config import weather_api_key import sys from datetime import datetime # Create a set of random latitute and longitude combinations. lats = np.random.uniform(low = -90.000, hi...
0.470007
0.495117
``` !pip install -U kaggle-cli !kg download -u <username> -p <password> -c 'plant-seedlings-classification' -f 'test.zip' !kg download -u <username> -p <password> -c 'plant-seedlings-classification' -f 'train.zip !unzip test.zip -d data !unzip train.zip -d data import os print(os.listdir('data/train/')) import fnmatch...
github_jupyter
!pip install -U kaggle-cli !kg download -u <username> -p <password> -c 'plant-seedlings-classification' -f 'test.zip' !kg download -u <username> -p <password> -c 'plant-seedlings-classification' -f 'train.zip !unzip test.zip -d data !unzip train.zip -d data import os print(os.listdir('data/train/')) import fnmatch imp...
0.387343
0.308255
## Descrição: As a data scientist working for an investment firm, you will extract the revenue data for Tesla and GameStop and build a dashboard to compare the price of the stock vs the revenue. ## Tarefas: - Question 1 - Extracting Tesla Stock Data Using yfinance - 2 Points - Question 2 - Extracting Tesla ...
github_jupyter
# installing dependencies !pip install yfinance pandas bs4 # importing modules import yfinance as yf import pandas as pd import requests from bs4 import BeautifulSoup # needed to cast datetime values from datetime import datetime # making Ticker object tesla_ticker = yf.Ticker("TSLA") # creating a dataframe with hi...
0.335133
0.941493
# Info Name: Seyed Ali Mirferdos Student ID: 99201465 # 0. Importing the necessary modules ``` import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import classification_report, confusion_matrix from sklear...
github_jupyter
import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import classification_report, confusion_matrix from sklearn.svm import SVC !gdown --id 1oRmkmOMD5t_vA35N8IBmFcQM-WfE0_7x df = pd.read_csv('bill_authentica...
0.555918
0.935169
``` import youtube_dl import re import os from tqdm import tqdm import pandas as pd import numpy as np WAV_DIR = 'wav_files/' genre_dict = { '/m/064t9': 'Pop_music', '/m/0glt670': 'Hip_hop_music', '/m/0y4f8': 'Vocal', '/m/06cqb': 'Reggae', } genre_set = set(...
github_jupyter
import youtube_dl import re import os from tqdm import tqdm import pandas as pd import numpy as np WAV_DIR = 'wav_files/' genre_dict = { '/m/064t9': 'Pop_music', '/m/0glt670': 'Hip_hop_music', '/m/0y4f8': 'Vocal', '/m/06cqb': 'Reggae', } genre_set = set(genr...
0.233969
0.280339
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/JavaScripts/Image/Hillshade.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" ...
github_jupyter
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import gee...
0.524882
0.946646
<img src='./img/egu_2020.png' alt='Logo EU Copernicus EUMETSAT' align='left' width='30%'></img><img src='./img/atmos_logos.png' alt='Logo EU Copernicus EUMETSAT' align='right' width='60%'></img></span> <br> <a href="./12_AC_SAF_GOME-2_L2_preprocess.ipynb"><< 12 - AC SAF GOME-2 Level 2 - preprocess </a><span style="fl...
github_jupyter
%matplotlib inline import os import xarray as xr import numpy as np import netCDF4 as nc import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from matplotlib.axes import Axes from cartopy.mpl.geoaxes ...
0.495361
0.964355
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pronobis/libspn-keras/blob/master/examples/notebooks/Sampling%20with%20conv%20SPNs.ipynb) # **Image Sampling**: Sampling MNIST images In this notebook, we'll set up an SPN to generate new MNIST images ...
github_jupyter
!pip install libspn-keras matplotlib import libspn_keras as spnk from tensorflow import keras spnk.set_default_accumulator_initializer( spnk.initializers.Dirichlet() ) import numpy as np import tensorflow_datasets as tfds from libspn_keras.layers import NormalizeAxes import tensorflow as tf def take_first(a, b)...
0.819388
0.990112
``` 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.157363
0.407098
## 2.6 Q学習で迷路を攻略 ``` # 使用するパッケージの宣言 import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 初期位置での迷路の様子 # 図を描く大きさと、図の変数名を宣言 fig = plt.figure(figsize=(5, 5)) ax = plt.gca() # 赤い壁を描く plt.plot([1, 1], [0, 1], color='red', linewidth=2) plt.plot([1, 2], [2, 2], color='red', linewidth=2) plt.plot([2, 2], [...
github_jupyter
# 使用するパッケージの宣言 import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 初期位置での迷路の様子 # 図を描く大きさと、図の変数名を宣言 fig = plt.figure(figsize=(5, 5)) ax = plt.gca() # 赤い壁を描く plt.plot([1, 1], [0, 1], color='red', linewidth=2) plt.plot([1, 2], [2, 2], color='red', linewidth=2) plt.plot([2, 2], [2, 1], color='red', li...
0.335351
0.889481
``` from datetime import datetime import logging logging.basicConfig(filename='train_initialization.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO) logging.info('SCRIPT INICIADO') import os from keras.preprocessing.image import ImageDataGenerator...
github_jupyter
from datetime import datetime import logging logging.basicConfig(filename='train_initialization.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO) logging.info('SCRIPT INICIADO') import os from keras.preprocessing.image import ImageDataGenerator fro...
0.740268
0.141548
# 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 json # Import API key from config import g_key gmaps.configure(api_key=g_key) city_data = "..\\WeatherPy\\weather_py_city_data.csv" city_data_df = pd.read_csv(city_data) city_d...
0.349533
0.834474
``` #Dependencies import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 from scipy.ndimage.filters import gaussian_filter #load image and smooth it img = cv2.imread("simulated_rails.png", cv2.IMREAD_GRAYSCALE) img = gaussian_filter(img, sigma=0.8) print(img.shape) plt.imshow(img, cmap =...
github_jupyter
#Dependencies import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 from scipy.ndimage.filters import gaussian_filter #load image and smooth it img = cv2.imread("simulated_rails.png", cv2.IMREAD_GRAYSCALE) img = gaussian_filter(img, sigma=0.8) print(img.shape) plt.imshow(img, cmap ="gra...
0.571169
0.539287
<a href="https://colab.research.google.com/github/angeruzzi/RegressionModel_ProdutividadeAgricola/blob/main/RegressionModel_ProdutividadeAgricola_Amendoin.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #Predição Produtividade Agrícola: Produção de ...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.linear_model import LassoLars from sklearn.linear_model import BayesianRidge from sklearn.neighbors import KNeighborsRegres...
0.596903
0.954605
# Odds and Addends Think Bayes, Second Edition Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ impo...
github_jupyter
# If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py and create directories import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/Thi...
0.70028
0.983597
``` import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler from sklearn.model_selection import train_test_split import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt train_data = pd.read_csv('data/heart.csv') tr...
github_jupyter
import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler from sklearn.model_selection import train_test_split import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt train_data = pd.read_csv('data/heart.csv') train_...
0.705886
0.500854
# Training Neural Networks The network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritt...
github_jupyter
import torch from torch import nn import torch.nn.functional as F from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ...
0.843057
0.992489
### Geek and the equation Given a number N, find the value of below equation for the given number. Input: First line of input contains testcase T. For each testcase, there will be a single line containing a number N as input. Output: For each testcase, print the resultant of the equation. Constraints: 1<=T<=100 1<=...
github_jupyter
t = int(input()) for i in range(t): n = int(input()) res = 0 for m in range(1, n+1): res += ((m+1)**2) - ((3*m)+1) + m print(res) # Input: # 5 # 1 # 2 # 3 # 4 # 5 # Output: # 1 # 2 # 10 # 11 # 12 def ternary (n): if n == 0: return '0' nums = [] while n: n, r = div...
0.196017
0.970716
``` import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="robotic-tract-334610-6605cbffd65c.json" import numpy as np import pandas as pd from google.cloud import bigquery client = bigquery.Client() import random random.seed(38) import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab # Jo...
github_jupyter
import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="robotic-tract-334610-6605cbffd65c.json" import numpy as np import pandas as pd from google.cloud import bigquery client = bigquery.Client() import random random.seed(38) import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab # Join E...
0.367157
0.449634
# Artificial Intelligence Nanodegree ## Convolutional Neural Networks --- In this notebook, we train an MLP to classify images from the MNIST database. ### 1. Load MNIST Database ``` from keras.datasets import mnist # use Keras to import pre-shuffled MNIST database (X_train, y_train), (X_test, y_test) = mnist.loa...
github_jupyter
from keras.datasets import mnist # use Keras to import pre-shuffled MNIST database (X_train, y_train), (X_test, y_test) = mnist.load_data() print("The MNIST database has a training set of %d examples." % len(X_train)) print("The MNIST database has a test set of %d examples." % len(X_test)) import matplotlib.pyplot a...
0.686055
0.980375
# Deep Q-Network (DQN) --- In this notebook, you will implement a DQN agent with OpenAI Gym's LunarLander-v2 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 ``` ### 2. Insta...
github_jupyter
import gym import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline env = gym.make('LunarLander-v2') env.seed(0) print('State shape: ', env.observation_space.shape) print('Number of actions: ', env.action_space.n) from dqn_agent import Agent agent...
0.608478
0.953923
# Módulo 4: APIs ## Spotify <img src="https://developer.spotify.com/assets/branding-guidelines/logo@2x.png" width=400></img> En este módulo utilizaremos APIs para obtener información sobre artistas, discos y tracks disponibles en Spotify. Pero primero.. ¿Qué es una **API**?<br> Por sus siglas en inglés, una API es una...
github_jupyter
import requests id_im = '6mdiAmATAx73kdxrNrnlao' url_base = 'https://api.spotify.com/v1' ep_artist = '/artists/{artist_id}' url_base+ep_artist.format(artist_id=id_im) r = requests.get(url_base+ep_artist.format(artist_id=id_im)) r.status_code r.json()
0.244724
0.924005
# Tokenizing notebook First, the all important `import` statement. ``` from ideas import token_utils ``` ## Getting information We start with a very simple example, where we have a repeated token, `a`. ``` source = "a = a" tokens = token_utils.tokenize(source) for token in tokens: print(token) ``` Notice how t...
github_jupyter
from ideas import token_utils source = "a = a" tokens = token_utils.tokenize(source) for token in tokens: print(token) print(tokens[0] == tokens[2]) print(tokens[0] == tokens[2].string) print(tokens[0] == 'a') # <-- Our normal choice source = """ if True: pass """ token_utils.print_tokens(source) source ...
0.338952
0.977989
Compare speed between native and cythonized math functions ``` %load_ext Cython %%cython from libc.math cimport log, sqrt def log_c(float x): return log(x)/2.302585092994046 def sqrt_c(float x): return sqrt(x) import os from os.path import expanduser import pandas as pd import pandas.io.sql as pd_sql import ma...
github_jupyter
%load_ext Cython %%cython from libc.math cimport log, sqrt def log_c(float x): return log(x)/2.302585092994046 def sqrt_c(float x): return sqrt(x) import os from os.path import expanduser import pandas as pd import pandas.io.sql as pd_sql import math from functions.auth.connections import postgres_connection c...
0.367043
0.787605
# 横向联邦学习任务示例 这是一个使用Delta框架编写的横向联邦学习的任务示例。 数据是分布在多个节点上的[MNIST数据集](http://yann.lecun.com/exdb/mnist/),每个节点上只有其中的一部分样本。任务是训练一个卷积神经网络的模型,进行手写数字的识别。 本示例可以直接在Deltaboard中执行并查看结果。<span style="color:#FF8F8F;font-weight:bold">在点击执行之前,需要修改一下个人的Deltaboard API的地址,具体请看下面第4节的说明。</span> ## 1. 引入需要的包 我们的计算逻辑是用torch写的。所以首先引入```nump...
github_jupyter
from typing import Dict, Iterable, List, Tuple, Any, Union import numpy as np import torch from delta import DeltaNode from delta.task import HorizontalTask from delta.algorithm.horizontal import FedAvg class LeNet(torch.nn.Module): def __init__(self): super().__init__() self.conv1 = torch.nn.Con...
0.850701
0.976602
# Building Python Function-based Components > Building your own lightweight pipelines components using the Pipelines SDK v2 and Python A Kubeflow Pipelines component is a self-contained set of code that performs one step in your ML workflow. A pipeline component is composed of: * The component code, which implement...
github_jupyter
!pip install --upgrade kfp import kfp import kfp.dsl as dsl from kfp.v2.dsl import ( component, Input, Output, Dataset, Metrics, ) client = kfp.Client() # change arguments accordingly @component def add(a: float, b: float) -> float: '''Calculates sum of two arguments''' return a + b import k...
0.830594
0.980949
``` import netCDF4 import math import xarray as xr import dask import numpy as np import time import scipy import matplotlib.pyplot as plt from matplotlib import animation from matplotlib import transforms from matplotlib.animation import PillowWriter path_to_file = '/DFS-L/DATA/pritchard/gmooers/Workflow/MAPS/SPCAM/Sm...
github_jupyter
import netCDF4 import math import xarray as xr import dask import numpy as np import time import scipy import matplotlib.pyplot as plt from matplotlib import animation from matplotlib import transforms from matplotlib.animation import PillowWriter path_to_file = '/DFS-L/DATA/pritchard/gmooers/Workflow/MAPS/SPCAM/Small_...
0.196132
0.30795
<a href="https://colab.research.google.com/github/Ipsit1234/QML-HEP-Evaluation-Test-GSOC-2021/blob/main/QML_HEP_GSoC_2021_Task_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Task II: Quantum Generative Adversarial Network (QGAN) Part You will e...
github_jupyter
!gdown --id 1r_MZB_crfpij6r3SxPDeU_3JD6t6AxAj -O events.npz !pip install -q tensorflow==2.3.1 !pip install -q tensorflow-quantum import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np import seaborn as sns from sklearn.metrics import roc_curve, auc %matplotlib inline imp...
0.771499
0.989327
# Simple Stock Backtesting https://www.investopedia.com/terms/b/backtesting.asp ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # fix_yahoo_finance is used to fetch data import fix_yahoo_finance as yf yf.pdr_override() # input symbol = 'M...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # fix_yahoo_finance is used to fetch data import fix_yahoo_finance as yf yf.pdr_override() # input symbol = 'MSFT' start = '2016-01-01' end = '2019-01-01' # Read data df = yf.download(symbol,sta...
0.576542
0.869271
<center><font size="4"><span style="color:blue">Demonstration 1: general presentation with some quantities and statistics</span></font></center> This is a general presentation of the 3W dataset, to the best of its authors' knowledge, the first realistic and public dataset with rare undesirable real events in oil wells...
github_jupyter
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.colors as mcolors from matplotlib.patches import Patch from pathlib import Path from multiprocessing.dummy import Pool as ThreadPool from collections import defaultdict from natsort import natsorte...
0.423696
0.936314
# Data De [link](https://github.com/chihyaoma/regretful-agent/tree/master/tasks/R2R-pano) Each JSON Lines entry contains a guide annotation for a path in the environment. Data schema: ```python {'split': str, 'instruction_id': int, 'annotator_id': int, 'language': str, 'path_id': int, 'scan': str, 'path': Seq...
github_jupyter
{'split': str, 'instruction_id': int, 'annotator_id': int, 'language': str, 'path_id': int, 'scan': str, 'path': Sequence[str], 'heading': float, 'instruction': str, 'timed_instruction': Sequence[Mapping[str, Union[str, float]]], 'edit_distance': float} # Las features de todos los puntos del dataset pesan 3....
0.281011
0.890056
``` # default_exp utils ``` # Utils > contains various util functions and classes ``` #hide from nbdev.showdoc import * #export import os import re import pandas as pd import numpy as np from random import randrange from pm4py.objects.log.importer.xes import importer as xes_importer from pm4py.objects.conversion.l...
github_jupyter
# default_exp utils #hide from nbdev.showdoc import * #export import os import re import pandas as pd import numpy as np from random import randrange from pm4py.objects.log.importer.xes import importer as xes_importer from pm4py.objects.conversion.log import converter as log_converter from fastai.torch_basics impor...
0.155784
0.669853
# 选择 ## 布尔类型、数值和表达式 ![](../Photo/33.png) - 注意:比较运算符的相等是两个等到,一个等到代表赋值 - 在Python中可以用整型0来代表False,其他数字来代表True - 后面还会讲到 is 在判断语句中的用发 ``` print(1>2) yu=10000 a=eval(input('input money:')) if a<=yu: yu=yu-a print("余额为:",yu) else: print("余额不足") import os a=eval(input('input money:')) if a<=yu: yu=yu-a prin...
github_jupyter
print(1>2) yu=10000 a=eval(input('input money:')) if a<=yu: yu=yu-a print("余额为:",yu) else: print("余额不足") import os a=eval(input('input money:')) if a<=yu: yu=yu-a print("余额为:",yu) else: print("余额不足") 'a'>'A' 'abc'>'acd' bool(1.0) bool(0.0) import random random.randint(0,10) random.random() r...
0.029118
0.692102
# Основы Jupyter ## Simple python Все данные храняться в оперативной памяти. Однажды созданную переменную можно использовать пока она не будет явно удалена. ``` a = 1 print(a) ``` Каждая ячейка аналогична выполнению кода в глобальной области видимости. ``` def mult_list(lst, n): return lst * n arr = mult_list...
github_jupyter
a = 1 print(a) def mult_list(lst, n): return lst * n arr = mult_list([1, 2, 3], 3) print(arr) arr print(mult_list(arr, 10)) mult_list(arr, 10) mult_list(arr, 10); import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set(font_scale=2, style='whitegrid', rc={'figure.figsize': (10, 6), '...
0.295433
0.982339
``` import pandas as pd from statsmodels.tsa.arima.model import ARIMA import pymongo from pymongo import MongoClient # Connection to mongo client = MongoClient('mongodb+srv://<user>:<password>@cluster0.l3pqt.mongodb.net/MSA?retryWrites=true&w=majority') # Select database db = client['MSA'] # see list of collections cli...
github_jupyter
import pandas as pd from statsmodels.tsa.arima.model import ARIMA import pymongo from pymongo import MongoClient # Connection to mongo client = MongoClient('mongodb+srv://<user>:<password>@cluster0.l3pqt.mongodb.net/MSA?retryWrites=true&w=majority') # Select database db = client['MSA'] # see list of collections client....
0.29931
0.262464
``` %%javascript MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "AMS" } } }); MathJax.Hub.Queue( ["resetEquationNumbers", MathJax.InputJax.TeX], ["PreProcess", MathJax.Hub], ["Reprocess", MathJax.Hub] ); ``` # Greek Letters | Name | lower case | lower LaTeX | upper case | upper LaTeX | |:---...
github_jupyter
%%javascript MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "AMS" } } }); MathJax.Hub.Queue( ["resetEquationNumbers", MathJax.InputJax.TeX], ["PreProcess", MathJax.Hub], ["Reprocess", MathJax.Hub] ); $$ \frac{\partial z}{\partial x} = \lim_{\Delta x \rightarrow 0} \frac{f(x+\Delta x, y) - f(x,y)}...
0.483648
0.988481
# Loan Credit Risk Prediction When a financial institution examines a request for a loan, it is crucial to assess the risk of default to determine whether to grant it, and if so, what will be the interest rate. This notebook takes advantage of the power of SQL Server and RevoScaleR (Microsoft R Server). The tables a...
github_jupyter
# WARNING. # We recommend not using Internet Explorer as it does not support plotting, and may crash your session. # INPUT DATA SETS: point to the correct path. Loan <- "C:/Solutions/Loans/Data/Loan.txt" Borrower <- "C:/Solutions/Loans/Data/Borrower.txt" # Load packages. library(RevoScaleR) library("MicrosoftML") lib...
0.519278
0.911101
# mlp及深度学习常见技巧 我们将以mlp对为,基础模型,然后介绍一些深度学习常见技巧, 如: 权重初始化, 激活函数, 优化器, 批规范化, dropout,模型集成 ``` import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) ``` ## 导入数据 ``` (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.reshape([...
github_jupyter
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.reshape([x_train.shape[0], -1]) x_test = x_test.reshape([x_test.shape[0], -1]) print(x_train.shape, ' ', y_train.shape...
0.94036
0.945399
# Prueba de concepto ## Emplazamiento local y post valoración global para ajustamiento con random forest ``` import sys print(sys.version) #Python version import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestRegressor from sklearn.metri...
github_jupyter
import sys print(sys.version) #Python version import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error from sklearn.model_selection import cross_val_score, train_test_split, RepeatedKFo...
0.233444
0.778291
<div> <img src="..\Week 01\img\R_logo.svg" width="100"/> </div> <div style="line-height:600%;"> <font color=#1363E1 face="Britannic" size=10> <div align=center>Variables</div> </font> </div> <div style="line-height:300%;"> <font color=#9A0909 face="Britannic" size=6> ...
github_jupyter
# valid: Has letters, numbers, dot and underscore var_name.2 = 1 print(var_name.2) # Invalid: Has the character '%'. Only dot(.) and underscore allowed var_name% = 1 print(var_name%) # Invalid: Starts with a number 2var_name = 1 print(2var_name) # Valid: Can start with a dot(.) but the dot(.)should not be followed by a...
0.344664
0.874077
# Mass on a spring The computation itself comes from from Chabay and Sherwood's exercises VP07 and VP09 http://www.compadre.org/portal/items/detail.cfm?ID=5692#tabs. They have great learning activities in the assignments as well. # Model the spring force Let's call the current length of the spring $L$ and relaxed len...
github_jupyter
## constants and data g = 9.8 L0 = 0.26 ks = 1.8 dt = .02 ## objects (origin is at ceiling) ceiling = box(pos=vector(0,0,0), length=0.2, height=0.01, width=0.2) ball = sphere(radius=0.025,color=color.orange, make_trail = True) spring = helix(pos=ceiling.pos, color=color.cyan, thickness=.003, coils=40, radius=0.010) #...
0.525612
0.984246
``` import numpy as np import pandas as pd import scipy as sp import sklearn as sl import seaborn as sns; sns.set() import matplotlib as mpl from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm %matplotlib inline ``` # ...
github_jupyter
import numpy as np import pandas as pd import scipy as sp import sklearn as sl import seaborn as sns; sns.set() import matplotlib as mpl from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm %matplotlib inline df = pd.re...
0.434701
0.879871
<a href="https://colab.research.google.com/github/thehimalayanleo/Private-Machine-Learning/blob/master/Fed_Averaging_Pytorch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import torch import torch.optim as optim import torch.nn as nn import t...
github_jupyter
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.transforms as transforms import numpy as np import copy from torch.utils.data import DataLoader, Dataset class Net(nn.Module): def __init__(se...
0.764628
0.864081
# Training a model on the UD Corpus This notebook looks at how to train a model using the Universal Dependencies Corpus. We will learn how to (1) download the UD Corpus, (2) train a tokenizer and a tagger model on a specific language and then (3) pack it all up in a zip model that we'll use locally. This notebook is...
github_jupyter
! cd /work; curl --remote-name-all https://lindat.mff.cuni.cz/repository/xmlui/bitstream/handle/11234/1-2837/ud-treebanks-v2.2.tgz ! tar -xzf /work/ud-treebanks-v2.2.tgz -C /work ! ls -lh /work/ud-treebanks-v2.2/UD_English-ParTUT ! mkdir /work/my_model-1.0 python3 /work/NLP-Cube/cube/main.py --train=tokenizer --tra...
0.471223
0.942242
# Chapter 2 Housing Example ## Data ``` import sys sys.path.append('../src/') from fetch_housing_data import fetch_housing_data,load_housing_data from CombinedAttrAdders import CombinedAttributesAdder fetch_housing_data() housing = load_housing_data() housing.head() ``` ## Take a look ``` housing.info() housing.oc...
github_jupyter
import sys sys.path.append('../src/') from fetch_housing_data import fetch_housing_data,load_housing_data from CombinedAttrAdders import CombinedAttributesAdder fetch_housing_data() housing = load_housing_data() housing.head() housing.info() housing.ocean_proximity.value_counts() housing.describe() %matplotlib inlin...
0.45641
0.928926
``` import keras keras.__version__ ``` # Text generation with LSTM This notebook contains the code samples found in Chapter 8, Section 1 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 content, in particu...
github_jupyter
import keras keras.__version__ import keras import numpy as np path = keras.utils.get_file( 'nietzsche.txt', origin='https://s3.amazonaws.com/text-datasets/nietzsche.txt') text = open(path).read().lower() print('Corpus length:', len(text)) # Length of extracted character sequences maxlen = 60 # We sample a ...
0.599602
0.970604
**7장 – 앙상블 학습과 랜덤 포레스트** _이 노트북은 7장에 있는 모든 샘플 코드와 연습문제 해답을 가지고 있습니다._ <table align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/rickiepark/handson-ml2/blob/master/07_ensemble_learning_and_random_forests.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />구...
github_jupyter
# 파이썬 ≥3.5 필수 import sys assert sys.version_info >= (3, 5) # 사이킷런 ≥0.20 필수 import sklearn assert sklearn.__version__ >= "0.20" # 공통 모듈 임포트 import numpy as np import os # 노트북 실행 결과를 동일하게 유지하기 위해 np.random.seed(42) # 깔끔한 그래프 출력을 위해 %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt mpl.rc('ax...
0.382257
0.978426
# Data Visualization ## Specifications This workflow should produce three publication-quality visualizations: 1. Daily-mean radiative fluxes at top of atmosphere and surface from ERA5 for 22 September 2020. 2. Intrinsic atmospheric radiative properties (reflectivity, absorptivity, and transmissivity) based on the St...
github_jupyter
from utils import check_environment check_environment("visualize") import logging import os import cartopy.crs as ccrs from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from google.cloud import storage import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import colors import n...
0.654122
0.912864
``` %reload_ext autoreload %autoreload 2 %matplotlib inline ``` # ResNet34 inference ``` import albumentations import gc import numpy as np import pandas as pd import pretrainedmodels import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from pathlib import Path from torch.utils.dat...
github_jupyter
%reload_ext autoreload %autoreload 2 %matplotlib inline import albumentations import gc import numpy as np import pandas as pd import pretrainedmodels import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from pathlib import Path from torch.utils.data import DataLoader from tqdm impo...
0.762247
0.701585
``` import pandas as pd import numpy as np import seaborn as sb import matplotlib.pyplot as plt df = pd.read_csv("COVIDiSTRESS June 17.csv",encoding='latin-1') df.head() df=df.drop(columns=['Dem_Expat','Country', 'Unnamed: 0', 'neu', 'ext', 'ope', 'agr', 'con', 'Duration..in.seconds.', 'UserLanguage', 'Scale_PSS10_UCLA...
github_jupyter
import pandas as pd import numpy as np import seaborn as sb import matplotlib.pyplot as plt df = pd.read_csv("COVIDiSTRESS June 17.csv",encoding='latin-1') df.head() df=df.drop(columns=['Dem_Expat','Country', 'Unnamed: 0', 'neu', 'ext', 'ope', 'agr', 'con', 'Duration..in.seconds.', 'UserLanguage', 'Scale_PSS10_UCLA_1',...
0.48121
0.136695
<a href="https://colab.research.google.com/github/davidbro-in/natural-language-processing/blob/main/3_custom_embedding_using_gensim.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <a href="https://www.inove.com.ar"><img src="https://github.com/herna...
github_jupyter
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import multiprocessing from gensim.models import Word2Vec !wget https://www.gutenberg.org/cache/epub/31193/pg31193.txt # Armar el dataset utilizando salto de línea para separar las oraciones/docs df = pd.read_csv('/content/pg31193.txt', sep='/n...
0.638497
0.917266
# Applications ``` import numpy as np import matplotlib.pyplot as plt import scipy.linalg as la ``` ## Polynomial Interpolation [Polynomial interpolation](https://en.wikipedia.org/wiki/Polynomial_interpolation) finds the unique polynomial of degree $n$ which passes through $n+1$ points in the $xy$-plane. For example...
github_jupyter
import numpy as np import matplotlib.pyplot as plt import scipy.linalg as la x = np.array([-1,0,1]) X = np.column_stack([[1,1,1],x,x**2]) print(X) y = np.array([1,0,1]).reshape(3,1) print(y) a = la.solve(X,y) print(a) x = np.array([0,3,8]) X = np.column_stack([[1,1,1],x,x**2]) print(X) y = np.array([6,1,2]).reshap...
0.326379
0.988503
Human Strategy ---------------- Human strategy is a strategy which asks the user to input a move rather than deriving its own action. The history of the match is also shown in the terminal, thus you will be able to see the history of the game. We are now going to open an editor. There we are going to create a script ...
github_jupyter
import axelrod as axl import random strategies = [s() for s in axl.strategies] opponent = random.choice(axl.strategies) me = axl.Human(name='Nikoleta') players = [opponent(), me] # play the match and return winner and final score match = axl.Match(players, turns=3) match.play() print('You have competed against {}, t...
0.173288
0.828384
# Max-Voting ### Getting Ready ``` import os import pandas as pd os.chdir(".../Chapter 2") os.getcwd() ``` #### Download the dataset Cryotherapy.csv from the github location and copy the same to your working directory. Let's read the dataset. ``` cryotherapy_data = pd.read_csv("Cryotherapy.csv") ``` #### Let's tak...
github_jupyter
import os import pandas as pd os.chdir(".../Chapter 2") os.getcwd() cryotherapy_data = pd.read_csv("Cryotherapy.csv") cryotherapy_data.head(5) # Import required libraries from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.ensem...
0.646125
0.868213
## Random Forest importance ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.feature_selection import SelectFromModel ``` ## Read Data ``` data = pd.r...
github_jupyter
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.feature_selection import SelectFromModel data = pd.read_csv('../DoHBrwTest.csv') data.shape data.head() X_...
0.659076
0.894144
# Data preparation ``` import sqlite3 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import Cdf import Pmf # suppress unnecessary warnings import warnings warnings.filterwarnings("ignore", module="numpy") # define global plot parameters params = {'axes.labe...
github_jupyter
import sqlite3 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import Cdf import Pmf # suppress unnecessary warnings import warnings warnings.filterwarnings("ignore", module="numpy") # define global plot parameters params = {'axes.labelsize' : 12, 'axes.title...
0.537041
0.832713
<center> <h1>DatatableTon</h1> 💯 datatable exercises <br> <br> <a href='https://github.com/vopani/datatableton/blob/master/LICENSE'> <img src='https://img.shields.io/badge/license-Apache%202.0-blue.svg?logo=apache'> </a> <a href='https://github.com/vopani/datatableton'> <img...
github_jupyter
!python3 -m pip install -U pip !python3 -m pip install -U datatable import datatable as dt dt.__version__ data = dt.Frame() data = dt.Frame(v1=range(10), v2=['Y', 'O', 'U', 'C', 'A', 'N', 'D', 'O', 'I', 'T']) data data.head(5) data.tail(3) data.nrows data.ncols data.shape data.names
0.370112
0.956145
Classical probability distributions can be written as a stochastic vector, which can be transformed to another stochastic vector by applying a stochastic matrix. In other words, the evolution of stochastic vectors can be described by a stochastic matrix. Quantum states also evolve and their evolution is described by u...
github_jupyter
import numpy as np X = np.array([[0, 1], [1, 0]]) print("XX^dagger") print(X @ X.T.conj()) print("X^daggerX") print(X.T.conj() @ X) print("The norm of the state |0> before applying X") zero_ket = np.array([[1], [0]]) print(np.linalg.norm(zero_ket)) print("The norm of the state after applying X") print(np.linalg.norm(X...
0.510252
0.991828
# Think Bayes Second Edition Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = ...
github_jupyter
# If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/cod...
0.5083
0.972623
# Chainer MNIST Model Deployment * Wrap a Chainer MNIST python model for use as a prediction microservice in seldon-core * Run locally on Docker to test * Deploy on seldon-core running on minikube ## Dependencies * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/miniku...
github_jupyter
pip install seldon-core pip install chainer==6.2.0 #!/usr/bin/env python import argparse import chainer import chainer.functions as F import chainer.links as L from chainer import training from chainer.training import extensions import chainerx # Network definition class MLP(chainer.Chain): def __init__(self, ...
0.57678
0.892234
# Data Visualization - Plotting Data - its import to explore and understand your data in Data Science - typically various statistical graphics are plotted to quickly visualize and understand data - various libraries work together with Pandas DataFrame and Series datastructrue to quickly plot a data table - `matplotlib...
github_jupyter
DataFrame.plot(*args, **kwargs) import pandas as pd import matplotlib.pyplot as plt # online raw data URLs no2_url = 'https://raw.githubusercontent.com/pandas-dev/pandas/master/doc/data/air_quality_no2.csv' pm2_url = 'https://raw.githubusercontent.com/pandas-dev/pandas/master/doc/data/air_quality_pm25_long.csv' air_qu...
0.619932
0.975762
``` import numpy as np import pandas as pd from scipy.interpolate import interp1d import matplotlib.pyplot as plt %matplotlib inline from glob import glob all_q = {} x_dirs = glob('yz/*/') x_dirs[0].split('/') '1qtable'.split('1') for x_dir in x_dirs: chain_length = x_dir.split('/')[1] qtables = glob(f'{x_di...
github_jupyter
import numpy as np import pandas as pd from scipy.interpolate import interp1d import matplotlib.pyplot as plt %matplotlib inline from glob import glob all_q = {} x_dirs = glob('yz/*/') x_dirs[0].split('/') '1qtable'.split('1') for x_dir in x_dirs: chain_length = x_dir.split('/')[1] qtables = glob(f'{x_dir}{c...
0.286469
0.281937
``` from theano.sandbox import cuda cuda.use('gpu2') %matplotlib inline import utils; reload(utils) from utils import * from __future__ import division, print_function ?? BatchNormalization ``` ## Setup ``` batch_size=64 from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() (X_trai...
github_jupyter
from theano.sandbox import cuda cuda.use('gpu2') %matplotlib inline import utils; reload(utils) from utils import * from __future__ import division, print_function ?? BatchNormalization batch_size=64 from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() (X_train.shape, y_train.shape...
0.715921
0.837819
<img src="Polygons.png" width="320"/> # Polygons and polylines You can draw polygons or polylines on canvases by providing a sequence of points. The polygons can have transparent colors and they may be filled or not (stroked). A point can be an [x,y] pair or any but the first point can be a triple of [x,y] pairs rep...
github_jupyter
from jp_doodle import dual_canvas from IPython.display import display # In this demonstration we do most of the work in Javascript. demo = dual_canvas.DualCanvasWidget(width=320, height=220) display(demo) demo.js_init(""" // Last entry in points list gives Bezier control points [[2,2], [1,0], [0,0]] var points = [[5...
0.716814
0.947575
# Path and shape regimes of rising bubbles ## Outline 1. [Starting point](#starting_point) 2. [Data visualization](#data_visualization) 3. [Manual binary classification - creating a functional relationship](#manuel_classification) 4. [Using gradient descent to find the parameters/weights](#gradient_descent) 5. [Using...
github_jupyter
# load and process .csv files import pandas as pd # python arrays import numpy as np # plotting import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, LinearSegmentedColormap # machine learning import sklearn from sklearn import preprocessing import torch from torch import nn, optim import torch....
0.561455
0.980525
``` import matplotlib.pyplot as plt import pandas as pd import numpy as np import json import sys import os import scipy import scipy.io from scipy import stats path_root = os.environ.get('DECIDENET_PATH') path_code = os.path.join(path_root, 'code') if path_code not in sys.path: sys.path.append(path_code) from dn...
github_jupyter
import matplotlib.pyplot as plt import pandas as pd import numpy as np import json import sys import os import scipy import scipy.io from scipy import stats path_root = os.environ.get('DECIDENET_PATH') path_code = os.path.join(path_root, 'code') if path_code not in sys.path: sys.path.append(path_code) from dn_uti...
0.541409
0.772101
``` import numpy as np import pandas as pd import plotly.express as px from scipy import stats from statsmodels.formula.api import ols from statsmodels.stats.anova import anova_lm as anova import itertools from sklearn import linear_model from numpy import ones,vstack from numpy.linalg import lstsq df=pd.read_csv('../d...
github_jupyter
import numpy as np import pandas as pd import plotly.express as px from scipy import stats from statsmodels.formula.api import ols from statsmodels.stats.anova import anova_lm as anova import itertools from sklearn import linear_model from numpy import ones,vstack from numpy.linalg import lstsq df=pd.read_csv('../data/...
0.37502
0.312344
# Compare slit profile with reference profile for [O III] Repeat of previous workbook but for a different line I first work through all the steps individually, looking at graphs of the intermediate results. This was used while iterating on the algorithm, by swapping out the value of `db` below for different slits th...
github_jupyter
from pathlib import Path import yaml import numpy as np from numpy.polynomial import Chebyshev from astropy.io import fits from astropy.wcs import WCS import astropy.units as u from matplotlib import pyplot as plt import seaborn as sns import mes_longslit as mes dpath = Path.cwd().parent / "data" pvpath = dpath / "pve...
0.507324
0.903932
## 1. The World Bank's international debt data <p>It's not that we humans only take debts to manage our necessities. A country may also take debt to manage its economy. For example, infrastructure spending is one costly ingredient required for a country's citizens to lead comfortable lives. <a href="https://www.worldba...
github_jupyter
%%sql postgresql:///international_debt SELECT * FROM international_debt LIMIT 10; %%sql SELECT COUNT(DISTINCT (country_name)) AS total_distinct_countries FROM international_debt; %%sql SELECT DISTINCT(indicator_code) AS distinct_debt_indicators FROM international_debt ORDER BY distinct_debt_indicators; %%sql SE...
0.262464
0.989682
<a href="https://colab.research.google.com/github/ibaiGorordo/Deeplab-ADE20K-Inference/blob/master/DeepLab_ADE20K_inference_Demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Overview This colab demonstrates the steps to use the DeepLab model t...
github_jupyter
import os from io import BytesIO import tarfile import tempfile from six.moves import urllib from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np from PIL import Image %tensorflow_version 1.x import tensorflow as tf class DeepLabModel(object): """Class to load deeplab model and r...
0.7324
0.985977
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import pymc3 as pm import numpy.random as npr %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' ``` # Introduction Let's say there are three bacteria species that characterize the gut, and we...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import pymc3 as pm import numpy.random as npr %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' def proportion(arr): arr = np.asarray(arr) return arr / arr.sum() healthy_proportions = pro...
0.486332
0.956796
# Exampville Mode Choice Discrete choice modeling is at the heart of many transportion planning models. In this example, we will examine the development of a mode choice model for Exampville, an entirely fictional town built for the express purpose of demostrating the use of discrete choice modeling tools for transp...
github_jupyter
import larch, numpy, pandas, os import larch.exampville skims = larch.OMX( larch.exampville.files.skims, mode='r' ) skims hh = pandas.read_csv( larch.exampville.files.hh ) pp = pandas.read_csv( larch.exampville.files.person ) tour = pandas.read_csv( larch.exampville.files.tour ) hh.info() pp.info() tour.info() tou...
0.338186
0.989662
### Analyze_rotated_stable_points - evaluate bias in rotated DEMs using selected unchanged points These points were picked on hopefully stable points in mostly flat places: docks, lawns, bare spots in middens. Also, the yurt roofs. Typically, 3 to 5 points were picked on most features. ``` import pandas as pd import ...
github_jupyter
import pandas as pd import numpy as np import xarray as xr import matplotlib.pyplot as plt %matplotlib inline # define some functions def pcoord(x, y): """ Convert x, y to polar coordinates r, az (geographic convention) r,az = pcoord(x, y) """ r = np.sqrt( x**2 + y**2 ) az=np.degrees( np.arcta...
0.499512
0.894698
# Calculating NDVI: Part 2 This exercise follows on from the previous section. In the [previous part of this exercise](../session_4/03_calculate_ndvi_part_2.ipynb), you constructed a notebook to resample a year's worth of Sentinel-2 data into quarterly time steps. In this section, you will conitnue from where you end...
github_jupyter
measurements = ['red', 'green', 'blue', 'nir'] ``` If you completed the above step, your `load_ard` cell should look like: sentinel_2_ds = load_ard( dc=dc, products=["s2_l2a"], x=x, y=y, time=("2019-01", "2019-12"), output_crs="EPSG:6933", measurements=['red...
0.94672
0.991381
[![pythonista.io](imagenes/pythonista.png)](https://www.pythonista.io) # Expresiones con operadores en Python. Los operadores son signos o palabras reservadas que el intérprete de Python identifica dentro de sus sintaxis para realizar una acción (operación) específica. ``` <objeto 1> <operador> <objeto 2> ``` ``` <...
github_jupyter
<objeto 1> <operador> <objeto 2> <objeto 1> <operador 1> <objeto 2> <operador 2> .... <operador n-1> <objeto n> 1 + 1 15 * 4 + 1 / 3 ** 5 3 + 2 3 - 2 3 * 2 3 ** 2 3 ** 0.5 3 / 2 3 // 2 3 % 2 12 * 5 + 2 / 4 ** 2 (12 * 5) + (2 / (4 ** 2)) (12 * 5) + (2 / 4) ** 2 (12 * (5 + 2) / 3) ** 2 >>> 3 / 4 0 >>> 10 / ...
0.525612
0.97506