code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# CA Coronavirus Cases and Deaths Trends CA's [Blueprint for a Safer Economy](https://www.cdph.ca.gov/Programs/CID/DCDC/Pages/COVID-19/COVID19CountyMonitoringOverview.aspx) assigns each county [to a tier](https://www.cdph.ca.gov/Programs/CID/DCDC/Pages/COVID-19/COVID19CountyMonitoringOverview.aspx) based on case rate ...
github_jupyter
``` from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf sess_config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) np.random.seed(219) tf.set_random_seed(219) # Load training and eval data from tf.ker...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import json import tensorflow as tf import nltk from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequence...
github_jupyter
# Simulators ## Introduction This notebook shows how to import the *Qiskit Aer* simulator backend and use it to run ideal (noise free) Qiskit Terra circuits. ``` import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogr...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training/train-within-notebook/train-within-notebook.png) # Train and deploy a model _**Create and d...
github_jupyter
# Setup ``` !pip install git+https://github.com/hafidhrendyanto/gpt2-absa.git ``` # Code Sample ``` from gpt2absa.constant import restaurant_aspect_categories, laptop_aspect_categories from gpt2absa import aspect_polarity_pair from transformers import TFAutoModelWithLMHead model = TFAutoModelWithLMHead.from_pretrain...
github_jupyter
# Regression using Decision Trees In this notebook, we will use decision trees to solve regression problems. The dataset used here originates from a project to build a surrogate model for predicting the band gap of a material from its composition. This surrogate model was used to replace expensive qunatum mecahnical...
github_jupyter
# Exercise 13. Nonparametric tests, goodness-of-fit tests ## Michal Béreš, Martina Litschmannová, Adéla Vrtková # Conformance distribution probability testing of discrete NV(finite number of values) - good agreement test - we test whether the measured data(their relative frequencies) agree with any specific distrib...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np import os import tensorflow as tf import tensorflow_datasets as tfds print("TensorFlow version:", tf.__version__) mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 (x_train_...
github_jupyter
``` repo_directory = '/Users/iaincarmichael/Dropbox/Research/law/law-net/' data_dir = '/Users/iaincarmichael/Documents/courtlistener/data/' import numpy as np import sys import matplotlib.pyplot as plt from scipy.stats import rankdata from collections import Counter # graph package import igraph as ig # our code sy...
github_jupyter
# Distance Based Statistical Method for Planar Point Patterns **Authors: Serge Rey <sjsrey@gmail.com> and Wei Kang <weikang9009@gmail.com>** ## Introduction Distance based methods for point patterns are of three types: * [Mean Nearest Neighbor Distance Statistics](#Mean-Nearest-Neighbor-Distance-Statistics) * [Near...
github_jupyter
<a href="https://colab.research.google.com/github/Amro-source/Deep-Learning/blob/main/imageprocessing1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import numpy as np def im2double(im): min_val = np.min(im.ravel()) max_val = np.max(i...
github_jupyter
``` import pandas as pd from datetime import datetime from _lib.data_preparation import remove_substandard_trips, df_calc_basic, df_join_generic_with_gps, read_gpx, calc_context from _lib.data_preparation import get_df_detail_final, get_df_generic_final from _lib.helper import val2year, val2zip, val2utf8, get_filepath...
github_jupyter
<a href="https://www.bigdatauniversity.com"><img src="https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png" width="400" align="center"></a> <h1 align="center"><font size="5">Classification with Python</font></h1> In this notebook we try to practice all the classification algorithms that we learned i...
github_jupyter
``` # 사용할 데이터 import import pandas as pd df = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases' '/breast-cancer-wisconsin/wdbc.data', header=None) from sklearn.preprocessing import LabelEncoder X = df.loc[:, 2:].values y = df.loc[:, 1].values le = LabelEnco...
github_jupyter
``` import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.3 tf.Session(config=config) import keras from keras.models import * from keras.layers import * from keras import optimizers from keras.applications.resnet50 import ResNet5...
github_jupyter
``` import ase import numpy as np import cPickle as pck from ase.visualize import view import quippy as qp def qp2ase(qpatoms): from ase import Atoms as aseAtoms positions = qpatoms.get_positions() cell = qpatoms.get_cell() numbers = qpatoms.get_atomic_numbers() pbc = qpatoms.get_pbc() atoms = a...
github_jupyter
``` %matplotlib inline import csv import random import numpy as np from sklearn.feature_extraction.text import * import pickle import tensorflow as tf import nn_model from sklearn.metrics import label_ranking_loss from collections import Counter, defaultdict import matplotlib.pyplot as plt from operator import itemgett...
github_jupyter
# Loss and Regularization ``` %load_ext autoreload %autoreload 2 import numpy as np from numpy import linalg as nplin from cs771 import plotData as pd from cs771 import optLib as opt from sklearn import linear_model from matplotlib import pyplot as plt from matplotlib.ticker import MaxNLocator import random ``` **Loa...
github_jupyter
# Import statements ``` from google.colab import drive drive.mount('/content/drive') from my_ml_lib import MetricTools, PlotTools import os import numpy as np import matplotlib.pyplot as plt import pickle import pandas as pd import matplotlib.pyplot as plt from matplotlib.pyplot import figure import json import dat...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from utils import get_ts from warnings import simplefilter simplefilter("ignore") df = get_ts(coin="nexo",days=500) df.head(3) # Set Matplotlib defaults plt.style.use("seaborn-whitegrid") plt.rc("figure", autolayout=True, f...
github_jupyter
# Planar data classification with one hidden layer Welcome to your week 3 programming assignment! It's time to build your first neural network, which will have one hidden layer. Now, you'll notice a big difference between this model and the one you implemented previously using logistic regression. By the end of this ...
github_jupyter
#### From Quarks to Cosmos with AI: Tutorial Day 4 --- # Field-level cosmological inference with IMNN + DELFI by Lucas Makinen [<img src="https://raw.githubusercontent.com/tlmakinen/FieldIMNNs/master/tutorial/plots/Orcid-ID.png" alt="drawing" width="20"/>](https://orcid.org/0000-0002-3795-6933 "") [<img src="https://r...
github_jupyter
# Task 6: Regularisation _All credit for this jupyter notebook tutorial goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by Aurelien Geron. Modifications were made in preparation for the hands-on sessions._ # Setup First, let's import a few common modules, ensure MatplotLib plots figures i...
github_jupyter
``` #hide from perutils.nbutils import simple_export_all_nb,simple_export_one_nb ``` # Personal Utils (perutils) > Notebook -> module conversion with #export flags and nothing else **Purpose:** The purpose and main use of this module is for adhoc projects where a full blown nbdev project is not necessary **Exampl...
github_jupyter
``` import pandas as pd ``` # Import Data ``` schiz_pre = pd.read_csv('data/schizophrenia_pre_features_tfidf_256.csv') schiz_post = pd.read_csv('data/schizophrenia_post_features_tfidf_256.csv') ``` # High-Level Look at Datasets ## Preface These datasets contain a very large number of features. For this project we ...
github_jupyter
<a href="https://colab.research.google.com/github/BrianThomasRoss/DS-Unit-2-Linear-Models/blob/master/module3-ridge-regression/Brian_Ross_LS_DS_213_assignment.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, Sprin...
github_jupyter
# Supervised Stylometric Analysis of the Pentateuch ### Table of Contents 1. [Introduction](#intro) 2. [Preprocess Data](#preprocess) 3. [Embedding Experimentation](#embed) 4. [Results](#results) <a name='intro'></a> ### 1. Introduction Modern biblical scholarship holds that the Pentateuch, also known as the To...
github_jupyter
``` import tensorflow as tf import os import numpy as np import ujson as json from importlib import reload from scipy import stats from func import cudnn_gru, native_gru, dot_attention, summ, ptr_net from prepro import word_tokenize, convert_idx import inference # reload(inference.InfModel) # reload(inference.Inferen...
github_jupyter
<a href="https://colab.research.google.com/github/gordeli/textanalysis/blob/master/03_Data_Collection_DS3Text.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #Fundamentals of Text Analysis for User Generated Content @ EDHEC, 2021 # Part 3: Data Col...
github_jupyter
``` import boto3 import botocore import os import sagemaker bucket = sagemaker.Session().default_bucket() prefix = "sagemaker/ipinsights-tutorial" execution_role = sagemaker.get_execution_role() region = boto3.Session().region_name # check if the bucket exists try: boto3.Session().client("s3").head_bucket(Bucket...
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#ALGO1-:-Introduction-à-l'algorithmique" data-toc-modified-id="ALGO1-:-Introduction-à-l'algorithmique-1"><span class="toc-item-num">1&nbsp;&nbsp;</span><a href="https://perso.crans.org/besson/teach/info1_algo1_2019/" target="_blank">ALGO1 : Introduction à l'al...
github_jupyter
``` import pandas as pd import numpy as np ``` ## Load data from csv file ``` names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','PRICE'] df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data', header=None, names=name...
github_jupyter
``` from copy import deepcopy import json import pandas as pd DATA_DIR = 'data' # Define template payloads CS_TEMPLATE = { 'resourceType': 'CodeSystem', 'status': 'draft', 'experimental': False, 'hierarchyMeaning': 'is-a', 'compositional': False, 'content': 'fragment', 'concept': [] } ``` ...
github_jupyter
## Caroline's raw material planning <img align='right' src='https://drive.google.com/uc?export=view&id=1FYTs46ptGHrOaUMEi5BzePH9Gl3YM_2C' width=200> As we know, BIM produces logic and memory chips using copper, silicon, germanium and plastic. Each chip has the following consumption of materials: | chip | copper...
github_jupyter
## AutoGraph: examples of simple algorithms This notebook shows how you can use AutoGraph to compile simple algorithms and run them in TensorFlow. It requires the nightly build of TensorFlow, which is installed below. ``` !pip install -U -q tf-nightly-2.0-preview import tensorflow as tf tf = tf.compat.v2 tf.enable_...
github_jupyter
# T81-558: Applications of Deep Neural Networks **Module 7: Generative Adversarial Networks** * Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) * For more information visit the...
github_jupyter
#### Copyright 2017 Google LLC. ``` # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
github_jupyter
``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed u...
github_jupyter
``` !env | grep -i python ! which python ! which pip ! pip install catboost from catboost import CatBoostClassifier ``` A fork of `catboost-go-5.0-subset.ipynb` where we exclude run ID and study ID from the features ``` !pip install --user catboost ipywidgets !conda install -y python-graphviz !jupyter nbextension ena...
github_jupyter
``` %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import os import gc import time import math import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from sklearn.metrics import roc_auc_score from nltk.tokenize ...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib import numpy as np import utils matplotlib.rcParams['figure.figsize'] = (0.89 * 12, 6) matplotlib.rcParams['lines.linewidth'] = 10 matplotlib.rcParams['lines.markersize'] = 20 ``` # The Dataset $$y = x^3 + x^2 - 4x$$ ``` x, y, X, transform, sc...
github_jupyter
``` ####################################################### # Script: # trainPerf.py # Usage: # python trainPerf.py <input_file> <output_file> # Description: # Build the prediction model based on training data # Pass 1: prediction based on hours in a week # Authors: # Jasmin Nakic, jnakic@salesforce.com ...
github_jupyter
# Rotation Transformation We meta-learn how to rotate images so that we can accurately classify rotated images. We use MNIST. Import relevant packages ``` from operator import mul from itertools import cycle import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torch.backends.cudnn...
github_jupyter
# Daily Load Profile Timeseries Clustering Evaluation ``` import pandas as pd import numpy as np import datetime as dt import os from math import ceil, log import plotly.plotly as py import plotly.offline as po import plotly.graph_objs as go import plotly.figure_factory as ff import plotly.tools as tools import color...
github_jupyter
``` import pandas as pd import numpy as np data = { 'color': [ 'blue', 'green', 'yellow', 'red', 'white' ], 'object': ['ball', 'pen', 'pencil', 'paper', 'mug'], 'price': [ 1.2, 1.0, 0.6, 0.9, 1.7 ] } frame = pd.DataFrame(data) frame frame2 = pd.DataFrame(data, columns=['object', 'price']) frame2 frame2 = pd...
github_jupyter
In Ipython Notebook, I can write down the mathmatical expression with latex, which allows me to understand my codes better. ## q_3 word2vec.py ``` import numpy as np import random from q1_softmax import softmax from q2_gradcheck import gradcheck_naive from q2_sigmoid import sigmoid, sigmoid_grad def normalizeRows(x)...
github_jupyter
<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> # Enforce conformal 3-metric $\det{\bar{\gamma}_{ij}}=\det{...
github_jupyter
<div align="center"><h1>Perspectives on Text</h1> <h3>_Synthesizing Textual Knowledge through Markup_</h3> <br/> <h4>Elli Bleeker, Bram Buitendijk, Ronald Haentjens Dekker, Astrid Kulsdom <br/>R&amp;D - Dutch Royal Academy of Arts and Science</h4> <h6>Computational Methods for Literary Historical Textual Schola...
github_jupyter
Miscilanous plots of spectra. ``` #first get the python modules we need import numpy as np import matplotlib.pyplot as plt import astropy.io.fits as fits import os import glob from astropy.convolution import convolve, Box1DKernel from astropy.table import Table import astropy.units as u from astropy.modeling import mo...
github_jupyter
# Project description - Beta Bank customers are leaving: little by little, chipping away every month. The bankers figured out it’s cheaper to save the existing customers rather than to attract new ones. - We need to predict whether a customer will leave the bank soon. You have the data on clients’ past behavior and t...
github_jupyter
# Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and...
github_jupyter
# Lab 1 Second section is kind of exploring the subject. The proper homework is presented in last two sections, showing differences similarities for different parameters (noise and function). ## Simulation preparation ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #import seaborn as sns ...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime import pickle from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score # functions def rem_outliers(df, col): ''' Remove outl...
github_jupyter
# Import ``` import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import TensorDataset, Dataset, DataLoader, random_split from torch.nn.utils.rnn import pack_padded_sequence, pack_sequence, pad_packed_sequence, pad_sequ...
github_jupyter
# NLP - Hotel review sentiment analysis in python ``` #warnings :) import warnings warnings.filterwarnings('ignore') import os dir_Path = 'D:\\01_DATA_SCIENCE_FINAL\\D-00000-NLP\\NLP-CODES\\AMAN-NLP-CODES\\AMAN_NLP_VIMP-CODE\\Project-6_Sentiment_Analysis_Amn\\' os.chdir(dir_Path) ``` ## Data Facts and Import ``` im...
github_jupyter
## TrainingPhase and General scheduler Creates a scheduler that lets you train a model with following different [`TrainingPhase`](/callbacks.general_sched.html#TrainingPhase). ``` from fastai.gen_doc.nbdoc import * from fastai.callbacks.general_sched import * from fastai.vision import * show_doc(TrainingPhase) ``` ...
github_jupyter
## Problem Definition In the following different ways of loading or implementing an optimization problem in our framework are discussed. ### By Class A very detailed description of defining a problem through a class is already provided in the [Getting Started Guide](../getting_started.ipynb). The following definitio...
github_jupyter
``` import os, platform, pprint, sys import fastai import keras import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sn import sklearn # from fastai.tabular.data import TabularDataLoaders # from fastai.tabular.all import FillMissing, Categorify, N...
github_jupyter
# Using AWS Lambda and PyWren for Landsat 8 Time Series This notebook is a simple demonstration of drilling a timeseries of NDVI values from the [Landsat 8 scenes held on AWS](https://landsatonaws.com/) ### Credits - NDVI PyWren - [Peter Scarth](mailto:p.scarth@uq.edu.au?subject=AWS%20Lambda%20and%20PyWren) (Joint Rem...
github_jupyter
``` import xgboost as xgb import pandas as pd # 読み出し data = pd.read_pickle('data.pkl') nomination_onehot = pd.read_pickle('nomination_onehot.pkl') selected_performers_onehot = pd.read_pickle('selected_performers_onehot.pkl') selected_directors_onehot = pd.read_pickle('selected_directors_onehot.pkl') selected_studio_one...
github_jupyter
``` %tensorflow_version 2.x import tensorflow as tf #from tf.keras.models import Sequential #from tf.keras.layers import Dense import os import io tf.__version__ ``` # Download Data ``` # Download the zip file path_to_zip = tf.keras.utils.get_file("smsspamcollection.zip", origin="https://archive.ic...
github_jupyter
``` import os from skimage.filters.rank import median import numpy as np import matplotlib.pyplot as plt import skimage.data as data import skimage.segmentation as seg import skimage.filters as filters import skimage.draw as draw import skimage.color as color from scipy.ndimage.filters import convolve from skimage.fil...
github_jupyter
# 3D Partially coherent ODT forward simulation This forward simulation is based on the SEAGLE paper ([here](https://ieeexplore.ieee.org/abstract/document/8074742)): <br> ```H.-Y. Liu, D. Liu, H. Mansour, P. T. Boufounos, L. Waller, and U. S. Kamilov, "SEAGLE: Sparsity-Driven Image Reconstruction Under Multiple Scatteri...
github_jupyter
``` #default_exp fastai.dataloader ``` # DataLoader Errors > Errors and exceptions for any step of the `DataLoader` process This includes `after_item`, `after_batch`, and collating. Anything in relation to the `Datasets` or anything before the `DataLoader` process can be found in `fastdebug.fastai.dataset` ``` #expo...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt x = np.arange(5) y = x t = x fig, (ax1, ax2) = plt.subplots(1, 2) ax1.scatter(x, y, c=t, cmap='viridis') ax2.scatter(x, y, c=t, cmap='viridis_r') color = "red" plt.scatter(x, y, c=color) sequence_of_colors = ["red", "orange", "yellow", "green", "blue","red", "ora...
github_jupyter
--- _You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._ --- ## Assignment 4 - ...
github_jupyter
``` # ============================================================================== # Copyright 2021 Google LLC. This software is provided as-is, without warranty # or representation for any use or purpose. Your use of it is subject to your # agreement with Google. # ===================================================...
github_jupyter
# Hertzian conatct 1 ## Assumptions When two objects are brought into contact they intially touch along a line or at a single point. If any load is transmitted throught the contact the point or line grows to an area. The size of this area, the pressure distribtion inside it and the resulting stresses in each solid req...
github_jupyter
``` import matplotlib.pyplot as plt import numpy from numpy import genfromtxt import csv import pandas as pd from operator import itemgetter from datetime import* from openpyxl import load_workbook,Workbook from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font import openpyxl from win32com ...
github_jupyter
<center> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png" width="300" alt="cognitiveclass.ai logo" /> </center> # Loops in Python Estimated time needed: **20** minutes ## Objectives After completing this lab you will be ab...
github_jupyter
``` import json import requests import numpy as np import pandas as pd import pandas as pd import requests from requests.auth import HTTPBasicAuth USERNAME = 'damminhtien' PASSWORD = '**********' TARGET_USER = 'damminhtien' authentication = HTTPBasicAuth(USERNAME, PASSWORD) import uuid from IPython.display import dis...
github_jupyter
<a href="https://colab.research.google.com/github/trucabrac/blob_Jan2022/blob/main/Blob_batch_processing.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import numpy as np import cv2 import os import glob from skimage.filters import gaussian fro...
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 ``` # ...
github_jupyter
# Missing Data Missing values are a common problem within datasets. Data can be missing for a number of reasons, including tool/sensor failure, data vintage, telemetry issues, stick and pull, and omissing by choice. There are a number of tools we can use to identify missing data, some of these methods include: - Pa...
github_jupyter
# Applying Chords to 2D and 3D Images ## Importing packages ``` import time import porespy as ps ps.visualization.set_mpl_style() ``` Import the usual packages from the Scipy ecosystem: ``` import scipy as sp import scipy.ndimage as spim import matplotlib.pyplot as plt ``` ## Demonstration on 2D Image Start by cre...
github_jupyter
# Exercise 6 ``` # Importing libs import cv2 import numpy as np import matplotlib.pyplot as plt apple = cv2.imread('images/apple.jpg') apple = cv2.cvtColor(apple, cv2.COLOR_BGR2RGB) apple = cv2.resize(apple, (512,512)) orange = cv2.imread('images/orange.jpg') orange = cv2.cvtColor(orange, cv2.COLOR_BGR2RGB) orange = ...
github_jupyter
``` from bs4 import BeautifulSoup import os import random from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import LabelEncoder from sklearn.datasets import fetch_20newsgroups from sklearn.svm import LinearSVC from sklearn.naive_bayes import ComplementNB from sklearn.model_selection...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt from IPython.core.debugger import Pdb; pdb = Pdb() def get_down_centre_last_low(p_list): zn_num = len(p_list) - 1 available_num = min(9, (zn_num - 6)) index = len(p_list) - 4 for i in range(0, available_num // 2): if p_list[index - 2...
github_jupyter
``` # default_exp core ``` # module name here > API details. ``` #hide from nbdev.showdoc import * #export import pandas as pd from tqdm import tqdm_notebook as tqdm import json import numpy as np from fastai.vision.all import * import albumentations as A import skimage.io as skio import warnings warnings.filterwarn...
github_jupyter
# Machine Learning and Statistics for Physicists Material for a [UC Irvine](https://uci.edu/) course offered by the [Department of Physics and Astronomy](https://www.physics.uci.edu/). Content is maintained on [github](github.com/dkirkby/MachineLearningStatistics) and distributed under a [BSD3 license](https://openso...
github_jupyter
# Offline analysis of a [mindaffectBCI](https://github.com/mindaffect) savefile So you have successfully run a BCI experiment and want to have a closer look at the data, and try different analysis settings? Or you have a BCI experiment file from the internet, e.g. MOABB, and want to try it with the mindaffectBCI an...
github_jupyter
``` import numpy as np from scipy.integrate import odeint from TricubicInterpolation import TriCubic class Fermat(object): def __init__(self,neTCI=None,frequency = 120e6,type='s',straightLineApprox=True): '''Fermat principle. type = "s" means arch length is the indepedent variable type="z" means z ...
github_jupyter
## Desafio Final ``` # imports de avisos import sys import warnings import matplotlib.cbook warnings.simplefilter("ignore") warnings.simplefilter(action='ignore', category=FutureWarning) warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation...
github_jupyter
# Database engineering In this section we'll create: + table schemas using SQLAlchemy ORM + create a database in SQLite + load the cleaned Hawaii climate data into pandas dataframes + upload the data from the pandas dataframes into the SQLite database ``` # Dependencies import pandas as pd import sqlite3 from sqlalc...
github_jupyter
<div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="https://cocl.us/corsera_da0101en_notebook_top"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/Images/TopAd.png" width="750" align="center"> </a> </div> <a href="https://ww...
github_jupyter
# Aula 01 - Parte 1 ## Transformações Lineares Nesta primeira parte da aula faremos uma breve revisão de transformações lineares. Vamos começar pensando em transformações em 2D. ### Rotação Crie uma função que recebe um ângulo $\theta$ e devolve uma matriz de rotação representada por um *numpy.array*. Os pontos são ...
github_jupyter
``` #CREATE CLASS #CLASS VS INSTANCE #CREATE CLASS class SoftwareEngineer: def __init__(self, name, age, level, salary): #instance attribute self.name = name self.age = age self.level = level self.salary = salary #instance se1 = SoftwareEngineer("Max", 20, "Junior", 50...
github_jupyter
``` import cv2 cap = cv2.VideoCapture(0) car_model=cv2.CascadeClassifier('cars.xml') ``` # TO DETECT CAR ON LIVE VIDEO OR PHOTO..... ``` while True: ret,frame=cap.read() cars=car_model.detectMultiScale(frame) gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) for(x,y,w,h) in cars: cv2.rectangle(fram...
github_jupyter
<h1>datetime library</h1> <li>Time is linear <li>progresses as a straightline trajectory from the big bag <li>to now and into the future <li>日期库官方说明 https://docs.python.org/3.5/library/datetime.html <h3>Reasoning about time is important in data analysis</h3> <li>Analyzing financial timeseries data <li>Looking at comm...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/landsat457_surface_reflectance.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> ...
github_jupyter
``` %%pyspark df = spark.read.load('abfss://capture@splacceler5lmevhdeon4ym.dfs.core.windows.net/SeattlePublicLibrary/Library_Collection_Inventory.csv', format='csv' ## If header exists uncomment line below , header=True ) display(df.limit(10)) %%pyspark # Show Schema df.printSchema() %%pyspark from pyspark.sql i...
github_jupyter
# LinearSVR with MinMaxScaler & Power Transformer This Code template is for the Classification task using Support Vector Regressor (SVR) based on the Support Vector Machine algorithm with Power Transformer as Feature Transformation Technique and MinMaxScaler for Feature Scaling in a pipeline. ### Required Packages ...
github_jupyter
<img src="../images/26-weeks-of-data-science-banner.jpg"/> # Getting Started with Python ## About Python <img src="../images/python-logo.png" alt="Python" style="width: 500px;"/> Python is a - general purpose programming language - interpreted, not compiled - both **dynamically typed** _and_ **strongly typed** -...
github_jupyter
#Instalamos pytorch ``` #pip install torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html ``` #Clonamos el repositorio para obtener el dataset ``` !git clone https://github.com/joanby/deeplearning-az.git from google.colab import drive drive.mount('/content/drive') ``` # Importar l...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df=pd.read_csv("phl_hec_all_confirmed.csv") ; # df.head() sns.heatmap(df.isnull(),yticklabels=False,cbar=False) df.drop(['P. Name KOI'],axis=1,inplace=True) df.drop(['P. Min Mass (EU)'],axis=1,inplace=True) df.drop(['P. Ma...
github_jupyter
``` ``` --- title: "Pipes and Filters" teaching: 25 exercises: 10 questions: - "How can I combine existing commands to do new things?" objectives: - "Redirect a command's output to a file." - "Process a file instead of keyboard input using redirection." - "Construct command pipelines with two or more stages." - "Expl...
github_jupyter
``` %load_ext autoreload %autoreload 2 import molsysmt as msm ``` # Info *Printing out summary information of a molecular system* There is in MolSysMT a method to print out a brief overview of a molecular system and its elements. The output of this method can be a `pandas.DataFrame` or a `string`. Lets load a molecu...
github_jupyter
# [Detecting the difficulty level of French texts](https://www.kaggle.com/c/detecting-the-difficulty-level-of-french-texts/overview/evaluation) ## Hyper parameters tuning --- In this notebook, we will use cross-validation to find the best parameters of the models that showed the most promising result in first approach....
github_jupyter
#### Основы программирования в Python для социальных наук ## Web-scraping таблиц. Подготовка к самостоятельной Семинар 7 *Автор: Татьяна Рогович, НИУ ВШЭ* Этот блокнот поможет вам разобраться, как подходить к самостоятельной работе. Один из пунктов - это скрейпинг таблицы из википедии. Посмотрим на примере, как это...
github_jupyter