text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
import os
import numpy as np
import matplotlib.pyplot as plt
from pymedphys.level1.mudensity import *
from pymedphys.level1.mudensity import (
_determine_reference_grid_position, _determine_leaf_centres
)
def single_mlc_pair(left_mlc, right_mlc, grid_resolution, time_steps=50):
leaf_pair_widths = [grid_r... | github_jupyter |
# Degrading the data
What happens when we lower the retirement limit of a galaxy? Can we still recover meaningful spiral arms?
This is the question we explore in this chapter: we take our 47 classifications and obtain samples of ten
```
%matplotlib inline
%load_ext autoreload
%autoreload 2
import matplotlib.pyplot a... | github_jupyter |
# Defining a grid from scratch
In this example we are going to create a grid just by using GrdiCal's comands and we will run a power flow study.
```
import pandas as pd
import numpy as np
from GridCal.Engine import *
%matplotlib inline
```
Let's create a new grid object:
```
grid = MultiCircuit(name='lynn 5 bus')... | github_jupyter |
# Convolutional neural networks for CIFAR-10 data
* Cifar-10 data를 가지고 자신만의 **convolutional neural networks**를 만들어보자.
* [참고: TensorFlow.org](https://www.tensorflow.org/get_started/mnist/pros)
* [`tf.layers` API](https://www.tensorflow.org/api_docs/python/tf/layers)
* [`tf.contrib.layers` API](https://www.tensorf... | github_jupyter |
# Modelos de Secuencias
### Intermedios
* Las tareas de prediccion de secuencias requiren que etiquetemos cada item en una secuencia
* Estas tareas son comunes en NLP:
* _language modeling_: predecir la siguiente palabra dada una secuencia de palabras en cada paso.
* _named entity recognition_: predecir si cad... | github_jupyter |
# List And Dictionaries
## LIST
```
from IPython.display import Image
Image('images/lists.jpeg')
```
### How to create a list?
```
# empty list
my_list = []
print(my_list)
from IPython.display import Image
Image('images/empty list.png')
# list of integers
my_list = [1, 2, 3]
print(my_list)
# Adding the values irre... | github_jupyter |
### Previous knowledge
https://github.com/ScienceParkStudyGroup/studyGroup/blob/gh-pages/lessons/20171010_Intro_to_Python_Like/1hr_python_workshop.ipynb
# Pipelines in Python
Reproducability is pivotal in science.
Reproducability means that you or someone else can replicate exactly what you have done and check whet... | github_jupyter |
<a href="https://colab.research.google.com/github/yvonneleoo/Real-Time-Voice-Swapping/blob/master/voice_swapping_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# Clone git repo
!git clone https://github.com/thegreatwarlo/Real-Time-Voice-Sw... | github_jupyter |
# Challenge: Billboard Top 100 dataset
Este conjunto de datos representa la clasificación semanal de las canciones desde el momento en que ingresan al Billboard Top 100 hasta las 75 semanas siguientes.
### Problemas:
- Los encabezados de las columnas se componen de valores: el número de semana (x1st.week,…)
- Si una c... | github_jupyter |
# Notebook03: POPC/POPE mixture
In this notebook, we will show you how to reconstruct hydrogens, calculate the order parameters and produce output trajectories on a POPC/POPE (50:50) mixture. Again, this example is based on the Berger united-atom force field.
Before going on, we advise you to get started with [Notebo... | github_jupyter |
**Note**: Click on "*Kernel*" > "*Restart Kernel and Run All*" in [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) *after* finishing the exercises to ensure that your solution runs top to bottom *without* any errors. If you cannot run this file on your machine, you may want to open it [in the cloud <img heigh... | github_jupyter |
# Lab2: Variables, Statements, Expressions and Operators
#### Student: Juan Vecino
#### Group: B
#### Date: 15/09/2020
### Lab 2.2 User Input in Python
```
name = input("Write your name and hit ENTER:\n")
print("The name you enter was:", name)
```
### Lab 2.3 Even or Odd
```
number = input("Que número escoges?")
p... | github_jupyter |
# Imports
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from lets_plot import *
from typing import List, Optional, Union
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
def to_scalar(x, i):
"""... | github_jupyter |
# Language Translation
## Get the Data
```
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
```
## Explore the Data
```
view_sentence_range = (0, 10)
impor... | github_jupyter |
# Scraping JavaScript data ("dynamic webpages")
### by [Jason DeBacker](http://jasondebacker.com), October 2017 (with thanks to [Adam Rennhoff](http://mtweb.mtsu.edu/rennhoff/) )
This notebook provides a tutorial and examples showing how to scrape webpages with JavaScript data.
## Example: scrape the store locations ... | github_jupyter |
<a href="https://colab.research.google.com/github/Machine-Learning-Tokyo/DL-workshop-series/blob/master/Part%20II%20-%20Learning%20in%20Deep%20Networks/custom_loss_functions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## Custom loss functions
-... | github_jupyter |
Exercise 4 - Polynomial Regression
===
Sometimes our data doesn't have a linear relationship, but we still want to predict an outcome.
Suppose we want to predict how satisfied people might be with a piece of fruit. We would expect satisfaction would be low if the fruit is under-ripe or over-ripe, and satisfaction wou... | github_jupyter |
```
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from index_data_handler import IndexDataHandler
```
# Simulating Returns
In our past analysis we tried to figure out the best portfolio for us. In this analysis we want to see: *What can we expect from a given porfoli... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import itertools
%matplotlib inline
```
## Introduction
In this notebook, we explore how 6 genes are distributed in different types of cells. Most of the genes can't co-exist in one type of cell. The data file path is hard coded.
```
genes = {
"RBFOX3":"ENSG000... | github_jupyter |
<h2>IMDB sentiment analysis</h2>
Deep Learning using Word Embedding for the IMDB sentiment analysis dataset.
Based on <a href="https://machinelearningmastery.com/predict-sentiment-movie-reviews-using-deep-learning/">How to Predict Sentiment From Movie Reviews Using Deep Learning (Text Classification)</a>.
<h3>Imports... | github_jupyter |
<a href="https://colab.research.google.com/github/Tessellate-Imaging/Monk_Object_Detection/blob/master/example_notebooks/5_pytorch_retinanet/Train%20Resnet18%20-%20With%20validation%20Dataset.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Install... | github_jupyter |
# Running EnergyPlus from Eppy
It would be great if we could run EnergyPlus directly from our IDF wouldn’t it?
Well here’s how we can.
```
# you would normaly install eppy by doing
# python setup.py install
# or
# pip install eppy
# or
# easy_install eppy
# if you have not done so, uncomment the following three lin... | github_jupyter |
# H2O.ai GPU Edition Machine Learning $-$ Multi-GPU GBM Demo
### In this demo, we will train 16 gradient boosting models (aka GBMs) on the Higgs boson dataset, with the goal to predict whether a given event in the particle detector stems from an actual Higgs boson.
### The dataset is about 500MB in memory (2M rows, 2... | github_jupyter |
# PCA for Algorithmic Trading: Data-Driven Risk Factors
PCA is useful for algorithmic trading in several respects. These include the data-driven derivation of risk factors by applying PCA to asset returns, and the construction of uncorrelated portfolios based on the principal components of the correlation matrix of as... | github_jupyter |
## Non Compliance Experiment=1
Test top norms for different w_nc
```
import sys
sys.path.append('../src')
import yaml
from IPython.utils import io
from tqdm.notebook import tqdm
from pathlib import Path
import pandas as pd
import numpy as np
from mcmc_norm_learning.algorithm_1_v4 import to_tuple
def write_log(output,p... | github_jupyter |
```
import numpy as np
import pylab as plt
%matplotlib inline
import tqdm, json
from frbpa.search import pr3_search, riptide_search, p4j_search
from frbpa.utils import get_phase
with open('r3_data.json', 'r') as f:
r3_data = json.load(f)
r3_data.keys()
burst_dict = r3_data['bursts']
startmjds_dict = r3_data['obs_st... | github_jupyter |
The change in the CMB intensity due to Compton scattering of CMB
photons off of thermal electrons in galaxy clusters, otherwise known as the
Sunyaev-Zeldovich (S-Z) effect, can to a reasonable approximation be represented by a
projection of the pressure field of a cluster. However, the *full* S-Z signal is a combinatio... | github_jupyter |
# Introduction
Run this notebook to create an analytical application for the SBM charge - based of the Equity Delta Example. The input data will be stored in-memory and Atoti will perform the computation "on-the-fly" based on user query. You can filter, drill down and explore your data and the SBM metrics.
<img src=.... | github_jupyter |
```
# Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = 'congratulations' + '!!!'
# Print shout_word
print(shout_word)
# Call shout
shout()
# Define shout with the parameter, word
def shout(word):
"""Pri... | github_jupyter |
# Themes
## Introduction
- elements, like `plot.title`, `legend.key.height`...
- associated element function, like `element_text()` to set the font size
- `theme()`, use it like `theme(plot.title = element_text(colour = "red"))`
- Complete themes, like `theme_grey()`
```
library(ggplot2)
library(repr)
options(repr.p... | github_jupyter |
<p align="center">
<img width="100%" src="../../../multimedia/mindstorms_51515_logo.png">
</p>
# `hello_world`
Python equivalent of the `Hello World` program. Displays an image and plays a sound using the hub.
# Required robot
* Charlie (head)
<img src="../multimedia/charlie_head.png" width="50%" align="center">
... | github_jupyter |
<table align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/ShopRunner/collie/blob/main/tutorials/03_advanced_matrix_factorization.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://... | github_jupyter |
```
from collections import defaultdict, OrderedDict
import warnings
import gffutils
import pybedtools
import pandas as pd
import copy
import os
import re
from gffutils.pybedtools_integration import tsses
from copy import deepcopy
from collections import OrderedDict, Callable
import errno
def mkdir_p(path):
try:
... | github_jupyter |
## TL streamfunction
```
import warnings
warnings.filterwarnings("ignore") # noqa
# Data analysis and viz libraries
import aeolus.calc as acalc
import aeolus.coord as acoord
import aeolus.meta as ameta
import aeolus.plot as aplt
import iris
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from ... | github_jupyter |
```
import numpy as np
import pandas as pd
import itertools
import collections
import re
import operator
import os
import ast
from multiprefixspan import *
import time
```
# Small Data: event with single item executed by a function for signle events
```
db = [
[0, 1, 2, 3, 4],
[1, 1, 1, 3, 4],
[2, 1, 2, 2... | github_jupyter |
```
# It is convention to import numpy as `np`
import numpy as np
```
# Arrays
You can make an array from a regular python list of numbers.
```
np.array([1, 7, 4, 2])
```
There are also functions for making specific arrays, such as a range of numbers. For example, make an array from 0 to 9:
```
a = np.arange(10)
... | github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True)
def trend(time, slope=0):
ret... | github_jupyter |
# Coin Toss (MLE, MAP, Fully Bayesian) in TF Probability
- toc: true
- badges: true
- comments: true
- author: Nipun Batra
- categories: [ML, TFP, TF]
### Goals
We will be studying the problem of coin tosses. I will not go into derivations but mostly deal with automatic gradient computation in TF Probability.
We ... | github_jupyter |
# Lab_3 TCV3151 Computer Vision
Bagja 9102 Kurniawan <br> **1211501345**
## Preparatory Work
```
#Mount Google Drive.
from google.colab import drive
drive.mount('/content/gdrive')
#Import the packages.
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
## Question 1: Contrast Stretc... | github_jupyter |
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys
from time import time
import os
%pylab inline
pylab.rcParams['figure.figsize'] = (20.0, 10.0)
%load_ext autoreload
%autoreload 2
sys.path.append('..')
import isolation
import sample_players
import run_match
import my_baseline_play... | github_jupyter |
```
%pylab inline
import sys
import os.path as op
import shutil
# sys.path.insert(0, "/home/mjirik/projects/pyseg_base/")
sys.path.insert(0, op.abspath("../"))
import scipy
import time
import pandas as pd
import platform
import itertools
from pathlib import Path
import lisa
from imcut import pycut
import sed3
latex_d... | github_jupyter |
# How-to Finetune
This tutorial shows how to adapt a pretrained model to a different, eventually much smaller dataset, a concept called finetuning. Finetuning is well-established in machine learning and thus nothing new. Generally speaking, the idea is to use a (very) large and diverse dataset to learn a general under... | github_jupyter |
<font size="+5">#01 | Machine Learning & Linear Regression</font>
<div class="alert alert-warning">
<ul>
<li>
<b>Python</b> + <b>Data Science</b> Tutorials in ↓
<ul>
<li>
<a href="https://www.youtube.com/c/PythonResolver?sub_confirmation=1"
>YouTube</a
>
... | github_jupyter |
```
import os
import zlib
corona = """
1 attaaaggtt tataccttcc caggtaacaa accaaccaac tttcgatctc ttgtagatct
61 gttctctaaa cgaactttaa aatctgtgtg gctgtcactc ggctgcatgc ttagtgcact
121 cacgcagtat aattaataac taattactgt cgttgacagg acacgagtaa ctcgtctatc
181 ttctgcaggc tgcttacggt ttcgtccgtg ttgcagccga tcatcag... | github_jupyter |
```
! pip install transformers -q
! pip install tokenizers -q
import re
import os
import sys
import json
import ast
import pandas as pd
from pathlib import Path
import matplotlib.cm as cm
import numpy as np
import pandas as pd
from typing import *
from tqdm.notebook import tqdm
from sklearn.utils.extmath import softmax... | github_jupyter |
# Cross-Entropy Method
The cross-entropy (CE) method is a Monte Carlo method for importance sampling and optimization. It is applicable to both combinatorialand continuous problems, with either a static or noisy objective.
The method approximates the optimal importance sampling estimator by repeating two phases:[1]
1.... | github_jupyter |
```
entities = {'self', 'addressee', 'other'}
```
### 1 entity referent
* self ("me")
* addressee ("you here")
* other ("somebody else")
### 2+ entity referent
* self, addressee ("me and you here" / inclusive we)
* self, other ("me and somebody else" / exclusive we)
* addressee, addressee ("the two or more of you her... | github_jupyter |
```
import requests
import textacy
import tarfile
from fastcore.utils import Path
import pandas as pd
Path.ls = lambda x: list(x.iterdir())
from typing import Dict
def extract(tar_url, extract_path='.')->None:
"""Function to extract tar files
Args:
tar_url ([type]): [description]
extract_path ... | github_jupyter |
## Summary
We face the problem of predicting tweets sentiment.
We have coded the text as Bag of Words and applied an SVM model. We have built a pipeline to check different hyperparameters using cross-validation. At the end, we have obtained a good model which achieve an AUC of **0.92**
## Data loading and cleaning
... | github_jupyter |
<a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/21_export_map_to_html_png.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a>
Uncomment the following line to install [geemap](https://geemap.org) if needed.
```
# !pip ins... | github_jupyter |
```
from policy import NEATProperty, PropertyArray, properties_to_json
from cib import CIB
from pib import PIB, NEATPolicy
```
# Application Request
We consider an application that would like to open a new TCP connection using NEAT to a destination host `d1` with the IP `10.1.23.45`. Further, if possible, the MTU of ... | github_jupyter |
```
import os
import re
def update_dict(data_dict, key, img_name):
"""Keeps track of how many images each pokemon has"""
if key in data_dict:
data_dict[key]['count'] += 1
data_dict[key]['img_names'].append(img_name)
else:
data_dict[key] = {'count': 1, 'img_names': [img_name]}
re... | github_jupyter |

# Setup
```
from arcgis import GIS
gis = GIS('https://python.playground.esri.com/portal', 'arcgis_python')
counties_item = gis.content.search('USA Counties', 'Feature Layer', sort_field='avgRating',
outside_org=True)[0]
counties_item
counties = counties_item.layers[0]
c... | github_jupyter |
If Statements
===
By allowing you to respond selectively to different situations and conditions, if statements open up whole new possibilities for your programs. In this section, you will learn how to test for certain conditions, and then respond in appropriate ways to those conditions.
What is an *if* statement?
===
... | github_jupyter |
# CHSH不等式の破れを確認する
この最初の実習では、量子コンピュータにおいて量子力学的状態、特に「**エンタングルメント**」が実現しているか検証してみましょう。実習を通じて量子力学の概念と量子コンピューティングの基礎を紹介していきます。
```{contents} 目次
---
local: true
---
```
$\newcommand{\ket}[1]{|#1\rangle}$
## 本当に量子コンピュータなのか?
このワークブックの主旨が量子コンピュータ(QC)を使おう、ということですが、QCなんて数年前までSFの世界の存在でした。それが今やクラウドの計算リソースとして使えるというわけですが、ではそもそも私... | github_jupyter |
# Alexnet insights: visualizing the pruning process
This notebook examines the results of pruning Alexnet using sensitivity pruning, through a few chosen visualizations created from checkpoints created during pruning. We also compare the results of an element-wise pruning session, with 2D (kernel) regularization.
Fo... | github_jupyter |
```
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time, datetime
import nibabel as nib
from sklearn.model_selection import train_test_split
from scipy.ndimage.interpolation import zoom
from nitorch.data import load_nifti
from settings import settings
from tabulate ... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

s3 = ... | github_jupyter |
# Description: this program uses an artificial recurrent neural netwrok called Long Short Term Memory (LSTM) to predict the closing price of an Index (S&P 500) using the past 60 day Index price.
```
# Import the libraries
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.p... | github_jupyter |
## Title: Holdridge Life-Zones
### Description
Holdridge's work aimed to correlate world plant formations with simple climatic data. The system embraces all major environmental factors in three hierarchical tiers. Level I - The Life Zone. This is determined by specific quantitative ranges of long-term average annual pr... | github_jupyter |
## Neural Networks
Mathematically this looks like:
$$
\begin{align}
y &= f(w_1 x_1 + w_2 x_2 + b) \\
y &= f\left(\sum_i w_i x_i +b \right)
\end{align}
$$
With vectors this is the dot/inner product of two vectors:
$$
h = \begin{bmatrix}
x_1 \, x_2 \cdots x_n
\end{bmatrix}
\cdot
\begin{bmatrix}
w_... | github_jupyter |
# Name
Data preparation using SparkSQL on YARN with Cloud Dataproc
# Label
Cloud Dataproc, GCP, Cloud Storage, YARN, SparkSQL, Kubeflow, pipelines, components
# Summary
A Kubeflow Pipeline component to prepare data by submitting a SparkSql job on YARN to Cloud Dataproc.
# Details
## Intended use
Use the component... | github_jupyter |
```
# st_dataframe -> stationary values
# bm_dataframe -> body massage values
# hos_dataframe -> hospital values
from geopy.geocoders import Nominatim # module to convert an address into latitude and longitude values
import requests # library to handle requests
import pandas as pd # library for data analsysis
import nu... | github_jupyter |
```
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.mllib.tree import DecisionTree, DecisionTreeModel
from pyspark.mllib.util import MLUtils
import pandas as pd
from pyspark.mllib.linalg import SparseVector
from pyspark.mllib.regression import LabeledPoint
sc = SparkCo... | github_jupyter |
# Introduction to Data Engineering
```
## The database schema
# Complete the SELECT statement
data = pd.read_sql("""
SELECT first_name, last_name FROM "Customer"
ORDER BY last_name, first_name
""", db_engine)
# Show the first 3 rows of the DataFrame
print(data.head(3))
# Show the info of the DataFrame
print(data.in... | github_jupyter |
# AoC Day 10
Jenna Jordan
10 December 2021
## Prompt
--- Day 10: Syntax Scoring ---
You ask the submarine to determine the best route out of the deep-sea cave, but it only replies:
`Syntax error in navigation subsystem on line: all of them`
All of them?! The damage is worse than you thought. You bring up a copy ... | github_jupyter |
### If you like this kernel greatly appreciate an UP VOTE
# Two Sigma Stock Prediction
## Introduction
<img src="http://i65.tinypic.com/2im5eno.jpg">
Can we use the content of news analytics to predict stock price performance? The ubiquity of data today enables investors at any scale to make better investment dec... | github_jupyter |
# Redis
REmote DIctionary Service is a key-value database.
- [Official docs](https://redis.io/documentation)
- [Use cases](https://redislabs.com/solutions/use-cases/)
- More about [redis-py](https://github.com/andymccurdy/redis-py)
## Concepts
Redis is a very simple database conceptually. From a programmer perspect... | github_jupyter |
# Developing an AI application
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall appli... | github_jupyter |
<a href="https://colab.research.google.com/github/darthwaydr007/kaggle/blob/master/Plant_pathology_updated1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Setup
```
!pip uninstall torch -y
!pip uninstall torchvision -y
!pip install torch==1.4.0 ... | github_jupyter |
```
import numpy as np
from tensorly import kruskal_to_tensor, kron
from tensorly.tenalg import khatri_rao
from sporco.linalg import fftconv, fftn, ifftn
from sporco.metric import snr
from scipy import linalg
from scipy.sparse import csr_matrix, hstack, kron, identity, diags
from scipy.sparse.linalg import eigsh
import... | github_jupyter |
```
import sys
sys.path.append("/mnt/home/TF_NEW/tf-transformers/src/")
import datasets
import json
import os
import glob
import time
from tf_transformers.models import GPT2Model
from transformers import GPT2Tokenizer
from tf_transformers.data.squad_utils_sp import (
read_squad_examples)
from tf_transformers.data ... | github_jupyter |
# T81-558: Applications of Deep Neural Networks
**Module 10: Time Series in Keras**
**Part 10.1: Time Series Data Encoding for Deep Learning**
* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/P... | github_jupyter |
# This is a simplified version of my 18th place solution in the **Shopee - Price Match Guarantee** contest
## I replaced my image models with resnet18 to showcase that even a very basic model could do well and was enough to score a silver medal in this competition
# The outline of my approach
### Step 1 training
I u... | github_jupyter |
```
import os
import sys
import ast
import pandas as pd
import seaborn as sns
import pathlib
import numpy as np
import matplotlib.pyplot as plt
import fbprophet as pro
%matplotlib inline
```
# 1. Importing data
## 1.1 Pageview and revisions
```
combined_data = pd.read_csv('../data/test15/cleaned/combined.csv')
com... | github_jupyter |
# Recommending movies: retrieval
**Learning Objectives**
In this notebook, we're going to build and train such a two-tower model using the Movielens dataset.
We're going to:
1. Get our data and split it into a training and test set.
2. Implement a retrieval model.
3. Fit and evaluate it.
4. Export it for efficient ... | github_jupyter |
```
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=20, random_state=4)
def plot_KMeans(n):
model = KMeans(n_clusters=2, init="random", n_init=1, max_iter=n, random_state=6).fit(X)
c0, c1 = model.cluster_centers_
plt.scatter(X[model.labels_ == 0, 0], ... | github_jupyter |
# Plots of Classification Results
Load imports
```
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
```
Create arrays containing the data.
```
training_set_sizes_proportional = [12, 60, 120, 600, 1200, 6000, 12000, 60000, 72488]
training_set_sizes_balanced = [12, 60, 120, 600, 1200, 6000]
#----... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.svm import SVC
from sklearn import metrics
from mlxtend.plotting import plot_decision_regions
from sklearn import preprocessing
from skl... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Evaluation-Functions" data-toc-modified-id="Evaluation-Functions-1"><span class="toc-item-num">1 </span>Evaluation Functions</a></span></li><li><span><a href="#Show-ground-truth-only" data-toc-mo... | github_jupyter |
# **Packages and Modules**
Quando trabalhamos com testes unitarios muitas vezes estamos preocupados com o ***coverage***. Essa métrica mostra qual a porcentagem das linhas dos nossos arquivos que estão passando por testes.
Suponha a seguinte estrutura de diretório:
```shell
.
├── src
│ ├── example
│ │ └── fun... | github_jupyter |
This notebook will be a short review of key concepts in python. The goal of this notebook is to jog your memory and refresh concepts.
#### Table of contents
* Jupyter notebook
* Libraries
* Plotting
* Pandas DataFrame manipulation
* Unit testing
* Randomness and reproducibility
* Bonus: list comprehension
## Jupyte... | github_jupyter |
## Dependencies
```
import json, glob
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras import layers
from tensorflow.keras.models import Model
```
# Load ... | github_jupyter |
# Lambda School Data Science Module 143
## Introduction to Bayesian Inference
!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_v... | github_jupyter |
```
import tensorflow as tf
node1 = tf.constant(3.0, dtype= tf.float32)
node2 = tf.constant(4.0)
sess = tf.Session()
print(sess.run([node1, node2]))
print(sess.run([node1,node2]))
node3 = tf.add(node1,node2)
print("Addition is : ", sess.run([node3]))
M = tf.Variable(.6 ,dtype=tf.float32)
C = tf.Variable(-.6, dtype = t... | github_jupyter |
# Support Vector Machines
```
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns; sns.set()
from sklearn.datasets.samples_generator import make_blobs
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.6)
plt.scatter(X[:,0], X[:,1], c = Y, s = 50, cma... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from importlib import reload
from deeprank.dataset import DataLoader, PairGenerator, ListGenerator
from deeprank import utils
seed =... | github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | github_jupyter |
# <center/>使用PyNative进行神经网络的训练调试体验
## 概述
在神经网络训练过程中,数据是否按照自己设计的神经网络运行,是使用者非常关心的事情,如何去查看数据是怎样经过神经网络,并产生变化的呢?这时候需要AI框架提供一个功能,方便使用者将计算图中的每一步变化拆开成单个算子或者深层网络拆分成多个单层来调试观察,了解分析数据在经过算子或者计算层后的变化情况,MindSpore在设计之初就提供了这样的功能模式--`PyNative_MODE`,与此对应的是`GRAPH_MODE`,他们的特点分别如下:
- PyNative模式:也称动态图模式,将神经网络中的各个算子逐一下发执行,方便用户编写和调试神经网络模型。
-... | github_jupyter |
```
import tensorflow as tf
import numpy as np
from tqdm import tqdm
maxlen = 20
max_vocab = 20000
word2idx = tf.keras.datasets.imdb.get_word_index()
word2idx = {k: (v + 4) for k, v in word2idx.items()}
word2idx['<PAD>'] = 0
word2idx['<START>'] = 1
word2idx['<UNK>'] = 2
word2idx['<END>'] = 3
idx2word = {i: w for w, i i... | github_jupyter |
Copyright (c) Microsoft Corporation.<br>
Licensed under the MIT License.
# 1. Collect Data from the Azure Percept DK Vision
In this notebook we will:
- Learn how to connect to cameras on the dev kit and collect data
**Prerequisites to run the notebooks if have not completed already**
Follow the `readme.md` for info... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Gena/map_center_object.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href=... | github_jupyter |
```
%matplotlib inline
```
Model Freezing in TorchScript
=============================
In this tutorial, we introduce the syntax for *model freezing* in TorchScript.
Freezing is the process of inlining Pytorch module parameters and attributes
values into the TorchScript internal representation. Parameter and attribu... | github_jupyter |
# Types
We have so far encountered several different 'types' of Python object:
- integer numbers, for example `42`,
- real numbers, for example `3.14`,
- strings, for example `"abc"`,
- functions, for example `print`,
- the special 'null'-value `None`.
The built-in function `type` when passed a single argument wi... | github_jupyter |
```
import numpy as np
from qiskit import *
from qiskit.circuit import Qubit
from qiskit.quantum_info import Statevector
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
```
Based on the adaptation of Möttönen et al's paper "Transformation of quantum states using uniformly controlled rotatio... | github_jupyter |
# Kaplan-Meier Estimation
[Run this notebook on Colab](https://colab.research.google.com/github/AllenDowney/SurvivalAnalysisPython/blob/master/02_kaplan_meier.ipynb)
This notebook introduces Kaplan-Meier estimation, a way to estimate a hazard function when the dataset includes both complete and incomplete cases.
To d... | github_jupyter |
```
import pandas as pd
from matplotlib import pyplot as plt
pd.options.display.max_columns = None
%matplotlib inline
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:80% !important; }</style>"))
df = pd.read_csv('../data/raw/train.csv')
df.head()
df.shape
df['MachineIdentifier']... | github_jupyter |
```
import pandas as pd
import numpy as np
##### Scikit Learn modules needed for Decision Trees
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import ... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.