code stringlengths 2.5k 6.36M | kind stringclasses 2
values | parsed_code stringlengths 0 404k | quality_prob float64 0 0.98 | learning_prob float64 0.03 1 |
|---|---|---|---|---|
```
import netCDF4 as nc
from matplotlib import pyplot as plt
import numpy as np
import glob
import pickle
from salishsea_tools import evaltools as et, places
import datetime as dt
import os
import re
import cmocean
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matpl... | github_jupyter | import netCDF4 as nc
from matplotlib import pyplot as plt
import numpy as np
import glob
import pickle
from salishsea_tools import evaltools as et, places
import datetime as dt
import os
import re
import cmocean
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matplotli... | 0.166608 | 0.367696 |
# The Problem
Research paper topic modeling is an unsupervised machine learning method that helps us discover hidden semantic structures in a paper, that allows us to learn topic representations of papers in a corpus. The model can be applied to any kinds of labels on documents, such as tags on posts on the website.
... | github_jupyter | import spacy
spacy.load('en')
from spacy.lang.en import English
parser = English()
def tokenize(text):
lda_tokens = []
tokens = parser(text)
for token in tokens:
if token.orth_.isspace():
continue
elif token.like_url:
lda_tokens.append('URL')
elif token.orth_... | 0.315525 | 0.929312 |
```
%pylab inline
from pyannote.core import notebook
```
# Timeline (`pyannote.core.timeline.Timeline`)
```
from pyannote.core import Timeline
```
**`Timeline`** instances are used to describe sets of temporal fragments (e.g. of an audio file).
One can optionally store an identifier of the associated multimedia do... | github_jupyter | %pylab inline
from pyannote.core import notebook
from pyannote.core import Timeline
timeline = Timeline(uri='MyAudioFile')
from pyannote.core import Segment
timeline.add(Segment(6, 8))
timeline.add(Segment(0.5, 3))
timeline.add(Segment(8.5, 10))
timeline.add(Segment(1, 4))
timeline.add(Segment(5, 7))
timeline.add(Se... | 0.365457 | 0.929696 |
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
class_df.columns
relevant_cols = ['Had you had sexual intercourse before starting university?', 'If you have used recreational drugs, which ones? (If you have not used drugs, indicate as such)']
drugs_v... | github_jupyter | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
class_df.columns
relevant_cols = ['Had you had sexual intercourse before starting university?', 'If you have used recreational drugs, which ones? (If you have not used drugs, indicate as such)']
drugs_virgi... | 0.261614 | 0.334318 |
# Log metrics with MLflow in PyTorch Lightning
description: log mlflow metrics in pytorch lightning with azureml as the backend tracking store
Lightning supports many popular [logging frameworks](https://pytorch-lightning.readthedocs.io/en/stable/loggers.html). [MLflow](https://mlflow.org/) is a popular open-source l... | github_jupyter | from azureml.core import Workspace
ws = Workspace.from_config()
ws
import git
from pathlib import Path
# get root of git repo
prefix = Path(git.Repo(".", search_parent_directories=True).working_tree_dir)
# training script
source_dir = prefix.joinpath(
"code", "train", "pytorch-lightning", "mnist-autoencoder"
)
s... | 0.414425 | 0.987104 |
# Interact Exercise 6
## Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
```
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
```
## Exploring th... | github_jupyter | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
Image('fermidist.png')
def fermidist(energy, mu, kT):
"""Compute the Fermi distribution at energy, mu and kT."""
F = 1/(np.exp((energy-mu)/kT)+1... | 0.694821 | 0.992489 |
Hal - hal yang harus diperhatikan
1. Tetha dan X sebagai vector
2. Feature scaling dan mean normalization dari data
3. Define feature baru dari feature2 yang sudah ada, bisa untuk polynomial regression
4. data x dan y bertipe np.array
5. matriks x ke samping training example, kebawah banyaknya feature
```
import numpy... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
set_matplotlib_formats("svg")
%matplotlib inline
import matplotlib
#matplotlib.style.use("dark_background")
matplotlib.style.use("default")
import scipy.optimize as optim
def normalize(x, mu, s) :
return (x - mu) /... | 0.503906 | 0.918809 |
```
import datajoint as dj
dj.config['database.host'] = 'datajoint.internationalbrainlab.org'
from ibl_pipeline import subject, acquisition, action, behavior, reference
from ibl_pipeline.analyses.behavior import PsychResults
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
myPath = r"C... | github_jupyter | import datajoint as dj
dj.config['database.host'] = 'datajoint.internationalbrainlab.org'
from ibl_pipeline import subject, acquisition, action, behavior, reference
from ibl_pipeline.analyses.behavior import PsychResults
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
myPath = r"C:\Us... | 0.46393 | 0.441914 |
<a href="https://colab.research.google.com/github/kdstheace/Project_FinancialAnalysis/blob/Daniel/Financial_analysis.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
impo... | github_jupyter | import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
import tensorflow as tf
import seaborn as sns
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.utils import to_categorical
from sklearn.preprocess... | 0.509276 | 0.873107 |
```
# Python library imports: numpy, random, sklearn, pandas, etc
import warnings
warnings.filterwarnings('ignore')
import sys
import random
import numpy as np
from sklearn import linear_model, cross_validation, metrics, svm
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_scor... | github_jupyter | # Python library imports: numpy, random, sklearn, pandas, etc
import warnings
warnings.filterwarnings('ignore')
import sys
import random
import numpy as np
from sklearn import linear_model, cross_validation, metrics, svm
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score
fr... | 0.293911 | 0.428652 |
Trying to determine where to impose a $M_{halo}$ cut based on either $M_{halo}$ or $M_{max}$ cuts
```
import numpy as np
# --- centralms ---
from centralMS import util as UT
from centralMS import catalog as Cat
import corner as DFM
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] ... | github_jupyter | import numpy as np
# --- centralms ---
from centralMS import util as UT
from centralMS import catalog as Cat
import corner as DFM
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['axes.linewidth'] = 1.5
mpl.rcParams['axes.xm... | 0.271445 | 0.738315 |
# Lab 05 : Final code -- demo
```
# For Google Colaboratory
import sys, os
if 'google.colab' in sys.modules:
# mount google drive
from google.colab import drive
drive.mount('/content/gdrive')
path_to_file = '/content/gdrive/My Drive/CS4243_codes/codes/labs_lecture05/lab05_final'
print(path_to_file)... | github_jupyter | # For Google Colaboratory
import sys, os
if 'google.colab' in sys.modules:
# mount google drive
from google.colab import drive
drive.mount('/content/gdrive')
path_to_file = '/content/gdrive/My Drive/CS4243_codes/codes/labs_lecture05/lab05_final'
print(path_to_file)
# move to Google Drive directo... | 0.682785 | 0.751443 |
```
try:
import cirq
from cirq_iqm import Adonis, circuit_from_qasm
from cirq_iqm.optimizers import simplify_circuit
except ImportError:
print('Installing missing dependencies...')
!pip install --quiet cirq cirq_iqm
from cirq_iqm import Adonis, circuit_from_qasm
from cirq_iqm.optimizers impo... | github_jupyter | try:
import cirq
from cirq_iqm import Adonis, circuit_from_qasm
from cirq_iqm.optimizers import simplify_circuit
except ImportError:
print('Installing missing dependencies...')
!pip install --quiet cirq cirq_iqm
from cirq_iqm import Adonis, circuit_from_qasm
from cirq_iqm.optimizers import s... | 0.38168 | 0.865622 |
<a href="https://colab.research.google.com/github/will-cotton4/DS-Unit-2-Sprint-4-Practicing-Understanding/blob/master/DS_Unit_2_Sprint_Challenge_4_Practicing_Understanding.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
_Lambda School Data Science ... | github_jupyter | import pandas as pd
train_url = 'https://drive.google.com/uc?export=download&id=13_tP9JpLcZHSPVpWcua4t2rY44K_s4H5'
test_url = 'https://drive.google.com/uc?export=download&id=1GkDHjsiGrzOXoF_xcYjdzBTSjOIi3g5a'
train = pd.read_csv(train_url)
test = pd.read_csv(test_url)
assert train.shape == (51916, 17)
assert test.... | 0.472927 | 0.917746 |
## CNN - tf.keras
```
import pandas as pd
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
stop_words = stopwords.words('english')
training_data = pd.read_csv('train.csv')
```
#### Combining the 3 columns ( keyword + location + text ) - ... | github_jupyter | import pandas as pd
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
stop_words = stopwords.words('english')
training_data = pd.read_csv('train.csv')
training_data['text'] = training_data['keyword'].fillna('') + training_data['location'].... | 0.615897 | 0.774796 |
```
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import minimize
```
### Definition of the model
```
# The SIR model differential equations.
def deriv(y, t, N, beta,gamma):
S,I,R = y
dSdt = -(beta*I/N)*S
dIdt = (beta*S/N)*I... | github_jupyter | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import minimize
# The SIR model differential equations.
def deriv(y, t, N, beta,gamma):
S,I,R = y
dSdt = -(beta*I/N)*S
dIdt = (beta*S/N)*I - gamma*I
dRdt = gamma*I
... | 0.343342 | 0.834238 |
```
import Ouzo_Graph_Tools as ouzo_graphs
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.colors as colors
import numpy as np
from scipy import interpolate, stats
def extract_plates(path, sheet_list):
"""Will return a sublist of plates absorbance information in datafr... | github_jupyter | import Ouzo_Graph_Tools as ouzo_graphs
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.colors as colors
import numpy as np
from scipy import interpolate, stats
def extract_plates(path, sheet_list):
"""Will return a sublist of plates absorbance information in dataframe ... | 0.629091 | 0.618377 |
```
from argotools.dataFormatter import Load
from argotools.visualize import InputVis
from argotools.visualize import OutputVis
from argotools.experiment import ARGO_lrmse
from argotools.forecastlib.argo_methods_ import *
from argotools.forecastlib.functions import *
from sklearn.linear_model import LassoCV
path_to_ili... | github_jupyter | from argotools.dataFormatter import Load
from argotools.visualize import InputVis
from argotools.visualize import OutputVis
from argotools.experiment import ARGO_lrmse
from argotools.forecastlib.argo_methods_ import *
from argotools.forecastlib.functions import *
from sklearn.linear_model import LassoCV
path_to_ili = '... | 0.487551 | 0.771801 |
# NearMiss
This procedures aims to select samples that are somewhat similar to the minority class, using 1 of three alternative procedures:
1) Select observations closer to the closest minority class
2) Select observations closer to the farthest minority class
3) Select observations furthest from their nearest neig... | github_jupyter | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from imblearn.under_sampling import NearMiss
de... | 0.727879 | 0.968768 |
```
import ROOT
import ostap.fixes.fixes
from ostap.core.core import cpp, Ostap
from ostap.core.core import pwd, cwd, ROOTCWD
from ostap.core.core import rootID, funcID, funID, fID, histoID, hID, dsID
from ostap.core.core import VE
from ostap.histos.histos import h1_axis, h2_axes, h3_axes
from ostap.histos.graphs impor... | github_jupyter | import ROOT
import ostap.fixes.fixes
from ostap.core.core import cpp, Ostap
from ostap.core.core import pwd, cwd, ROOTCWD
from ostap.core.core import rootID, funcID, funID, fID, histoID, hID, dsID
from ostap.core.core import VE
from ostap.histos.histos import h1_axis, h2_axes, h3_axes
from ostap.histos.graphs import ma... | 0.188399 | 0.283515 |
# Least squares problems
We sometimes wish to solve problems of the form
$$
\boldsymbol{A} \boldsymbol{x} = \boldsymbol{b}
$$
where $\boldsymbol{A}$ is a $m \times n$ matrix, where $m > n$. Clearly $\boldsymbol{A}$ is not square, and in general no solution to the problem exists. This is a typical of an over-determin... | github_jupyter | import numpy as np
N = 20
x_p = np.linspace(-np.pi, np.pi, N)
y_p = np.sin(x_p)
%matplotlib inline
import matplotlib.pyplot as plt
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Points on a sine graph')
plt.plot(x_p, y_p,'ro');
A = np.vander(x_p, N)
c = np.linalg.solve(A, y_p)
p = np.poly1d(c)
print(p)
# Create a... | 0.805747 | 0.996016 |
# MNIST Image Classification with TensorFlow
This notebook demonstrates how to implement different image models on MNIST using the [tf.keras API](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras).
## Learning Objectives
1. Understand how to build a Dense Neural Network (DNN) for image classification
... | github_jupyter | !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
from datetime import datetime
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.layers imp... | 0.623606 | 0.981058 |
```
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
```
Training and Testing Data
=====================================
To evaluate how well our supervised models generalize, we can split our data into a training and a test set:
<img src="figures/train_test_split_matrix.svg" width="100%">
```
... | github_jupyter | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
y
from sklearn.model_selection import train_test_split
train_X, test_X, train_y, test_y = train_test_split(X, y,
... | 0.654784 | 0.990006 |
# Putting It All Together: A Realistic Example
In this section we're going to work through a realistic example of a deep learning workflow. We'll be working with a smallish dataset featuring different kinds of flowers from Kaggle. We're going to apply data augmentation to synthetically expand the size of our dataset. ... | github_jupyter | # All of this should look familiar from previous notebooks:
import matplotlib.pyplot as plt
import numpy as np
import os
from PIL import Image, ImageOps
from keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input
from keras.layers import Dense, GlobalAveragePooling2D, Dropout
from keras.models import Mod... | 0.755907 | 0.962603 |
# Temporal-Difference Methods
In this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.
While we have provided some starter code, you are welcome to erase these hints and write your code from scratch.
---
### Part 0: Explore CliffWalkingEnv
We begin by importing the necess... | github_jupyter | import sys
import gym
import numpy as np
import random
import math
from collections import defaultdict, deque
import matplotlib.pyplot as plt
%matplotlib inline
import check_test
from plot_utils import plot_values
env = gym.make('CliffWalking-v0')
[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, ... | 0.522446 | 0.960878 |
# 1. Descarga Pubmed
### Hacemos una consulta por cada especialidad para obtener los IDs de los documentos de PubMed
```
import os
from Bio import Entrez
from urllib.request import urlopen
path_file_queries = 'total_queries.txt'
path_files_xmls = 'specialties_subespecialties_xml'
path_casesreports_xml = 'specialties_s... | github_jupyter | import os
from Bio import Entrez
from urllib.request import urlopen
path_file_queries = 'total_queries.txt'
path_files_xmls = 'specialties_subespecialties_xml'
path_casesreports_xml = 'specialties_subespecialties_case_report_xml'
url_entrez = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=... | 0.115836 | 0.44903 |
```
%matplotlib inline
%reload_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
%reload_ext lab_black
```
## Number of Tetrodes Active >= 5
```
import logging
import string
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from src.figure_utilit... | github_jupyter | %matplotlib inline
%reload_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
%reload_ext lab_black
import logging
import string
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from src.figure_utilities import (
PAGE_HEIGHT,
ONE_COLUMN,
... | 0.399812 | 0.63375 |
# A History of NLP
The history of NLP can be broken down in many different ways. We will be taking a look at the long-term history and the *approach* that researchers have taken through the decades. There are three *eras* of NLP that we can consider, which correlate with the trends in Machine Learning as a whole.
## ... | github_jupyter | IF 'happy' IN SENTENCE
SENTIMENT IS POSITIVE
IF 'sad' IN SENTENCE
SENTIMENT IS NEGATIVE | 0.351311 | 0.987711 |
```
# !wget https://raw.githubusercontent.com/synalp/NER/master/corpus/CoNLL-2003/eng.train
# !wget https://raw.githubusercontent.com/synalp/NER/master/corpus/CoNLL-2003/eng.testa
def parse(file):
with open(file) as fopen:
texts = fopen.read().split('\n')
left, right = [], []
for text in texts:
... | github_jupyter | # !wget https://raw.githubusercontent.com/synalp/NER/master/corpus/CoNLL-2003/eng.train
# !wget https://raw.githubusercontent.com/synalp/NER/master/corpus/CoNLL-2003/eng.testa
def parse(file):
with open(file) as fopen:
texts = fopen.read().split('\n')
left, right = [], []
for text in texts:
... | 0.486819 | 0.374705 |
# Machine Learning Engineer Nanodegree
## Unsupervised Learning
## Project: Creating Customer Segments
Welcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality nece... | github_jupyter | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the wholesale custo... | 0.559771 | 0.994688 |
# "Hong Kong Elevation map with rayshader (with R)"
> Inspired by https://www.reddit.com/r/dataisbeautiful/comments/bjp8bg/the_united_states_of_elevation_oc/. This is my little weekend project, Hong Kong elevation tile with `rayshader`, powered by `fastpages` with Jupyter notebook! I haven't used R in years, so I spent... | github_jupyter | ## Library
library(rayshader)
library(sp)
library(raster)
library(scales)
library(dplyr)
elevation1 = raster::raster("../data/rayshader/HongKong/N21E113.hgt")
elevation2 = raster::raster("../data/rayshader/HongKong/N21E114.hgt")
elevation3 = raster::raster("../data/rayshader/HongKong/N22E113.hgt")
elevation4 = raster::... | 0.533397 | 0.802981 |
## Task 1
Вектор – это частный случай матрицы 1хN и Nх1. Повторите материал для векторов, уделяя особое внимание умножению A∙B.
Вычислите, по возможности не используя программирование: $(5Е)^{–1}$, где Е – единичная матрица размера 5х5
```
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
E =... | github_jupyter | import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
E = np.identity(5)
E
A = 5*E
A
#Определитель диагональной матрицы равен произведению элементов стоящих на главной диагонали
D = 5**5
D
A11 = 5**4
A11
A_1 = np.identity(5)*(A11/D)
A_1
np.dot(A_1, A)
A = np.matrix([[1, 2,3], [4,0,6],[7,8,9]])
A... | 0.301465 | 0.983847 |
```
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.models import Sequential
from keras.layers import Dense, LSTM, Conv1D, MaxPooling1D, Flatten, TimeDistributed, ConvLSTM2D, Reshape
import tensorflow as tf
import sklearn.metrics as sm
import keras
... | github_jupyter | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.models import Sequential
from keras.layers import Dense, LSTM, Conv1D, MaxPooling1D, Flatten, TimeDistributed, ConvLSTM2D, Reshape
import tensorflow as tf
import sklearn.metrics as sm
import keras
fro... | 0.753104 | 0.548613 |
```
# default_exp cloudsearch
```
# cloudsearch
> a library to trigger aws cloudsearch endpoint
```
#hide
from nbdev.showdoc import *
#export
import pandas as pd
from pprint import pprint
import boto3
#hide
import pickle, os
KEY = ''
PW = ''
keypath = '/Users/nic/.villa-search-2'
if KEY and PW:
with open (keypath,... | github_jupyter | # default_exp cloudsearch
#hide
from nbdev.showdoc import *
#export
import pandas as pd
from pprint import pprint
import boto3
#hide
import pickle, os
KEY = ''
PW = ''
keypath = '/Users/nic/.villa-search-2'
if KEY and PW:
with open (keypath, 'wb') as f:
pickle.dump({
'KEY': KEY,
'PW': PW
}, f... | 0.238018 | 0.352787 |
# Course set-up
```
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2020"
```
This notebook covers the steps you'll need to take to get set up for [CS224u](http://web.stanford.edu/class/cs224u/).
## Contents
1. [Anaconda](#Anaconda)
1. [The course Github repository](#The-course-Github-repos... | github_jupyter | __author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2020"
to create an environment called `nlu`.
Then, to enter the environment, run
To leave it, you can just close the window, or run
If your version of Anaconda is older than version 4.4 (see `conda --version`), then replace `conda` with `... | 0.623262 | 0.939637 |
<h2 style="color:#B22222">Ejercicios</h2>
1. Lea la documentación de la función ```find``` y pruébela con el siguiente texto
```python
"Una gran gran máquina"
```
¿cómo localizaría la posición del segundo ```gran```?
2. ¿Qué sucede al correr el siguiente programa: `"Una gran maquina".find()`?
3. Crea un programa que... | github_jupyter | "Una gran gran máquina"
"Una gran gran máquina".find('gran', "Una gran gran máquina".find('gran') + 1)
#Error
"Una gran maquina".find()
"MINÚSCULAS".lower()
cadena = "Python"
print(cadena[0:3])
print(cadena[2:])
print(cadena[1:4])
print(cadena[::2])
print(cadena[::-1])
print(cadena[0::2])
print(cadena[-1:-5:-1])
¿Cu... | 0.340376 | 0.948202 |
```
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
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
# Add a channels dimension
x_train = x_train[..., tf.new... | github_jupyter | import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
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
# Add a channels dimension
x_train = x_train[..., tf.newaxis... | 0.949658 | 0.787482 |
```
# autoreload nangs
%reload_ext autoreload
%autoreload 2
%matplotlib inline
```
# Basic use
We want to solve the following PDE:
\begin{equation}
\frac{\partial \phi}{\partial t} + u \frac{\partial \phi}{\partial x} = 0
\end{equation}
The independent variables (i.e, $x$ and $t$) are used as input values for t... | github_jupyter | # autoreload nangs
%reload_ext autoreload
%autoreload 2
%matplotlib inline
# imports
import numpy as np
import matplotlib.pyplot as plt
import nangs
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
nangs.__version__, torch.__version__
from nangs import PDE
class Adv1d(PDE):
def computePDE... | 0.562177 | 0.982774 |
# Table of contents
0. [Introduction](0-Introduction.ipynb)
1. [Variables](1-Variables.ipynb)
2. [Data structures](2-Data-Structures.ipynb)
3. [Conditional statements and loops](3-Conditional-Statements-Loops.ipynb)
4. [Some exercises](4-Some-Exercises.ipynb)
5. [Introduction to functions](5-0-Introduction-function.ipy... | github_jupyter | f'test_a{A[0]}_i{I[0]}_dt{dt}'
'test_a0.4_i0.15_dt0.001'
from Resources.UsefulFunctions import *
from Resources.Answers import answer, hint
# Carry over here the previously declared variables and the code from the previous exercises
mu_a = 2.8e-4
mu_i = 5e-3
tau = .1
k = -.005
size = 100
dx = dy = 2. / size
T = 9.0
... | 0.368747 | 0.979472 |
# Audio Alignment for Harmonix Set
This notebook tries to align purchased audio with original audio from Harmonix.
More specifically, for each pair of audio files:
- Load both audio files
- Compute chromagrams
- Use DTW to find the correct start and end points of alignment
- Produce the new aligned mp3s from the pur... | github_jupyter | from __future__ import print_function
import glob
import IPython
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import librosa
from librosa import display
from tqdm import tqdm_notebook as tqdm
# ORIG_MP3_PATH = "/Users/onieto/Desktop/Harmonix/audio/"
# PURC_MP3_PATH = "/Users/onieto... | 0.693992 | 0.675009 |
```
import tensorflow as tf
from utils import *
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('dataset', 'pubmed', 'Dataset string.') # 'cora', 'citeseer', 'pubmed'
flags.DEFINE_string('model', 'gcn', 'Model string.') # 'gcn', 'gcn_cheby', 'dense'
flags.DEFINE_float('learning_rate', 0.01, 'Initial lear... | github_jupyter | import tensorflow as tf
from utils import *
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('dataset', 'pubmed', 'Dataset string.') # 'cora', 'citeseer', 'pubmed'
flags.DEFINE_string('model', 'gcn', 'Model string.') # 'gcn', 'gcn_cheby', 'dense'
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning... | 0.701406 | 0.291364 |
```
#hide
import sys
path = '/home/ddpham/git/tabint/'
sys.path.insert(1, path)
#default_exp pre_processing
%load_ext autoreload
%autoreload 2
#hide
from nbdev.showdoc import *
#export
from tabint.utils import *
from pandas.api.types import is_string_dtype, is_numeric_dtype
from sklearn.preprocessing import StandardSca... | github_jupyter | #hide
import sys
path = '/home/ddpham/git/tabint/'
sys.path.insert(1, path)
#default_exp pre_processing
%load_ext autoreload
%autoreload 2
#hide
from nbdev.showdoc import *
#export
from tabint.utils import *
from pandas.api.types import is_string_dtype, is_numeric_dtype
from sklearn.preprocessing import StandardScaler
... | 0.263031 | 0.333842 |
<!-- dom:TITLE: Data Analysis and Machine Learning Lectures: Optimization and Gradient Methods -->
# Data Analysis and Machine Learning Lectures: Optimization and Gradient Methods
<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Su... | github_jupyter | %matplotlib inline
# Importing various packages
from random import random, seed
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import sys
x = 2*np.random.rand(100,1)
y = 4+3*x+np.rand... | 0.434461 | 0.989801 |
# System Design Primer
## Scalability Basics
### Vertical Scaling - upgrade machine to have more RAM, cores, disks, etc.
### Horizontal Scaling - getting more machines
In order to scale horizontally, we want to make sure we have the same codebase on all our servers. So how can we change code on all servers at once... | github_jupyter | # System Design Primer
## Scalability Basics
### Vertical Scaling - upgrade machine to have more RAM, cores, disks, etc.
### Horizontal Scaling - getting more machines
In order to scale horizontally, we want to make sure we have the same codebase on all our servers. So how can we change code on all servers at once... | 0.782746 | 0.852629 |
<h2 id="Modern-Portfolio-Theory">Modern Portfolio Theory<a class="anchor-link" href="#Modern-Portfolio-Theory">¶</a></h2>
<p>Modern portfolio theory also popularly called as <strong><code>Mean-Variance Portofolio Theory</code> (MVP)</strong> is a major breakthrough in finance. It is based on the premises that return... | github_jupyter | import pandas as pd
import xlwings as xw
import numpy as np
from numpy import *
from numpy.linalg import multi_dot
import matplotlib.pyplot as plt
from matplotlib.pyplot import rcParams
rcParams['figure.figsize'] = 16, 8
from openpyxl import Workbook, load_workbook
# FAANG stocks
symbols = ['AAPL', 'AMZN', 'FB', 'GO... | 0.745954 | 0.986218 |
# Happy 2017
We have some GPX files which we want to plot on a nice map.
A lot of the the code below is based on [this python4oceanographers blog post](https://ocefpaf.github.io/python4oceanographers/blog/2014/08/18/gpx/).
First we import some packages necessary to achieve what we want.
```
import matplotlib.pyplot a... | github_jupyter | import matplotlib.pyplot as plt
%matplotlib inline
import numpy
import gpxpy
import mplleaflet
import glob
import os
import pandas
plt.rcParams['figure.figsize'] = (16, 9) # Size up figures a bit
def load_run_data(gpx_path, filter=""):
gpx_files = glob.glob(os.path.join(gpx_path, filter + "*.gpx"))
run_data ... | 0.22431 | 0.858659 |
```
import copy
import datetime
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import bumps
import os
import math
from numpy import exp, linspace, random
from scipy.optimize import curve_fit
from scipy import stats
originpath = '../Documents/data'
path = originpath + '/conductivity... | github_jupyter | import copy
import datetime
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import bumps
import os
import math
from numpy import exp, linspace, random
from scipy.optimize import curve_fit
from scipy import stats
originpath = '../Documents/data'
path = originpath + '/conductivity'
""... | 0.253122 | 0.338924 |
<a href="https://colab.research.google.com/github/msmsd778/multiple-linear-regression/blob/main/Multiple_Linear_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Importing Needed packages
```
import numpy as np
import matplotlib.pyplot a... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
%matplotlib inline
!wget -O FuelConsumption.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv
df = pd.read_csv("Fu... | 0.403802 | 0.815967 |
# Neural Networks, gradient descent, and regression, no tears
In this notebook, we show how to use neural networks (NNs) with [PyTorch](https://pytorch.org/) to solve a linear regression problem using different gradient descent methods. The three gradient descent methods we will look at are
* batch gradient descent,
... | github_jupyter | %matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import torch
import torch.nn as nn
from torch import optim
from numpy.random import normal
from sklearn.metrics import r2_score
np.random.seed(37)
n = 1000
X = np.hstack([
np.ones(n).reshape(n, 1),
normal(2.0, 1.... | 0.918503 | 0.995448 |
```
import pandas as pd
import numpy as np
import logging
import sys
from datetime import datetime
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import scipy
import copy
from scipy.stats import skewnorm
from random import expovariate
# a little hacky, but works... | github_jupyter | import pandas as pd
import numpy as np
import logging
import sys
from datetime import datetime
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import scipy
import copy
from scipy.stats import skewnorm
from random import expovariate
# a little hacky, but works if ... | 0.369998 | 0.408955 |
```
import numpy as np
import matplotlib.pyplot as plt
import os
import pathlib
from zipfile import ZipFile
import PIL
import tensorflow as tf
train_dir = pathlib.Path("/Users/admin/Desktop/Fruit_classifier/fruits-360/Training")
test_dir = pathlib.Path("/Users/admin/Desktop/Fruit_classifier/fruits-360/Test")
image_co... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
import os
import pathlib
from zipfile import ZipFile
import PIL
import tensorflow as tf
train_dir = pathlib.Path("/Users/admin/Desktop/Fruit_classifier/fruits-360/Training")
test_dir = pathlib.Path("/Users/admin/Desktop/Fruit_classifier/fruits-360/Test")
image_count ... | 0.616474 | 0.412708 |
```
import numpy as np
import pandas as pd
import datetime as dtm
import matplotlib.pyplot as plt
import matplotlib.dates as dts
import netCDF4 as nc
import os
import re
import pytz
%matplotlib inline
```
# read in SOG data:
```
filename='/data/eolson/SOG/SOG-runs/SOGCompMZEff/profiles/hoff-SOG.dat'
file_obj = open(... | github_jupyter | import numpy as np
import pandas as pd
import datetime as dtm
import matplotlib.pyplot as plt
import matplotlib.dates as dts
import netCDF4 as nc
import os
import re
import pytz
%matplotlib inline
filename='/data/eolson/SOG/SOG-runs/SOGCompMZEff/profiles/hoff-SOG.dat'
file_obj = open(filename, 'rt')
for index, line i... | 0.058379 | 0.643889 |
## Chapter 12 - Bayesian Approaches to Testing a Point ("Null") Hypothesis
- [12.2.2 - Are different groups equal or not?](#12.2.2---Are-different-groups-equal-or-not?)
```
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwa... | github_jupyter | import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import theano.tensor as tt
from matplotlib import gridspec
%matplotlib inline
plt.style.use('seaborn-white')
color = '#87ceeb'
%loa... | 0.61832 | 0.927034 |
# Preprocess text
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
#export
from exp.nb_11a import *
```
## Data
We will use the IMDB dataset that consists of 50,000 labeled reviews of movies (positive or negative) and 50,000 unlabelled ones.
[Jump_to lesson 12 video](https://course19.fast.ai/videos/?lesso... | github_jupyter | %load_ext autoreload
%autoreload 2
%matplotlib inline
#export
from exp.nb_11a import *
path = untar_data(URLs.IMDB)
path.ls()
#export
def read_file(fn):
with open(fn, 'r', encoding = 'utf8') as f: return f.read()
class TextList(ItemList):
@classmethod
def from_files(cls, path, extensions='.txt', re... | 0.425009 | 0.878835 |
```
import keras
keras.__version__
```
# 5.2 - 소규모 데이터셋에서 컨브넷 사용하기
이 노트북은 [케라스 창시자에게 배우는 딥러닝](https://tensorflow.blog/%EC%BC%80%EB%9D%BC%EC%8A%A4-%EB%94%A5%EB%9F%AC%EB%8B%9D/) 책의 5장 2절의 코드 예제입니다. 책에는 더 많은 내용과 그림이 있습니다. 이 노트북에는 소스 코드에 관련된 설명만 포함합니다.
## 소규모 데이터셋에서 밑바닥부터 컨브넷을 훈련하기
매우 적은 데이터를 사용해 이미지 분류 모델을 훈련하는 일은 흔한 ... | github_jupyter | import keras
keras.__version__
import os, shutil
# 원본 데이터셋을 압축 해제한 디렉터리 경로
original_dataset_dir = './datasets/cats_and_dogs/train'
# 소규모 데이터셋을 저장할 디렉터리
base_dir = './datasets/cats_and_dogs_small'
if os.path.exists(base_dir): # 반복적인 실행을 위해 디렉토리를 삭제합니다.
shutil.rmtree(base_dir) # 이 코드는 책에 포함되어 있지 않습니다.
os.mkdir(b... | 0.36886 | 0.911653 |
# TensorFlow Semi-supervised Object Detection Architecture (TSODA)
Welcome to this project, I'll explain to you the necessary steps to run this application and train your own semi-supervised model.
If you forgot something, here is the original tutorial: https://medium.com/p/757b9c88f270/edit.
Also check the GitHub re... | github_jupyter | repo_url = 'https://github.com/AlvaroCavalcante/tf-models' # replace by your repo
MODEL = 'ssd_inception_v2_coco_2018_01_28' # replace by the model you want use
pipeline_file = 'ssd_inception_v2_coco.config'
# Model hyperparameters
num_steps = 2500
num_eval_steps = 50
batch_size = 16
import os
%cd /content
repo_d... | 0.337313 | 0.793106 |
```
import nltk
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np
#nltk.download_shell()
#messages = [line.rstrip() for line in open('SMSSpamCollection')]
messages = pd.read_csv("SMSSpamCollection", sep="\t", names=["label","message"])
messages.head()
messages.describe()
messag... | github_jupyter | import nltk
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np
#nltk.download_shell()
#messages = [line.rstrip() for line in open('SMSSpamCollection')]
messages = pd.read_csv("SMSSpamCollection", sep="\t", names=["label","message"])
messages.head()
messages.describe()
messages.g... | 0.459076 | 0.202089 |
# Optimal Ensemble Learning with the [`sl3`](https://jeremyrcoyle.github.io/sl3/) R package
## Author: [Nima Hejazi](https://nimahejazi.org)
## Date: 14 February 2018
### _Attribution:_ based on materials by David Benkeser, Jeremy Coyle, Ivana Malenica, and Oleg Sofrygin
## Introduction
In this demonstration, we w... | github_jupyter | set.seed(49753)
# packages we'll be using
library(data.table)
library(SuperLearner)
library(origami)
library(sl3)
# load example data set
data(cpp_imputed)
# take a peek at the data
head(cpp_imputed)
# here are the covariates we are interested in and, of course, the outcome
covars <- c("apgar1", "apgar5", "parity",... | 0.668339 | 0.994077 |
# ML-Agents Open a UnityEnvironment
<img src="https://github.com/Unity-Technologies/ml-agents/blob/release_18_docs/docs/images/image-banner.png?raw=true" align="middle" width="435"/>
## Setup
```
#@title Install Rendering Dependencies { display-mode: "form" }
#@markdown (You only need to run this code when using Cola... | github_jupyter | #@title Install Rendering Dependencies { display-mode: "form" }
#@markdown (You only need to run this code when using Colab's hosted runtime)
import os
from IPython.display import HTML, display
def progress(value, max=100):
return HTML("""
<progress
value='{value}'
max='{max}',
... | 0.374791 | 0.692486 |
Risk Off Strategy
=================
```
# If you would like to refresh your data, please execute the bellow codes.
import pandas as pd
import numpy as np
from datetime import datetime
from tqdm import tqdm
import matplotlib.pyplot as plt
from mypo import Loader
DOWNLOAD = False
if DOWNLOAD:
tickers = pd.read_c... | github_jupyter | # If you would like to refresh your data, please execute the bellow codes.
import pandas as pd
import numpy as np
from datetime import datetime
from tqdm import tqdm
import matplotlib.pyplot as plt
from mypo import Loader
DOWNLOAD = False
if DOWNLOAD:
tickers = pd.read_csv("/app/docs/tutorial/tickers.csv")
... | 0.514644 | 0.768255 |
```
from IPython.core.interactiveshell import InteractiveShell
import os
import sys
import time
from functools import partial
import pickle
import multiprocessing
import pixiedust as pxdb
import PIL
from matplotlib import pyplot as plt
import seaborn as sns
from collections import OrderedDict as ODict
import numpy as n... | github_jupyter | from IPython.core.interactiveshell import InteractiveShell
import os
import sys
import time
from functools import partial
import pickle
import multiprocessing
import pixiedust as pxdb
import PIL
from matplotlib import pyplot as plt
import seaborn as sns
from collections import OrderedDict as ODict
import numpy as np
im... | 0.591723 | 0.297993 |
## Numerical Differentiation
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
```
Applications:
1. Derivative difficult to compute analytically
2. Rate of change in a dataset
- You have position data but you want to know velocity
3. Finding extrema
- Important for fitting models to data (**... | github_jupyter | %matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
from IPython.display import Image
Image(url='http://wordlesstech.com/wp-content/uploads/2011/11/New-Map-of-the-Moon-2.jpg')
def forwardDifference(f, x, h):
"""
A first order differentiation technique.
Parameters
----------
f... | 0.879652 | 0.988602 |
## Basic ML Classification
This notebook is based on `Chapter 3 - Classification` of Hands-On ML, which uses the standard MNIST dataset
```
# common imports
import sys
import sklearn
import numpy as np
import os
import pandas as pd
from pathlib import Path
# Setting seed value
np.random.seed(42)
#figures
%matplotli... | github_jupyter | # common imports
import sys
import sklearn
import numpy as np
import os
import pandas as pd
from pathlib import Path
# Setting seed value
np.random.seed(42)
#figures
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
# Sets defaults/can also be imported from a style file
mpl.rc('axes', label... | 0.666171 | 0.951006 |
# Deploy and predict with Keras model on Cloud AI Platform.
**Learning Objectives**
1. Setup up the environment
1. Deploy trained Keras model to Cloud AI Platform
1. Online predict from model on Cloud AI Platform
1. Batch predict from model on Cloud AI Platform
## Introduction
**Verify that you have previously Tra... | github_jupyter | import os
%%bash
PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
# Change these to try this notebook out
PROJECT = "cloud-training-demos" # TODO 1: Replace with your PROJECT
BUCKET = PROJECT # defaults to PROJECT
REGION = "us-central1" # TODO 1:... | 0.108519 | 0.945801 |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.feature_selection import SelectFro... | github_jupyter | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.feature_selection import SelectFromMod... | 0.516352 | 0.463019 |
```
%matplotlib inline
%load_ext autoreload
%autoreload 2
import os
import sys
import copy
import warnings
import _pickle as pickle
from astropy.table import Table, Column, vstack, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from asap import io
from asap import s... | github_jupyter | %matplotlib inline
%load_ext autoreload
%autoreload 2
import os
import sys
import copy
import warnings
import _pickle as pickle
from astropy.table import Table, Column, vstack, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from asap import io
from asap import smf
... | 0.553023 | 0.576333 |
```
import numpy as np
# --- centralms ---
from centralms import util as UT
from centralms import abcee as ABC
from centralms import catalog as Cat
from centralms import evolver as Evo
from centralms import observables as Obvs
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] = Tru... | github_jupyter | import numpy as np
# --- centralms ---
from centralms import util as UT
from centralms import abcee as ABC
from centralms import catalog as Cat
from centralms import evolver as Evo
from centralms import observables as Obvs
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] = True
mp... | 0.419767 | 0.508117 |
```
%load_ext nb_black
%load_ext autoreload
%autoreload 2
import os
print(os.getcwd())
def update_working_directory():
from pathlib import Path
p = Path(os.getcwd()).parents[0]
os.chdir(p)
print(p)
update_working_directory()
```
# Import
```
import dill
import numpy as np
import pandas as pd
p... | github_jupyter | %load_ext nb_black
%load_ext autoreload
%autoreload 2
import os
print(os.getcwd())
def update_working_directory():
from pathlib import Path
p = Path(os.getcwd()).parents[0]
os.chdir(p)
print(p)
update_working_directory()
import dill
import numpy as np
import pandas as pd
pd.set_option("display.... | 0.459561 | 0.717516 |
## Load Data
```
from data import Images_load
train, validation, test = Images_load.load_data()
train.features.shape
```
# ResNet 50 transfer learning:
```
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.applications.resnet50 import ResNet50, decode_predictions, pr... | github_jupyter | from data import Images_load
train, validation, test = Images_load.load_data()
train.features.shape
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.applications.resnet50 import ResNet50, decode_predictions, preprocess_input
def _prepare_data(train, validation, test):... | 0.936894 | 0.87142 |
## Nice Extensions
#### Too long, didn't read:
- Gist-it - Share your notebook in just a few clicks
- Code Folding - Allows you to fold inside of code cells just like a regular IDE
- AutoSaveTime - Auto save your notebook every n minutes
- ExecuteTime - Automatically show how long each cell took to execute. No need f... | github_jupyter | !jupyter nbextension enable gist_it/main
!jupyter nbextension enable codefolding/main
!jupyter nbextension enable autosavetime/main
!jupyter nbextension enable execute_time/ExecuteTime
!jupyter nbextension enable hinterland/hinterland
!jupyter nbextension enable rubberband/main
!jupyter nbextension enable move_selected... | 0.457379 | 0.851583 |
```
class Solution:
def permuteUnique(self, nums):
self.res = set()
self.dfs(nums, [])
return self.res
def dfs(self, nums, path):
if not nums and path not in self.res:
self.res.append(list(path))
return
for i in range(len(nums)):
... | github_jupyter | class Solution:
def permuteUnique(self, nums):
self.res = set()
self.dfs(nums, [])
return self.res
def dfs(self, nums, path):
if not nums and path not in self.res:
self.res.append(list(path))
return
for i in range(len(nums)):
... | 0.362518 | 0.516839 |
```
import pandas as pd
from matplotlib import pyplot as plt
import itertools
sample_data = pd.read_csv('../sample_data_wk5.csv')
real_data = pd.read_csv('../real_week5.csv')
sample_data[0:1000:15]
real_data
nfl_marg_d={}
homecount = len(set(sample_data.hometeam))
for i,home_t in enumerate(set(sample_data.hometeam)):
... | github_jupyter | import pandas as pd
from matplotlib import pyplot as plt
import itertools
sample_data = pd.read_csv('../sample_data_wk5.csv')
real_data = pd.read_csv('../real_week5.csv')
sample_data[0:1000:15]
real_data
nfl_marg_d={}
homecount = len(set(sample_data.hometeam))
for i,home_t in enumerate(set(sample_data.hometeam)):
h... | 0.281011 | 0.245684 |
# ServerSim Overview and Tutorial
## Introduction
This is an overview and tutorial about ***ServerSim***, a framework for the creation of discrete event simulation models to analyze the performance, throughput, and scalability of services deployed on computer servers.
Following the overview of ServerSim, we will pro... | github_jupyter | # %load simulate_deployment_scenario.py
from __future__ import print_function
from typing import List, Tuple, Sequence
from collections import namedtuple
import random
import simpy
from serversim import *
def simulate_deployment_scenario(num_users, weight1, weight2, server_range1,
... | 0.63114 | 0.869548 |
# Edit polygon
This notebook implements polygon editor which illustrates combining mouse event modalities with reference frames.
Click to start the polygon.
Type "." to drop a new vertex.
Click again to close the polygon.
Press the reset button to play again.
```
from jp_doodle import dual_canvas
from IPython.... | github_jupyter | from jp_doodle import dual_canvas
from IPython.display import display
poly_edit = dual_canvas.SnapshotCanvas("editted polygon.png", width=320, height=320)
poly_edit.display_all()
poly_edit.js_init("""
// Add a light backdrop
var background = element.rect({name: "background", x:-15, y:-15, w:370, h:370, color:"#def"})... | 0.456894 | 0.81582 |
# Frequentist & Bayesian Statistics With Py4J & PyMC3
-----
__[1. Introduction](#first-bullet)__
__[2. Sampling A Distribution Written In Scala Using Py4J](#second-bullet)__
__[3. The Maximum Likelihood Estimator](#third-bullet)__
__[4. Confidence Intervals From Fisher Information](#fourth-bullet)__
__[5. Bayesian... | github_jupyter | from py4j.java_gateway import JavaGateway, GatewayParameters, CallbackServerParameters
gateway = JavaGateway(
gateway_parameters=GatewayParameters(address='py4jserver', port=25333),
callback_server_parameters=CallbackServerParameters(address='jupyter', port=25334)
)
app = gateway.entry_point
type(app)
dir(a... | 0.822046 | 0.931774 |
<br>
**<font face="calibri" color="black" size="6">Data Exploration and Prediction of House Price</font>**
<br><br>
**<font face="calibri"size="4" color="black" >July 2017</font>** <br> <br> <br> <br>
**<font face="calibri" color="blue" size="5">Part I Introduction</font>**
<br><br>
**<font face="calibri" size="4" colo... | github_jupyter | library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library(gplots)
library(repr)
# Change plot size to 9 x 6
options(repr.plot.width=9, repr.plot.height=6)
list.files("../input")
train <- read.csv("../input/train.csv")
# list rows of data that have missing values
missing... | 0.467332 | 0.969584 |
# Getting monthly deaths
## Importing required modules
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
```
## Loading csv file as pandas dataframe
```
usaDeath = pd.read_csv("assets/main data/florida/covid_deaths_usafacts.csv")
usaDeath.tail()
```
## Cropping and managing date column
... | github_jupyter | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
usaDeath = pd.read_csv("assets/main data/florida/covid_deaths_usafacts.csv")
usaDeath.tail()
florida = usaDeath[usaDeath["State"] == "FL"].drop(
columns=["County Name", "State", "StateFIPS", "countyFIPS"]).transpose().diff().reset_index().... | 0.382372 | 0.850841 |
```
import nibabel as nib
import matplotlib.pyplot as plt
def show_mid_slices(image):
""" Function to display row of image middle slices """
shape = image.shape
slices = [image[int(shape[0]/2), :, :],
image[:, int(shape[1]/2), :],
image[:, :, int(shape[2]/2)]]
fig, axes =... | github_jupyter | import nibabel as nib
import matplotlib.pyplot as plt
def show_mid_slices(image):
""" Function to display row of image middle slices """
shape = image.shape
slices = [image[int(shape[0]/2), :, :],
image[:, int(shape[1]/2), :],
image[:, :, int(shape[2]/2)]]
fig, axes = plt... | 0.179818 | 0.828454 |
# Geolocalizacion de dataset de escuelas argentinas
```
#Importar librerias
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
```
### Preparacion de data
```
# Vamos a cargar ...
# Leer csv
df = pd.read_csv('../../datos/Población_estudiantil.cs... | github_jupyter | #Importar librerias
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
# Vamos a cargar ...
# Leer csv
df = pd.read_csv('../../datos/Población_estudiantil.csv', header= None)
df.columns = ['Universidad']
df['Address'] = 'Universidad ' + df['Unive... | 0.258232 | 0.698972 |
<table>
<tr align=left><td><img align=left src="./images/CC-BY.png">
<td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli</td>
</table>
```
from __future__ import print_function
from __future__ import absolute_import
... | github_jupyter | from __future__ import print_function
from __future__ import absolute_import
%matplotlib inline
import numpy
import matplotlib.pyplot as plt
# =============================================================
# Plot the two example basis functions in the current example
x = numpy.linspace(1.0, 3.0, 2)
fig_Ex0a = plt.figu... | 0.843283 | 0.993372 |
```
from gensim.models import FastText
model = FastText.load_fasttext_format("./model/fasttext.bin")
from konlpy.tag import Kkma
from konlpy.tag import Okt
kkma = Kkma()
okt = Okt()
kkma.pos("아버지가방에 들어가신다")
okt.pos("맛있고 춥고 더러워요", stem=True)
model.wv.distance("아이즈원", "최예나")
posed = okt.pos('생각보다 사람들도 많았고 넓어서 놀랐어용! 외관에서부... | github_jupyter | from gensim.models import FastText
model = FastText.load_fasttext_format("./model/fasttext.bin")
from konlpy.tag import Kkma
from konlpy.tag import Okt
kkma = Kkma()
okt = Okt()
kkma.pos("아버지가방에 들어가신다")
okt.pos("맛있고 춥고 더러워요", stem=True)
model.wv.distance("아이즈원", "최예나")
posed = okt.pos('생각보다 사람들도 많았고 넓어서 놀랐어용! 외관에서부터 풍기... | 0.14143 | 0.496704 |
# Cholangiocarcinoma (CHOL)
[Jump to the urls to download the GCT and CLS files](#Downloads)
<p><strong>Authors:</strong> Alejandra Ramos, Marylu Villa, and Edwin Juarez</p>
<p><strong>Contact info:</strong> Email Edwin at ejuarez@cloud.ucsd.edu or post a question in <a href="http://www.genepattern.org/help" target="_... | github_jupyter | # Requires GenePattern Notebook: pip install genepattern-notebook
import gp
import genepattern
# Username and password removed for security reasons.
genepattern.display(genepattern.session.register("https://cloud.genepattern.org/gp", "", ""))
tcgaimporter_task = gp.GPTask(genepattern.session.get(0), 'urn:lsid:broad.m... | 0.379608 | 0.950778 |
```
%matplotlib inline
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from PIL import Image
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input di... | github_jupyter | %matplotlib inline
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from PIL import Image
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input direct... | 0.570571 | 0.387777 |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
This notebook demonstrates how to run batch scoring job. __[Inception-V3 model](https://arxiv.org/abs/1512.00567)__ and unlabeled images from __[ImageNet](http://image-net.org/)__ dataset will be used. It registers a pretrained... | github_jupyter | import os
from azureml.core import Workspace, Run, Experiment
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
# Also create a Project and attach to Worksp... | 0.512449 | 0.846197 |
# Convolutional Neural Networks
In this notebook we will implement a convolutional neural network. Rather than doing everything from scratch we will make use of [TensorFlow 2](https://www.tensorflow.org/) and the [Keras](https://keras.io) high level interface.
## Installing TensorFlow and Keras
TensorFlow and Keras ... | github_jupyter | conda install notebook jupyterlab nb_conda_kernels
conda create -n tf tensorflow ipykernel mkl
import tensorflow as tf
(x_train, y_train),(x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shap... | 0.886727 | 0.995354 |
# Функции в Pandas
```
import pandas as pd
stats = pd.read_excel('ad_campaigns.xlsx')
stats.head()
?stats.rename
stats.columns = ['group', 'phrase', 'effect', 'ad_id', 'title', 'text', 'link']
stats.head()
```
### Lambda-функции
Хотим посчитать распределение количества слов в столбце с фразами
```
stats['word_count'... | github_jupyter | import pandas as pd
stats = pd.read_excel('ad_campaigns.xlsx')
stats.head()
?stats.rename
stats.columns = ['group', 'phrase', 'effect', 'ad_id', 'title', 'text', 'link']
stats.head()
stats['word_count'] = stats['phrase'].apply(lambda x: len(x.split(' ')))
stats.head()
# вариант с передачей всей строчки функции
# тут н... | 0.294316 | 0.870927 |
# Bite Size Bayes
Copyright 2020 Allen B. Downey
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
## Review
[In the previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/04_dice.ipynb) ... | github_jupyter | from IPython.display import YouTubeVideo
YouTubeVideo('otdaJPVQIgg')
import pandas as pd
table = pd.DataFrame(index=['condition', 'no condition'])
table['prior'] = 0.01, 0.99
table
table['likelihood'] = 0.95, 0.05
table
table['unnorm'] = table['prior'] * table['likelihood']
table
prob_data = table['unnorm'].sum()
... | 0.711431 | 0.992725 |
```
import numpy as np
from sklearn.decomposition import PCA
import scipy.io as sio
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import os
import random
from random import shuffle
from skimage.transform import rotate
import scipy.ndimage
def loadIndianPinesData():
data_path... | github_jupyter | import numpy as np
from sklearn.decomposition import PCA
import scipy.io as sio
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import os
import random
from random import shuffle
from skimage.transform import rotate
import scipy.ndimage
def loadIndianPinesData():
data_path = o... | 0.488527 | 0.568296 |
```
import os
import pandas as pd
import numpy as np
import pickle
import json
FILES_DIR = "/home/blagojce/EPFL_semester3/NTDS/ntds_project/ml-100k"
```
<b>u.data</b> -- The full u data set, 100000 ratings by 943 users on 1682 items.
Each user has rated at least 20 movies. Users and items are
... | github_jupyter | import os
import pandas as pd
import numpy as np
import pickle
import json
FILES_DIR = "/home/blagojce/EPFL_semester3/NTDS/ntds_project/ml-100k"
df_data_path = os.path.join(FILES_DIR, "u.data")
df_data = pd.read_csv(df_data_path, header=None, delimiter="\t")
df_data.columns = ["user_id", "item_id", "rating", "timesta... | 0.144269 | 0.444625 |
# Data Analysis - Data Exploration
```
import pandas as pd
import sklearn
import missingno as msno
import numpy as np
from sklearn.impute import KNNImputer
import sklearn.neighbors._base
import sys
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
from sklearn.decomposition import PCA
from missingpy imp... | github_jupyter | import pandas as pd
import sklearn
import missingno as msno
import numpy as np
from sklearn.impute import KNNImputer
import sklearn.neighbors._base
import sys
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
from sklearn.decomposition import PCA
from missingpy import MissForest
from sklearn.cluster impo... | 0.317638 | 0.676406 |
```
from __future__ import absolute_import, division, print_function, unicode_literals
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
dataset_path = keras.utils.ge... | github_jupyter | from __future__ import absolute_import, division, print_function, unicode_literals
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
dataset_path = keras.utils.get_fi... | 0.89214 | 0.884838 |
# Домашняя работа №4
# Студент: Правилов Михаил
# Задание 1
"Напишите программу вычисляющую корни полиномов Лежандра, используя любой из методов с лекции, кроме половинного деления. Используйте для вычисления значений полиномов scipy.special.legendre и перемежаемость корней полномов послежовательных степеней."
Я пре... | github_jupyter | from scipy.special import legendre
def get_legendre_derivative(n):
def derivative(x):
P_n_1 = legendre(n - 1)
P_n = legendre(n)
return n / (1 - x ** 2) * (P_n_1(x) - x * P_n(x))
return derivative
def calculate_legendre_i_root_cos(n, i):
number_of_iterations = 10
x_cur = np.cos(... | 0.724773 | 0.939969 |
# A group-based test
Next, we test bilateral symmetry by making an assumption that the left and the right
hemispheres both come from a stochastic block model, which models the probability
of any potential edge as a function of the groups that the source and target nodes
are part of.
For now, we use some broad cell typ... | github_jupyter | from pkg.utils import set_warnings
set_warnings()
import datetime
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from giskard.plot import rotate_labels
from matplotlib.transforms import Bbox
from myst_nb import glue as default_glue
from pkg.data import load_n... | 0.747524 | 0.935169 |
```
import warnings
warnings.filterwarnings('ignore')
import sys
print(sys.executable)
!{sys.executable} -m pip install scikit-image
!{sys.executable} -m pip install scipy
!{sys.executable} -m pip install opencv-python
!{sys.executable} -m pip install pillow
!{sys.executable} -m pip install matplotlib
!{sys.executable... | github_jupyter | import warnings
warnings.filterwarnings('ignore')
import sys
print(sys.executable)
!{sys.executable} -m pip install scikit-image
!{sys.executable} -m pip install scipy
!{sys.executable} -m pip install opencv-python
!{sys.executable} -m pip install pillow
!{sys.executable} -m pip install matplotlib
!{sys.executable} -m... | 0.350644 | 0.382055 |
## 1. Two Sum
```
;;; 使用散列表
(defun two-sum (nums target)
(let ((hash-table (make-hash-table)))
(loop for i below (length nums) do
(let* ((key (- target (nth i nums)))
(value (gethash key hash-table)))
(if value
(return (list value i))
(setf (getha... | github_jupyter | ;;; 使用散列表
(defun two-sum (nums target)
(let ((hash-table (make-hash-table)))
(loop for i below (length nums) do
(let* ((key (- target (nth i nums)))
(value (gethash key hash-table)))
(if value
(return (list value i))
(setf (gethash (nth i nums) has... | 0.194712 | 0.825273 |
# Números
Se estudian dos categorías de números:
- Enteros (Naturales)
- Reales
- Imaginarios
- Fracciones
## Enteros
```
2 + 2
type(2+2)
a = 2
b = 3
a
b
type(a)
type(b)
```
### Operaciones aritméticas con enteros:
```
a + b
a - b
a * b
a / b
a // b
type(a/b)
type(a//b)
a % b
a ** b
```
### Conversiones
```
cad... | github_jupyter | 2 + 2
type(2+2)
a = 2
b = 3
a
b
type(a)
type(b)
a + b
a - b
a * b
a / b
a // b
type(a/b)
type(a//b)
a % b
a ** b
cadena = '1000'
type(cadena)
# a + cadena # Genera error de tipo TypeError. No se pueden sumar valores numéricos con valores textuales.
numero_1000 = int(cadena)
numero_1000
type(numero_1000)
c = 2.0
d = ... | 0.311636 | 0.893681 |
# Hartree-Fock Self-Consistent Field Theory
## I. Theoretical Overview
In this tutorial, we will seek to introduce the theory and implementation of the quantum chemical method known as Hartree-Fock Self-Consistent Field Theory (HF-SCF) with restricted orbitals and closed-shell systems (RHF). This theory seeks to solve... | github_jupyter | # ==> Import Psi4 & NumPy <==
import psi4
import numpy as np
# ==> Set Basic Psi4 Options <==
# Memory specification
psi4.set_memory(int(5e8))
numpy_memory = 2
# Set output file
psi4.core.set_output_file('output.dat', False)
# Define Physicist's water -- don't forget C1 symmetry!
mol = psi4.geometry("""
O
H 1 1.1
H ... | 0.54359 | 0.99251 |
```
%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import norm
from sklearn.naive_bayes import GaussianNB
matplotlib.style.use('ggplot')
# generate a 2D gaussian with density
def gauss_pdf(mean, cov, x):
return (1./((... | github_jupyter | %matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import norm
from sklearn.naive_bayes import GaussianNB
matplotlib.style.use('ggplot')
# generate a 2D gaussian with density
def gauss_pdf(mean, cov, x):
return (1./(((2*n... | 0.603932 | 0.850903 |
```
import os
import json
import requests
import regex as re
from functools import lru_cache
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode chara... | github_jupyter | import os
import json
import requests
import regex as re
from functools import lru_cache
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode character... | 0.4856 | 0.291932 |
RIHAD VARIAWA, Data Scientist - Who has fun LEARNING, EXPLORING & GROWING
<h1>Clustering Algorithms</h1>
<h3>Unsupervised learning</h3>
In unsupervised learning, we do something slightly different.
We say, all right, here's our space of independent variables.
Now try and see the many features that we have.
And now try ... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_digits
from sklearn.preprocessing import scale
digits = load_digits()
digits
type(digits)
for item in digits:
print(item)
len(digits.data)
digits.data[0]
digits.images[0]
len(digits.target)
digits.target[10]
digi... | 0.645455 | 0.985286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.