code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
```
from scipy.spatial import distance as dist
import numpy as np
import cv2
from imutils import face_utils
from imutils.video import VideoStream
import imutils
from fastai.vision import *
import argparse
import time
import dlib
from playsound import playsound
from torch.serialization import SourceChangeWarning
warning... | github_jupyter |
## The QLBS model for a European option
Welcome to your 2nd assignment in Reinforcement Learning in Finance. In this exercise you will arrive to an option price and the hedging portfolio via standard toolkit of Dynamic Pogramming (DP).
QLBS model learns both the optimal option price and optimal hedge directly from tra... | github_jupyter |
```
import copy
import random
import numpy as np
import pandas as pd
import torch
from scipy import stats
from torch import nn
from torchtext.legacy import data
from torchtext.vocab import Vectors
from tqdm import tqdm
from util import calc_accuracy, calc_f1, init_device, load_params
from util.model import MyClassifi... | github_jupyter |
### Installation
`devtools::install_github("zji90/SCRATdatahg19")`
`source("https://raw.githubusercontent.com/zji90/SCRATdata/master/installcode.R")`
### Import packages
```
library(devtools)
library(GenomicAlignments)
library(Rsamtools)
library(SCRATdatahg19)
library(SCRAT)
```
### Obtain Feature Matrix
```
st... | github_jupyter |
# Copper grains classification based on thermal images
This demo shows construction and usage of a neural network that classifies
copper grains.
The grains are recorded with a thermal camera using active thermovision
approach.
The network is fed with numbers of low emissivity spots on every stage of
cooling down the g... | github_jupyter |
# Задание 2.1 - Нейронные сети
В этом задании вы реализуете и натренируете настоящую нейроную сеть своими руками!
В некотором смысле это будет расширением прошлого задания - нам нужно просто составить несколько линейных классификаторов вместе!
<img src="https://i.redd.it/n9fgba8b0qr01.png" alt="Stack_more_layers" wi... | github_jupyter |
# Project: Valuing real estate properties using machine learning
## Part 1: From EDA to data preparation
The objective of this project is to create a machine learning model that values real estate properties in Argentina.
For this we will use the dataset available at https://www.properati.com.ar.
This dataset contai... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import statistics
from scipy import stats
buldy_RGG_50_rep100_045 = pd.read_csv('Raw_data/Processed/proc_buldy_RGG_50_rep100_045.csv')
del buldy_RGG_50_rep100_045['Unnamed: 0']
buldy_RGG_50_rep100_045
buldy_RGG_50_rep100_067 = pd.read_csv('pro... | github_jupyter |
# Access Computation
This tutorial demonstrates how to compute access.
## Setup
```
import numpy as np
import pandas as pd
import plotly.graph_objs as go
from ostk.mathematics.objects import RealInterval
from ostk.physics.units import Length
from ostk.physics.units import Angle
from ostk.physics.time import Scale... | github_jupyter |
```
import tensorflow as tf
from tensorflow.keras import models
import numpy as np
import matplotlib.pyplot as plt
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
#creating a callback function that activates if the accuracy is greater than 60%
if(logs.get('accuracy... | github_jupyter |
```
import numpy as np
from sklearn.linear_model import LogisticRegression
import mlflow
import mlflow.sklearn
if __name__ == "__main__":
X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1, 0])
lr = LogisticRegression()
lr.fit(X, y)
score = lr.score(X, y)
print("Scor... | github_jupyter |
# TV Script Generation
In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will gen... | github_jupyter |
## Importing Libraries & getting Data
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
data = pd.read_csv("dataset/winequalityN.csv")
data.head()
data.info()
data.describe()
data.columns
columns = ['type', 'fix... | github_jupyter |
```
from fastai import *
from fastai.vision import *
from fastai.callbacks import *
from fastai.utils.mem import *
from fastai.vision.gan import *
from PIL import Image
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data.... | github_jupyter |
```
import xgboost as xgb
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("ggplot")
%matplotlib inline
from xgboost import XGBRegressor
from sklearn import preprocessing
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin
from sklearn.linear_model import Elast... | github_jupyter |
# Self-Driving Car Engineer Nanodegree
## Deep Learning
## Project: Build a Traffic Sign Recognition Classifier
In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included i... | 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 |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import numpy as np
import tensorflow as tf
import json
with open('dataset-bpe.json') as fopen:
data = json.load(fopen)
train_X = data['train_X']
train_Y = data['train_Y']
test_X = data['test_X']
test_Y = data['test_Y']
EOS = 2
GO = 1
vocab_size = 32000
train_Y ... | github_jupyter |
# Workshop 2: Regression and Neural Networks
https://github.com/Imperial-College-Data-Science-Society/workshops
1. Introduction to Data Science
2. **Regression and Neural Networks**
3. Classifying Character and Organ Images
4. Demystifying Causality and Causal Inference
5. A Primer to Data Engineering
6. Natural Lang... | github_jupyter |
```
%matplotlib widget
from pathlib import Path
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import svd
import imageio
from scipy import ndimage
import h5py
import stempy.io as stio
import stempy.image as stim
# Set up Cori paths
ncemhub = Path('/global/cfs... | github_jupyter |
```
# input
# pmid list: ../../data/ft_info/ft_id_lst.csv
# (ft json file) ../../data/raw_data/ft/
# (ft abs file) ../../data/raw_data/abs/
# result file at ../../data/raw_data/ft/T0 (all section)
# ../../data/raw_data/ft/T1 (no abs), etc
# setp 1 download full-text
import pandas as pd
import pickle
i... | github_jupyter |
```
from __future__ import print_function
import warnings
warnings.filterwarnings(action='ignore')
import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers... | github_jupyter |
# A Guided Tour of Ray Core: Multiprocessing Pool

© 2019-2022, Anyscale. All Rights Reserved
[*Distributed multiprocessing.Pool*](https://docs.ray.io/en/latest/multiprocessing.html) makes it easy to scale existing Python applications that use [`multiprocessing.P... | github_jupyter |
# <b>Blog project - Airbnb revenue maximization
## <b> What do I want to learn about the data
1. What is the main factor for high revenue?
2. Which neighbourhoods in Boston and Seattle are giving the most revenue and which ones the least?
3. Is it more lucrative to rent out a full apartment/house or individual rooms?... | github_jupyter |
# Graphical view of param sweep results (Figure 3A-C, G)
```
%matplotlib inline
from copy import deepcopy as copy
import json
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from disp import set_font_size, set_n_x_ticks, set_n_y_ticks
from replay import analysis
cc = np.concatenate
... | github_jupyter |
##### Copyright 2019 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 |
# Interpreting Neural Network Weights
Neural nets (especially deep neural nets) are some of the most powerful machine learning algorithms available. However, it can be difficult to understand (intuitively) how they work.
In the first part of this notebook, I highlight the connection between neural networks and tem... | github_jupyter |
# Qcodes example with Alazar ATS 9360
```
# import all necessary things
%matplotlib nbagg
import qcodes as qc
import qcodes.instrument.parameter as parameter
import qcodes.instrument_drivers.AlazarTech.ATS9360 as ATSdriver
import qcodes.instrument_drivers.AlazarTech.ATS_acquisition_controllers as ats_contr
```
First... | github_jupyter |
# *tridesclous* example with olfactory bulb dataset
```
%matplotlib inline
import time
import numpy as np
import matplotlib.pyplot as plt
import tridesclous as tdc
from tridesclous import DataIO, CatalogueConstructor, Peeler
```
# DataIO = define datasource and working dir
trideclous provide some datasets than can... | github_jupyter |
[//]: #
<img src="idaes_icon.png" width="100">
<h1><center>Welcome to the IDAES Stakeholder Workshop</center></h1>
Welcome and thank you for taking the time to attend today's workshop. Today we will introduce you to the fundamentals of working with the IDAES process modeling toolset, and w... | 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 |
# Lazy Mode and Logging
So far, we have seen Ibis in interactive mode. Interactive mode (also known as eager mode) makes Ibis return the
results of an operation immediately.
In most cases, instead of using interactive mode, it makes more sense to use the default lazy mode.
In lazy mode, Ibis won't be executing the op... | github_jupyter |
## Mutual information
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import mutual_info_classif, mutual_info_regression
from sklearn.feature_selection import SelectKBest, SelectPercentile
```
## Read Data
... | github_jupyter |
# Plotting
In this notebook, I'll develop a function to plot subjects and their labels.
```
from astropy.coordinates import SkyCoord
import astropy.io.fits
import astropy.wcs
import h5py
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import numpy
import skimage.exposure
import sklearn.neighbors
impo... | github_jupyter |
# Particle Filtering for Sequential Bayesian Inference
## Introduction
In this notebook, we produce an implementation of the particle filtering methods discussed in the accompanying article. In particular, we introduce the *bearings-only tracking* problem, a nonlinear non-Gaussian sequential inference problem. Next, w... | github_jupyter |
# Single Beam
This notebook will run the ISR simulator with a set of data created from a function that makes test data. The results along with error bars are plotted below.
```
%matplotlib inline
import matplotlib.pyplot as plt
import os,inspect
from SimISR import Path
import scipy as sp
from SimISR.utilFunctions impo... | github_jupyter |
## Monte Carlo on policy evaluation
Monte Carlo on policy evaluation is an important model free policy evaluation algorithm which uses the popular computational method called the Monte Carlo method.
It is important since it is usually the first model free algorithm studied in reinforcement learning.
Model free algorit... | github_jupyter |
# Monte Carlo Simulation
Today, we will work with the Lennard Jones equation.
$$ U(r) = 4 \epsilon \left[\left(\frac{\sigma}{r}\right)^{12} -\left(\frac{\sigma}{r}\right)^{6} \right] $$
Reduced Units:
$$ U^*\left(r_{ij} \right) = 4 \left[\left(\frac{1}{r^*_{ij}}\right)^{12} -\left(\frac{1}{r^*_{ij}}\right)^{6} \r... | github_jupyter |
```
try:
import tinygp
except ImportError:
%pip install -q tinygp
try:
import jaxopt
except ImportError:
%pip install -q jaxopt
```
(mixture)=
# Mixture of Kernels
It can be useful to model a dataset using a mixture of GPs.
For example, the data might have both systematic effects and a physical sign... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
from xentropy import dihedrals
from astropy import units as au
```
# single Gaussian distro
## create artificial data
```
data= np.random.randn(100000)*30
```
## perform kde
```
dih_ent = dihedrals.dihedralEntropy(data=data,verbose=True)
dih_ent.calculate()
``... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.ticker as ticker
import seaborn as sns
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics im... | github_jupyter |
##### Copyright 2018 The TF-Agents 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 a... | github_jupyter |
```
"""
This notebook contains codes to run hyper-parameter tuning using a genetic algorithm.
Use another notebook if you wish to use *grid search* instead.
# Under development.
"""
import os, sys
import numpy as np
import pandas as pd
import tensorflow as tf
import sklearn
from sklearn.model_selection import train_tes... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Demo-of-RISE-for-slides-with-Jupyter-notebooks-(Python)" data-toc-modified-id="Demo-of-RISE-for-slides-with-Jupyter-notebooks-(Python)-1"><span class="toc-item-num">1 </span>Demo of RISE for slid... | github_jupyter |
```
import numpy as np
import pickle
import time
from src.data.make_dataset import generate_dataset
from src.models.train_model import BO_loop, grid_search, dist_loop
from src.models.acquisition import Random, MaxVariance
from functools import partial
# run trig basis tests
iters = 5
rng = np.random.default_rng(seed ... | github_jupyter |
# Unit conversion for the valve coefficient
## Friction losses in energy balance
The contribution of friction losses is considered as a head loss in the enrgy balance.
EB   $0~m=\frac{\Delta p}{\rho g}+\Delta z+\frac{\Delta w^2}{2 g}+\Delta H_{v}+\frac{\dot Q}{\rho g \dot V}+\frac{C_v\Delta T}{g}+\frac{-\dot W_... | github_jupyter |
ERROR: type should be string, got "https://towardsdatascience.com/a-production-ready-multi-class-text-classifier-96490408757\n\n```\nimport os\nimport re\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.multiclass import OneVsRestClassifier\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\ndata_path = 'data'\n\nrows = []\nfor root, _, file in os.walk(data_path):\n for filename in file:\n if '.txt' in filename:\n cuisine = os.path.splitext(filename)[0]\n text_file = open(os.path.join(data_path, filename), \"r\")\n lines = text_file.readlines()\n for line in lines:\n row = {\n 'cuisine': cuisine,\n 'ingredients': line\n }\n rows.append(row)\n text_file.close()\n\ndf = pd.DataFrame.from_dict(rows)\ndf = df.sample(frac=1).reset_index(drop=True)\ndf.head()\ndf.shape\ndf.groupby('cuisine').count()\n#pre-processing\nimport re \ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for dataset\n Every dataset is lower cased except\n \"\"\"\n string = re.sub(r\"\\n\", \"\", string) \n string = re.sub(r\"\\r\", \"\", string) \n string = re.sub(r\"[0-9]\", \"digit\", string)\n string = re.sub(r\"\\'\", \"\", string) \n string = re.sub(r\"\\\"\", \"\", string) \n return string.strip().lower()\nX = []\nfor i in range(df.shape[0]):\n X.append(clean_str(df.iloc[i][1]))\ny = np.array(df[\"cuisine\"])\ny.size\n#train test split\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5)\n#pipeline of feature engineering and model\n\nmodel = Pipeline([\n ('vectorizer', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', OneVsRestClassifier(LinearSVC(class_weight=\"balanced\")))\n])\n#the class_weight=\"balanced\" option tries to remove the biasedness of model towards majority sample\n#parameter selection\nfrom sklearn.model_selection import GridSearchCV\nparameters = {'vectorizer__ngram_range': [(1, 1), (1, 2),(2,2)],\n 'tfidf__use_idf': (True, False)}\ngs_clf_svm = GridSearchCV(model, parameters, n_jobs=-1)\ngs_clf_svm = gs_clf_svm.fit(X, y)\nprint(gs_clf_svm.best_score_)\nprint(gs_clf_svm.best_params_)\n#preparing the final pipeline using the selected parameters\nmodel = Pipeline([('vectorizer', CountVectorizer(ngram_range=(1,2))),\n ('tfidf', TfidfTransformer(use_idf=True)),\n ('clf', OneVsRestClassifier(LinearSVC(class_weight=\"balanced\")))])\n#fit model with training data\nmodel.fit(X_train, y_train)\n#evaluation on test data\npred = model.predict(X_test)\nmodel.classes_\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nconfusion_matrix(pred, y_test)\naccuracy_score(y_test, pred)\n#save the model\nfrom sklearn.externals import joblib\njoblib.dump(model, 'model_cuisine_ingredients.pkl', compress=1)\nfrom sklearn.externals import joblib\nmodel = joblib.load('model_cuisine_ingredients.pkl')\ntest_recipe = \"1 2 1/2 to 3 pound boneless pork shoulder or butt, trimmed and cut in half 1 small butternut squash (about 1 1/2 pounds)—peeled, seeded, and cut into 1 inch pieces 1 14.5 ounce can diced tomatoes 1 jalapeño pepper, seeded and chopped 2 cloves garlic, chopped 1 tablespoon chili powder kosher salt 4 6 inch corn tortillas, cut into 1/2 inch wide strips 1 tablespoon canola oil sliced radishes, cilantro sprigs, and lime wedges, for serving\"\nmodel.predict([test_recipe])[0]\nsteak_hache = \"1 tbsp vegetable oil 4 shallots , very finely chopped 600g freshly ground beef (ask the butcher for something with roughly 15% fat - we used chuck) 8 thyme sprigs, leaves picked and chopped 2 tsp Dijon mustard 2 tbsp plain flour 200ml crème fraîche 1 egg yolk 6 tarragon sprigs, leaves picked and finely chopped dressed green salad, to serve\"\nmodel.predict([steak_hache])[0]\ntoad_in_the_hole = \"140g plain flour 3 eggs 300ml milk 2 tsp Dijon mustard 2 tbsp vegetable oil 8 Cumberland sausages 8 sage leaves 4 rosemary sprigs\"\nmodel.predict([toad_in_the_hole])[0]\n```\n\n" | github_jupyter |
# Problem statement
We have data from a Portuguese bank on details of customers related to selling a term deposit
The objective of the project is to help the marketing team identify potential customers who are relatively more likely to subscribe to the term deposit and this increase the hit ratio
# Data dictionary
*... | github_jupyter |
```
import pickle
import math
from nltk import word_tokenize
from nltk.translate.bleu_score import modified_precision, closest_ref_length, brevity_penalty, SmoothingFunction, sentence_bleu
from collections import Counter
from fractions import Fraction
from modules.sentence import tokenizer, read, detokenize
from mo... | github_jupyter |
# EDA
```
%load_ext autoreload
%autoreload 2
import sys
sys.path.append("../src")
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import scipy
from collections import Counter
```
## Data Preparation
```
ds_links = pd.read_csv("../ml-latest-small/links.csv")
ds_movies = pd... | github_jupyter |
# Composipy for strength analysis of a laminate
In this exemple we will use the exercise 6-7 from *Analysis and Performance of Fiber Composites by B. Agarwal* pg. 244.
```
from composipy import Ply, Laminate, Load, Strength
```
Fist, lets consider the following laminate
$[45_{ply1}/0_{ply2}/45_{ply1}]$
Where $ply_... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import time
import os
import copy
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
... | github_jupyter |
# <font color='cyan'>AI Chatbot Test</font>
```
import nltk
import numpy as np
import random
import string # process standard python strings
```
### Read the raw txt file
```
f = open('chatbot.txt', 'r', errors = 'ignore')
raw = f.read()
raw = raw.lower()
# 1st time use only
# nltk.download('punkt')
# nltk.download(... | github_jupyter |
```
import os
import matplotlib.pyplot as plt
import numpy as np
import qiskit.ignis.mitigation.measurement as mc
from dotenv import load_dotenv
from numpy import pi
from qiskit import (IBMQ, Aer, ClassicalRegister, QuantumCircuit,
QuantumRegister, transpile)
from qiskit.ignis.verification... | github_jupyter |
```
# If you run on colab uncomment the following line
#!pip install git+https://github.com/clementchadebec/benchmark_VAE.git
import torch
import torchvision.datasets as datasets
%load_ext autoreload
%autoreload 2
mnist_trainset = datasets.MNIST(root='../../data', train=True, download=True, transform=None)
train_data... | github_jupyter |
# **PointRend - Image Segmentation as Rendering**
**Authors: Alexander Kirillov, Yuxin Wu, Kaiming H,e Ross Girshick - Facebook AI Research (FAIR)**
**Official Github**: https://github.com/facebookresearch/detectron2/tree/main/projects/PointRend
---
**Edited By Su Hyung Choi (Key Summary & Code Practice)**
If you ... | github_jupyter |
<div style='background-image: url("share/baku.jpg") ; padding: 0px ; background-size: cover ; border-radius: 15px ; height: 250px; background-position: 0% 80%'>
<div style="float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.9) ; width: 50% ; height: 150px">
<div style="positi... | github_jupyter |
# Simple Analysis with Pandas and Numpy
***ABSTRACT***
* If a donor gives aid for a project that the recipient government would have undertaken anyway, then the aid is financing some expenditure other than the intended project. The notion that aid in this sense may be "fungible," while long recognized, has recently be... | github_jupyter |
# Word vectors (FastText) for Baseline
#### Create Spacy model from word vectors
```bash
python -m spacy init-model en output/cord19_docrel/spacy/en_cord19_fasttext_300d --vectors-loc output/cord19_docrel/cord19.fasttext.w2v.txt
python -m spacy init-model en output/acl_docrel/spacy/en_acl_fasttext_300d --vectors-loc ... | github_jupyter |
# workbook C: lists and strings
This activity builds on the Python you have become familiar with in
* *Chapter 2 Python Lists*
* *Chapter 3 Functions and packages*
from the
[DataCamp online course *Intro to Python for Data Science*](https://www.datacamp.com/courses/intro-to-python-for-data-science). Here we will lo... | github_jupyter |
# 2.3 KL divergence and cross-entropy
```
from IPython.display import IFrame
IFrame(src="https://cdnapisec.kaltura.com/p/2356971/sp/235697100/embedIframeJs/uiconf_id/41416911/partner_id/2356971?iframeembed=true&playerId=kaltura_player&entry_id=1_1x5pta90&flashvars[streamerType]=auto&flashvars[localizationCode]=en... | github_jupyter |
```
!pip install tf-nightly-2.0-preview
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(Fals... | github_jupyter |
<table>
<tr><td align="right" style="background-color:#ffffff;">
<img src="../images/logo.jpg" width="20%" align="right">
</td></tr>
<tr><td align="right" style="color:#777777;background-color:#ffffff;font-size:12px;">
Abuzer Yakaryilmaz | April 30, 2019 (updated)
</td></tr>
<tr><td... | github_jupyter |
# Classification of UK Charities
In this notebook, data from several sources has been used to classify UK charities
```
from google.colab import drive
drive.mount('/content/drive/')
import json
import pandas as pd
import networkx as nx
from numpy.core.numeric import NaN
with open('drive/My Drive/UK_Data/json/publicext... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
%matplotlib inline
isolados = pd.read_csv('data/01 - geral_normalizada.csv')
isolados.sample(5)
df = pd.read_csv('data/02 - reacoes_normalizada.csv', names=['Ano','CCR','Composto','Resultado'], header=None, index_col=0)
df... | github_jupyter |
```
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import *
from pyspark.sql.types import *
from pyspark.sql.functions import udf
from pyspark.sql.functions import *
from pyspark.sql.window import Window
NoneType = type(None)
import os
import socket
import hashlib
impo... | github_jupyter |
# GSD: Rpb1 orthologs in 1011 genomes collection
This collects Rpb1 gene and protein sequences from a collection of natural isolates of sequenced yeast genomes from [Peter et al 2017](https://www.ncbi.nlm.nih.gov/pubmed/29643504), and then estimates the count of the heptad repeats. It builds directly on the notebook [... | github_jupyter |
```
#pip install seaborn
```
# Import Libraries
```
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
```
# Read the CSV and Perform Basic Data Cleaning
```
# Raw dataset drop NA
df = pd.read_csv("../resources/train_predict.csv")
# Drop the null columns ... | github_jupyter |
## Dependencies
```
import glob
import numpy as np
import pandas as pd
from transformers import TFDistilBertModel
from tokenizers import BertWordPieceTokenizer
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Dropout, GlobalAveragePooling1D, Concatenat... | github_jupyter |
MNIST
Aproximate error rate BEFORE training is 90.7 %
Aproximate error rate during iteration 0 is 80.8 %
Aproximate error rate during iteration 100 is 6.6 %
Aproximate error rate during iteration 200 is 4.6 %
Aproximate error rate during iteration 300 is 3.4 %
Aproximate error rate during iteration 400 is 3.4 %
Aproxim... | github_jupyter |
# Art(ists)(work)
(Milestone 3 - Task 1: Address project feedback)
## Introduction
### Information About the Data
The data I am working on is from the Musuem of Modern Art (MoMA) and it consists of two datasets: Artists and Artworks.
Artists' columns are Artist ID, Name, Nationality, Gender, Birth Year, and Death Yea... | github_jupyter |
```
import astropy.coordinates as coord
import astropy.table as at
import astropy.units as u
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from scipy.spatial import cKDTree
from scipy.stats import binned_statistic
from scipy.interpolate import interp1d
# gala
import gal... | github_jupyter |
## Importing necessary library
```
import snscrape.modules.twitter as sntwitter
import pandas as pd
import itertools
import plotly.graph_objects as go
from datetime import datetime
```
## Creating a data frame called "df" for storing the data to be scraped. Here, "2019 Elections" was the search keyword"
```
df = pd... | github_jupyter |
# 머신 러닝 교과서 3판
# HalvingGridSearchCV
### 경고: 이 노트북은 사이킷런 0.24 이상에서 실행할 수 있습니다.
```
# 코랩에서 실행할 경우 최신 버전의 사이킷런을 설치합니다.
!pip install --upgrade scikit-learn
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
'machine-learning-databases'
'/breast-cancer-wisconsin/wdb... | github_jupyter |
# RadiusNeighborsRegressor with MinMaxScaler & Polynomial Features
**This Code template is for the regression analysis using a RadiusNeighbors Regression and the feature rescaling technique MinMaxScaler along with Polynomial Features as a feature transformation technique in a pipeline**
### Required Packages
```
imp... | github_jupyter |
# Read Washington Medicaid Fee Schedules
The Washington state Health Care Authority website for fee schedules is [here](http://www.hca.wa.gov/medicaid/rbrvs/Pages/index.aspx).
* Fee schedules come in Excel format
* Fee schedules are *usually* biannual (January and July)
* Publicly available fee schedules go back to J... | github_jupyter |
# Convolutional Neural Networks
---
In this notebook, we train a **CNN** to classify images from the CIFAR-10 database.
The images in this database are small color images that fall into one of ten classes; some example images are pictured below.
:
print('{:0.3e}'.format(number))
```
### Synapse Firings as FLOPS
The brain is a massive computational substrate that performs countless computations per second.
Many people have speculated a... | github_jupyter |
---
### Universidad de Costa Rica
#### IE0405 - Modelos Probabilísticos de Señales y Sistemas
---
# `Py4` - *Librerías de manipulación de datos*
> **Pandas**, en particular, es una útil librería de manipulación de datos que ofrece estructuras de datos para el análisis de tablas numéricas y series de tiempo. Esta es u... | github_jupyter |
```
import os
import sys
import numpy as np
import cv2
from data_loader import *
from fbs_config import TrainFBSConfig, InferenceFBSConfig
from fbs_dataset import FBSDataset
from mrcnn import model as modellib
from datahandler import DataHandler
from sklearn.metrics import f1_score
from scipy.ndimage import _ni_supp... | github_jupyter |
Lambda School Data Science
*Unit 2, Sprint 2, Module 3*
---
# Cross-Validation
## Assignment
- [ ] [Review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset.
- [ ] Continue to participate in our Kaggle challenge.
- [ ] Use scikit-learn for hyperparameter o... | github_jupyter |
<a name="top"></a>
<div style="width:1000 px">
<div style="float:right; width:98 px; height:98px;">
<img src="https://raw.githubusercontent.com/Unidata/MetPy/master/src/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;">
</div>
<h1>Intermediate NumPy</h1>
<h3>Unidata Python Workshop</h3... | github_jupyter |
```
def dig_pow(n, p):
# creating a placholder
length = len(str(n))
total=0
for digits in range(1,length):
a= n % (10**digits)
print(a)
total+= (a ** (p+length-digits))
print(total)
if total % n==0:
return total //n
else:
return -1
dig_pow... | github_jupyter |
<h1> 2c. Refactoring to add batching and feature-creation </h1>
In this notebook, we continue reading the same small dataset, but refactor our ML pipeline in two small, but significant, ways:
<ol>
<li> Refactor the input to read data in batches.
<li> Refactor the feature creation so that it is not one-to-one with inpu... | github_jupyter |
# Food Image Classifier
This part of the Manning Live project - https://liveproject.manning.com/project/210 . In synposis, By working on this project, I will be classying the food variety of 101 type. Dataset is already availble in public but we will be starting with subset of the classifier
## Dataset
As a general ... | github_jupyter |
```
import datetime
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from skimage import color, exposure
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,... | github_jupyter |
```
import torch
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import numpy as np
import pickle
from collections import namedtuple
from tqdm import tqdm
import torch
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
import torch.n... | github_jupyter |
<a href="https://colab.research.google.com/github/WittmannF/udemy-deep-learning-cnns/blob/main/assignment_cnn_preenchido.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## Assignment: Fashion MNIST
Now it is your turn! You are going to use the same ... | github_jupyter |
```
# Load library
import nltk
import os
from nltk import tokenize
from nltk.tokenize import sent_tokenize,word_tokenize
os.getcwd()
# Read the Data
raw=open("C:\\Users\\vivek\\Desktop\\NLP Python Practice\\Labeled Dateset.txt").read()
```
# Tokenize and make the Data into the Lower Case
```
# Change the Data in lo... | github_jupyter |
<img alt="Colaboratory logo" height="45px" src="https://colab.research.google.com/img/colab_favicon.ico" align="left" hspace="10px" vspace="0px">
<h1>Welcome to Colaboratory!</h1>
Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.
With Colaboratory you can writ... | github_jupyter |
# PyTorch
# Intro to Neural Networks
Lets use some simple models and try to match some simple problems
```
import numpy as np
import torch
import torch.nn as nn
from tensorboardX import SummaryWriter
import matplotlib.pyplot as plt
```
### Data Loading
Before we dive deep into the nerual net, lets take a brief as... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.5, 10, 0.001)
y1 = np.log(x)
y2 = 5 * np.sin(x) / x
plt.style.use('seaborn-darkgrid') # Define o fundo do gráfico
plt.figure(figsize=(8,5)) # Define o tamanho do gráfico
# Estipula os parametros das letras do titulo, eixo x e eixo y
plt.title('D... | github_jupyter |
<a href="https://colab.research.google.com/github/WuilsonEstacio/Procesamiento-de-lenguaje-natural/blob/main/codigo_para_abrir_y_contar_palabras_de_archivos.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# para leer un archivo
archivo = open('/... | github_jupyter |
```
import os
import sys
import glob
import numpy as np
from parse import load_ps
import matplotlib.pyplot as plt
def split_num(s):
head = s.rstrip('0123456789')
tail = s[len(head):]
return head, tail
def files_in_order(folderpath):
npy_files = os.listdir(folderpath)
no_extensions = [os.path.spli... | github_jupyter |
```
fuelNeeded = 42/1000
tank1 = 36/1000
tank2 = 6/1000
tank1 + tank2 >= fuelNeeded
from decimal import Decimal
fN = Decimal(fuelNeeded)
t1 = Decimal(tank1)
t2 = Decimal(tank2)
t1 + t2 >= fN
class Rational(object):
def __init__ (self, num, denom):
self.numerator = num
self.denominator = denom
... | github_jupyter |
# Week 7 worksheet: Spherically symmetric parabolic PDEs
This worksheet contains a number of exercises covering only the numerical aspects of the course. Some parts, however, still require you to solve the problem by hand, i.e. with pen and paper. The rest needs you to write pythob code. It should usually be obvious w... | github_jupyter |
---
_You are currently looking at **version 1.5** 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 2
In... | github_jupyter |
```
from pymongo import MongoClient
import pandas as pd
import datetime
# Open Database and find history data collection
client = MongoClient()
db = client.test_database
shdaily = db.indexdata
# KDJ calculation formula
def KDJCalculation(K1, D1, high, low, close):
# input last K1, D1, max value, min value and cur... | github_jupyter |
```
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
from keras.utils import to_categorical
from keras.datasets import mnist
import numpy as np
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.cm as cm
%matplotlib i... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.