text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
import seaborn as sns
import numpy as np
import json
from pprint import pprint
import matplotlib.pyplot as plt
def read_performances(path_prefix, run_dirs, filename, num_goals):
all_performances = []
for run_dir in run_dirs:
with open(path_prefix + run_dir + filename, "r") as performance_file:
... | github_jupyter |
# Exploration: Linear Regression and Classification
A fundamental component of mastering data science concepts is applying and practicing them. This exploratory notebook is designed to provide you with a semi-directed space to do just that with the Python, linear regression, and ML-based classification skills that you... | github_jupyter |
```
import pandas as pd
from collections import Counter
from langdetect import detect
import langdetect
import numpy as np
import importlib
current_dir = os.getcwd()
%cd ..
import textmining.text_miner
import textmining.topic_modeler as tm
importlib.reload(textmining.text_miner)
importlib.reload(textmining.topic_mod... | github_jupyter |
# Name Classifier
http://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
```
import glob
import unicodedata
import string
def findFiles(path): return glob.glob(path)
print(findFiles('data/names/*.txt'))
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
# Turn a Un... | github_jupyter |
# Tensorflowing (small stream)
```
%matplotlib inline
import tensorflow as tf
from skimage import data
from matplotlib import pyplot as plt
import numpy as np
# create a tf Tensor that holds 100 values evenly spaced from -3 to 3
x = tf.linspace(-3.0, 3.0, 100)
print(x)
# create a graph (holds the theory of the computa... | github_jupyter |
# Configuring Sonnet's BatchNorm Module
This colab walks you through Sonnet's BatchNorm module's different modes of operation.
The module's behaviour is determined by three main parameters: One constructor argument (```update_ops_collection```) and two arguments that are passed to the graph builder (```is_training``... | github_jupyter |
In this python script, I have done:
- EDA
- Data collection
- Checking null and inf in the data
- Drop all the null data
- Visualization
- Plot data adistribution
- Plot candle stick
- Plot volumn
- Model training
- Xg-boosting
- Loop over all assets (training)
- Model Prediction
... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(41)
sns.set()
df = pd.read_csv('https://huseinhouse.com/dataset/mall-customer.csv')
df.head()
X = df.iloc[:, -2:].values
X.shape
plt.figure(figsize = (7, 5))
plt.scatter(X[:,0], X[:, 1])
plt.ylabel('Spending ... | github_jupyter |
# Rapid Eye Movements (REMs) detection
This notebook demonstrates how to use YASA to automatically detect rapid eye movements (REMs) on EOG data.
Please make sure to install the latest version of YASA first by typing the following line in your terminal or command prompt:
`pip install --upgrade yasa`
```
import yasa... | github_jupyter |
2017
Machine Learning Practical
University of Edinburgh
Georgios Pligoropoulos - s1687568
Coursework 4 (part 5a)
### Imports, Inits, and helper functions
```
jupyterNotebookEnabled = True
plotting = True
saving = True
coursework, part = 4, "5a"
if jupyterNotebookEnabled:
#%load_ext autoreload
%reload_ext... | github_jupyter |
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/1_getting_started_roadmap/6_hyperparameter_tuning/1)%20Analyse%20Learning%20Rates.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Goals
### L... | github_jupyter |
In this tutorial, you will learn what a **categorical variable** is, along with three approaches for handling this type of data.
# Introduction
A **categorical variable** takes only a limited number of values.
- Consider a survey that asks how often you eat breakfast and provides four options: "Never", "Rarely", ... | github_jupyter |
# NVE
## Phase Space, Liuville's Theorem and Ergoicity ideas
Conservative systems are govenred by Hamilton's equation of motion. That is changes in position and momenta stay on the surface: $H(p,q)=E$
$$\dot{q} = \frac{\partial H}{\partial p}$$
$$\dot{p} = -\frac{\partial H}{\partial q}$$
To see how ensemble N bod... | github_jupyter |
# Accessing the Youtube API
This Notebook explores convenience functions for accessing the Youtube API.
Writen by Leon Yin and Megan Brown
```
import os
import sys
import json
import datetime
import pandas as pd
# this is to import youtube_api from the py directory
sys.path.append(os.path.abspath('../'))
import yout... | github_jupyter |
```
import h5py
import numpy as np
from sklearn import model_selection
import matplotlib.pyplot as plt
from sklearn import metrics
import os
import tensorflow as tf
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Conv2D, UpSampling2D, MaxPooling2D, AveragePooling2D, Attention
from tensorfl... | 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 |
# Daqss API Tutorial
## Overview
An application program interface (API) is a set of routines, protocols, and tools for building software applications. A good APi makes it easier to develop a program by providing the building blocks. A programmer then puts those blocks together.
The Daqss API provides an easy way to ... | github_jupyter |
# Interpret Models
You can use Azure Machine Learning to interpret a model by using an *explainer* that quantifies the amount of influence each feature contribues to the predicted label. There are many common explainers, each suitable for different kinds of modeling algorithm; but the basic approach to using them is t... | github_jupyter |
## Pipelines
Pipeline can be used to chain multiple estimators into one. This is useful as there is often a fixed sequence of steps in processing the data, for example feature selection, normalization and classification. Pipeline serves two purposes here:
* Convenience: You only have to call fit and predict once on y... | github_jupyter |

# PyTorch
PyTorch is an open source machine learning library for Python, based on Torch, used for applications such as natural language processing. It is primarily developed by Facebook's artificial-intelligence research group, and Uber's "Pyro" s... | github_jupyter |
# Multi-model metadata generation
> experiment in combining text and tabular models to generate web archive metadata
- toc: true
- badges: false
- comments: true
- categories: [metadata, multi-model]
- search_exclude: false
# Learning from multiple input types
Deep learning models usually take one type of input ... | github_jupyter |
```
# from google.colab import drive
# drive.mount('/content/drive')
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.data import Dataset, DataLoader... | github_jupyter |
# Supervised Contrastive Learning
**Author:** [Khalid Salama](https://www.linkedin.com/in/khalid-salama-24403144/)<br>
**Date created:** 2020/11/30<br>
**Last modified:** 2020/11/30<br>
**Description:** Using supervised contrastive learning for image classification.
```
import tensorflow as tf
import tensorflow_addon... | github_jupyter |
# Intro to Seismology: Programming for Homework 3
## Name:
## Introduction
The goal of this assignment is to locate an earthquake based on travel times. To do this will require three ingredients
1. A function that generates travel times from any point in the media to all receivers.
- We will use a closed-fo... | github_jupyter |
```
# PCA
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
dataset.head()
# X is created by extracting the Age and Estimated Salary... | github_jupyter |
# CT-LTI: Multi-sample Training and Eval
In this notebook we train over different graphs and initial-target state pairs.
We change parametrization slightly from the single sample, using Xavier normal instead of Kaiming initialization and higher decelaration rate for training. Preliminary results on few runs indicated t... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.plotting.register_matplotlib_converters.html
# Register converters for handling time... | github_jupyter |
# Ballot-polling SPRT
This notebook explores the ballot-polling SPRT we've developed.
```
%matplotlib inline
from __future__ import division
import math
import numpy as np
import numpy.random
import scipy as sp
import scipy.stats
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sprt impo... | github_jupyter |
# Preprocessing for simulation 5
## Effects at phylum level and order level with Mis-specified tree information
#### Method comparison based on MSE and Pearson correlation coefficient
#### for outcome associated taxa clustering at phylum & order level under regression design when using a mis-specified phylogenetic t... | github_jupyter |
```
import json
from dataclasses import dataclass
from typing import Any, Dict, List
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import resample
from sklearn.metrics import accuracy_score
from sklearn.linear_model import Perceptron
from sklearn.tree import DecisionTreeClassifier
from sklearn.... | github_jupyter |

# Graded Assignment: Machine Learning
### Lenin Escobar - Real-time Data Analysis
<h1 style="background-color:powderblue;">Setting Virtual Env</h1>
```
#General
import sys
import os
import subprocess
import ti... | github_jupyter |
# Character level language model - Dinosaurus land
Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to gi... | github_jupyter |
# Unsplash Image Search
Using this notebook you can search for images from the [Unsplash Dataset](https://unsplash.com/data) using natural language queries. The search is powered by OpenAI's [CLIP](https://github.com/openai/CLIP) neural network.
This notebook uses the precomputed feature vectors for almost 2 million ... | github_jupyter |
<a href="https://colab.research.google.com/github/ipavlopoulos/diagnostic_captioning/blob/master/DC_show_n_tell.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
#Medical Image To Diagnostic Text
---
### Use the IU-Xray dataset, including radiology X... | github_jupyter |
# <center>Introduction to Python Programming and Best Practices</center>
## <center>Instructors: Matt Slivinski and Andras Zsom</center>
### <center>[Center for Computation and Visualization](https://ccv.brown.edu/)</center>
### <center>Sponsored by the [Data Science Initiative](https://www.brown.edu/initiatives/data-s... | github_jupyter |
## GANs
```
%matplotlib inline
from fastai.gen_doc.nbdoc import *
from fastai.vision import *
from fastai.vision.gan import *
```
GAN stands for [Generative Adversarial Nets](https://arxiv.org/pdf/1406.2661.pdf) and were invented by Ian Goodfellow. The concept is that we will train two models at the same time: a gen... | github_jupyter |
<a id=top></a>
# Pea3 smFISH Analysis
## Table of Contents
----
1. [Preparations](#prep)
2. [QC: Spot Detection](#QC_spots)
3. [QC: Cell Shape](#QC_shape)
4. [Data Visualization](#viz)
5. [Predicting Expression from Shape: Testing](#atlas_test)
6. [Predicting Expression from Shape: Running](#atlas_run)
7. [Predictin... | github_jupyter |
# Heart disease classification
## USING SUPPORT VECTOR MACHINE (SVM)
### IMPORTING THE LIBRARIES
```
#importing the libraries.....
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
### IMPORTING THE DATASET
```
#Reading the dataset
ds=pd.read_csv('heart.csv')
print(ds)
ds.head()
ds.descr... | github_jupyter |
```
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import os
import csv
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.preprocessing import... | github_jupyter |
## Recurrent neural network with an LSTM unit
```
import numpy as np
import pandas as pd
import gensim
import sklearn
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation, Embedding, Input, TimeDistributed, Dropout, Masking
from keras.optimizers import RMSprop
# hyperparameters
B = 50 ... | github_jupyter |
```
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
if not 'spark' in locals():
spark = SparkSession.builder \
.master("local[*]") \
.config("spark.driver.memory","64G") \
.getOrCreate()
spark
```
# Get Data from S3
First we load the data source containing raw we... | github_jupyter |
# BRAINWORKS - Generate Graph Data
[Mohammad M. Ghassemi](https://ghassemi.xyz), DATA Scholar, 2021
<hr>
## 0. Install Dependencies:
To begin, please import the following external and internal python libraries
```
import re
import pandas as pd
import os
import sys
from pprint import pprint
currentdir = os.getcwd()... | github_jupyter |
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/Pyth... | github_jupyter |
<a href="https://colab.research.google.com/github/Saurabh-Bagchi/Traffic-Sign-Classification.keras/blob/master/Questions_Project_1_Computer_Vision_JPMC_v3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

```
## 日本語の出力
```
print('日本語')
```
## コメントの書き方
```
# ここはコメントです、プログラムの実行に影響がありません
print('コメントの書き方は #で始まります。')
```
## 演算
```
# 足し算 +
print(4+5)
# 引き... | github_jupyter |
# Search jobs abroad
## Scrape jobs abroad from peoplenjob.com
```
from selenium import webdriver
from time import sleep
ch_driver = webdriver.Chrome('C:/Users/beave/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Python 3.7/chromedriver.exe')
ch_driver.implicitly_wait(5)
url = 'https://www.peoplenjob.com/'
ch... | github_jupyter |
#### Copyright 2017 Google LLC.
```
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | github_jupyter |
```
# Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import random
from random import gauss
import math
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
import warnings
warnings.filterwarnings('ignore')
# CONSTANT Variab... | github_jupyter |
# Out-of-core Learning - Large Scale Text Classification for Sentiment Analysis
## Scalability Issues
The `sklearn.feature_extraction.text.CountVectorizer` and `sklearn.feature_extraction.text.TfidfVectorizer` classes suffer from a number of scalability issues that all stem from the internal usage of the `vocabulary_... | github_jupyter |
# Numpy Basics
NumPy provides an N-dimensional array type, the ndarray, which describes a collection of “items” of the *same* type.
The items can be indexed using for example N integers.
All ndarrays are homogeneous: every item takes up the same size block of memory, and all blocks are interpreted in exactly the s... | github_jupyter |
# Project 3: Implement SLAM
---
## Project Overview
In this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!
SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research... | github_jupyter |
# Quality Metrics and Reconstruction Demo
Demonstrate the use of full reference metrics by comparing the reconstruction of a simulated phantom using SIRT, ART, and MLEM.
```
import numpy as np
import matplotlib.pyplot as plt
from xdesign import *
NPIXEL = 128
```
## Generate a phantom
Use one of XDesign's various p... | github_jupyter |
```
from __future__ import division, print_function
import numpy as np
import cPickle as pickle
import os, glob
from utils import models
from utils.sample_helpers import JumpProposal, get_parameter_groups
from enterprise.pulsar import Pulsar
from PTMCMCSampler.PTMCMCSampler import PTSampler as ptmcmc
from astropy.tim... | github_jupyter |
# Initial Setups
## (Google Colab use only)
```
# Use Google Colab
use_colab = True
# Is this notebook running on Colab?
# If so, then google.colab package (github.com/googlecolab/colabtools)
# should be available in this environment
# Previous version used importlib, but we could do the same thing with
# just atte... | github_jupyter |
## Face and Facial Keypoint detection
After you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.
1. Detect... | github_jupyter |
# <center>Using Ordinary Differential Equations (ODEs) in Simulating 2-D Wildland Fire Behavior</center>
<center>by Diane Wang</center>
---
# ODEs used in fire behavior simulation
Indoor fire models are subdivided into two categories, zone models and field models (Rehm et al. 2011). The formulation of both zone and fie... | github_jupyter |
# A Neural Network for Regression (Estimate blood pressure from PPG signal)
*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [HW page](http://kovan.ceng.metu.edu.tr/~sinan/DL/index.html) on ... | github_jupyter |
## GPS Spoofing Detection
### 1. load data and preprocess
```
# Load Data
import utils
import os
import numpy as np
import config
A, B = utils.load_image_pairs(path=config.SWISS_1280x720)
assert A.shape[0]==B.shape[0]
n = A.shape[0]
print(A.shape, B.shape)
# Some configuration
#feature_map_file_name = './mid_produc... | github_jupyter |
```
!pip install qucumber
import numpy as np
import torch
import matplotlib.pyplot as plt
from qucumber.nn_states import ComplexWaveFunction
from qucumber.callbacks import MetricEvaluator
import qucumber.utils.unitaries as unitaries
import qucumber.utils.cplx as cplx
import qucumber.utils.training_statistics as ts
impo... | github_jupyter |
# Solutions: Corollary 0.0.4 in $\mathbb R^2$
*These are **solutions** to the worksheet on corollary 0.0.4. Please **DO NOT LOOK AT IT** if you haven't given the worksheet a fair amount of thought.*
In this worksheet we will run through the proof of Corollary 0.0.4 from Vershynin. We will "pythonize" the proof step-b... | github_jupyter |
```
import math,random
m=int(input("请输入一个整数作为上界\n"))
k=int(input("请输入一个整数作为下界\n"))
n=int(input("请输入你要随机生成的整数的个数\n"))
def fun ():
i=0
total=0
while i<n:
num=random.randint(k,m)
print("第",i+1,"次随机生成的数为:",num)
total=total+num
i+=1
aver=total/n
root=math.sqrt(aver)
pr... | github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# $\texttt{GiRaFFE}$: Solving GRFFE equations at a higher F... | github_jupyter |
```
import pandas as pd
startups = pd.read_csv('data/startups_1.csv', index_col=0)
startups[:3]
```
### With the variables we found so far here, we achieved a maximum performance of 75% (ROC AUC), so let's try to extract some more features in order to increase the model performance
### Let's find the # of acquisitons... | github_jupyter |
# Lab: Titanic Survival Exploration with Decision Trees
## Getting Started
In this lab, you will see how decision trees work by implementing a decision tree in sklearn.
We'll start by loading the dataset and displaying some of its rows.
```
# Import libraries necessary for this project
import numpy as np
import pand... | github_jupyter |
# Pypi & Pip
PyPi is short form for Python Package Index (PyPI). PyPI helps you find and install open source software developed and shared by the Python community. All the python packages are distributed to python community through pypi.org . These packages are called as Distributed or intallable packages. To install ... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/AssetManagement/export_FeatureCollection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a targ... | github_jupyter |
<h1> Structured data prediction using Cloud ML Engine </h1>
This notebook illustrates:
<ol>
<li> Exploring a BigQuery dataset using Datalab
<li> Creating datasets for Machine Learning using Dataflow
<li> Creating a model using the high-level Estimator API
<li> Training on Cloud ML Engine
<li> Deploying model
<li> Pre... | github_jupyter |
```
# default_exp key_driver_analysis
#hide
%reload_ext autoreload
%autoreload 2
%matplotlib inline
```
# Key Driver Analysis
> Key driver analysis to yield clues into **potential** causal relationships in your data by determining variables with high predictive power, high correlation with outcome, etc.
```
#hide
tr... | github_jupyter |
# Missing values in scikit-learn
```
#code adapted from https://github.com/thomasjpfan/ml-workshop-intermediate-1-of-2
```
## SimpleImputer
```
from sklearn.impute import SimpleImputer
import numpy as np
import sklearn
sklearn.set_config(display='diagram')
import pandas as pd
url = 'https://raw.githubusercontent.com... | github_jupyter |
# Logistic Regression
Implementation of logistic regression for binary class.
### Imports
```
import torch
import numpy as np
import matplotlib.pyplot as plt
from io import BytesIO
%matplotlib inline
```
### Dataset
```
data_source = np.lib.DataSource()
data = data_source.open('http://archive.ics.uci.edu/ml/machine... | github_jupyter |
```
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.commit` to work
!pip install jovian --upgrade -q
import jovian
jovian.set_project('05b-cifar10-resnet')
jovian.set_colab_id('1JkC4y1mnrW0E0JPrhY-6aWug3uGExuRf')
```
# Classifying CIFAR10 images using ResNets... | github_jupyter |
```
#python deep_dream.py path_to_your_base_image.jpg prefix_for_results
#python deep_dream.py img/mypic.jpg results/dream
from __future__ import print_function
from keras.preprocessing.image import load_img, img_to_array
import numpy as np
import scipy
import argparse
from keras.applications import inception_v3
fro... | github_jupyter |
# Getting Started with the AppEEARS API: Submitting and Downloading a Point Request
### This tutorial demonstrates how to use Python to connect to the AppEEARS API
The Application for Extracting and Exploring Analysis Ready Samples ([AppEEARS](https://lpdaacsvc.cr.usgs.gov/appeears/)) offers a simple and efficient way... | github_jupyter |
# Make a plot with both redshift and universe age axes using astropy.cosmology
## Authors
Neil Crighton, Stephanie T. Douglas
## Learning Goals
* Plot relationships using `matplotlib`
* Add a second axis to a `matplotlib` plot
* Relate distance, redshift, and age for two different types of cosmology using `astropy.co... | github_jupyter |
ERROR: type should be string, got "https://www.kaggle.com/CVxTz/keras-bidirectional-lstm-baseline-lb-0-051\n\n```\nimport gc\nimport numpy as np\nimport pandas as pd\n\nfrom nltk.corpus import stopwords\nfrom gensim.models import KeyedVectors\nfrom tqdm import tqdm\n\nfrom keras.models import Model\nfrom keras.layers import Dense, Embedding, Input\nfrom keras.layers import LSTM, Bidirectional, GlobalAveragePooling1D, GlobalMaxPooling3D, Dropout\nfrom keras.preprocessing import text, sequence\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nmax_features = 200000\nsequence_length = 196\nembedding_dim = 300\ncreate_embedding = False\n\n\ntrain = pd.read_pickle(\"../data/train_spacy_clean.pkl\")\ntest = pd.read_pickle(\"../data/test_spacy_clean.pkl\")\n\ntrain['comment_reversed'] = train.comment_text.apply(lambda x: ' '.join(x.split(' ')[::-1]))\ntest['comment_reversed'] = test.comment_text.apply(lambda x: ' '.join(x.split(' ')[::-1]))\nlist_classes = [\"toxic\", \"severe_toxic\", \"obscene\", \"threat\", \"insult\", \"identity_hate\"]\n\ntokenizer = text.Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(train.comment_text.values.tolist() + train.comment_reversed.values.tolist() +\n test.comment_text.values.tolist() + test.comment_reversed.values.tolist())\n\nlist_tokenized_train = tokenizer.texts_to_sequences(train.comment_text.values)\nlist_tokenized_train2 = tokenizer.texts_to_sequences(train.comment_reversed.values)\nlist_tokenized_test = tokenizer.texts_to_sequences(test.comment_text.values)\nlist_tokenized_test2 = tokenizer.texts_to_sequences(test.comment_reversed.values)\n\n\nword_index = tokenizer.word_index\nnb_words = min(max_features, len(word_index)) + 1\n\nX_train = sequence.pad_sequences(list_tokenized_train, maxlen=sequence_length)\nX_train2 = sequence.pad_sequences(list_tokenized_train2, maxlen=sequence_length)\ny_train = train[list_classes].values\n\nX_test = sequence.pad_sequences(list_tokenized_test, maxlen=sequence_length)\nX_test2 = sequence.pad_sequences(list_tokenized_test2, maxlen=sequence_length)\n\ndel train, test, list_tokenized_train, list_tokenized_train2, list_tokenized_test, list_tokenized_test2\ngc.collect()\nif create_embedding:\n embedding_file = '/home/w/Projects/Toxic/data/embeddings/GoogleNews-vectors-negative300.bin.gz'\n word2vec = KeyedVectors.load_word2vec_format(embedding_file, binary=True)\n print('Found %s word vectors of word2vec' % len(word2vec.vocab))\n\n embedding_matrix = np.zeros((nb_words, embedding_dim))\n for word, i in tqdm(word_index.items()):\n if word in word2vec.vocab:\n embedding_matrix[i] = word2vec.word_vec(word)\n print('Null word embeddings: %d' % np.sum(np.sum(embedding_matrix, axis=1) == 0))\nelse:\n embedding_matrix = pd.read_pickle('../data/embeddings/GoogleNews_300dim_embedding.pkl')\nimport keras_models_quora\n\n\nepochs = 100\nbatch_size = 128\n\n\nmodel_callbacks = [EarlyStopping(monitor='val_loss', patience=6, verbose=1, mode='min'),\n ReduceLROnPlateau(monitor='val_loss', factor=0.7, verbose=1,\n patience=4, min_lr=1e-6)]\n\n\nmodel = keras_models_quora.decomposable_attention('../data/embeddings/GoogleNews_300dim_embedding.pkl', maxlen=196)\nmodel.fit([X_train, X_train2], y_train, batch_size=batch_size, epochs=epochs, \n validation_split=0.1, callbacks=model_callbacks)\n\ny_test = model.predict(X_test)\n```\n\n" | github_jupyter |

#### <a href="https://github.com/rdipietro"><i class="fab fa-github"></i> GitHub</a> <a href="https://twitter.com/rsdipietro"><i class="fab fa-twitter"></i> Twitter</a>
I'm Rob DiPietro, a PhD student in the [Department of Computer Science at Johns Hopkins](https://www.cs.jhu.edu/... | github_jupyter |
# Table of Contents
<p><div class="lev1"><a href="#Learning-Objectives"><span class="toc-item-num">1 </span>Learning Objectives</a></div><div class="lev2"><a href="#Disclaimer"><span class="toc-item-num">1.1 </span>Disclaimer</a></div><div class="lev1"><a href="#Plotting-with-ggplot"><span class=... | github_jupyter |
# Travelling Salesman Problem with subtour elimination
This example shows how to solve a TSP by eliminating subtours using:
1. amplpy (defining the subtour elimination constraint in AMPL and instantiating it appropriately)
2. ampls (adding cuts directly from the solver callback)
### Options
```
SOLVER = "xpress"
S... | github_jupyter |
# 动手实现胶囊网络
## 前言
2017年,Hinton团队提出胶囊网络,首次将标量型网络扩展到矢量。本着learning by doing的态度,我尝试对原论文进行复现,因此这里不会对其原论文原理和思想有太多解释。尽可能保证工程性和完整性,并在实现过程中不断总结和反思。实现过程中也许会有一些bug,欢迎交流和提交issue~
**Author**: QiangZiBro
**Github**: https://github/QiangZiBro
## 1.1 引入必备的包
本文依赖第三方框架pytorch,实验使用1.2,基本来说各个版本都可以用。
```
import os
import torch
impo... | github_jupyter |
```
import networkx as nx
import matplotlib.pyplot as plt
from collections import Counter
from custom import custom_funcs as cf
import warnings
warnings.filterwarnings('ignore')
from circos import CircosPlot
%load_ext autoreload
%autoreload 2
%matplotlib inline
```
## Load Data
We will load the [sociopatterns netwo... | github_jupyter |
```
print("Bismillahir Rahmanir Rahim")
```
## Imports and Paths
```
from IPython.display import display, HTML
from lime.lime_tabular import LimeTabularExplainer
from pprint import pprint
from scipy.spatial.distance import pdist, squareform
from sklearn.linear_model import LogisticRegression
from sklearn.tree imp... | github_jupyter |
# 1. Multi-layer Perceptron
### Train and evaluate a simple MLP on the Reuters newswire topic classification task.
This is a collection of documents that appeared on Reuters newswire in 1987. The documents were assembled and indexed with categories.
Dataset of 11,228 newswires from Reuters, labeled over 46 topics.... | github_jupyter |
## Approach 1: Dynamic Programming
Throughout this document, the following packages are required:
```
import numpy as np
import scipy, math
from scipy.stats import poisson
from scipy.optimize import minimize
```
### Heterogeneous Exponential Case
The following functions implement the heterogeneous exponential case ... | github_jupyter |
<a href="https://github.com/PaddlePaddle/PaddleSpeech"><img style="position: absolute; z-index: 999; top: 0; right: 0; border: 0; width: 128px; height: 128px;" src="https://nosir.github.io/cleave.js/images/right-graphite@2x.png" alt="Fork me on GitHub"></a>
# 使用 Transformer 进行语音识别
# 0. 视频理解与字幕
```
# 下载demo视频
!test... | github_jupyter |
# Assignment 1 - Creating and Manipulating Graphs
Eight employees at a small company were asked to choose 3 movies that they would most enjoy watching for the upcoming company movie night. These choices are stored in the file `Employee_Movie_Choices.txt`.
A second file, `Employee_Relationships.txt`, has data on the r... | github_jupyter |
# Distributed
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Distributed" data-toc-modified-id="Distributed-1"><span class="toc-item-num">1 </span>Distributed</a></span><ul class="toc-item"><li><span><a href="#Distributed-Cluster" data-toc-m... | github_jupyter |
# DAG Creation and Submission
Launch this tutorial in a Jupyter Notebook on Binder:
[](https://mybinder.org/v2/gh/htcondor/htcondor-python-bindings-tutorials/master?urlpath=lab/tree/DAG-Creation-And-Submission.ipynb)
In this tutorial, we will learn how to use `htcondor.d... | github_jupyter |
<a href="https://colab.research.google.com/github/shivammehta007/NLPinEnglishLearning/blob/master/Sequence_2_sequence_Generation/Sequence2SequenceQuestionGenerator.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Question Generation
Additional Dep... | github_jupyter |
```
import figurefirst
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from IPython.display import display,SVG
def make_plot(template_filename, output_filename):
## Define colors, spine locations, and notes for data ######################
colors = {'group1': 'green',
'gr... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import scanpy.api as sc
import scipy as sp
import itertools
import numpy as np
import scipy.stats as stats
from scipy.integrate import dblquad
import seaborn as sns
from statsmodels.stats.multitest import fdrcorrection
import imp
np.arange(1, 5, 0.001).shape
%%tim... | github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_excel('Tips.xlsx')
df
df.drop(244,inplace = True)
```
**1.What is the overall average tip?**
```
df['tip'].mean()
```
**2.Get a numerical summary for 'tip' - are the median and mean very different? What does... | github_jupyter |
# [NTDS'19] assignment 2: learning with graphs — solution
[ntds'19]: https://github.com/mdeff/ntds_2019
[Clément Vignac](https://people.epfl.ch/clement.vignac), [EPFL LTS4](https://lts4.epfl.ch) and
[Guillermo Ortiz Jiménez](https://gortizji.github.io), [EPFL LTS4](https://lts4.epfl.ch).
## Students
* Team: `<your t... | github_jupyter |
# __Fundamentos de programación__
<strong>Hecho por:</strong> Juan David Argüello Plata
## __1. Variables__
Una variable es el <u>nombre</u> con el que se identifica información de interés.
```
nom_variable = contenido
```
El contenido de una variable puede cambiar de naturaleza; por eso se dice que Python es un l... | github_jupyter |
# Multi-level Models in Keras Playground
Linear Mixed effects models, also known as hiearchical linear models, also known as multi-level models, are powerful linear ensemble modeling tools that can do both regression and classification tasks for many structured data sets. This notebook describes what a multi-level mod... | github_jupyter |
**Exercise set 1**
==================
>The goal of this exercise is to introduce some concepts from
>Chapter 1, for instance the difference between **hard** and **soft** modeling.
**Exercise 1.1** A traveling juggling group has an act out in the open where they shoot a person out from
a cannon. The problem is to pre... | github_jupyter |
# Data Preparation
Clone GitHub repository to Colab storage.
```
!git clone https://github.com/megagonlabs/HappyDB.git
!ls
!ls HappyDB/happydb/data
```
# Utility functions
```
import numpy as np
from sklearn.base import clone
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extracti... | github_jupyter |
```
from utils import whiteboard as wb
from compas.datastructures import Mesh
from compas.datastructures import subdivision as sd
from compas_plotters import MeshPlotter
mesh = Mesh.from_polyhedron(8)
mesh.summary()
mesh2 = sd.mesh_subdivide_tri(mesh)
mesh3 = sd.trimesh_subdivide_loop(mesh2)
mesh4 = sd.mesh_subdivide_c... | github_jupyter |
# Collaborative filtering on the MovieLense Dataset
## Learning Objectives
1. Know how to build a BigQuery ML Matrix Factorization Model
2. Know how to use the model to make recommendations for a user
3. Know how to use the model to recommend an item to a group of users
###### This notebook is based on part of Chapte... | github_jupyter |
# Scikit-Learn
<!--<badge>--><a href="https://colab.research.google.com/github/TheAIDojo/Machine_Learning_Bootcamp/blob/main/Week 03 - Machine Learning Algorithms/1- Scikit_Learn.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a><!--</badge>-->
[Sci... | github_jupyter |
# NOTES:
- Waiting vs blocking
--> blocking holds up everything (could be selective?)
--> waiting for specific resources to reach inactive state (flags?)
- Platemap vs positionmap
- Axes orientation
# TODO:
- tip touch
- get motor current position
- tip touch
- calibration
- initialization reference
- GUI
- pyV... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.