code
stringlengths
2.5k
150k
kind
stringclasses
1 value
### Import Library and Dataset ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime pd.set_option('display.max_columns', None) data_train = pd.read_excel('Data_Train.xlsx') data_test = pd.read_excel('Data_Test.xlsx') ``` ### Combining the Dataset ``` price_train = data_train.Pri...
github_jupyter
``` # Import dependencies import pandas as pd import pathlib # Identifying CSV file path csv_path = pathlib.Path('../../Resources/Raw/COVID-19_Case_Surveillance_Public_Use_Data_with_Geography.csv') # Reading and previewing CSV file data_df = pd.read_csv(csv_path, low_memory=False) data_df.head() # Filtering for only C...
github_jupyter
``` # Load dependencies import numpy as np import pandas as pd from uncertainties import ufloat from uncertainties import unumpy ``` # Biomass C content estimation Biomass is presented in the paper on a dry-weight basis. As part of the biomass calculation, we converted biomass in carbon-weight basis to dry-weight ba...
github_jupyter
``` !pip install -q efficientnet import math, re, os, random import tensorflow as tf, tensorflow.keras.backend as K import numpy as np import pandas as pd import efficientnet.tfkeras as efn from matplotlib import pyplot as plt from kaggle_datasets import KaggleDatasets from sklearn.metrics import f1_score, precision_sc...
github_jupyter
## A Simple Pair Trading Strategy **_Please go through the "building strategies" notebook before looking at this notebook._** Let's build a aimple pair trading strategy to show how you can trade multiple symbols in a strategy. We will trade 2 stocks, Coca-Cola (KO) and Pepsi (PEP) 1. We will buy KO and sell PEP wh...
github_jupyter
# Introduction <div class="alert alert-info"> **Code not tidied, but should work OK** </div> <img src="../Udacity_DL_Nanodegree/031%20RNN%20Super%20Basics/SimpleRNN01.png" align="left"/> # Neural Network ``` import numpy as np import matplotlib.pyplot as plt import pdb ``` **Sigmoid** ``` def sigmoid(x): re...
github_jupyter
<a id="title_ID"></a> # JWST Pipeline Validation Notebook: calwebb_detector1, dark_current unit tests <span style="color:red"> **Instruments Affected**</span>: NIRCam, NIRISS, NIRSpec, MIRI, FGS ### Table of Contents <div style="text-align: left"> <br> [Introduction](#intro) <br> [JWST Unit Tests](#unit) <br> ...
github_jupyter
## Dự án 01: Xây dựng Raspberry PI thành máy tính cho Data Scientist (PIDS) ## Bài 01. Cài đặt TensorFlow và các thư viện cần thiết ##### Người soạn: Dương Trần Hà Phương ##### Website: [Mechasolution Việt Nam](https://mechasolution.vn) ##### Email: mechasolutionvietnam@gmail.com --- ## 1. Mở đầu Nếu bạn muốn chạy mộ...
github_jupyter
# Transform points from pitch to texture and vice-versa ### Matrix P - Projection The P matrix is a 3x4 matrix that given a 3D point in the world reference frame, it is projected into the 2D image in **texture coordinate** reference frame, i.e: \begin{align} \mathbf{pt_{world}} = (x, y, z, 1) \\ \mathbf{pt_{pitch}} = ...
github_jupyter
# House Price Prediction With TensorFlow [![open_in_colab][colab_badge]][colab_notebook_link] [![open_in_binder][binder_badge]][binder_notebook_link] [colab_badge]: https://colab.research.google.com/assets/colab-badge.svg [colab_notebook_link]: https://colab.research.google.com/github/UnfoldedInc/examples/blob/master...
github_jupyter
Lambda School Data Science *Unit 2, Sprint 2, Module 3* --- <p style="padding: 10px; border: 2px solid red;"> <b>Before you start:</b> Today is the day you should submit the dataset for your Unit 2 Build Week project. You can review the guidelines and make your submission in the Build Week course for your cohort ...
github_jupyter
# Semantic Image Clustering **Author:** [Khalid Salama](https://www.linkedin.com/in/khalid-salama-24403144/)<br> **Date created:** 2021/02/28<br> **Last modified:** 2021/02/28<br> **Description:** Semantic Clustering by Adopting Nearest neighbors (SCAN) algorithm. ## Introduction This example demonstrates how to app...
github_jupyter
``` import json import numpy as np from sklearn.model_selection import train_test_split import tensorflow.keras as keras import matplotlib.pyplot as plt import random import librosa import math # path to json data_path = "C:\\Users\\Saad\\Desktop\\Project\\MGC\\Data\\data.json" def load_data(data_path): with ope...
github_jupyter
# Notebook 3 - Advanced Data Structures So far, we have seen numbers, strings, and lists. In this notebook, we will learn three more data structures, which allow us to organize data. The data structures are `tuple`, `set`, and `dict` (dictionary). ## Tuples A tuple is like a list, but is immutable, meaning that it ca...
github_jupyter
### Mount Google Drive (Works only on Google Colab) ``` from google.colab import drive drive.mount('/content/gdrive') ``` # Import Packages ``` import os import numpy as np import pandas as pd from zipfile import ZipFile from PIL import Image from tqdm.autonotebook import tqdm from IPython.display import display fr...
github_jupyter
<a id='pd'></a> <div id="qe-notebook-header" align="right" style="text-align:right;"> <a href="https://quantecon.org/" title="quantecon.org"> <img style="width:250px;display:inline;" width="250px" src="https://assets.quantecon.org/img/qe-menubar-logo.svg" alt="QuantEcon"> </a> </div> #...
github_jupyter
``` import numpy import scipy import scipy.sparse import sklearn.metrics.pairwise from sklearn import datasets from sklearn.metrics.pairwise import pairwise_distances #%% descriptions = [] with open('descriptions.txt', encoding = "utf8") as f: for line in f: text = line.low...
github_jupyter
# Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [i...
github_jupyter
``` print('Kazuma Shachou') nome_do_filme = "Bakamon" print(nome_do_filme) nome_do_filme import pandas as pd filmes = pd.read_csv("https://raw.githubusercontent.com/alura-cursos/introducao-a-data-science/master/aula0/ml-latest-small/movies.csv") filmes.columns = ["filmeid", "titulo", "generos"] filmes.head() # Lendo a...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
github_jupyter
# Import Dependencies ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker # scaling and dataset split from sklearn import preprocessing from sklearn.model_selection import train_test_split # OLS, Ridge from sklearn.linear_model import LinearRegression, Ridge #...
github_jupyter
# Regression on Decison Trees and Random Forest ``` #importing important libraries #libraries for reading dataset import numpy as np import pandas as pd #libraries for data visualisation import matplotlib.pyplot as plt import seaborn as sns #libraries for model building and understanding import sklearn from sklearn...
github_jupyter
# In this note book the following steps are taken: 1. Remove highly correlated attributes 2. Find the best hyper parameters for estimator 3. Find the most important features by tunned random forest 4. Find f1 score of the tunned full model 5. Find best hyper parameter of model with selected features 6. Find f1 score of...
github_jupyter
# Anailís ghramadaí trí [deplacy](https://koichiyasuoka.github.io/deplacy/) ## le [Stanza](https://stanfordnlp.github.io/stanza) ``` !pip install deplacy stanza import stanza stanza.download("ga") nlp=stanza.Pipeline("ga") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplac...
github_jupyter
<a href="https://colab.research.google.com/github/open-mmlab/mmclassification/blob/master/docs/tutorials/MMClassification_python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # MMClassification Python API tutorial on Colab In this tutorial, we wi...
github_jupyter
<a href="https://colab.research.google.com/github/EnzoGolfetti/imersaoalura_dados_3/blob/main/aula05_imersao_alura_dados.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #Análise de Drugs Discovery - Imersão Dados Alura Desafio 1: Investigar por que ...
github_jupyter
<div class="alert alert-block alert-info"> <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b> </div> Copyright © 2021 Theodore G. Cleveland and Farhang Forghanparast Last GitHub Commit Date: # 14: Visual display of data This lesson is a prelude to the `matplotlib` external module package...
github_jupyter
``` from os import listdir from numpy import array from keras.preprocessing.text import Tokenizer, one_hot from keras.preprocessing.sequence import pad_sequences from keras.models import Model, Sequential, model_from_json from keras.utils import to_categorical from keras.layers.core import Dense, Dropout, Flatten from ...
github_jupyter
``` ``` # **Deep Convolutional Generative Adversarial Network (DC-GAN):** DC-GAN is a foundational adversarial framework developed in 2015. It had a major contribution in streamlining the process of designing adversarial frameworks and visualizing intermediate representations, thus, making GANs more accessible to b...
github_jupyter
## Code Equivalence ``` import ast import astpretty import showast import sys import re sys.path.insert(0, '../preprocess/') sys.path.insert(0, '../../coarse2fine.git/src') from sketch_generation import Sketch from tree import SketchRepresentation import table SKP_WORD = '<sk>' RIG_WORD = '<]>' LFT_WORD = '<[>' def...
github_jupyter
# Import Scikit Learn, Pandas and Numpy ``` import sklearn import numpy as np import pandas as pd ``` # 1. Read the Dataset using Pandas ``` data = pd.read_csv("data/amazon_baby.csv") data ``` # 2. Exploratory Data Analysis ``` data.head() data.info() ``` ### The first observation is that we have cells with null ...
github_jupyter
``` %autosave 0 ``` # MCPC rehearsal problem Oct 25 2017 at UCSY ## Problem E: Stacking Plates ### Input format - 1st Line: 1 integer, Number of Test Case, each Test Case has following data + 1 Line: 1 integer, **n**(Number of Stacks) + **n** Lines: first integer: **h** (Number of Plates), and **h** integers ...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt from functools import reduce import seaborn as sns; sns.set(rc={'figure.figsize':(15,15)}) import numpy as np import pandas as pd from sqlalchemy import create_engine from sklearn.preprocessing import MinMaxScaler engine = create_engine('postgresql://postgres:mimi...
github_jupyter
[View in Colaboratory](https://colab.research.google.com/github/tjh48/DCGAN/blob/master/dcgan.ipynb) First we'll import all the tools we need and set some initial parameters ``` import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt import os from keras.models import * from keras.layers...
github_jupyter
## Preprocessing ``` # Import our dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd import tensorflow as tf # Import and read the charity_data.csv. import pandas as pd application_df = pd.read_csv("Resources/charity_data.csv") appl...
github_jupyter
# Puts ALL WISE Astrometry reference catalogues into GAIA reference frame <img src=https://avatars1.githubusercontent.com/u/7880370?s=200&v=4> The WISE catalogues were produced by ../dmu16_allwise/make_wise_samples_for_stacking.csh In the catalogue, we keep: - The position; - The chi^2 This astrometric correction ...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file...
github_jupyter
``` from pykat import finesse from pykat.commands import * import numpy as np import matplotlib.pyplot as plt import scipy from IPython import display pykat.init_pykat_plotting(dpi=200) base1 = """ l L0 10 0 n0 #input laser ...
github_jupyter
-> Associated lecture videos: in Neural Networks/Lesson 4 - Deep Learning with PyTorch: video 4, video 5, video 6, video 7 # Introduction to Deep Learning with PyTorch In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot o...
github_jupyter
# Chapter 7 - Iterations ------------------------------- Computers do not get bored. If you want the computer to repeat a certain task hundreds of thousands of times, it does not protest. Humans hate too much repetition. Therefore, repetitious tasks should be performed by computers. All programming languages support ...
github_jupyter
# 2D Advection-Diffusion equation in this notebook we provide a simple example of the DeepMoD algorithm and apply it on the 2D advection-diffusion equation. ``` # General imports import numpy as np import torch import matplotlib.pylab as plt # DeepMoD functions from deepymod import DeepMoD from deepymod.model.func_...
github_jupyter
# Web crawling exercise ``` from selenium import webdriver ``` ## Quiz 1 - 아래 URL의 NBA 데이터를 크롤링하여 판다스 데이터 프레임으로 나타내세요. - http://stats.nba.com/teams/traditional/?sort=GP&dir=-1 ### 1.1 webdriver를 실행하고 사이트에 접속하기 ``` driver = webdriver.Chrome() url = "http://stats.nba.com/teams/traditional/?sort=GP&dir=-1" driver.get(...
github_jupyter
### Functions ``` # syntax # Declaring a function def function_name(): codes codes # Calling a function function_name() def generate_full_name (): first_name = 'Ayush' last_name = 'Jindal' space = ' ' full_name = first_name + space + last_name print(full_name) generate_full_name () # c...
github_jupyter
# Custom Building Recurrent Neural Network **Notation**: - Superscript $[l]$ denotes an object associated with the $l^{th}$ layer. - Superscript $(i)$ denotes an object associated with the $i^{th}$ example. - Superscript $\langle t \rangle$ denotes an object at the $t^{th}$ time-step. - **Sub**script $i$ den...
github_jupyter
# Data description: I'm going to solve the International Airline Passengers prediction problem. This is a problem where given a year and a month, the task is to predict the number of international airline passengers in units of 1,000. The data ranges from January 1949 to December 1960 or 12 years, with 144 observation...
github_jupyter
<font color ='0c6142' size=6)> Chemistry </font> <font color ='708090' size=3)> for Technology Students at GGC </font> <font color ='708090' size=3)> Measurement Uncertainty, Accuracy, and Precision </font> [Textbook: Chapter 1, section 5](https://openstax.org/books/chemistry-2e/pages/1-5-measurement-uncertainty-a...
github_jupyter
``` import sys sys.path.insert(1, '/home/maria/Documents/EnsemblePursuit') from EnsemblePursuit.EnsemblePursuit import EnsemblePursuit import numpy as np from scipy.stats import zscore import matplotlib.pyplot as plt from scipy.ndimage import gaussian_filter, gaussian_filter1d data_path='/home/maria/Documents/data_for_...
github_jupyter
# Comparing soundings from NCEP Reanalysis and various models We are going to plot the global, annual mean sounding (vertical temperature profile) from observations. Read in the necessary NCEP reanalysis data from the online server. The catalog is here: <https://psl.noaa.gov/psd/thredds/catalog/Datasets/ncep.reanaly...
github_jupyter
<a href="https://colab.research.google.com/github/boopathiviky/Eulers-Project/blob/repo/euler's.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #1.multiples of 3 and 5 ``` sum1=0 x=int(input()) for i in range(1,x): if(i%3==0 or i%5==0): ...
github_jupyter
# `numpy` မင်္ဂလာပါ၊ welcome to the week 07 of Data Science Using Python. We will go into details of `numpy` this week (as well as do some linear algebra stuffs). ## `numpy` အကြောင်း သိပြီးသမျှ * `numpy` ဟာ array library ဖြစ်တယ်၊ * efficient ဖြစ်တယ်၊ * vector နဲ့ matrix တွေကို လွယ်လွယ်ကူကူ ကိုင်တွယ်နိုင်တယ...
github_jupyter
# Building your Deep Neural Network: Step by Step Welcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want! - In this notebook, you'll implement all the functions require...
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
github_jupyter
``` import pandas as pd import datetime from finquant.portfolio import build_portfolio from finquant.moving_average import compute_ma, ema from finquant.moving_average import plot_bollinger_band from finquant.efficient_frontier import EfficientFrontier ### DOES OUR OPTIMIZATION ACTUALLY WORK? # COMPARING AN OPTIMIZED ...
github_jupyter
# Isolation Forest (IF) outlier detector deployment Wrap a scikit-learn Isolation Forest python model for use as a prediction microservice in seldon-core and deploy on seldon-core running on minikube or a Kubernetes cluster using GCP. ## Dependencies - [helm](https://github.com/helm/helm) - [minikube](https://github...
github_jupyter
``` import numpy as np import pandas as pd import os import spacy import en_core_web_sm from spacy.lang.en import English from spacy.lang.en.stop_words import STOP_WORDS import string from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn import metrics fro...
github_jupyter
# Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. We will: * Extract features from Amazon product reviews. * Convert an SFrame into a NumPy array. * Implement the link function for logistic regression. * Write a function to compute t...
github_jupyter
## Demo: MultiContainer feeder example The basic steps to set up an OpenCLSim simulation are: * Import libraries * Initialise simpy environment * Define object classes * Create objects * Create sites * Create vessels * Create activities * Register processes and run simpy ---- #### 0. Import libraries ``` impor...
github_jupyter
``` from IPython.display import Latex # Latex(r"""\begin{eqnarray} \large # Z_{n+1} = Z_{n}^(-e^(Z_{n}^p)^(e^(Z_{n}^p)^(-e^(Z_{n}^p)^(e^(Z_{n}^p)^(-e^(Z_{n}^p)))))) # \end{eqnarray}""") ``` # Parameterized machine learning algo: ## tanh(Z) = (a exp(Z) - b exp(-Z)) / (c exp(Z) + d exp(-Z)) ### with parameters a,b,c,...
github_jupyter
# Hashtags ``` from nltk.tokenize import TweetTokenizer import os import pandas as pd import re import sys from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation from IPython.display import clear_output def squeal(text=None): clear_output(wait=True) ...
github_jupyter
``` from IPython.core.display import HTML HTML("<style>.container { width:95% !important; }</style>") ``` # Lecture 11, Solution methods for multiobjective optimization ## Reminder: ### Mathematical formulation of multiobjective optimization problems Multiobjective optimization problems are often formulated as $$ \...
github_jupyter
``` import pandas as pd import os, sys from sklearn.gaussian_process import GaussianProcessRegressor import shapefile from functools import partial import pyproj from shapely.geometry import shape, Point, mapping from shapely.ops import transform processeddir = "../data/processed/" rawdir = "../data/raw/" df = pd.read_...
github_jupyter
# Graph > in progress - toc: true - badges: true - comments: true - categories: [self-taught] - image: images/bone.jpeg - hide: true https://towardsdatascience.com/using-graph-convolutional-neural-networks-on-structured-documents-for-information-extraction-c1088dcd2b8f CNNs effectively capture patterns in data in Eu...
github_jupyter
# All those moments will be los(s)t in time, like tears in rain. > I am completely operational, and all my circuits are functioning perfectly. - toc: true - badges: true - comments: true - categories: [jupyter] - image: images/posts/2020-12-10-Tears-In-Rain/Tears-In-Rain.jpg ``` #hide !pip install -Uqq fastbook impo...
github_jupyter
# 08 - Common problems & bad data situations <a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons Licence" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" title='This work is licensed under a Creative Commons Attribution 4.0 International License....
github_jupyter
## Define the Convolutional Neural Network After you've looked at the data you're working with and, in this case, know the shapes of the images and of the keypoints, you are ready to define a convolutional neural network that can *learn* from this data. In this notebook and in `models.py`, you will: 1. Define a CNN w...
github_jupyter
``` import tensorflow as tf import tensorflow as tf from tensorflow.python.keras.applications.vgg19 import VGG19 model=VGG19( include_top=False, weights='imagenet' ) model.trainable=False model.summary() from tensorflow.python.keras.preprocessing.image import load_img, img_to_array from tensorflow.python.keras....
github_jupyter
``` from sklearn import datasets wine = datasets.load_wine() print(wine.DESCR) print('Features: ', wine.feature_names) print('Labels: ', wine.target_names) #wine=wine.sample(frac=1) data = wine.data target = wine.target from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_s...
github_jupyter
``` %reload_ext watermark %matplotlib inline from os.path import exists from metapool.metapool import * from metapool import (validate_plate_metadata, assign_emp_index, make_sample_sheet, KLSampleSheet, parse_prep, validate_and_scrub_sample_sheet, generate_qiita_prep_file) %watermark -i -v -iv -m -h -p metapool,sample...
github_jupyter
<p align="center"> <h1 align="center">Machine Learning and Statistics Tasks 2020</h1> <h1 align="center"> Task 1: Python function sqrt2</h1> <h2 align="center"> Author: Ezekiel Onaloye</h2> <h2 align="center"> Created: November 2020 </h2> </p> ![squareroot](img/sqrt2.jpg) ### Task 1 Write a Python fu...
github_jupyter
``` %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline from tqdm.autonotebook import tqdm from joblib import Parallel, delayed import umap import pandas as pd from avgn.utils.paths import DATA_DIR, most_recent_subdirectory, ensure_dir DATASET_ID = 'swamp_sparrow' fr...
github_jupyter
<img src="../../images/banners/python-basics.png" width="600"/> # <img src="../../images/logos/python.png" width="23"/> Conda Environments ## <img src="../../images/logos/toc.png" width="20"/> Table of Contents * [Understanding Conda Environments](#understanding_conda_environments) * [Understanding Basic Package Man...
github_jupyter
# Configuraciones para el Grupo de Estudio <img src="./img/f_mail.png" style="width: 700px;"/> ## Contenidos - ¿Por qué jupyter notebooks? - Bash - ¿Que es un *kernel*? - Instalación - Deberes ## Python y proyecto Jupyter <img src="./img/py.jpg" style="width: 500px;"/> <img src="./img/jp.png" style="width: 100px;"/...
github_jupyter
# Generación de observaciones aleatorias a partir de una distribución de probabilidad La primera etapa de la simulación es la **generación de números aleatorios**. Los números aleatorios sirven como el bloque de construcción de la simulación. La segunda etapa de la simulación es la **generación de variables aleatorias...
github_jupyter
# MHKiT Quality Control Module The following example runs a simple quality control analysis on wave elevation data using the [MHKiT QC module](https://mhkit-software.github.io/MHKiT/mhkit-python/api.qc.html). The data file used in this example is stored in the [\\\\MHKiT\\\\examples\\\\data](https://github.com/MHKiT-S...
github_jupyter
``` import numpy as np import pandas as pd import scipy as sp from scipy.stats import mode from sklearn import linear_model import matplotlib import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn import preprocessing import sklearn as sk import sklearn.discriminant_analysis as da import skl...
github_jupyter
``` import random import copy import os import time import numpy as np import matplotlib.pyplot as plt import warnings # warnings.filterwarnings("ignore") %matplotlib inline class Dataset: def __init__(self,X,y,proportion=0.8,shuffle=True, mini_batch=0): """ Dataset class provide tools to manage dat...
github_jupyter
``` import tushare as ts import sina_data import numpy as np import pandas as pd from pandas import DataFrame, Series from datetime import datetime, timedelta from dateutil.parser import parse import time import common_util import os def get_time(date=False, utc=False, msl=3): if date: time_fmt = "%Y-%m-%d ...
github_jupyter
``` %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] = (10, 6) import numpy as np from numpy.lib import stride_tricks import cv2 from matplotlib.colors import hsv_to_rgb import matplotlib.pyplot as plt import numpy as np np.set_printoptions(precision=3) class PatchMatch(object): def __init__(self, ...
github_jupyter
``` # -*- coding: utf-8 -*- # เรียกใช้งานโมดูล file_name="data" import codecs from tqdm import tqdm from pythainlp.tokenize import word_tokenize #import deepcut from pythainlp.tag import pos_tag from nltk.tokenize import RegexpTokenizer import glob import nltk import re # thai cut thaicut="newmm" from sklearn_crfsuite ...
github_jupyter
# Introduction This notebook can be used to both train a discriminator on the AG news dataset and steering text generation in the direction of each of the four classes of this dataset, namely world, sports, business and sci/tech. My code uses and builds on a text generation plug-and-play model developed by the Ube...
github_jupyter
``` %run ../Python_files/util_data_storage_and_load.py %run ../Python_files/load_dicts.py %run ../Python_files/util.py import numpy as np from numpy.linalg import inv # load link flow data import json with open('../temp_files/link_day_minute_Apr_dict_JSON_adjusted.json', 'r') as json_file: link_day_minute_Apr_dic...
github_jupyter
<a href="https://colab.research.google.com/github/sapinspys/DS-Unit-2-Regression-Classification/blob/master/DS7_Sprint_Challenge_5_Regression_Classification.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_ # Reg...
github_jupyter
``` import cv2 import numpy as np import matplotlib.pyplot as plt import glob import pandas as pd import os def imshow(img): img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) plt.imshow(img) def get_lane_mask(sample,lane_idx): points_lane = [] h_max = np.max(data['h_samples'][sample]) h_min = np.min(data['h...
github_jupyter
# Navigation --- In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). ### 1. Start the Environment We begin by importing some necessary packages...
github_jupyter
# Data Download - *read description before running* Term project for ESS 490/590 Grad: Erik Fredrickson Undergrad: Ashika Capirala *This notebook demonstrates how the open access datasets can be downloaded, but these data are provided at significantly higher temporal resolution than needed for the purposes of our s...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import keras from keras.models import Sequential from keras.layers import Dense, Dropout, ReLU, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.losses import categorical_cro...
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@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 ...
github_jupyter
# Character level language model - Dinosaurus Island Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to ...
github_jupyter
``` import cv2 as cv import matplotlib.pyplot as plt import numpy as np import argparse net = cv.dnn.readNetFromTensorflow("graph_opt.pb") inWidth = 368 inHeight = 368 thr = 0.2 BODY_PARTS = { "Nose": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4, "LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip"...
github_jupyter
## Moodle Database: Educational Data Log Analysis The Moodle LMS is a free and open-source learning management system written in PHP and distributed under the GNU General Public License. It is used for blended learning, distance education, flipped classroom and other e-learning projects in schools, universities, work...
github_jupyter
# Format DataFrame ``` import pandas as pd from sklearn.datasets import make_regression data = make_regression(n_samples=600, n_features=50, noise=0.1, random_state=42) train_df = pd.DataFrame(data[0], columns=["x_{}".format(_) for _ in range(data[0].shape[1])]) train_df["target"] = data[1] print(train_df.shape) tra...
github_jupyter
# Durables vs Non Durables At Low And High Frequencies ``` !pip install numpy !pip install matplotlib !pip install pandas !pip install pandas_datareader !pip install datetime !pip install seaborn # Some initial setup from matplotlib import pyplot as plt import numpy as np plt.style.use('seaborn-darkgrid') import pan...
github_jupyter
[source](../../api/alibi_detect.od.isolationforest.rst) # Isolation Forest ## Overview [Isolation forests](https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf) (IF) are tree based models specifically used for outlier detection. The IF isolates observations by randomly selecting a feature and then rando...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') import warnings warnings.filterwarnings('ignore') # !pip install tensorflow_text !pip install transformers emoji # !pip install ktrain from transformers import AutoTokenizer import pandas as pd dataset = pd.read_excel("/content/drive/MyDrive/English Cate...
github_jupyter
# Self-Driving Car Engineer Nanodegree ## Project: **Finding Lane Lines on the Road** *** In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really j...
github_jupyter
# Classification models using python and scikit-learn There are many users of online trading platforms and these companies would like to run analytics on and predict churn based on user activity on the platform. Keeping customers happy so they do not move their investments elsewhere is key to maintaining profitability...
github_jupyter
``` from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd with Browser("chrome") as browser: # Visit URL url = "https://mars.nasa.gov/news/" browser.visit(url) browser.fill('search', 'splinter - python acceptance testing for web applications') # Find and click the 'sea...
github_jupyter
<small><small><i> Introduction to Python - available from https://gitlab.erc.monash.edu.au/andrease/Python4Maths.git The original version was written by Rajath Kumar and is available at https://github.com/rajathkumarmp/Python-Lectures. The notes have been updated for Python 3 and amended for use in Monash University m...
github_jupyter
# Overfitting demo ## Create a dataset based on a true sinusoidal relationship Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$: ``` import graphlab import math import random import numpy from matplotlib import pyplot as plt %matplotlib inline ``` Create random values ...
github_jupyter
# Gridworld ![gridworld](../pictures/gridworld.png) The Gridworld environment (inspired from Sutton and Barto, Reinforcement Learning: an Introduction) is represented in figure. The environment is a finite MDP in which states are represented by grid cells. The available actions are 4: left, right, up, down. Actions m...
github_jupyter