code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# Mining Twitter
Twitter implements OAuth 1.0A as its standard authentication mechanism, and in order to use it to make requests to Twitter's API, you'll need to go to https://developer.twitter.com/en/apps and create a sample application. It is possible that Twitter no longer supports sandboxed applications and you ma... | github_jupyter |
```
"""
Today we will be looking at the 2 Naive Bayes classification algorithms SeaLion has to offer - gaussian and multinomial (more common).
Both of them use the same underlying principles and as usual we'll explain them step by step.
"""
# first import
import sealion as sl
from sealion.naive_bayes import Gaussian... | github_jupyter |
<a href="https://colab.research.google.com/github/Sid-Oya/DS-Unit-2-Linear-Models/blob/master/DSPT7_LESSON_Unit_2_Sprint_1_Module_1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Lambda School Data Science
*Unit 2, Sprint 1, Module 1*
---
# Regr... | github_jupyter |
<a href="https://colab.research.google.com/github/Wee7/FinancialEngineering_IR_xVA/blob/main/FE_xVA_code.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Lecture 02- Understanding of Filtrations and Measures
```
#%% Martingale.py
"""
Created on Ju... | github_jupyter |
<h1><center>Deep Learning Helping Navigate Robots</center></h1>
<img src="https://storage.googleapis.com/kaggle-competitions/kaggle/13242/logos/thumb76_76.png?t=2019-03-12-23-33-31" width="300"></img>
### Dependencies
```
import warnings
import cufflinks
import numpy as np
import pandas as pd
import seaborn as sns
im... | github_jupyter |
# TV Script Generation
In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will gen... | github_jupyter |
# Introduction to Deep Learning with PyTorch
In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tenso... | github_jupyter |
## Explore The Data: Plot Categorical Features
Using the Titanic dataset from [this](https://www.kaggle.com/c/titanic/overview) Kaggle competition.
This dataset contains information about 891 people who were on board the ship when departed on April 15th, 1912. As noted in the description on Kaggle's website, some peo... | github_jupyter |
```
%matplotlib inline
```
# Tensors
Tensors are a specialized data structure that are very similar to arrays and matrices.
In PyTorch, we use tensors to encode the inputs and outputs of a model, as well as the model’s parameters.
Tensors are similar to [NumPy’s](https://numpy.org/) ndarrays, except that tensors ca... | github_jupyter |
# Deep Learning & Art: Neural Style Transfer
Welcome to the second assignment of this week. In this assignment, you will learn about Neural Style Transfer. This algorithm was created by Gatys et al. (2015) (https://arxiv.org/abs/1508.06576).
**In this assignment, you will:**
- Implement the neural style transfer alg... | github_jupyter |
## Evaluate CNTK Fast-RCNN model directly from python
This notebook demonstrates how to evaluate a single image using a CNTK Fast-RCNN model.
For a full description of the model and the algorithm, please see the following <a href="https://docs.microsoft.com/en-us/cognitive-toolkit/Object-Detection-using-Fast-R-CNN" t... | github_jupyter |
# Predicting Review rating from review text
# <span style="color:dodgerblue"> Naive Bayes Classifier Using 5 Classes (1,2,3,4 and 5 Rating)</span>
```
%pylab inline
import warnings
warnings.filterwarnings('ignore')
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "a... | github_jupyter |
# Exact Cover問題
最初にExact Cover問題について説明します。
ある自然数の集合Uを考えます。またその自然数を含むいくつかのグループ$V_{1}, V_{2}, \ldots, V_{N}$を想定します。1つの自然数が複数のグループに属していても構いません。さて、そのグループ$V_{i}$からいくつかピックアップしたときに、それらに同じ自然数が複数回含まれず、Uに含まれる自然数セットと同じになるようにピックアップする問題をExact Cover問題といいます。
さらに、選んだグループ数を最小になるようにするものを、Smallest Exact Coverといいます。
## 準備
```
%matplot... | github_jupyter |
# Preprocessing
Source: https://www.kaggle.com/c/GiveMeSomeCredit/
```
import os
import numpy as np
import pandas as pd
import config as cfg
from sklearn.model_selection import train_test_split
from imblearn.under_sampling import RandomUnderSampler
from pandas_profiling import ProfileReport
pd.set_option("display.m... | github_jupyter |
# Bayesian optimization
## Introduction
Many optimization problems in machine learning are black box optimization problems where the objective function $f(\mathbf{x})$ is a black box function<sup>[1][2]</sup>. We do not have an analytical expression for $f$ nor do we know its derivatives. Evaluation of the function ... | github_jupyter |
# Simple genetic algorithm
## Step-by-step implementation
```
import numpy as np
# initiate random number generator
seed = 1
rng = np.random.default_rng(seed)
# population number
population_size = 4
# initialize the population
population = list()
for i in range(population_size):
gene = rng.integers(low=0, high=... | github_jupyter |
# Introduction to optimization
The basic components
* The objective function (also called the 'cost' function)
```
import numpy as np
objective = np.poly1d([1.3, 4.0, 0.6])
print(objective)
```
* The "optimizer"
```
import scipy.optimize as opt
x_ = opt.fmin(objective, [3])
print("solved: x={}".format(x_))
%matplo... | github_jupyter |
# Other programming languages
**Today we talk about various programming languages:** If you have learned one programming language, it is easy to learn the next.
**Different kinds** of programming languages:
1. **Low-level, compiled (C/C++, Fortran):** You are in full control, but need to specify types, allocate memo... | github_jupyter |
```
import pickle
import codecs
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.python.layers.core import Dense
import time
from nltk.corpus import stopwords
from os import listdir
import re
class BasePreprocessor:
"""The abstract class for a preprocessor. You should subclass
this... | github_jupyter |
```
import networkx as nx
from custom import load_data as cf
from networkx.algorithms import bipartite
from nxviz import CircosPlot
import numpy as np
import matplotlib.pyplot as plt
%load_ext autoreload
%autoreload 2
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
```
# Introduction
Bipartite grap... | github_jupyter |
```
import numpy as np
from scipy.stats import binom, norm, multinomial
from scipy.special import comb
```
### Solution 1
```
# 변수 초기화
n = 25
p = 0.1
## 직접 계산
# a)
probs = [(comb(n, i) * (p**i) * ((1-p)**(n-i))) for i in range(4)]
prob = 1 - sum(probs)
print(f"a) 적어도 4대가 검은 색: {prob:.4f}")
# b)
probs = [(comb(n, i)... | github_jupyter |
# Introduction
In the [Intro to SQL micro-course](https://www.kaggle.com/learn/intro-to-sql), you learned how to use [**INNER JOIN**](https://www.kaggle.com/dansbecker/joining-data) to consolidate information from two different tables. Now you'll learn about a few more types of **JOIN**, along with how to use **UNION... | github_jupyter |
<a name='main'></a>
# **AI IN PRACTICE : HOW TO TRAIN AN IMAGE CLASSIFIER**
### **Author: Sheetal Reddy**
### **Contact : sheetal.reddy@ai.se**
---
**Introduction**
The training "AI in Practice" will give you, at a basic level, knowledge about how to train a pre-trained model, the pre-requisites, what techniques tha... | github_jupyter |
```
!pip install transformers datasets tweet-preprocessor ray[tune] hyperopt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import wordcloud
import preprocessor as p # tweet-preprocessor
import nltk
import re
import seaborn as sns
import torch
from transformers import BertTokenizer, B... | github_jupyter |
```
import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from fastapi import FastAPI
import uv... | github_jupyter |
```
import pandas as pd
fin = pd.read_pickle('fin.pkl')
mc = pd.read_pickle('mc.pkl')
info = pd.read_pickle('info.pkl')
```
# 전략
* input = 날짜
* output = 종목별 투자비중
```
date = '2018-12-31' # input
fisyear = 2017
position = fin['매출액'].xs(fisyear, level=1).nlargest(10)
position[:] = 1/len(position); position # output; [:... | github_jupyter |
# Finding cellular regions with superpixel analysis
**Overview:**
Whole-slide images often contain artifacts like marker or acellular regions that
need to be avoided during analysis. In this example we show how HistomicsTK can
be used to develop saliency detection algorithms that segment the slide at low
magnificatio... | github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import pathlib
from tqdm import tqdm
f... | github_jupyter |
```
# General imports
import numpy as np
import pandas as pd
import os, sys, gc, time, warnings, pickle, psutil, random
warnings.filterwarnings('ignore')
# :seed to make all processes deterministic # type: int
def seed_everything(seed=0):
random.seed(seed)
np.random.seed(seed)
# Read data
def get_data_by_s... | github_jupyter |
### Bag of words model
```
# load all necessary libraries
import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
pd.set_option('max_colwidth', 100)
```
#### Let's build a basic bag of words model on three sample docume... | github_jupyter |
# 📃 Solution for Exercise M2.01
The aim of this exercise is to make the following experiments:
* train and test a support vector machine classifier through
cross-validation;
* study the effect of the parameter gamma of this classifier using a
validation curve;
* study if it would be useful in term of classificat... | github_jupyter |
# Improve accuracy of pdf batch processing with Amazon Textract and Amazon A2I
In this chapter and this accompanying notebook learn with an example on how you can use Amazon Textract in asynchronous mode by extracting content from multiple PDF files in batch, and sending specific content from these PDF documents to an... | github_jupyter |
import modules and get command-line parameters if running as script
```
from probrnn import models, data, inference
import numpy as np
import json
from matplotlib import pyplot as plt
from IPython.display import clear_output
```
parameters for the model and training
```
params = \
{
"N_ITERATIONS": 10 *... | github_jupyter |
```
import numpy as np
import pandas as pd
import os
import json
import time
from IPython.display import clear_output
from IPython.display import HTML
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import colors
import numpy as np
from skimage.segmentation import flood, flood_fill
... | github_jupyter |
# Inference and Validation
Now that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen... | github_jupyter |
# Point Spread Function Photometry with Photutils
The PSF photometry module of photutils is intended to be a fully modular tool such that users are able to completly customise the photometry procedure, e.g., by using different source detection algorithms, background estimators, PSF models, etc. Photutils provides impl... | github_jupyter |
```
import numpy as np
from astropy.table import Table, join, MaskedColumn, vstack
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import scipy
from astropy.time import Time
import pandas as pd
import re
import seaborn as sns
import datetime
from datetime import datetime
from datetime import timedelt... | github_jupyter |
# Inexact Move Function
Let's see how we can incorporate **uncertain** motion into our motion update. We include the `sense` function that you've seen, which updates an initial distribution based on whether a robot senses a grid color: red or green.
Next, you're tasked with modifying the `move` function so that it i... | github_jupyter |
# 🦌 RuDOLPH 350M
<b><font color="white" size="+2">Official colab of [RuDOLPH: One Hyper-Modal Transformer can be creative as DALL-E and smart as CLIP](https://github.com/sberbank-ai/ru-dolph)</font></b>
<font color="white" size="-0.75."><b>RuDOLPH</b> is a fast and light text-image-text transformer (350M GPT-3) for... | github_jupyter |
# Quantitative omics
The exercises of this notebook correspond to different steps of the data analysis of quantitative omics data. We use data from transcriptomics and proteomics experiments.
## Installation of libraries and necessary software
Copy the files *me_bestprobes.csv* and _AllQuantProteinsInAllSamples.csv_... | github_jupyter |
<table><tr>
<td style="background-color:#ffffff;text-align:left;"><a href="http://qworld.lu.lv" target="_blank"><img src="../images/qworld.jpg" width="30%" align="left"></a></td>
<td style="background-color:#ffffff;"> </td>
<td style="background-color:#ffffff;vertical-align:text-middle;text-align:righ... | github_jupyter |
<img src="https://s8.hostingkartinok.com/uploads/images/2018/08/308b49fcfbc619d629fe4604bceb67ac.jpg" width=500, height=450>
<h3 style="text-align: center;"><b>Физтех-Школа Прикладной математики и информатики (ФПМИ) МФТИ</b></h3>
***Some parts of the notebook are almost the exact copy of [ML-MIPT course](https://githu... | github_jupyter |
# Laboratorio: Convolutional Neural Networks
En este laboratorio, vamos a trabajar con Convolutional Neural Networks para resolver un problema de clasificación de imágenes. En particular, vamos a clasificar imágenes de personajes de la conocida serie de los Simpsons.
Como las CNN profundas son un tipo de modelo basta... | github_jupyter |
```
import torch
import gym
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
env = gym.make('Acrobot-v1')
env.seed(0)
print('State shape: ', env.observation_space.shape)
print('Number of actions:... | github_jupyter |
```
#STA 663 Final Project
#Juncheng Dong, Xiaoqiao Xing
#May 2020
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
from numpy import linalg as la
import random
from sklearn.cross_decomposition import PLSRegression
from sklearn.linear_model import Ridge
from sklearn.model_selectio... | github_jupyter |
## 15.9.1 Loading the IMDb Movie Reviews Dataset (1 of 2)
* Contains **25,000 training samples** and **25,000 testing samples**, each **labeled** with its positive (1) or negative (0) sentiment
```
from tensorflow.keras.datasets import imdb
```
* **Over 88,000 unique words** in the dataset
* Can specify **number of u... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
cd 'drive/My Drive/Colab Notebooks/machine_translation'
from dataset import MTDataset
from model import Encoder, Decoder
from language import Language
from utils import preprocess
from train import train
from eval import validate
from ... | github_jupyter |
<a href="https://colab.research.google.com/github/gathoni/hypothesis_testing/blob/master/Hypthesis_Testing_Redo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# **Autolib Dataset**
## **1.1 INTRODUCTION**
### **1.1.1 Defining the question**
Inve... | github_jupyter |
```
import warnings
import pprint
import skrebate
import imblearn
from imblearn import under_sampling, over_sampling, combine
from imblearn.pipeline import Pipeline as imbPipeline
from sklearn import (preprocessing, svm, linear_model, ensemble, naive_bayes,
tree, neighbors, decomposition, kernel_app... | github_jupyter |

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/FractionMultiplication/Frac... | github_jupyter |
# Transfer Learning Template
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
... | github_jupyter |
# Web_Crawling
## 하루 시작을 알리는 크롤링 프로젝트
- 하루를 시작하면서 자동으로 내가 원하는 정보를 모아서 메세지로 보내주는 서비스가 있으면 좋겠다 생각했습니다. 기존의 서비스는 제가 원하지 않는 정보가 있어 더이상 찾거나 결재를 하지 않았지만 이번 기회로 직접 만들자 생각이 들어 시작하게 되었습니다.

## 크롤링 사이트
### 다음 뉴스
1. [media.daum.net](https://media.daum.net/)

### 케이웨더
2. [www.kweathe... | github_jupyter |
# <img style="float: left; padding-right: 10px; width: 45px" src="https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png"> CS109B Data Science 2: Advanced Topics in Data Science
## Homework 7: Generative Models - Variational Autoencoders and GANs [100 pts]
**Harvard University**<... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
#export
from exp.nb_07 import *
```
## Layerwise Sequential Unit Variance (LSUV)
### paper: https://arxiv.org/pdf/1511.06422.pdf
Getting the MNIST data and a CNN
[Jump_to lesson 11 video](https://course.fast.ai/videos/?lesson=11&t=235)
```
x_train,y_train,x... | github_jupyter |
# 1 - Sequence to Sequence Learning with Neural Networks
In this series we'll be building a machine learning model to go from once sequence to another, using PyTorch and torchtext. This will be done on German to English translations, but the models can be applied to any problem that involves going from one sequence to... | github_jupyter |
```
conda install pandas
conda install numpy
conda install matplotlib
pip install plotly
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from scipy import stats
import warnings
%matplotlib inline
warnings.filterwarnings("ignore")
from sklearn.mod... | github_jupyter |
# Cleaning up the academy awards dataset and creating a SQLite table
```
import pandas as pd
academy_awards = pd.read_csv("academy_awards.csv", encoding = "ISO-8859-1")
academy_awards.head()
for column in academy_awards.columns:
print("No. of unique values in '{0}' are".format(column),len(academy_awards[column].... | github_jupyter |
```
import pandas as pd
import numpy as np
# Tools
from collections import Counter
import pickle
# Preprocessing & Selections
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.preprocessing import MinMaxScaler
from sklearn.feature_selection import SelectKBest, chi2, f_classif
from sklearn.mod... | github_jupyter |
# mlforecast
> Scalable machine learning based time series forecasting.
**mlforecast** is a framework to perform time series forecasting using machine learning models, with the option to scale to massive amounts of data using remote clusters.
[
To compare the means of two independent samples of internval or ratio data (assuming the samples are from normally distributed populations having equal variance) we can do a t-test. But what if you have more than two groups that you want to compare? You could do multiple t-tests... | github_jupyter |
```
import pandas as pd
from sklearn.metrics import mean_squared_error
from scipy.optimize import curve_fit
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
def logistic_model(x, a, b, c):
return c / (1 + np.exp(-(x - b) / a))
def exponen... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
```
# Forecast like observations
Use observation files to produce new files that fit the shape of a forecast file.
That makes them easier to use for ML purposes.
At the core of this task is the forecast_like_observations provided by the organizers.
This notebooks loads the appro... | github_jupyter |
```
import pandas as pd
import pandera as pa
valores_ausentes = ['**','###!','####','****','*****','NULL']
df = pd.read_csv("data.csv", sep=";", parse_dates=['ocorrencia_dia'], dayfirst=True, na_values=valores_ausentes)
df.head(10)
schema = pa.DataFrameSchema(
columns = {
"codigo_ocorrencia": pa.Column(pa.I... | github_jupyter |
Author: Xi Ming.
## Build a Multilayer Perceptron from Scratch based on PyTorch.
PyTorch's automatic differentiation mechanism can help quickly implement multilayer perceptrons.
### Import Packages.
```
import torch
import torchvision
import torch.nn as nn
from torchvision import datasets,transforms
from torch.util... | github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
os.system('rm -rf tacotron2-female-alignment')
os.system('mkdir tacotron2-female-alignment')
import tensorflow as tf
import numpy as np
from glob import glob
import tensorflow as tf
import malaya_speech
import malaya_speech.train
from malaya_speech.train.model imp... | github_jupyter |
```
import numpy as np
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
# Problem data
reservations = np.array([110, 118, 103, 161, 140])
flight_capacities = np.array([100, 100, 100, 150, 150])
cost_per_hour = 50
cost_external_company = 75
# Build transportation grah
G = nx.DiGraph()
# Add node... | github_jupyter |
```
import tempfile
import urllib.request
train_file = "datasets/thermostat/sample-training-data.csv"
test_file = "datasets/thermostat/test-data.csv"
import pandas as pd
COLUMNS = ["month", "day", "hour", "min", "pirstatus",
"isDay", "extTemp", "extHumidity", "loungeTemp", "loungeHumidity",
"state... | github_jupyter |
```
%matplotlib inline
from datetime import date
import pandas as pd
import urllib.request
import xmltodict
from ipywidgets import HTML
from ipyleaflet import *
import configparser
config = configparser.ConfigParser()
config.read("config.cfg")
import math
axis = None # Semi-major axis of the ellipsoid.
flattening = N... | github_jupyter |
# Fuzzing APIs
So far, we have always generated _system input_, i.e. data that the program as a whole obtains via its input channels. However, we can also generate inputs that go directly into individual functions, gaining flexibility and speed in the process. In this chapter, we explore the use of grammars to synth... | github_jupyter |
```
#Copyright 2020 Vraj Shah, Arun Kumar
#
#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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in w... | github_jupyter |
```
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | github_jupyter |
# Poincare Map
This example shows how to calculate a simple Poincare Map with REBOUND. A Poincare Map (or sometimes calles Poincare Section) can be helpful to understand dynamical systems.
```
import rebound
import numpy as np
```
We first create the initial conditions for our map. The most interesting Poincare maps ... | github_jupyter |
```
#import libraries
import rasterio as rs
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import math
from osgeo import gdal
from rasterio.plot import show
import os
print('*********** Libraries were imported successfuly **********')
print('working directory: '+ str(os.getcwd()))
#load clas... | github_jupyter |
```
import os
import sys
from tqdm import trange
from tqdm import tqdm
from skimage.util import montage
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import medmnist
from medm... | github_jupyter |
Perform SVM with PCA operation on Breast Cancer Dataset and Iris Dataset.
With Breast Cancer Dataset
```
from sklearn import datasets
breast_cancer = datasets.load_breast_cancer()
breast_data = breast_cancer.data
breast_labels = breast_cancer.target
print(breast_data.shape)
print(breast_labels.shape)
import numpy as... | github_jupyter |
```
import gaussianfft
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import cdist
from gaussianfft.util import EmpiricalVariogram
%matplotlib inline
plt.rcParams['figure.figsize'] = [15,7]
def filter_deltas(m, d):
# Filter nans
deltas_nan = np.array(d)
nan_cols = np.any(np.i... | github_jupyter |
# Creating a class
```
class Student: # created a class "Student"
name = "Tom"
grade = "A"
age = 15
def display(self):
print(self.name,self.grade,self.age)
# There will be no output here, because we are not invoking (calling) the "display" function to print
```
##... | github_jupyter |
# Linear Discriminant Analysis (LDA)
## Importing the libraries
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
```
## Importing the dataset
```
dataset = pd.read_csv('Wine.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
```
## Splitting the dataset into the Training... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
# Inference PyTorch Bert Model with ONNX Runtime on CPU
In this tutorial, you'll be introduced to how to load a Bert model from PyTorch, convert it to ONNX, and inference it for high performance using ONNX Runtime. In the foll... | github_jupyter |
```
args = {
'model_name':'2019_04_11_DRIVE',
'FP':'float16',
'optimizer': 'Adam', #SGD, RMSprop, Adadelta, Adagrad, Adam, Adamax, Nadam
'dataset':['101/training_data.csv', '102/training_data.csv', '103/training_data.csv', '104/training_data.csv', '105/training_data.csv', '106/training_data.csv', '107/t... | github_jupyter |
## Import libraries
```
from google.colab import drive
from pathlib import Path
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import time
import os
import csv
import concurrent.futures
```
## Utility functions
### Create annot and load descriptors
```
def create_annot(path):
image_l... | github_jupyter |

[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/NER_TUMOR.ipynb)
# **Detect tumor characteri... | github_jupyter |
```
!pip install chart_studio
import plotly.graph_objects as go
import plotly.offline as offline_py
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import plotly.figure_factory as ff
import numpy as np
%matplotlib inline
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/DSEI21000-... | github_jupyter |
```
# 加载文本分类数据集
from sklearn.datasets import fetch_20newsgroups
import random
newsgroups_train = fetch_20newsgroups(subset='train')
newsgroups_test = fetch_20newsgroups(subset='test')
X_train = newsgroups_train.data
X_test = newsgroups_test.data
y_train = newsgroups_train.target
y_test = newsgroups_test.target
print(... | github_jupyter |
# MDP from multidimensional HJB
see [pdf](https://github.com/songqsh/foo1/blob/master/doc/191206HJB.pdf) for its math derivation
see souce code at
- [py](hjb_mdp_v05_3.py) for tabular approach and
- [py](hjb_mdp_nn_v05.py) for deep learning approach
```
import numpy as np
import time
#import ipdb
import itertools... | github_jupyter |
# Code Reuse
Let’s put what we learned about code reuse all together.
<br><br>
First, let’s look back at **inheritance**. Run the following cell that defines a generic `Animal` class.
```
class Animal:
name = ""
category = ""
def __init__(self, name):
self.name = name
def set_catego... | github_jupyter |
```
!nvidia-smi
import sys
if 'google.colab' in sys.modules:
!pip install -Uqq fastcore onnx onnxruntime sentencepiece seqeval rouge-score
!pip install -Uqq --no-deps fastai ohmeow-blurr
!pip install -Uqq transformers datasets wandb
from fastai.text.all import *
from fastai.callback.wandb import *
from tran... | github_jupyter |
```
import pandas as pd
import numpy as np
from pathlib import Path
dir_path = Path().resolve().parent / 'demand_patterns'
low_patterns = "demand_patterns_train_low.csv"
fullrange_patterns = "demand_patterns_train_full_range.csv"
combined_pattern = 'demand_patterns_train_combined.csv'
comb = pd.read_csv(dir_path / com... | github_jupyter |
# Practical 7. Assignment 3.
Due date is March 7, before the class. You can work with a partner
Partner: Mohamed Salama, utorid: salamam5
## Problem 1. Your first MD simulation.
Read through section 6 and example 6.1-6.2 of the lecture. Run 3 simulations of fully extended polyglycine `data/polyGLY.pdb` for 1 nanose... | github_jupyter |
<h3>Cleaning Bad data
-Strip white space
-Replace bad data
-Fill missing data
-Drop bad data
-Drop duplicate
```
import pandas as pd
data = pd.read_csv('artwork_data.csv',low_memory=False)
data.head(2)
#finding data which has any white space
data.loc[data['title'].str.contains('\s$',... | github_jupyter |
# Interfaces
In Nipype, interfaces are python modules that allow you to use various external packages (e.g. FSL, SPM or FreeSurfer), even if they themselves are written in another programming language than python. Such an interface knows what sort of options an external program has and how to execute it.
## Interface... | github_jupyter |
<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 |
# Configuring pandas
```
# import numpy and pandas
import numpy as np
import pandas as pd
# used for dates
import datetime
from datetime import datetime, date
# Set some pandas options controlling output format
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 8)
pd.set_option('... | github_jupyter |
# Wind Statistics
### Introduction:
The data have been modified to contain some missing values, identified by NaN.
Using pandas should make this exercise
easier, in particular for the bonus question.
You should be able to perform all of these operations without using
a for loop or other looping construct.
1. The... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
pip install keras-self-attention
!pip install emoji
!pip install ekphrasis
!pip install transformers==4.2.1
import numpy as np
import pandas as pd
import string
from nltk.corpus import stopwords
import re
import os
from collections import Counter
from ek... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.