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 time
import os
import pandas as pd
import numpy as np
np.set_printoptions(precision=6, suppress=True)
from sklearn.utils import shuffle
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow.keras import *
tf.__version__
gpus = tf.config.experimental.list_physical_devices('... | github_jupyter | import time
import os
import pandas as pd
import numpy as np
np.set_printoptions(precision=6, suppress=True)
from sklearn.utils import shuffle
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow.keras import *
tf.__version__
gpus = tf.config.experimental.list_physical_devices('GPU'... | 0.825414 | 0.674855 |
<a href="https://colab.research.google.com/github/prachi-lad17/Python-Case-Studies/blob/main/Case_Study_2%3A%20Figuring_out_which_customer_may_leave.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# **Figuring out which customer may leave**
```
```... | github_jupyter | ```
# Figuring Our Which Customers May Leave - Churn Analysis
### About our Dataset
Source - https://www.kaggle.com/blastchar/telco-customer-churn
1. We have customer information for a Telecommunications company
2. We've got customer IDs, general customer info, the servies they've subscribed too, type of contrac... | 0.719285 | 0.934634 |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
from sklearn.tree import DecisionTreeClassifier
# reading data files and storing them in a dataframe
df = pd.read_csv('Downloads/Features_Variant_1.csv')
df.info()
df.columns = ['likes',... | github_jupyter | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score
from sklearn.tree import DecisionTreeClassifier
# reading data files and storing them in a dataframe
df = pd.read_csv('Downloads/Features_Variant_1.csv')
df.info()
df.columns = ['likes','Pag... | 0.538255 | 0.309682 |
```
from esper.prelude import *
def get_fps_map(vids):
from query.models import Video
vs = Video.objects.filter(id__in=vids)
return {v.id: v.fps for v in vs}
def frame_second_conversion(c, mode='f2s'):
from rekall.domain_interval_collection import DomainIntervalCollection
from rekall.interval_set_... | github_jupyter | from esper.prelude import *
def get_fps_map(vids):
from query.models import Video
vs = Video.objects.filter(id__in=vids)
return {v.id: v.fps for v in vs}
def frame_second_conversion(c, mode='f2s'):
from rekall.domain_interval_collection import DomainIntervalCollection
from rekall.interval_set_3d i... | 0.41561 | 0.450601 |
```
import pandas as pd
import numpy as np
import math
import sklearn.datasets
from sklearn.model_selection import train_test_split
import sklearn.tree
##Seaborn for fancy plots.
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = (8,8)
```
## Decision Trees
One classification alg... | github_jupyter | import pandas as pd
import numpy as np
import math
import sklearn.datasets
from sklearn.model_selection import train_test_split
import sklearn.tree
##Seaborn for fancy plots.
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = (8,8)
def sklearn_to_df(sklearn_dataset):
df = pd.D... | 0.535584 | 0.940243 |
# 04 - Full waveform inversion with Devito and Dask
## Introduction
In this tutorial we show how [Devito](http://www.devitoproject.org/devito-public) and [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) are used with [Dask](https://dask.pydata.org/en/latest/... | github_jupyter | scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
scipy.optimize.minimize(fun, x0, args=(), method='L-BFGS-B', jac=None, bounds=None, tol=None, callback=None, options={'disp': None, 'maxls': 20, 'iprint': -1, 'gto... | 0.857231 | 0.968081 |
# Code
**Date: February, 2017**
```
%matplotlib inline
import numpy as np
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# For linear regression
from scipy.stats import multivariate_normal
from scipy.integrate import dblquad
# Shut down warn... | github_jupyter | %matplotlib inline
import numpy as np
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# For linear regression
from scipy.stats import multivariate_normal
from scipy.integrate import dblquad
# Shut down warnings for nicer output
import warnings
... | 0.713232 | 0.832849 |
## CNN-Project-Exercise
We'll be using the CIFAR-10 dataset, which is very famous dataset for image recognition!
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batc... | github_jupyter | # Put file path as a string here
CIFAR_DIR = ''
def unpickle(file):
import pickle
with open(file, 'rb') as fo:
cifar_dict = pickle.load(fo, encoding='bytes')
return cifar_dict
dirs = ['batches.meta','data_batch_1','data_batch_2','data_batch_3','data_batch_4','data_batch_5','test_batch']
all_data = ... | 0.568296 | 0.987067 |
# Unsupervised clustering on rock properties
Sometimes we don't have labels, but would like to discover structure in a dataset. This is what clustering algorithms attempt to do. They don't require labels from us — they are 'unsupervised'.
We'll use a subset of the [Rock Property Catalog](http://subsurfwiki.org/... | github_jupyter | import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
uid = "1TMqV0d6zEqhP-gK_jQlagTuPN7pFEI5rhkVN0xJIx4g"
url = f"https://docs.google.com/spreadsheets/d/{uid}/export?format=csv"
df = pd.read_csv(url)
cols = ['Vp', 'Vs', 'Rho_n']
sns.pairplot(df.dropna(), va... | 0.575588 | 0.985524 |
## Classes
```
from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, account_number, balance):
self._account_number = account_number
self._balance = balance
def deposit(self, value):
if value > 0:
self._balance += value
else:
... | github_jupyter | from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, account_number, balance):
self._account_number = account_number
self._balance = balance
def deposit(self, value):
if value > 0:
self._balance += value
else:
print("Invalid... | 0.6488 | 0.646446 |
# String formatting
In many of the scripts in this series of lessons, you'll see something like this:
```python
msg_tmp = 'Hello, {}!'
print(msg_tmp.format('Matt'))
# => "Hello, Matt!"
```
Notice two things: the curly brackets `{}`, which is a placeholder, and the `.format()` method, which is where you specify what ... | github_jupyter | msg_tmp = 'Hello, {}!'
print(msg_tmp.format('Matt'))
# => "Hello, Matt!"
greeting = 'Hello, my name is {}. I am {} years old, and I live in {}.'
my_name = 'Cody'
my_age = 33
my_state = 'Colorado'
print(greeting.format(my_name, my_age, my_state))
print(greeting.format(my_age, my_state, my_name))
mad_lib = 'The {noun}... | 0.197599 | 0.890199 |
```
import pandas as pd
docs = pd.read_table('SMSSpamCollection', header=None, names=['Class', 'sms'])
docs.head()
#df.column_name.value_counts() - gives no. of unique inputs in that columns
docs.Class.value_counts()
ham_spam=docs.Class.value_counts()
ham_spam
print("Spam % is ",(ham_spam[1]/float(ham_spam[0]+ham_spam[... | github_jupyter | import pandas as pd
docs = pd.read_table('SMSSpamCollection', header=None, names=['Class', 'sms'])
docs.head()
#df.column_name.value_counts() - gives no. of unique inputs in that columns
docs.Class.value_counts()
ham_spam=docs.Class.value_counts()
ham_spam
print("Spam % is ",(ham_spam[1]/float(ham_spam[0]+ham_spam[1]))... | 0.616936 | 0.544378 |
## Summary
**Notes:**
This notebook should be run on a machine with > 32G of memory.
---
## Imports
```
import os
from pathlib import Path
import crc32c
import pyarrow as pa
import pyarrow.parquet as pq
from tqdm.notebook import tqdm
```
## Parameters
```
NOTEBOOK_NAME = "01_load_data"
NOTEBOOK_DIR = Path(NOTEB... | github_jupyter | import os
from pathlib import Path
import crc32c
import pyarrow as pa
import pyarrow.parquet as pq
from tqdm.notebook import tqdm
NOTEBOOK_NAME = "01_load_data"
NOTEBOOK_DIR = Path(NOTEBOOK_NAME).resolve()
NOTEBOOK_DIR.mkdir(exist_ok=True)
NOTEBOOK_DIR
if "DATAPKG_OUTPUT_DIR" in os.environ:
DATAPKG_OUTPUT_DIR = ... | 0.321353 | 0.678338 |
# Computation Biology Summer Program Hackathon
This [Jupyter notebook](https://jupyter.org/) gives examples on how to use the various [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) web services from the [Knowledge Systems Group](https://www.mskcc.org/research-areas/labs/nikolaus-schultz). In thi... | github_jupyter | conda install jupyter
conda install -c conda-forge bravado
conda install pandas matplotlib seaborn
git clone https://github.com/mskcc/cbsp-hackathon
cd cbsp-hackathon/0-introduction
jupyter
from bravado.client import SwaggerClient
cbioportal = SwaggerClient.from_url('https://www.cbioportal.org/api/api-docs',
... | 0.499268 | 0.988624 |
Straightforward translation of https://github.com/rmeinl/apricot-julia/blob/5f130f846f8b7f93bb4429e2b182f0765a61035c/notebooks/python_reimpl.ipynb
See also https://github.com/genkuroki/public/blob/main/0016/apricot/python_reimpl.ipynb
```
using Seaborn
using ScikitLearn: @sk_import
@sk_import datasets: fetch_covtype
... | github_jupyter | using Seaborn
using ScikitLearn: @sk_import
@sk_import datasets: fetch_covtype
using Random
using StatsBase: sample
digits_data = fetch_covtype()
X_digits = permutedims(abs.(digits_data["data"]))
summary(X_digits)
"""`calculate_gains!(X, gains, current_values, idxs, current_concave_values_sum)` mutates `gains` only"""
... | 0.66454 | 0.868882 |
# Setup
```
import os
import pandas as pd
import numpy as np
import torch
from transformers import BertModel, BertTokenizer
from transformers import RobertaModel, RobertaTokenizer
import utils
import vsm
VSM_HOME = os.path.join('data', 'vsmdata')
DATA_HOME = os.path.join('data', 'wordrelatedness')
utils.fix_random_se... | github_jupyter | import os
import pandas as pd
import numpy as np
import torch
from transformers import BertModel, BertTokenizer
from transformers import RobertaModel, RobertaTokenizer
import utils
import vsm
VSM_HOME = os.path.join('data', 'vsmdata')
DATA_HOME = os.path.join('data', 'wordrelatedness')
utils.fix_random_seeds()
dev_df ... | 0.54359 | 0.866246 |
# Programming with Python
## Episode 3 - Storing Multiple Values in Lists
Teaching: 30 min,
Exercises: 30 min
## Objectives
- Explain what a list is.
- Create and index lists of simple values.
- Change the values of individual elements
- Append values to an existing list
- Reorder and slice list elements
- Create a... | github_jupyter | odds = [1, 3, 5, 7]
print('odds are:', odds)
odds = [1, 3, 5, 7]
print('odds are:', odds)
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
print('first element:', odds[0])
print('last element:', odds[3])
print('"-1" element:', odds[-1])
word = 'lead'
print(word[0])
p... | 0.327776 | 0.98551 |
# Using Astronomer Airflow with Snowflake
### Prerequisites
1) A valid Snowflake and S3 account
2) The Astronomer CLI or a running version of Airflow. (This guide was written to work with Airflow on Astronomer, but the same code should work for vanilla Airflow as well)
Navigate here to get set up:
https://github.c... | github_jupyter | .
├── dags
│ └── example-dag.py
├── Dockerfile
├── include
├── packages.txt
├── plugins
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1fc88586da10 notebook/airflow:latest "tini -- /entrypoint... | 0.454472 | 0.918114 |
**Pandas Exercises - With the NY Times Covid data**
Run the cell below to pull get the data from the nytimes github
```
!git clone https://github.com/nytimes/covid-19-data.git
```
**1. Import Pandas and Check your Version of Pandas**
```
import pandas as pd
pd.__version__
```
**2. Read the *us-counties.csv* data i... | github_jupyter | !git clone https://github.com/nytimes/covid-19-data.git
import pandas as pd
pd.__version__
covid_data = pd.read_csv('/content/covid-19-data/us-counties.csv')
covid_data.head(5)
covid_data = covid_data.drop('fips', axis=1)
covid_data.dtypes
covid_data.date = pd.to_datetime(covid_data.date)
covid_data = covid_data... | 0.65202 | 0.966505 |
## Welcome to Coding Exercise 5.
We'll only have 2 questions and both of them will be difficult. You may import other libraries to help you here. Clue: find out more about the ```itertools``` and ```math``` library.
### Question 1.
* List item
* List item
### "Greatest Possible Combination"
We have a functio... | github_jupyter |
Given 3 list/array/vector containing possible values of x1, x2, and x3, find the maximum output possible.
#### Explanation:
If x1 = 2, x2 = 5, x3 = 3, then...
The function's output is: (2^2 + 5 * 3) modulo 20 = (4 + 15) modulo 20 = 19 modulo 20 = 19.
If x1 = 3, x2 = 5, x3 = 3, then...
The function's output is:... | 0.883324 | 0.989977 |
```
"""Bond Breaking"""
__authors__ = "Victor H. Chavez", "Lyudmila Slipchenko"
__credits__ = ["Victor H. Chavez", "Lyudmila Slipchenko"]
__email__ = ["gonza445@purdue.edu", "lslipchenko@purdue.edu"]
__copyright__ = "(c) 2008-2019, The Psi4Education Developers"
__license__ = "BSD-3-Clause"
__date__ = "2019-1... | github_jupyter | """Bond Breaking"""
__authors__ = "Victor H. Chavez", "Lyudmila Slipchenko"
__credits__ = ["Victor H. Chavez", "Lyudmila Slipchenko"]
__email__ = ["gonza445@purdue.edu", "lslipchenko@purdue.edu"]
__copyright__ = "(c) 2008-2019, The Psi4Education Developers"
__license__ = "BSD-3-Clause"
__date__ = "2019-11-18... | 0.79657 | 0.925095 |
```
import batoid
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
telescope = batoid.Optic.fromYaml("HSC.yaml")
def pupil(thx, thy, nside=512):
rays = batoid.RayVector.asGrid(
optic=telescope, wavelength=750e-9,
theta_x=thx, theta_y=thy,
nx=nside, ny=nside
)
ray... | github_jupyter | import batoid
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
telescope = batoid.Optic.fromYaml("HSC.yaml")
def pupil(thx, thy, nside=512):
rays = batoid.RayVector.asGrid(
optic=telescope, wavelength=750e-9,
theta_x=thx, theta_y=thy,
nx=nside, ny=nside
)
rays2 =... | 0.569494 | 0.697849 |
# Álgebra matricial
En este libro tratamos de minimizar la notación matemática tanto como sea posible. Además, evitamos usar el cálculo para motivar conceptos estadísticos. Sin embargo, Matrix Algebra (también conocida como Linear Algebra) y su notación matemática facilita enormemente la exposición de las técnicas ava... | github_jupyter | library(rafalib)
set.seed(1)
g <- 9.8 ##meters per second
n <- 25
tt <- seq(0,3.4,len=n) ##time in secs, note: we use tt because t is a base function
#rands = s.randi(0, 1, n, seed=1)
d <- 56.67 - 0.5*g*tt^2 + rnorm(n,sd=1) ##meters
mypar()
plot(tt,d,ylab="Distancia en metros",xlab="Tiempo en segundos")
father.son ... | 0.355216 | 0.983166 |
```
import pandas as pd
result = pd.read_csv('editeddata.csv')
result
from nltk.classify import NaiveBayesClassifier
import nltk.classify.util as cu
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklea... | github_jupyter | import pandas as pd
result = pd.read_csv('editeddata.csv')
result
from nltk.classify import NaiveBayesClassifier
import nltk.classify.util as cu
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.f... | 0.204183 | 0.683091 |
# Named Entity Recognition using Transformers
**Author:** [Varun Singh](https://www.linkedin.com/in/varunsingh2/)<br>
**Date created:** Jun 23, 2021<br>
**Last modified:** Jun 24, 2021<br>
**Description:** NER using the Transformers and data from CoNLL 2003 shared task.
## Introduction
Named Entity Recognition (NER)... | github_jupyter | !pip3 install datasets
!wget https://raw.githubusercontent.com/sighsmile/conlleval/master/conlleval.py
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from datasets import load_dataset
from collections import Counter
from conlleval import evaluate
... | 0.889966 | 0.936807 |
# Machine Learning
> A Summary of lecture "Introduction to Computational Thinking and Data Science", via MITx-6.00.2x (edX)
- toc: true
- badges: true
- comments: true
- author: Chanseok Kang
- categories: [Python, edX, Machine_Learning]
- image: images/ml_block.png
- What is Machine Learning
- Many useful progr... | github_jupyter | from lecture12_segment2 import *
cobra = Animal('cobra', [1,1,1,1,0])
rattlesnake = Animal('rattlesnake', [1,1,1,1,0])
boa = Animal('boa\nconstrictor', [0,1,0,1,0])
chicken = Animal('chicken', [1,1,0,1,2])
alligator = Animal('alligator', [1,1,0,1,4])
dartFrog = Animal('dart frog', [1,0,1,0,4])
zebra = Animal('zebra', [... | 0.641759 | 0.984246 |
# Retrieve Tweets
Takes a list of tweet IDs and outputs the full tweet dataset. When the script hits Twitter's API limit, it will automatically wait and restart after the appropriate amount of time. Because of the API rate limiting, this script could take up to a few hours.
```
import pandas as pd
import tweepy
impor... | github_jupyter | import pandas as pd
import tweepy
import csv
# Insert your Twitter API key here
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''
def retrieve_tweets(input_file, output_file):
"""
Takes an input filename/path of tweetIDs and outputs the full tweet data to a csv
"""
#... | 0.260578 | 0.582966 |
#### New to Plotly?
Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).
<br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-fo... | github_jupyter | import plotly
plotly.__version__
import datetime
import matplotlib.pyplot as plt
import numpy as np
import plotly.plotly as py
import plotly.tools as tls
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api
x = np.array([datetime.dateti... | 0.568296 | 0.919027 |
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from processwx import select_stn, process_stn
%matplotlib inline
%config InlineBackend.figure_format='retina'
```
# EDA with Teton avalanche observations and hazard forecasts
I've already preprocessed the avalanche events and forecasts, so... | github_jupyter | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from processwx import select_stn, process_stn
%matplotlib inline
%config InlineBackend.figure_format='retina'
events_df = pd.read_csv('btac_events.csv.gz', compression='gzip',
index_col=[0], parse_dates = [2])
hzrd_df = p... | 0.25945 | 0.920861 |
# Workshop 12: Introduction to Numerical ODE Solutions
*Source: Eric Ayars, PHYS 312 @ CSU Chico*
**Submit this notebook to bCourses to receive a grade for this Workshop.**
Please complete workshop activities in code cells in this iPython notebook. The activities titled **Practice** are purely for you to explore Pyt... | github_jupyter | # Run this cell before preceding
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Initial condition
t0 = 0.0
x0 = 0.75
# Make a grid of x,t values
t_values = np.linspace(t0, t0+3, 20)
x_values = np.linspace(-np.abs(x0)*1.2, np.abs(x0)*1.2, 20)
t, x = np.meshgrid(t_values, x_values)
# Evaluate ... | 0.828766 | 0.989928 |
<img src="ku_logo_uk_v.png" alt="drawing" width="130" style="float:right"/>
# <span style="color:#2c061f"> Exercise 5 </span>
<br>
## <span style="color:#374045"> Introduction to Programming and Numerical Analysis </span>
#### <span style="color:#d89216"> <br> Sebastian Honoré </span>
## Plan for today
<br>
1... | github_jupyter | # Imports
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
import OLG_trans as OLG #OLG transition functions
#Center images in notebook (optional)
from IPython.core.display import HTML
HTML("""
<style>
.output_png {
display: table-cell;
text-align: center;
vertical-align: midd... | 0.80969 | 0.975762 |
dataset: https://www.kaggle.com/blastchar/telco-customer-churn
```
from google.colab import drive # Import a library named google.colab
drive.mount('/content/drive', force_remount=True) # mount the content to the directory `/content/drive`
%cd /content/drive/MyDrive/Tensorflow_Practice
# !mkdir HW13 # I HAVE MADE... | github_jupyter | from google.colab import drive # Import a library named google.colab
drive.mount('/content/drive', force_remount=True) # mount the content to the directory `/content/drive`
%cd /content/drive/MyDrive/Tensorflow_Practice
# !mkdir HW13 # I HAVE MADE IT.
import tensorflow as tf
from tensorflow import keras # a hi... | 0.381335 | 0.669384 |
<!--NAVIGATION-->
< [Combining Datasets: Merge and Join](03.07-Merge-and-Join.ipynb) | [Contents](Index.ipynb) | [Pivot Tables](03.09-Pivot-Tables.ipynb) >
# Aggregation and Grouping
An essential piece of analysis of large data is efficient summarization: computing aggregations like ``sum()``, ``mean()``, ``median()`... | github_jupyter | import numpy as np
import pandas as pd
class display(object):
"""Display HTML representation of multiple objects"""
template = """<div style="float: left; padding: 10px;">
<p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
</div>"""
def __init__(self, *args):
self.args = ar... | 0.558207 | 0.987496 |
# Python para Data Science: Introdução à linguagem e Numpy - parte 2
```
import numpy as np
from numpy import arange
np.arange(10)
km = np.array([1000, 2300, 4985, 1400, 6482])
km
type(km)
km.dtype
km = np.loadtxt(fname = 'carros-km.txt', dtype = int)
km
km.dtype
dados = [
['Rodas de liga', 'Travas elétricas', '... | github_jupyter | import numpy as np
from numpy import arange
np.arange(10)
km = np.array([1000, 2300, 4985, 1400, 6482])
km
type(km)
km.dtype
km = np.loadtxt(fname = 'carros-km.txt', dtype = int)
km
km.dtype
dados = [
['Rodas de liga', 'Travas elétricas', 'Piloto automático', 'Bancos de couro', 'Ar condicionado', 'Sensor de estac... | 0.264453 | 0.904355 |
# Exploratory data analysis for vtalks.net
## Table of contents:
* [Introduction](#introduction)
* [Setup & Configuration](#setup-and-configuration)
* [Load the Data Set](#load-the-data-set)
* [Youtube Statistics Analysis](#youtube-statistics-analysis)
* [Youtube Views](#youtube-views)
* [Youtube... | github_jupyter | !pwd
import numpy as np
import pandas as pd
import pandas_profiling as pp
import matplotlib.pyplot as plt
import seaborn
%matplotlib inline
seaborn.set()
plt.rc('figure', figsize=(16,8))
plt.style.use('bmh')
plt.style.available
data_source = "../../.dataset/vtalks_dataset_2018.csv"
# data_source = "../../.dataset/... | 0.550124 | 0.979823 |
<a href="https://colab.research.google.com/github/SauravMaheshkar/trax/blob/SauravMaheshkar-example-1/examples/Deep_N_Gram_Models.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#@title
# Copyright 2020 Google LLC.
# Licensed under the Apache L... | github_jupyter | #@title
# Copyright 2020 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 writing... | 0.785966 | 0.960952 |
# **Decision Trees**
The Wisconsin Breast Cancer Dataset(WBCD) can be found here(https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data)
This dataset describes the characteristics of the cell nuclei of various patients with and without breast cancer. The task is... | github_jupyter | # Attribute Domain
-- -----------------------------------------
1. Sample code number id number
2. Clump Thickness 1 - 10
3. Uniformity of Cell Size 1 - 10
4. Uniformity of Cell Shape 1 - 10
5. Marginal Adhesion 1 - 10
6. Single E... | 0.483648 | 0.984411 |
# Bile Acids
Compare placebo v. letrozole and letrozole v. let-co-housed at time points 2 and 5.
```
library(tidyverse)
library(magrittr)
source("/Users/cayla/ANCOM/scripts/ancom_v2.1.R")
counts <- read_csv('https://github.com/bryansho/PCOS_WGS_16S_metabolome/raw/master/DESEQ2/Bile_Acids/Bile_Acids_Cutoff.csv')
head(c... | github_jupyter | library(tidyverse)
library(magrittr)
source("/Users/cayla/ANCOM/scripts/ancom_v2.1.R")
counts <- read_csv('https://github.com/bryansho/PCOS_WGS_16S_metabolome/raw/master/DESEQ2/Bile_Acids/Bile_Acids_Cutoff.csv')
head(counts, n=1)
counts$OTUs <- as.factor(counts$OTUs)
metadata <- read_csv('https://github.com/bryansho/PC... | 0.423696 | 0.837321 |
```
%matplotlib notebook
import control as c
import ipywidgets as w
import numpy as np
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.transforms as transforms
import matplotlib.animation as animation
display(HTML('<script> $(document).r... | github_jupyter | %matplotlib notebook
import control as c
import ipywidgets as w
import numpy as np
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.transforms as transforms
import matplotlib.animation as animation
display(HTML('<script> $(document).ready... | 0.47171 | 0.919208 |
# Advanced Circuits
```
import numpy as np
from qiskit import *
```
## Opaque gates
```
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw(... | github_jupyter | import numpy as np
from qiskit import *
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw()
# Build a sub-circuit
sub_q = QuantumRegister(2... | 0.381335 | 0.954732 |
# MLB Power Rankings and Casino Odds
> Part 3 - adding power rankings and odds into the MLB prediction model
- toc: false
- badges: true
- comments: true
- categories: [baseball, webscraping, Elo, Trueskill, Glick, machine learning]
- image: images/chart-preview.png
|MLB Baseball Prediction Series:|[Part 1](https://r... | github_jupyter | import pickle
df = pickle.load(open("dataframe.pkl","rb"))
pip install elote
from elote import EloCompetitor
ratings = {}
for x in df.home_team_abbr.unique():
ratings[x]=EloCompetitor()
for x in df.away_team_abbr.unique():
ratings[x]=EloCompetitor()
home_team_elo = []
away_team_elo = []
elo_exp = []
df = df... | 0.092191 | 0.850717 |
# Obtaining deflection in time for a sinc excited tip interacting with a viscoelastic solid (Standard Linear Solid)
```
import numpy as np
from numba import jit
from AFM_simulations import MDR_SLS_sinc, SLS_parabolic_LR_sinc, Hertzian_sinc
import matplotlib.pyplot as plt
from AFM_calculations import derivative_cd, av_... | github_jupyter | import numpy as np
from numba import jit
from AFM_simulations import MDR_SLS_sinc, SLS_parabolic_LR_sinc, Hertzian_sinc
import matplotlib.pyplot as plt
from AFM_calculations import derivative_cd, av_dt
%matplotlib inline
A = -1.36e-9 #amplitude of the sinc excitation
R = 10.0e-9 #radius of curvature of the paraboli... | 0.452536 | 0.945349 |
```
import os
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torchvision import models
import numpy as np
import pandas as pd
import math
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
```
### Load Best Model
```
# C... | github_jupyter | import os
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torchvision import models
import numpy as np
import pandas as pd
import math
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
# Create a feedforward NN with:
# 1 ... | 0.871557 | 0.887595 |
I refered the K-means Clustering on website : "https://machinelearningcoban.com/2017/01/01/kmeans/" while doing this
homework, so there will be similarities in the codebase.
Trying to follow the given paths.
Import libraries:
Note: Set seed = 200
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.spa... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
import logging
np.random.seed(200)
def display(dataset, label):
x0 = dataset[label == 0, :]
x1 = dataset[label == 1, :]
x2 = dataset[label == 2, :]
plt.plot(x0[:, 0], x0[:, 1], 'b^', markersize = 1)
plt.plo... | 0.276495 | 0.980692 |
# Decision Tree
Mateus Victor<br>
GitHub: <a href="https://github.com/mateusvictor">mateusvictor</a>
## Setup
```
import numpy as np
import pandas as pd
# To model the desision tree
from sklearn.tree import DecisionTreeClassifier
# Transform the data
from sklearn import preprocessing
# To create a train and test ... | github_jupyter | import numpy as np
import pandas as pd
# To model the desision tree
from sklearn.tree import DecisionTreeClassifier
# Transform the data
from sklearn import preprocessing
# To create a train and test set
from sklearn.model_selection import train_test_split
# Metrics to evaluating
from sklearn import metrics
# For... | 0.740925 | 0.964656 |
# Título 1
## Título 2

```
print("Hola Mundo!")
# No tipado!
# Variables primitivas
entero = 4
decimales = 1.1
nombre = "Jeff"
segundo_nombre = "Otro nombre" #no camel case
casado = False
profesor = True
h... | github_jupyter | print("Hola Mundo!")
# No tipado!
# Variables primitivas
entero = 4
decimales = 1.1
nombre = "Jeff"
segundo_nombre = "Otro nombre" #no camel case
casado = False
profesor = True
hijos = None
apellido = 'Velasquez'
print(type(entero))
print(type(decimales))
print(type(nombre))
print(type(segundo_nombre))
print(type(casad... | 0.046638 | 0.708326 |
# Exercise 11.1 - Solution
## Air-shower reconstruction
Follow the description of a cosmic-ray observatory in Example 11.2 and Fig. 11.2(b).
The simulated data contain 9 × 9 detector stations which record traversing particles from the cosmic-ray induced air shower.
Each station measures two quantities, which are stor... | github_jupyter | from tensorflow import keras
import numpy as np
from matplotlib import pyplot as plt
layers = keras.layers
print("keras", keras.__version__)
import os
import gdown
url = "https://drive.google.com/u/0/uc?export=download&confirm=HgGH&id=1nQDddS36y4AcJ87ocoMjyx46HGueiU6k"
output = 'airshowers.npz'
if os.path.exists(ou... | 0.785432 | 0.97506 |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
```
## Does nn.Conv2d init work well?
[Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=21)
```
#export
from exp.nb_02 import *
def get_data():
path = datasets.download_data(MNIST_URL, ext='.gz')
with gzip.open(path, 'rb') as f:
... | github_jupyter | %load_ext autoreload
%autoreload 2
%matplotlib inline
#export
from exp.nb_02 import *
def get_data():
path = datasets.download_data(MNIST_URL, ext='.gz')
with gzip.open(path, 'rb') as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')
return map(tensor, (x_train,y... | 0.734976 | 0.81538 |
# The $\chi^2$ Distribution
## $\chi^2$ Test Statistic
If we make $n$ ranom samples (observations) from Gaussian (Normal) distributions with known means, $\mu_i$, and known variances, $\sigma_i^2$, it is seen that the total squared deviation,
$$
\chi^2 = \sum_{i=1}^{n} \left(\frac{x_i - \mu_i}{\sigma_i}\right)^2\,,
... | github_jupyter | import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
# Plot the chi^2 distribution
x = np.linspace(0., 10., num=1000)
[plt.plot(x, stats.chi2.pdf(x, df=ndf), label=r'$k = ${}'.format(ndf))
for ndf in range(1, 7)]
plt.ylim(-0.01, 0.5)
plt.xlabel(r'$x=\chi^2$')
plt.ylabel(r'$f\left(... | 0.877896 | 0.993063 |
# Visualisation of critical points
---
## Use of TensorFlow optimizers to locate function minima
***Author: Piotr Skalski***
### Imports
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
```
### Settings
```
# learning rate
LR = 0.005
# paramete... | github_jupyter | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# learning rate
LR = 0.005
# parameters a and b of the real function
REAL_PARAMS = [1, 1]
# starting point for gradient descent
INIT_PARAMS = [1, 0]
# output directory (the folder must be created on the d... | 0.542136 | 0.948632 |
```
import QC_Library as qc
file='/Users/oz/downloads/kaneohe_all.json'
retDict_SST_7_20 = qc.outliers.analyze(file, 'sst', gross_range=[1, 35],verbosity=1)
qc.outliers.diagnostic_plots(retDict_SST_7_20['parameter'], retDict_SST_7_20['data'], retDict_SST_7_20['times'],
xlabel='Time')
qc.outliers.diagno... | github_jupyter | import QC_Library as qc
file='/Users/oz/downloads/kaneohe_all.json'
retDict_SST_7_20 = qc.outliers.analyze(file, 'sst', gross_range=[1, 35],verbosity=1)
qc.outliers.diagnostic_plots(retDict_SST_7_20['parameter'], retDict_SST_7_20['data'], retDict_SST_7_20['times'],
xlabel='Time')
qc.outliers.diagnostic... | 0.229104 | 0.281492 |
TSG095 - Hadoop namenode logs
=============================
Steps
-----
### Parameters
```
import re
tail_lines = 2000
pod = None # All
container = "hadoop"
log_files = [ "/var/log/supervisor/log/namenode*.log" ]
expressions_to_analyze = [
re.compile(".{23} WARN "),
re.compile(".{23} ERROR ")
]
```
### I... | github_jupyter | import re
tail_lines = 2000
pod = None # All
container = "hadoop"
log_files = [ "/var/log/supervisor/log/namenode*.log" ]
expressions_to_analyze = [
re.compile(".{23} WARN "),
re.compile(".{23} ERROR ")
]
# Instantiate the Python Kubernetes client into 'api' variable
import os
try:
from kubernetes imp... | 0.36557 | 0.723566 |
```
import pandas as pd
from pySankey.sankey import sankey
import plotly.graph_objects as go
from datetime import datetime as DateTime
```
## Proceso
### Adquisición de datos
```
## Cargamos los datos
df = pd.read_csv('data/TB_HOSP_VAC_FALLECIDOS.csv')
df.head(5)
df.columns
```
### Limpieza y transformación de dato... | github_jupyter | import pandas as pd
from pySankey.sankey import sankey
import plotly.graph_objects as go
from datetime import datetime as DateTime
## Cargamos los datos
df = pd.read_csv('data/TB_HOSP_VAC_FALLECIDOS.csv')
df.head(5)
df.columns
## Generamos las columnas necesarias para graficar
df['UCI'] = 'NO UCI'
df.loc[df[df['flag_... | 0.160595 | 0.516778 |
# Education theme - all audits - all data excluding PDF contents - including phrases and lemmas
This experiment used 8697 pages from GOV.UK related to the education theme. We extracted the following content from those pages:
- Title
- Description
- Indexable content (i.e. the body of the document stored in Search)
- ... | github_jupyter | diff --git a/corpus_building.py b/corpus_building.py
index 76ddc0c..af12da1 100644
--- a/corpus_building.py
+++ b/corpus_building.py
@@ -39,12 +39,10 @@ class CorpusReader(object):
"""
Extract some kind of n-grams from a document
"""
- if self.use_phrasemachine:
- phrases = ... | 0.579281 | 0.804098 |
<a href="https://colab.research.google.com/github/wwangwe/labour-market-analysis/blob/working/notebooks/Web_Scrapping.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Real-time Kenyan Labour Market Analysis
## Web Scrapping
```
import json
import... | github_jupyter | import json
import time
from datetime import datetime
from random import randint
import requests
from bs4 import BeautifulSoup
headers = [
({
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
}),
({
'... | 0.470737 | 0.585783 |
```
x="India"
x
X <- "Hello, World!"
X
x=10
y=20
x+y
x-y
x*y
x/y
# Interest (I) of a principal amount (P) of 10000 for 4 years with an interest rate (R) of 8 %
P=10000
N=4
R=8/100
I=P*N*R
I
x=10
y="India"
x+y
x <- TRUE
class(x)
x<- 23.5
class(x)
x<- 23
class(x)
x<- 23+75i
class(x)
x<- "india"
class(x)
x<- TRUE
class(x)... | github_jupyter | x="India"
x
X <- "Hello, World!"
X
x=10
y=20
x+y
x-y
x*y
x/y
# Interest (I) of a principal amount (P) of 10000 for 4 years with an interest rate (R) of 8 %
P=10000
N=4
R=8/100
I=P*N*R
I
x=10
y="India"
x+y
x <- TRUE
class(x)
x<- 23.5
class(x)
x<- 23
class(x)
x<- 23+75i
class(x)
x<- "india"
class(x)
x<- TRUE
class(x)
x<-... | 0.151153 | 0.479747 |
```
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
```
# The Qiskit Cold Atom Provider
The qiskit-cold-atom module comes with a provider that manages access to cold atomic backends.
This tutorial shows the workflow of how a user interfaces with this provider.
<div class="alert alert-bl... | github_jupyter | from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
from qiskit_cold_atom.providers import ColdAtomProvider
# save an account to disk
# ColdAtomProvider.save_account(url = ["url_of_backend_1", "url_of_backend_2"], username="JohnDoe",token="123456")
# load the stored account
provider = ColdA... | 0.424889 | 0.984575 |
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
*This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jake... | github_jupyter | for i in range(10):
print(i, end=' ')
for value in [2, 4, 6, 8, 10]:
# do some operation
print(value + 1, end=' ')
iter([2, 4, 6, 8, 10])
I = iter([2, 4, 6, 8, 10])
print(next(I))
print(next(I))
print(next(I))
range(10)
iter(range(10))
for i in range(10):
print(i, end=' ')
N = 10 ** 12
for i in r... | 0.074471 | 0.962356 |
<a href="http://cocl.us/pytorch_link_top">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " />
</a>
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN... | github_jupyter | import torch
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
def get_hist(model,data_set):
activations=model.activation(data_set.x)
for i,activation in enumerate(activations):
p... | 0.843444 | 0.914099 |
```
from billboard import ChartData
import pandas as pd
import lyricsgenius as lg
# initialize the Genius API
genius = lg.Genius("1nVXMraHD3ieBaMJteYrKT4eqenseJ0WP78V85wRZ3sa1W9FSVUL-9Fg6WlpVon-")
genius.skip_non_songs = True
#create a list of dates given number of years. Will return dates in January, April, August, De... | github_jupyter | from billboard import ChartData
import pandas as pd
import lyricsgenius as lg
# initialize the Genius API
genius = lg.Genius("1nVXMraHD3ieBaMJteYrKT4eqenseJ0WP78V85wRZ3sa1W9FSVUL-9Fg6WlpVon-")
genius.skip_non_songs = True
#create a list of dates given number of years. Will return dates in January, April, August, Decemb... | 0.292696 | 0.302433 |
```
import os
import pandas as pd
os.getcwd()
a=pd.read_csv('D:\Project\Twitter_depression_detector\data\Depression_Annotated_Data (1)\Depression_Annotated_Data\DND_U_Id_Class.tsv', sep='\t')
a
a['1017147974999146496']
a['1017147974999146496'].to_csv('D:\Project\Twitter_depression_detector\data\Depression_Annotated_Dat... | github_jupyter | import os
import pandas as pd
os.getcwd()
a=pd.read_csv('D:\Project\Twitter_depression_detector\data\Depression_Annotated_Data (1)\Depression_Annotated_Data\DND_U_Id_Class.tsv', sep='\t')
a
a['1017147974999146496']
a['1017147974999146496'].to_csv('D:\Project\Twitter_depression_detector\data\Depression_Annotated_Data (1... | 0.148325 | 0.207998 |
# Crash course in Jupyter and Python
- Introduction to Jupyter
- Using Markdown
- Magic functions
- REPL
- Saving and exporting Jupyter notebooks
- Python
- Data types
- Operators
- Collections
- Functions and methods
- Control flow
- Loops, comprehension
- Packages and name... | github_jupyter | %load_ext rpy2.ipython
import warnings
warnings.simplefilter('ignore', FutureWarning)
df = %R iris
df.head()
%%R -i df -o res
library(tidyverse)
res <- df %>% group_by(Species) %>% summarize_all(mean)
res
%magic
1 + 2
True, False
1, 2, 3
import numpy as np
np.pi, np.e
3 + 4j
'hello, world'
"hell's bells"
"""三轮车跑的快... | 0.23467 | 0.958226 |
```
import numpy as np
from scipy import optimize, interpolate
import pandas as pd
from collections import namedtuple
import os
import shutil
import rwforcReader, rbdoutReader
def read_test_results(fileName):
"""
ToDO
"""
tests_dict = {}
excel = pd.ExcelFile(fileName)
for sheet in excel.sheet_na... | github_jupyter | import numpy as np
from scipy import optimize, interpolate
import pandas as pd
from collections import namedtuple
import os
import shutil
import rwforcReader, rbdoutReader
def read_test_results(fileName):
"""
ToDO
"""
tests_dict = {}
excel = pd.ExcelFile(fileName)
for sheet in excel.sheet_names:... | 0.240239 | 0.416144 |
```
%matplotlib inline
import os
import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
import numpy as np
HOUSING_PATH = os.path.join("datasets", "housing")
def load_housing_data(housing_path=HOUSING_PATH):
'''
return pandas dataframe with all housing data
'''
cs... | github_jupyter | %matplotlib inline
import os
import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
import numpy as np
HOUSING_PATH = os.path.join("datasets", "housing")
def load_housing_data(housing_path=HOUSING_PATH):
'''
return pandas dataframe with all housing data
'''
csv_pa... | 0.57081 | 0.691002 |
```
%matplotlib inline
import gym
import itertools
import matplotlib
import numpy as np
import pandas as pd
import sys
if "../" not in sys.path:
sys.path.append("../")
from collections import defaultdict
from lib.envs.windy_gridworld import WindyGridworldEnv
from lib import plotting
matplotlib.style.use('ggplot'... | github_jupyter | %matplotlib inline
import gym
import itertools
import matplotlib
import numpy as np
import pandas as pd
import sys
if "../" not in sys.path:
sys.path.append("../")
from collections import defaultdict
from lib.envs.windy_gridworld import WindyGridworldEnv
from lib import plotting
matplotlib.style.use('ggplot')
en... | 0.693992 | 0.759983 |
# Making Scalable Graphs with Python
* Importing the MatPlotLib PyPlot tools as plt
* Inline graph display vs saving a graph
* Your created graph will in in the same directory as the notebook that you created it in
* Each time you run the creation cell, you will overwrite the save file
* Basic line graphs, titles, and ... | github_jupyter | import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5], [6, 7,8, 9, 3])
plt.show()
# Write the code to plot the points given in the cell above here
x = [1,2,3,4,5]
y = [5,7,4,8,6]
plt.plot(x, y)
plt.xlabel('x Axis Label Example')
plt.ylabel("y Axis Label Example")
plt.title('Graph Title Example')
plt.show()
# Create ... | 0.693577 | 0.990505 |
```
import igraph as ig
import numpy as np
from sympy.solvers import nsolve
from sympy import *
from scipy.stats import norm
from __future__ import division
import powerlaw as pl
%matplotlib inline
import matplotlib.pyplot as plt
from sympy.solvers import nsolve
from sympy import *
from scipy import special
from scipy ... | github_jupyter | import igraph as ig
import numpy as np
from sympy.solvers import nsolve
from sympy import *
from scipy.stats import norm
from __future__ import division
import powerlaw as pl
%matplotlib inline
import matplotlib.pyplot as plt
from sympy.solvers import nsolve
from sympy import *
from scipy import special
from scipy impo... | 0.262275 | 0.426202 |
### Model
- 3 VGG Blocks
- Regularization: Dropout 20%
- Optimizer: SGD
- Loss: categorical_crossentropy
### Dataset
- Images cropped and resized
- Original Colorscheme
- Scaled in Generator and resized to 300x300x3
```
from google.colab import drive
drive.mount('/content/drive')
import pandas as pd
import numpy as ... | github_jupyter | from google.colab import drive
drive.mount('/content/drive')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras_preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization
from keras.lay... | 0.758063 | 0.804713 |
```
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torchvision import datasets, models, trans... | github_jupyter | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torchvision import datasets, models, transform... | 0.780202 | 0.471649 |
```
import nltk
import random
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
import pickle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from skl... | github_jupyter | import nltk
import random
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
import pickle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn... | 0.501221 | 0.402451 |
```
import pandas as pd
import numpy as np
import itertools
from sklearn.metrics import confusion_matrix,accuracy_score, roc_curve, auc
import matplotlib.pyplot as plt
from tqdm import tqdm
tqdm.pandas()
```
# Summary
We will apply ensemble learning for face recognition models supported in [deepface for python](https... | github_jupyter | import pandas as pd
import numpy as np
import itertools
from sklearn.metrics import confusion_matrix,accuracy_score, roc_curve, auc
import matplotlib.pyplot as plt
from tqdm import tqdm
tqdm.pandas()
# Ref: https://github.com/serengil/deepface/tree/master/tests/dataset
idendities = {
"Angelina": ["img1.jpg", "img2... | 0.449151 | 0.808521 |
# The dataset object
The dataset object reads standard csv files, checks the frequency, and creates the cross validation indicies for training. It is an interface between the data in csv format and then transform function that converts the dataset into an input appropriate for a particular algorithm.
```
import os
i... | github_jupyter | import os
import pandas as pd
import athena
ds = athena.Dataset("../test/data/dfw_demand.csv.gz",
index="timestamp",
freq="30min",
max_days=500,
max_training_days=10,
predition_length=48,
... | 0.189859 | 0.989791 |
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl
import warnings
import sklearn
sklearn.set_config(print_changed_only=True)
mpl.rcParams['legend.numpoints'] = 1
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=Fu... | github_jupyter | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl
import warnings
import sklearn
sklearn.set_config(print_changed_only=True)
mpl.rcParams['legend.numpoints'] = 1
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=Future... | 0.697712 | 0.819641 |
```
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/husein/t5/prepare/mesolitica-tpu.json'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import tensorflow as tf
from pegasus import transformer
vocab_size = 32000
hidden_size = 512
filter_size = 3072
num_encoder_layers = 6
num_decoder_layers = 6
num_heads = 8
... | github_jupyter | import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/husein/t5/prepare/mesolitica-tpu.json'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import tensorflow as tf
from pegasus import transformer
vocab_size = 32000
hidden_size = 512
filter_size = 3072
num_encoder_layers = 6
num_decoder_layers = 6
num_heads = 8
labe... | 0.305697 | 0.223652 |
Precursors!
```
import os, subprocess
if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fa... | github_jupyter | import os, subprocess
if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fai', shell=True)
i... | 0.255251 | 0.744912 |
<div style="width: 100%; clear: both;">
<div style="float: left; width: 50%;">
<img src="http://www.uoc.edu/portal/_resources/common/imatges/marca_UOC/UOC_Masterbrand.jpg", align="left">
</div>
<div style="float: right; width: 50%;">
<p style="margin: 0; padding-top: 22px; text-align:right;">M2.851 - Tipología y ciclo ... | github_jupyter | import sys
print(sys.version)
# Not necessary at all, but to demonstrate that I'm aware that BeautifulSoup4 must be installed
!{sys.executable} -m pip install --upgrade pip
!{sys.executable} -m pip install BeautifulSoup4
from bs4 import BeautifulSoup
from IPython.core.display import display, HTML
from time import sleep... | 0.522933 | 0.870542 |
# Analysis of teams
This notebook contains analyses of teams that participated at the **`Copa America 2021`**. The analyses included are: `Goal contribution`, `Goal scoring`, `Progressive actions`, `Defensive actions`, and others. Inspiration is primarly taken from [@TalkingUnited](https://twitter.com/TalkingUnited).
... | github_jupyter | import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.patheffects as path_effects
import seaborn as sns
from highlight_text import htext
from matplotlib.offsetbox import OffsetImage,AnchoredOffsetbox
from PIL import I... | 0.210036 | 0.837885 |
# Quality metrics
There are two different pruning methods:
- validation,
- direct.
The first group works on trees that is already built. The direct method works while building the tree. In both cases we need to set a testing data set to validate the accuracy.
```
%store -r labels
%store -r data_set
test_labels = [1... | github_jupyter | %store -r labels
%store -r data_set
test_labels = [1,1,-1,-1,1,1,1,-1]
test_data_set = [[1,1,2,2],[3,2,1,2],[2,3,1,2],
[2,2,1,2],[1,3,2,2],[2,1,1,2],
[3,1,2,1],[2,1,2,2]]
import math
import numpy as np
import pydot
import copy
from math import log
class BinaryLeaf:
def __init__(s... | 0.313105 | 0.810591 |
```
from google.colab import drive
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
import imageio
import glob
from skimage import io
imp... | github_jupyter | from google.colab import drive
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
import imageio
import glob
from skimage import io
import ... | 0.846356 | 0.599544 |
# Geometry and Linear Algebraic Operations
:label:`sec_geometry-linear-algebraic-ops`
In :numref:`sec_linear-algebra`, we encountered the basics of linear algebra
and saw how it could be used to express common operations for transforming our data.
Linear algebra is one of the key mathematical pillars
underlying much o... | github_jupyter | v = [1, 7, 0, 1]
%matplotlib inline
from d2l import torch as d2l
from IPython import display
import torch
from torchvision import transforms
import torchvision
def angle(v, w):
return torch.acos(v.dot(w) / (torch.norm(v) * torch.norm(w)))
angle(torch.tensor([0, 1, 2], dtype=torch.float32), torch.tensor([2.0, 3, ... | 0.902446 | 0.995104 |
```
import math
import random
import os
import numpy as np
from comet_ml import API
from matplotlib import pyplot as plt
import pandas as pd
from scipy import stats
COMET_API_KEY="bSyRm6vJpAwfehizXic7Fo0bY"
COMET_REST_API_KEY="S3g50KZWG8zEgk1PLzKUn0eEq"
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
... | github_jupyter | import math
import random
import os
import numpy as np
from comet_ml import API
from matplotlib import pyplot as plt
import pandas as pd
from scipy import stats
COMET_API_KEY="bSyRm6vJpAwfehizXic7Fo0bY"
COMET_REST_API_KEY="S3g50KZWG8zEgk1PLzKUn0eEq"
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y_sm... | 0.388386 | 0.472805 |
# Train-Valid-Test Split EDA / Sanity Check
```
# Import libraries
import numpy as np
import pandas as pd
# Load pickled data
train_df = pd.read_pickle("data/train.pkl")
valid_df = pd.read_pickle("data/val.pkl")
test_df = pd.read_pickle("data/test.pkl")
```
# Assert no users in multiple sets
```
# Unique users in ea... | github_jupyter | # Import libraries
import numpy as np
import pandas as pd
# Load pickled data
train_df = pd.read_pickle("data/train.pkl")
valid_df = pd.read_pickle("data/val.pkl")
test_df = pd.read_pickle("data/test.pkl")
# Unique users in each set
train_users = set(train_df['user_id'])
valid_users = set(valid_df['user_id'])
test_us... | 0.493653 | 0.716727 |
# TITANIC: Wrangling the Passenger Manifest
## Exploratory Analysis with ```Pandas```
On April 15, 1912, the RMS Titanic sunk after hitting an iceberg, killing 1502 out of 2224 passengers and crew about during her maiden voyage. While luck did play a role in the survival of some passengers, certain groups—women ... | github_jupyter | On April 15, 1912, the RMS Titanic sunk after hitting an iceberg, killing 1502 out of 2224 passengers and crew about during her maiden voyage. While luck did play a role in the survival of some passengers, certain groups—women and childen—were much more likely to survive.
In this tutorial you will gain exp... | 0.836688 | 0.987142 |
```
%run ../utils.ipynb
from bs4 import BeautifulSoup
import requests
import sys
import time
import pandas as pd
import numpy as np
import urllib.robotparser as urobot
from tqdm import tqdm_notebook as tqdm
import validators
import os
import threading
import logging
import random
header = {'User-Agent': 'Mozilla/5.0 (... | github_jupyter | %run ../utils.ipynb
from bs4 import BeautifulSoup
import requests
import sys
import time
import pandas as pd
import numpy as np
import urllib.robotparser as urobot
from tqdm import tqdm_notebook as tqdm
import validators
import os
import threading
import logging
import random
header = {'User-Agent': 'Mozilla/5.0 (Maci... | 0.165323 | 0.247919 |
# Women Techsters Fellowship 2021
## Group 3 Mini-project
### Proposal for NLP Search Engine APP
# Project Goals, Scope and Functionality
# Problem
Virtual assistants powered by artificial intelligence have become a commmon feature of the big-data revolution.
Cortana, Google assistant, and Siri are some of the m... | github_jupyter | # Women Techsters Fellowship 2021
## Group 3 Mini-project
### Proposal for NLP Search Engine APP
# Project Goals, Scope and Functionality
# Problem
Virtual assistants powered by artificial intelligence have become a commmon feature of the big-data revolution.
Cortana, Google assistant, and Siri are some of the m... | 0.575349 | 0.810104 |
## Step 3 - Climate Analysis and Exploration
You are now ready to use Python and SQLAlchemy to do basic climate analysis and data exploration on your new weather station tables. All of the following analysis should be completed using SQLAlchemy ORM queries, Pandas, and Matplotlib.
* Create a Jupyter Notebook file cal... | github_jupyter | # Dependencies and boilerplate
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sqlalchemy import Column, Float, Integer, String
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.sql.expression import func
import datetime as dt
# # Use a S... | 0.793746 | 0.980337 |
imports - numpy just to read data
```
import numpy as np
import pandas as pd
from keras.layers import Dense
from keras.models import Sequential
from keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
```
parameter 'patience' is the number of epochs to proceed without improvement
```
early_stopping_... | github_jupyter | import numpy as np
import pandas as pd
from keras.layers import Dense
from keras.models import Sequential
from keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
early_stopping_monitor = EarlyStopping(patience=3)
data_file = 'hourly_wages.csv'
df = pd.read_csv(data_file)
df = df.reindex(np.random.p... | 0.751648 | 0.893402 |
# IMDB movie review sentiment classification with CNNs
In this notebook, we'll train a convolutional neural network (CNN, ConvNet) for sentiment classification using Keras. Keras version $\ge$ 2 is required. This notebook is largely based on the [`imdb_cnn.py` script](https://github.com/keras-team/keras/blob/master/... | github_jupyter | %matplotlib inline
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, MaxPooling1D, GlobalMaxPooling1D
from keras.datasets import imdb
from distutils.version import LooseVe... | 0.725357 | 0.978508 |
SICP 习题 (2.10)解题总结: 区间除法中除于零的问题
SICP 习题 2.10 要求我们处理区间除法运算中除于零的问题。
题中讲到一个专业程序员Ben Bitdiddle看了Alyssa的工作后提出了除于零的问题,大家留意一下这个叫Ben的人,后面会不断出现这个人,只要是这个人提到的事情一般是对的,他的角色定位是个计算机牛人,不过是办公室经常能看到的那种牛人,后面还有更牛的。
对于区间运算的除于零的问题,处理起来也比较简单,只需要判断除数是不是为零,除数为零就报错。对于一个区间来讲,所谓为零就是这个区间横跨0,再直接一点讲就是起点是负数,终点是正数。
理解了以后写代码就很简单了:
```
(define (div... | github_jupyter | (define (div-interval x y)
(if (< (* (upper-bound y) (lower-bound y)) 0)
(error "div-interval" "Div 0: the input y is ~s" y))
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y)))))
(define (make-interval a b)
(cons a b))
(define (lower-bound x)
(car x))
(define (u... | 0.098177 | 0.90599 |
<a href="https://colab.research.google.com/github/ajeyalingam/Pneumonia-Detection/blob/main/pneumonia_detection_old.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
### About Dataset
* The dataset consists of training data, validation data, and test... | github_jupyter | # Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname,... | 0.450601 | 0.911967 |
# When To Invest?
I was wondering how import is timing when making an investment particularly if you have a longer holding period.
We are going to use the data from the the Federal Reserve Bank of St. Louis website more commonly known as FRED. There is a handy function available in the pandas module that will allow u... | github_jupyter | %matplotlib inline
import datetime as dt
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
import pandas as pd
import datetime as dt
import json
import os
import urllib.request
import pandas as pd
import sp500
def get_fed(data_id: str, start_date: str=None, end_date: str=None) -> pd.DataFram... | 0.759136 | 0.90291 |
## Basic training functionality
```
from fastai.basic_train import *
from fastai.gen_doc.nbdoc import *
from fastai.vision import *
from fastai.distributed import *
```
[`basic_train`](/basic_train.html#basic_train) wraps together the data (in a [`DataBunch`](/basic_data.html#DataBunch) object) with a PyTorch model t... | github_jupyter | from fastai.basic_train import *
from fastai.gen_doc.nbdoc import *
from fastai.vision import *
from fastai.distributed import *
show_doc(Learner, title_level=2)
path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
show_doc(Learner.... | 0.792504 | 0.951549 |

# Field Deployment : step by step
## • Step 1 : Mechanical position
### a) Use a bubble level on the mast to ensure the verticality

### b) Move the instrument into a horizontal position and adjus... | github_jupyter | from ipywidgets import HBox, VBox, FloatText, Button
from IPython.display import display
pan = FloatText(description="Pan :")
tilt = FloatText(description="Tilt :")
power = Button(description="Power Relay On")
move = Button(description="Move Pan-Tilt")
@power.on_click
def power_relay_on(_):
from hypernets.script... | 0.522689 | 0.796649 |
#1. Install Dependencies
First install the libraries needed to execute recipes, this only needs to be done once, then click play.
```
!pip install git+https://github.com/google/starthinker
```
#2. Get Cloud Project ID
To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/mast... | github_jupyter | !pip install git+https://github.com/google/starthinker
CLOUD_PROJECT = 'PASTE PROJECT ID HERE'
print("Cloud Project Set To: %s" % CLOUD_PROJECT)
CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE'
print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
FIELDS = {
'auth': 'service', # Credentials used for writing ... | 0.52342 | 0.783575 |
# Setting up Enviroment
```
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import plot_model
from sklearn.model_selection import train_test_split
from ten... | github_jupyter | import os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import plot_model
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import M... | 0.564459 | 0.885384 |
<a href="https://colab.research.google.com/github/aniketsharma00411/sign-language-to-text-translator/blob/main/metric_evaluation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Initialization
```
from google.colab import drive
drive.mount('/conte... | github_jupyter | from google.colab import drive
drive.mount('/content/drive')
from google.colab import files
import os
from keras.preprocessing.image import ImageDataGenerator
from keras import models
from keras.applications import efficientnet
from keras.applications import mobilenet
from sklearn.metrics import classification_report
... | 0.393968 | 0.656493 |
# Classificação de Imagem
O Serviço Cognitivo ***Computer Vision*** fornece modelos pré-construídos úteis para trabalhar com imagens, mas você vai ter que, com certa frequência, treinar o seu próprio modelo de visão computacional. Por exemplo, suponha que a empresa Northwind Traders quer criar um sistema de pagamento ... | github_jupyter | project_id = 'ID_DO_PROJETO'
cv_key = 'SUA_CHAVE'
cv_endpoint = 'SEU_ENDPOINT'
model_name = 'groceries' # esse valor deve ser idêntico ao nome do modelo de quando você publica a iteração do seu modelo (é case-sensitive)
print('Pronto para fazer predição usando o modelo {} no projeto {}'.format(model_name, project_id))... | 0.278944 | 0.74556 |
# VacationPy
----
#### Note
* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.
* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think throug... | github_jupyter | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import gmaps
import os
import json
# Import API key
from api_keys import g_key
weather_df =pd.read_csv('../WeatherPy/output_data/output_data_cities.csv')
# weather_df
# Remove extra index
del weather_df['U... | 0.52683 | 0.856812 |
```
!pip -q install PyGeodesy
!pip -q install numpy
!pip -q install polliwog
!pip -q install folium
from math import pi, sqrt, radians, degrees
import numpy as np
from pygeodesy.datum import Ellipsoid, Ellipsoids
from pygeodesy.vector3d import Vector3Tuple
WGS84 = Ellipsoids.WGS84
KM = 1000
from polliwog.transform.... | github_jupyter | !pip -q install PyGeodesy
!pip -q install numpy
!pip -q install polliwog
!pip -q install folium
from math import pi, sqrt, radians, degrees
import numpy as np
from pygeodesy.datum import Ellipsoid, Ellipsoids
from pygeodesy.vector3d import Vector3Tuple
WGS84 = Ellipsoids.WGS84
KM = 1000
from polliwog.transform.comp... | 0.881793 | 0.514583 |
<small><small><i>
All of these python notebooks are available at https://github.com/kipkurui/Python4Bioinformatics
# Working with strings
## The Print Statement
As seen previously, The **print()** function prints all of its arguments as strings, separated by spaces and follows by a linebreak:
- print("Hello Wor... | github_jupyter | print("Hello","World")
dna="ACGTATA"
dna.count(A)
print("Hello","World",sep='...',end='!!')
?print()
string1='World'
string2='!'
print('Hello' + " "+ string1 + string2 + str(267.00))
print("Hello %s" % string1)
print("Actual Number = %d" %18)
print("Float of the number = %.3f" % 18.87687)
print("Exponential equival... | 0.205296 | 0.944125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.