text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# Solution Notebook
## Problem: Determine if a linked list is a palindrome.
* [Constraints](#Constraints)
* [Test Cases](#Test-Cases)
* [Algorith... | github_jupyter |
```
import warnings
warnings.simplefilter('always', DeprecationWarning)
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
import numpy as np
import math
# from osgeo import gdal_array
# from osgeo import gdalnumeric
import os
import contextlib
import logging
gdal.UseExceptions()
DEBUG=True
logging.... | github_jupyter |
# Setup
```
#Save Checkpoints after each round of active learning
store_checkpoint=True
#Mount persistent storage for logs and checkpoints (Drive)
persistent=False
#Load initial model.
'''
Since there is a need to compare all strategies with same initial model,
the base model only needs to be trained once.
True: W... | github_jupyter |
```
from IPython import get_ipython
```
# part 5: models
construct gastrointestinal leak and VTE risk prediction models
* 'analysis populations' refer to the training, validation, and test populations
## 1. preliminaries
```
get_ipython().run_line_magic('matplotlib', 'inline')
get_ipython().run_line_magic('rel... | github_jupyter |
# pandapower WLS State Estimation
This is an introduction into the usage of the pandapower state estimation module. It shows how to
create measurements for a pandapower network and how to perform a state estimation with the weighted least squares (WLS) algorithm.
## Example Network
We will be using the reference net... | github_jupyter |
# Inference Pipeline with Custom Containers and xgBoost
Typically a Machine Learning (ML) process consists of few steps: data gathering with various ETL jobs, pre-processing the data, featurizing the dataset by incorporating standard techniques or prior knowledge, and finally training an ML model using an algorithm.
I... | github_jupyter |
```
#This notebook organizes a set of Image Quality Metrics from MRIQC to use for outlier detection
# Import some basic tools
import seaborn as sb # I import seaborn as sb a lot of other people use sns but I find that harder to remember
import numpy as np
import json
import pandas as pd
import os
#os.chdir('..')
cwd=o... | github_jupyter |
# Sequence Modeling
* Una secuencia es una coleccion de items ordenada
* ML tradicional asume que la data es independiente e identicamente distribuida (IID)
* Data en secuencia: un punto depende en los puntos que lo preceden o lo siguen.
* Lenguaje: La preposicion "of" es probablemente seguida del articulo "the";
... | github_jupyter |
# Word2Vec Tutorial
In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as "deep learning" (though word2vec itself is rather shallow). Using large amounts of unannotated plain text, word2vec learns relati... | github_jupyter |
This tutorial shows you how to use ETK to extract information for all soccer teams in Italy. Suppose that you want to construct a list of records containing team name, home city, latitude and longitude for every team in Italy.
We start with a Wikipedia page that lists all soccer teams in Italy:
https://en.wikipedia.or... | github_jupyter |
# Using Interact
The `interact` function (`ipywidgets.interact`) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython's widgets.
```
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, in... | github_jupyter |
# How to create Popups
```
import sys
sys.path.insert(0,'..')
import folium
print (folium.__file__)
print (folium.__version__)
```
## Simple popups
You can define your popup at the feature creation, but you can also overwrite them afterwards:
```
m = folium.Map([45,0], zoom_start=4)
folium.Marker([45,-30], popup="... | github_jupyter |
### What is Naive Bayes?
__Naive Bayes__ is among one of the most simple and powerful algorithms for classification based on Bayes’ Theorem with an assumption of independence among predictors. Naive Bayes model is easy to build and particularly useful for very large data sets. There are __two parts__ to this algorithm... | github_jupyter |
# Modeling and Simulation in Python
Chapter 1
Copyright 2020 Allen Downey
License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)
## Jupyter
Welcome to *Modeling and Simulation*, welcome to Python, and welcome to Jupyter.
This is a Jupyter notebook, which is a develo... | github_jupyter |
## assume std is always constant
```
# split the data into a train and validation sets
X1, X2, y1, y2 = train_test_split(X_train, y_train, test_size=0.5)
# base_model can be any regression
modelbase_mode.fit(X1, y1)
base_prediction = base_model.predict(X2)
#compute the RMSE value
error = mean_squared_error(base... | github_jupyter |
# Numerical optimization
You will learn to solve non-convex multi-dimensional optimization problems using numerical optimization with multistart and nesting (**scipy.optimize**). You will learn simple function approximation using linear interpolation (**scipy.interp**).
**Links:**
1. **scipy.optimize:** [overview](h... | github_jupyter |
# Probabilistic Grammar Fuzzing
Let us give grammars even more power by assigning _probabilities_ to individual expansions. This allows us to control how many of each element should be produced, and thus allows us to _target_ our generated tests towards specific functionality. We also show how to learn such probabil... | github_jupyter |
```
import numpy as np
import math
import cv2
from skimage.metrics import structural_similarity
import imutils
import os, sys
import statistics
import os
from prettytable import PrettyTable
import fnmatch
from glob import glob
import time
def psnr(img1, img2):
mse = np.mean( (img1 - img2) ** 2 )
if mse == 0:
... | github_jupyter |
```
from os.path import isfile, join
from os import listdir
import re
import requests
import pandas as pd
OUTPUT_PATH = join('..', 'data')
url = "https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:32015R2450&from=EN"
# amendment 2016
#url = "https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:320... | github_jupyter |
# Given the elmo embeddings pickled, generate the pickled files with them
```
%load_ext autoreload
%autoreload
import os, random, pandas as pd, numpy as np
from sklearn.model_selection import StratifiedKFold
import pickle
import sys
sys.path.append('..')
import relation_extraction.data.utils as utils
import itertools... | github_jupyter |
```
!pip install keras-tuner
from tensorflow.keras.datasets import fashion_mnist
(x_train, _), (x_test, _) = fashion_mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras import laye... | github_jupyter |
## Lecture04 Octave Tutorial
### Basic Operations
**numerical calculation**:
``` Octave
octave:1> 5+6
ans = 11
octave:2> 3-2
ans = 1
octave:3> 5*8
ans = 40
octave:4> 1/2
ans = 0.50000
octave:5> 2^6
ans = 64
```
**logical operation**:
``` Octave
octave:1> 1 == 2
ans = 0
octave:2> 1 ~= 2
ans = 1
octave:3> 1 && ... | github_jupyter |
# Name of the Contributer : SHIRSENDU KONER
# DATASET : 311_Customer_Service_Requests_Analysis
# PACKAGES/MODULES USED : NUMPY, PANDAS, MATPLOTLIB, SEABORN, DATETIME, SCIPY
# --------------------------------------------------------------------------------------------------------------
# <u>Solution :
# 1. Importing ... | github_jupyter |
# Consistent Bayes: Examples from the Paper
---
Copyright 2018 Michael Pilosov
Based on work done by ...
### Import Libraries
_tested with python 3.6 on 02/11/18_
```
# Mathematics and Plotting
from HelperFuns import * # pyplot wrapper functions useful for visualizations, numpy, scipy, etc.
# %matplotlib inline
%ma... | github_jupyter |
# Initialize Folders
```
from __future__ import print_function
from imutils import paths
import os
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import keras
from keras.preprocessing import image as image_utils
from keras.preprocessing.image import load_img
from keras.preprocessing.image import... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
pd.set_option('display.max_columns', 500)
data_path = './data'
idlist_path = '/player_idlist.csv'
players_path = '/players'
season = '/2018-19'
idlist = pd.read_csv(data_path + season + idlist_path)
... | github_jupyter |
```
import numpy as np
import pickle
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
import matplotlib.pyplot as plt
import cv2
from keras.layers import Dense, Input, Dropout, GlobalAveragePooling2D, Flatten, Conv2D, BatchNormalization, Activation, MaxPooling2D
from keras.models import Model, Sequ... | github_jupyter |
# Tools for SUITE Risk-Limiting Election Audits
This Jupyter notebook implements some tools to conduct "hybrid" stratified risk-limiting audits as described in Risk-Limiting Audits by Stratified Union-Intersection Tests of Elections (SUITE), by Ottoboni, Stark, Lindeman, and McBurnett.
For an implementation of tools ... | github_jupyter |
# 第一次作业-预测PM2.5
```
#萌新徒手抓瞎
import numpy as np
import pandas as pd
data=pd.read_csv('train.csv')
data=data[data["object-name"]=="PM2.5"]
data[["1","2"]][:5]
```
## 扒作业答案源码
```
import sys
import numpy as np
import pandas as pd
import csv
raw_data=np.genfromtxt("train.csv",delimiter=',') #读入文件
data=raw_data[1:,2:] #... | github_jupyter |
## What's this TensorFlow business?
You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.
For ... | github_jupyter |
```
# imports
%matplotlib inline
from IPython.display import YouTubeVideo
from IPython.display import Math
import sklearn
from sklearn import datasets, linear_model
from sklearn.linear_model import LinearRegression
import numpy as np
import numpy.random as rng
import matplotlib
import matplotlib.pyplot as plt
#... | github_jupyter |
# A Biblioteca PyQuery
PyQuery nos permite executarmos consultas **jQuery** em documentos XML. A API é bastante similar à biblioteca **[jQuery](https://jquery.com/)**.
PyQuery utiliza **[lxml](https://lxml.de/)** para manipulação rápida de documentos XML e HTML.
Você pode conhecer mais detalhes sobre PyQuery em sua ... | github_jupyter |
# Approach
Use of official APIs from Wikidata and DBpedia to retrieve candidates from the entities discovered. Then, apply a ranking algorithm to select the resource as the best candidate
```
%%capture
!pip install -U sentence-transformers
import nltk
nltk.download('omw-1.4')
nltk.download('wordnet')
from nltk.stem i... | github_jupyter |
# Yolov4 Pytorch 1.7 for Edge Devices with Amazon SageMaker
Amazon SageMaker is a fully managed machine learning service. With SageMaker, data scientists and developers can quickly and easily build and train machine learning models, and then directly deploy them into a production-ready hosted environment. It provides... | github_jupyter |
# Regressor de Posições da Face usando Tensorflow
Neste notebook iremos implementadar um modelo para regressão das posições da face, comumente conhecidas como __roll, pitch e yaw__. Regressão é uma das "tarefas" em que podemos utilizar Machine Learning. Nesta tarefa o ensino é **supervisionado**. Em outras palavras, n... | github_jupyter |
Copyright (c) 2017-2020 [Serpent-Tools developer team](https://github.com/CORE-GATECH-GROUP/serpent-tools/graphs/contributors), GTRC
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND N... | github_jupyter |
# Debug housing price predictions
This notebook demonstrates the use of the `responsibleai` API to assess a classification model trained on Kaggle's apartments dataset (https://www.kaggle.com/alphaepsilon/housing-prices-dataset). The model predicts if the house sells for more than median price or not. It walks through... | github_jupyter |
# Coordinates in Astronomy
Historically the sky was seen as the "celestial sphere" with everything at the same distance away. We're getting better at understanding true distances, but it is still a lot easier to point at a star and say "it's in that direction".
Coordinates on a unit sphere can be specified with two ... | github_jupyter |
<center>
<table style="border:none">
<tr style="border:none">
<th style="border:none">
<a href='https://colab.research.google.com/github/AmirMardan/ml_course/blob/main/6_classical_machine_learning/3_classification_1.ipynb'><img src='https://colab.research.google.com/assets/colab-badge.svg'></a>
</t... | github_jupyter |
(successive_over_relaxation)=
# Successive over-relaxation method
```{index} SOR algorithm
```
A very large proportion of the world's supercomputing capacity is dedicated to solving {ref}`PDEs <pde_basic_partial_differentiation>` - climate and weather simulations, aerodynamics, structural simulations, etc.
PDEs descri... | github_jupyter |
```
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torchvision.datasets import ImageFolder
import os
import random
import itertools
import numpy as np
from PIL import Image
impo... | github_jupyter |
```
import pandas as pd
import numpy as np
import math
```
# Getting the age distribution
```
df = pd.read_excel(
"https://censusindia.gov.in/2011census/C-series/c-13/DDW-2700C-13.xls",
verify=False,
skiprows = 1, header=list(range(0, 3))
).iloc[3:].reset_index(drop = True)
def col_mapper(x):
if ... | github_jupyter |
# Visualization for GIS users
1. Smart mapping - lines - vary by symbol size
2. Smart mapping - polygons - vary by symbol color
- definition queries
- basic plots
3. Smart mapping - points - vary by density
4. Visualizing imagery layers - dynamic raster function
## Smart mapping of line features
```
from ar... | github_jupyter |
```
%matplotlib inline
```
기초부터 시작하는 NLP: 문자-단위 RNN으로 이름 분류하기
********************************************************************************
**Author**: `Sean Robertson <https://github.com/spro/practical-pytorch>`_
**번역**: `황성수 <https://github.com/adonisues>`_
단어를 분류하기 위해 기초적인 문자-단위 RNN을 구축하고 학습 할 예정입니다.
이 튜토리얼... | github_jupyter |
# Getting started with TensorFlow
**Learning Objectives**
1. Practice defining and performing basic operations on constant Tensors
1. Use Tensorflow's automatic differentiation capability
1. Learn how to train a linear regression from scratch with TensorFLow
In this notebook, we will start by reviewing the main... | github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | github_jupyter |
# Tutorial 2 of 3: Digging Deeper into OpenPNM
This tutorial will follow the same outline as **Getting Started**, but will dig a little bit deeper at each step to reveal the important features of OpenPNM that were glossed over previously.
**Learning Objectives**
* Explore different network topologies, and learn some... | github_jupyter |
# DL dia a dia
<a href="https://colab.research.google.com/github/riiaa/Intro_MLDL_19/blob/master/notebooks/2b_DL_dia_a_dia.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul c... | github_jupyter |
# Beginner's Python—Session One Physics/Engineering Questions
## Planck Length
The Planck units are units defined in terms of 4 universal constants, namely the gravitational constant $G$, the (reduced) Planck constant $\hbar$, the speed of light $c$, and the Boltzmann constant $k_B$.
Go to https://bit.ly/3k0m3EK.... | github_jupyter |
```
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 torchvision import datasets, transforms
import numpy as np
import torch.utils.data as utils
import librosa
import soundfile as sf
import time
import os
from torch... | github_jupyter |
```
import os
from keras.models import Sequential
from keras.layers import Dense, add, Activation, MaxPooling2D, Conv2D, Dropout, Flatten
from keras.utils import np_utils
import numpy as np
import matplotlib.image as mpimg
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_spl... | github_jupyter |
```
!nvidia-smi
!pip --quiet install transformers
!pip --quiet install tokenizers
from google.colab import drive
drive.mount('/content/drive')
!cp -r '/content/drive/My Drive/Colab Notebooks/Tweet Sentiment Extraction/Scripts/.' .
COLAB_BASE_PATH = '/content/drive/My Drive/Colab Notebooks/Tweet Sentiment Extraction/'
M... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# How to u... | github_jupyter |
<h1> Explore and create ML datasets </h1>
In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the c... | github_jupyter |
# Getting Started
A simple example that demostrates (a) how to load existing data, or (b) generate your own dataset, followed by a learning task with 4 models.
### Load other modules
```
import argparse
import pandas
import numpy.random as random
import sklearn.metrics
import time
pandas.options.mode.chained_assignm... | github_jupyter |
# Эвристики для расстояния Левенштейна
Расстояние Левенштейна двух последовательностей символов -- это количество вставок, замен и уалений, которые нужно произвести над отдельными символами первой последовательности, чтобы получить вторую. Основные понятия и базовый способ подсчета через динамическое программирование о... | github_jupyter |
# Chapter 8. Pythonic Code 1
## Split
**String Type**의 값을 나눠서 **List** 형태로 변환<br/>
string.split() : 빈 칸을 기준으로 string split<br/>
string.split(",") : , 기준으로 string split<br/>
unpacking과 자주 함께 쓰임<br/>
```
#example 1: string.split()
items = 'zero one two three'.split()
print(items)
#example 2: unpacking & string.split(... | github_jupyter |
# Spark Structured Streaming and Delta Tables
Spark provides support for streaming data through *Spark Structured Streaming* and extends this support through *delta tables* that can be targets (*sinks*) or *sources* of streaming data.
In this exercise, you'll use Spark to ingest a stream of data from a folder of JSON... | github_jupyter |
```
# Run this cell before the lab !
# It will download PascalVOC dataset (400Mo) and
# pre-computed representations of images (450Mo)
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import os.path as op
import tarfile
try:
from urllib.request import urlretrieve
except ImportError: # Pytho... | github_jupyter |
```
import os
import numpy as np
import matplotlib.pyplot as plt
import sys
from EMAN2 import *
from sklearn.decomposition import PCA
from sklearn import cluster,mixture
plt.gray();
os.environ["CUDA_VISIBLE_DEVICES"]='0'
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"]='true'
import tensorflow as tf
## in theory float16 also ... | github_jupyter |
# Parallelization with TFDS
In this week's exercise, we'll go back to the classic cats versus dogs example, but instead of just naively loading the data to train a model, you will be parallelizing various stages of the Extract, Transform and Load processes. In particular, you will be performing following tasks:
1.... | github_jupyter |
# Introduction to building Autoencoders

Autoencoders (AE) are a family of neural networks for which the input is the same as the output.
They work by compressing the input into a latent-space representation, and then reconstructing the output from this repr... | github_jupyter |
## 케라스 콜백 사용 준비하기
```
from tensorflow.keras.datasets import mnist
# 텐서플로우 저장소에서 데이터를 다운로드 받습니다.
(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')
from sklearn.model_selection import train_test_split
# 훈련/검증 데이터를 얻기 위해 0.7/0.3의 비율로 분리합니다.
x_train, x_val, y_train, y_val = train_test_split(x_tra... | github_jupyter |
```
import torch
from dpp_nets.my_torch.simulator2 import SimulRegressor
from dpp_nets.helper.plotting import plot_floats, plot_dict
# Global Settings
input_set_size = 50
n_clusters = 20
dtype = torch.DoubleTensor
path = '/Users/Max/Desktop/master thesis/latex/figures/plots'
# Deterministic Network To see how difficult... | github_jupyter |
# Обнаружение объектов
*Обнаружение объектов* — это форма компьютерного зрения, в которой модель машинного обучения обучена классифицировать отдельные экземпляры объектов на изображении и обозначает *ограничивающие прямоугольники*, отмечающие местоположение объектов. Можно рассматривать это как переход от *классифик... | github_jupyter |
# Jupyter Notebook to develop a Model for accurate prediction of Diabetes through Machine Learning Algorithms
## In our analysis, we will use three Machine Learning Algorithms: Logistic Regression, Naive Bayes and Support Vector
```
#Importing important modules and library to perform our Data Analysis and Machine Lea... | github_jupyter |
```
import os
import numpy as np
from astropy import units as u
from astropy import coordinates
from astropy.io import fits
import matplotlib.pyplot as plt
import aplpy
%matplotlib inline
```
### Read the output of <code>SExtractor</code>
We extract the source with threshold 3 sigma
```
def read_sexofile(filename ... | github_jupyter |
# Principles and Theory of SAR Interferometry
Notebook author: Paul A. Rosen, Jet Propulsion Laboratory, California Institute of Technology
Contributors to content include: Scott Hensley, Anthony Freeman, Jakob van Zyl, Piyush Agram, Howard Zebker
This notebook presents the basics of synthetic aperture radar i... | github_jupyter |
# DEMO: Running FastCAM for the Exceptionally Impatient
### Import Libs
```
import os
from IPython.display import Image
```
Lets load the **PyTorch** Stuff.
```
import torch
import torch.nn.functional as F
from torchvision.utils import make_grid, save_image
import warnings
warnings.filterwarnings('ignore')
```
No... | github_jupyter |
```
!pip install git+https://github.com/ericsuh/dirichlet.git
import numpy as np
import dirichlet
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.da... | github_jupyter |
# MAT281
## Aplicaciones de la Matemática en la Ingeniería
## Módulo 1
### Clase 02: Data Science Toolkit
# ¿Qué contenidos aprenderemos?
* [Sistema Operativo](#so)
* [Interfaz de Línea de Comandos](#cli)
* [Entorno Virtual](#venv)
* [Python](#python)
* [Project Jupyter](#jupyter)
* [Git](#git)
## Objetivos de la... | github_jupyter |
# Vertex AI: Qwik Start
## Learning objectives
* Train a TensorFlow model locally in a hosted [**Vertex Notebook**](https://cloud.google.com/vertex-ai/docs/general/notebooks?hl=sv).
* Create a [**managed Tabular dataset**](https://cloud.google.com/vertex-ai/docs/training/using-managed-datasets?hl=sv) artifact for exp... | github_jupyter |
# **1-1. Tensor Manipulation**
**Jonathan Choi 2021**
**[Deep Learning By Torch] End to End study scripts of Deep Learning by implementing code practice with Pytorch.**
If you have an any issue, please PR below.
[[Deep Learning By Torch] - Github @JonyChoi](https://github.com/jonychoi/Deep-Learning-By-Torch)
## Im... | github_jupyter |
# 3. Linear Models for Regression
```
import numpy as np
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
%matplotlib inline
from prml.preprocess import GaussianFeature, PolynomialFeature, SigmoidalFeature
from prml.linear import (
BayesianRegression,
EmpiricalBayesRegression,
L... | github_jupyter |
# Relation extraction using distant supervision: experiments
```
__author__ = "Bill MacCartney and Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2021"
```
## Contents
1. [Overview](#Overview)
1. [Set-up](#Set-up)
1. [Building a classifier](#Building-a-classifier)
1. [Featurizers](#Featurizers)
1. [E... | github_jupyter |
```
from sklearn import datasets
import matplotlib.pyplot as plt
import matplotlib.animation
import seaborn as sns
%matplotlib inline
sns.set(style = 'ticks' , palette = 'Set2')
import pandas as pd
import numpy as np
import math
from __future__ import division
data = datasets.load_iris()
X = data.data[:100,:2]
y = dat... | github_jupyter |

# Data Cleaning
*ACC online course, Institute of Cognitive Science, University of Osnabrueck*
## Prerequisites
For this chapter, you should be familiar with the following concepts and techniques:
* Basic Python programming
* Working with Pandas
* Statistical Analysis
... | github_jupyter |
```
#default_exp torch_core
#export
from local.test import *
from local.core.all import *
from local.torch_imports import *
from fastprogress import progress_bar,master_bar
from local.notebook.showdoc import *
from PIL import Image
#export
_all_ = ['progress_bar','master_bar']
#export
if torch.cuda.is_available(): torc... | github_jupyter |
```
import os, sys
import h5py
import numpy as np
import corner as DFM
# -- galpopfm --
from galpopfm.catalogs import Catalog
from galpopfm import dustfm as dustFM
from galpopfm import dust_infer as dustInfer
from galpopfm import measure_obs as measureObs
# -- plotting --
import matplotlib as mpl
import matplotlib.py... | github_jupyter |
# Boston Housing Price Dataset
Find more information here : https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html#sphx-glr-auto-examples-preprocessing-plot-all-scaling-py
<p><b>Status: <span style=color:orange;>In progress</span></b></p>
##### LOAD THE DATA
Build the dataset from the datas... | github_jupyter |
<a href="https://colab.research.google.com/github/maitysuvo19/News-Articles-Classification/blob/main/Real_news_rnn_LIME.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import os
import pandas as pd
import numpy as np
!unzip news.zip -d news
# St... | github_jupyter |
<a href="https://colab.research.google.com/github/QuickLearner171998/CapsNet/blob/master/Traffic_Sign_Classifier.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
from google.colab import drive
drive.mount('/content/drive',force_remount=True)
# %... | github_jupyter |
## Train locally
### Import training data
For illustration purposes we will use the MNIST dataset. The following code downloads the dataset and puts it in `./mnist_data`.
The first 60000 images and targets are the original training set, while the last 10000 are the testing set. The training set is ordered by the l... | github_jupyter |
```
import pandas as pd
import numpy as np
import datetime
```
# This is buoy data
This datacomes from NOAA. The station is 42040: LUKE OFFSHORE TEST PLATFORM - 63 NM South of Dauphin Island, AL.
See https://www.ndbc.noaa.gov/station_history.php?station=42040
```
def read_file(fname, has_second_header=True):
if h... | github_jupyter |
```
import pandas as pd
df_1 = pd.read_csv('../noislamophobia-dataset-50k.csv')
df_2 = pd.read_csv('../noislamophobia-dataset-75k.csv')
df = pd.concat([df_1,df_2])
df.head()
df.columns
df = df.drop_duplicates()
df.head()['entities'][0]
df.shape
df['created_at'][0]
df['geo'].value_counts()
df['text'][0]
df_na = df.drop... | github_jupyter |
# Assignment 2: Costs and States
_See [Assignment 2: Costs and States](https://sikoried.github.io/sequence-learning/02/cost-and-states/)._
## Keyboard Aware Auto-Correct
In the previous assignment, we applied uniform cost to all substitutions.
This does not really make sense if you look at a keyboard: the QWERTY la... | github_jupyter |
```
from datetime import timedelta
import numpy as np
from time import time
import sys
from lib.data import load_data
start = time()
X, y = load_data('data.csv')
end = time()
print 'Data loading done in', timedelta(seconds=end - start)
data_size = 80000
start = time()
X_normal = X[y == 0]
X_fraud = X[y == 1]
y_normal ... | github_jupyter |
## Attribution Extraction Tutorial
> Tutorial author: 陶联宽(22051063@zju.edu.cn)
In this tutorial, we use `pretrain_language model` to extract attributions.
We hope this tutorial can help you understand the process of construction knowledge graph and the principles and common methods of triplet extraction.
This tutoria... | github_jupyter |
# Classification: Instant Recognition with Caffe
In this example we'll classify an image with the bundled CaffeNet model (which is based on the network architecture of Krizhevsky et al. for ImageNet).
We'll compare CPU and GPU modes and then dig into the model to inspect features and the output.
### 1. Setup
* Firs... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import seaborn as sns
from os.path import join
plt.style.use(["seaborn", "thesis"])
plt.rc("figure", figsize=(8,4))
```
# Dataset
```
data_path = "../../dataset/EthenT/"
postfix = "EthenT"
dim = 72
N_ELECTRON... | github_jupyter |
### Matrix Diagonalization
Consider a $n \times n$ matrix $A_{n, n}$ with $n$ linearly independent eigenvectors.
<br> Let $S_{n,n}$ be a matrix with these eigenvectors as its columns.
<br>Then $A_{n,n}$ can be factorized as
$$
A = S \Sigma S^{-1}
$$
where $\Sigma$ is a diagonal matrix (all off-digonal elements are zero... | github_jupyter |
# A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed representation of the input. Then, this representation is passed through a decoder to reconstruct the input data. Generally the encoder... | github_jupyter |
```
from bert_embedding import BertEmbedding
import sys
import os
sys.path.append("..")
from globals import ROOT_DIR
from data_providers import TextDataProvider
import argparse
import configparser
from torch import optim
from experiment_builder import ExperimentBuilder
from data_providers import *
import os
from models... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/gdrive')
cd /content/gdrive/My Drive/Colab Notebooks/NLP/BERT_SQUAD
!pip install transformers==3.5.1
import json, collections, os, random, glob, math, string, re, torch
import numpy as np
import timeit
from tqdm import trange, tqdm_notebook as tqdm
from torch.ut... | github_jupyter |
This is a modified version of the code published by TensorFlow https://www.tensorflow.org/alpha/tutorials/text/nmt_with_attention
##### Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
# Neural Machine Translation with Attention
```
from __future__ import absolu... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import savemat, loadmat
from imp import reload
#import DCA stuff
from dca import analysis
from dca import data_util
from dca import plotting
#import FastKF (todo: import installable package once FastKF is finalized)
import sys
sys.path.append("/User... | github_jupyter |
```
from cropclass import tsmask
import gippy
import gippy.algorithms as alg
import numpy as np
import pandas as pd
import os
import re
# For modeling
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
fr... | github_jupyter |
## Pipelines In SkLearn
```
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.tree impo... | github_jupyter |
```
import datetime
import matplotlib.pyplot as plt
import math
import numpy as np
import os
import torch
from torchvision import datasets
```
# Get MNIST data
```
def generate_pair_sets():
data_dir = os.environ.get('PYTORCH_DATA_DIR')
if data_dir is None:
data_dir = './data'
train_set = datasets... | github_jupyter |
# Probabilistic Language Models
How can we assign a probability to a sentence?
P(high winds tonight) > P(large winds tonight)
How do we do a proper spell correction?
- The office is about fifteen **minuets** from my house
P(about fifteen minutes from) > P(about fifteen minuets from)
... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.