code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [i... | github_jupyter |
# Exploring data to calculate bunches and gaps
This first half of this notebook is the exploratory code I used to find this method in the first place. The second half will be a cleaned version that can be run on its own.
## Initialize database connection
So I can load the data I'll need
```
import getpass
import p... | github_jupyter |
<a href="https://colab.research.google.com/github/mkhalil7625/DS-Unit-2-Linear-Models/blob/master/module4-logistic-regression/Copy_of_LS_DS_214_assignment.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,... | github_jupyter |
```
# Datset source
# https://www.kaggle.com/moltean/fruits
# Problem Statement: Multiclass classification problem for 131 categories of fruits and vegetables
# Created using the following tutorial template
# https://keras.io/examples/vision/image_classification_from_scratch/
# import required libraries
import matplot... | github_jupyter |
# Project Week 1: Creating an animated scatterplot with Python
```
#Import libraries
import pandas as pd
import imageio
import seaborn as sns
import matplotlib.pyplot as plt
```
### Step 1: Read in data
```
gdppercapitagrowth = pd.read_csv('data/gdp_per_capita_growth.csv', index_col=0)
gdppercapitagrowth
industry = ... | github_jupyter |
```
%load_ext autoreload
%autoreload 2 """Reloads all functions automatically"""
%matplotlib notebook
from irreversible_stressstrain import StressStrain as strainmodel
import test_suite as suite
import graph_suite as plot
import numpy as np
model = strainmodel('ref/HSRS/22').get_experimental_data()
slopes = suite.g... | github_jupyter |
# `scinum` example
```
from scinum import Number, Correlation, NOMINAL, UP, DOWN, ABS, REL
```
The examples below demonstrate
- [Numbers and formatting](#Numbers-and-formatting)
- [Defining uncertainties](#Defining-uncertainties)
- [Multiple uncertainties](#Multiple-uncertainties)
- [Configuration of correlations](#... | github_jupyter |
## Briefly
### __ Problem Statement __
- Obtain news from google news articles
- Sammarize the articles within 60 words
- Obtain keywords from the articles
##### Importing all the necessary libraries required to run the following code
```
from gnewsclient import gnewsclient # for fetching google news
fro... | github_jupyter |
<a href="https://colab.research.google.com/github/SamH3pn3r/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling/blob/master/Copy_of_Black_Friday.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# Imports
import pandas as pd
# Url
black_friday_csv_... | github_jupyter |
# ♠ Sell Prediction ♠
Importing necessary files
```
# Importing pandas to read file
import pandas as pd
# Reading csv file directly from url
data = pd.read_csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv", index_col = 0)
# Display data
data
# Checking the shape of data (Rows, Column)
data.shape
```
# Displa... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
%matplotlib inline
df_id_pos = pd.read_excel('978-4-274-22101-9.xlsx', 'ID付きPOSデータ(POSデータ)')
df_id_pos.head()
```
# 5 売り場の評価
## 5.1 集計による売上の評価
```
df7 = df_id_pos[df_id_pos['日'] <= 7][['大カテゴリ名', '日']]
# 表5.1 日別... | github_jupyter |
```
# !wget http://qim.fs.quoracdn.net/quora_duplicate_questions.tsv
import tensorflow as tf
import re
import numpy as np
import pandas as pd
from tqdm import tqdm
import collections
from unidecode import unidecode
from sklearn.cross_validation import train_test_split
def build_dataset(words, n_words):
count = [['P... | github_jupyter |
## Plotting Installation:
The plotting package allows you to make an interactive CRN plot. Plotting requires the [Bokeh](https://docs.bokeh.org/en/latest/docs/installation.html) and [ForceAtlas2](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0098679) libraries to be installed on your machine. Bokeh... | github_jupyter |
# Homework 04 - Numpy
### Exercise 1 - Terminology
Describe the following terms with your own words:
***numpy array:*** an array only readable/useable in numpy
***broadcasting:*** how numpy treats arrays
Answer the following questions:
***What is the difference between a Python list and a Numpy array?*** the nump... | github_jupyter |
# VAE outlier detection on CIFAR10
## Method
The Variational Auto-Encoder ([VAE](https://arxiv.org/abs/1312.6114)) outlier detector is first trained on a batch of unlabeled, but normal (*inlier*) data. Unsupervised training is desireable since labeled data is often scarce. The VAE detector tries to reconstruct the in... | github_jupyter |
## Full name: Farhang Forghanparast
## R#: 321654987
## HEX: 0x132c10cb
## Title of the notebook
## Date: 9/3/2020
# Laboratory 5 Functions
Functions are simply pre-written code fragments that perform a certain task.
In older procedural languages functions and subroutines are similar, but a function returns a value wh... | github_jupyter |
## Audio Monitor
Monitors the audio by continuously recording and plotting the recorded audio.
You will need to start osp running in a terminal.
```
# make Jupyter use the whole width of the browser
from IPython.display import Image, display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))... | github_jupyter |
```
# This line is a comment because it starts with a pound sign (#). That
# means Python ignores it. A comment is just for a human reading the ... | github_jupyter |
---
_You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._
---
# The Python Programm... | github_jupyter |
```
from prettytable import PrettyTable
def math_expr(x):
return 230*x**4+18*x**3+9*x**2-221*x-9
#return x**3 - 0.165*x**2 + 3.993e-4
#return (x-1)**3 + .512
dig = 5
u = -1
v = 1
it = 50
#u,v,it,dig
#x 3 − 0.165x 2 + 3.993×10−4 = 0
def bisection_method(func,xl=0,xu=5,iter=10,digits = 16):
tab = Pretty... | github_jupyter |
<font size="6"> <center> **[Open in Github](https://github.com/danielalcalde/apalis/blob/master/timings.ipynb)**</center></font>
# Timings
## Apalis vs Ray
In this notebook, the overhead of both the libraries' Ray and Apalis is measured. For Apalis also its different syntaxes are compared in the next section. We co... | github_jupyter |
```
import altair as alt
import pandas as pd
from pony.orm import *
from datetime import datetime
import random
from bail.db import DB, Case, Inmate
# Connect to SQLite database using Pony
db = DB()
statuses = set(select(i.status for i in Inmate))
pretrial = set(s for s in statuses if ("Prearraignment" in s or "Pretria... | github_jupyter |
# Notes:
This notebook is used to predict demand of Victoria state (without using any future dataset)
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from tsa_utils import *
from statsmodels.tsa.stattools import pacf
from sklearn.ensemble import RandomForestRegressor
... | github_jupyter |
# Converters for Quadratic Programs
Optimization problems in Qiskit's optimization module are represented with the `QuadraticProgram` class, which is generic and powerful representation for optimization problems. In general, optimization algorithms are defined for a certain formulation of a quadratic program and we ne... | github_jupyter |
<a href="https://colab.research.google.com/github/MattBizzo/alura-quarentenadados/blob/master/QuarentenaDados_aula03.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Introdução
Olá, seja bem-vinda e bem-vindo ao notebook da **aula 03**! A partir d... | github_jupyter |
```
import pyttsx3
import webbrowser
import smtplib
import random
import speech_recognition as sr
import wikipedia
import datetime
import wolframalpha
import os
import sys
import tkinter as tk
from tkinter import *
from datetime import datetime
import random
import re
from tkinter import messagebox
from tkinter.font im... | github_jupyter |
# Object Detection
*Object detection* is a form of computer vision in which a machine learning model is trained to classify individual instances of objects in an image, and indicate a *bounding box* that marks its location. Youi can think of this as a progression from *image classification* (in which the model answers... | github_jupyter |
# Classifier
Classifiers used to classify a song genre given its lyrics
## Loading and Processing Dataset
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
filename = '../data/dataset.csv'
df = pd.r... | github_jupyter |
# Facial Keypoint Detection
This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working ... | github_jupyter |
```
import nbformat as nbf
import textwrap
nb = nbf.v4.new_notebook()
#this creates a button to toggle to remove code in html
source_1 = textwrap.dedent("""
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').sho... | github_jupyter |
# Essential: Static file management with SourceLoader
Data pipelines usually interact with external systems such as SQL databases. Using relative paths to find such files is error-prone as the path to the file depends on the file loading it, on the other hand, absolute paths are to restrictive, the path will only work... | github_jupyter |
## Simulation Procedures
## The progress of simulation
We simulate paired scDNA and RNA data following the procedure as illustrated in supplement (Figure S1). The simulation principle is to coherently generate scRNA and scDNA data from the same ground truth genetic copy number and clonality while also allowing adding... | github_jupyter |
## Compile a training set using ASPCAP normalization
```
from utils_h5 import H5Compiler
from astropy.io import fits
import numpy as np
# To create a astroNN compiler instance
compiler_aspcap_train = H5Compiler()
compiler_aspcap_train.teff_low = 4000 # Effective Temperature Upper
compiler_aspcap_train.teff_high = 55... | github_jupyter |
## What is SPySort?
SPySort is a spike sorting package written entirely in Python. It takes advantage of Numpy, Scipy, Matplotlib, Pandas and Scikit-learn. Below, you can find a brief how-to-use tutorial.
### Load the data
To begin with, we have to load our raw data. This can be done either by using the **import_data... | github_jupyter |
```
import os; os.chdir('../')
from tqdm import tqdm
import pandas as pd
import numpy as np
from sklearn.neighbors import BallTree
%matplotlib inline
from urbansim_templates import modelmanager as mm
from urbansim_templates.models import MNLDiscreteChoiceStep
from urbansim.utils import misc
from scripts import datasour... | github_jupyter |
# Unsupervised Learning in R
> clustering and dimensionality reduction in R from a machine learning perspective
- author: Victor Omondi
- toc: true
- comments: true
- categories: [unsupervised-learning, machine-learning, r]
- image: images/ield.png
# Overview
Many times in machine learning, the goal is to find patt... | github_jupyter |
# Semantic Text Summarization
Here we are using the semantic method to understand the text and also keep up the standards of the extractive summarization. The task is implemnted using the various pre-defined models such **BERT, BART, T5, XLNet and GPT2** for summarizing the articles. It is also comapared with a classic... | github_jupyter |
## Case Study 1 DS7333
```
import sys
print(sys.path)
```
## Business Understanding
The objective behind this case study is to build a linear regression modeling using L1 (LASSO) or L2 (Ridge) regularization to predict the cirtical temperature. The team was given two files which contain the data and from this data ... | github_jupyter |
# Python Data Model
Most of the content of this book has been extracted from the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
http://shop.oreilly.com/product/0636920032519.do
>One of the best qualities of Python is its consistency.
>After working with Python for a while, you are able to start making info... | github_jupyter |
_Lambda School Data Science — Tree Ensembles_
# Decision Trees — with ipywidgets!
### Notebook requirements
- [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html): works in Jupyter but [doesn't work on Google Colab](https://github.com/googlecolab/colabtools/issues/60#issuecomment-... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Load-Network" data-toc-modified-id="Load-Network-1"><span class="toc-item-num">1 </span>Load Network</a></span></li><li><span><a href="#Explore-Directions" data-toc-modified-id="Explore-Direction... | github_jupyter |
```
import numpy as np
# to load mat files (from matlab) we need to import a special function
from scipy.io import loadmat
import matplotlib.pyplot as plt
#we will also need to import operating system tools through the os package- this will allow us to interact with the filesystem
import os
#Define the paths to the re... | github_jupyter |
# Importing the libraries
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
```
# Importing the datasets
```
dataset = pd.read_csv("train_ctrUa4K.csv")
dataset2 = pd.read_csv("test_lAUu6dG.csv")
dataset = dataset.drop(['Loan_ID'], axis = 1)
dataset2 = dataset2.drop(['Lo... | github_jupyter |
```
%matplotlib inline
```
Failed Model Fits
=================
Example of model fit failures and how to debug them.
```
# Import the FOOOFGroup object
from fooof import FOOOFGroup
# Import simulation code to create test power spectra
from fooof.sim.gen import gen_group_power_spectra
# Import FitError, which we wi... | github_jupyter |
# Part 2 Experiment with my dataset
## Prepare the model and load my dataset
```
#install torch in google colab
# http://pytorch.org/
from os.path import exists
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
cuda_outpu... | github_jupyter |
# Transfer Learning
In this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html).
ImageNet is a m... | github_jupyter |
<a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png" width = 300, align = "center"></a>
<h1 align=center><font size = 5>Data Analysis with Python</font></h1>
# House Sales in King County, USA
This dataset contains house sale prices for King ... | github_jupyter |
# **First run Ocean parcels on SSC fieldset**
```
%matplotlib inline
import numpy as np
import xarray as xr
import os
from matplotlib import pyplot as plt, animation, rc
import matplotlib.colors as mcolors
from datetime import datetime, timedelta
from dateutil.parser import parse
from scipy.io import loadmat
from cart... | github_jupyter |
```
#cell-width control
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:80% !important; }</style>"))
```
# Imports
```
#packages
import numpy
import tensorflow as tf
from tensorflow.core.example import example_pb2
#utils
import os
import random
import pickle
import struct
impor... | github_jupyter |
## Dependencies
```
!pip install --quiet /kaggle/input/kerasapplications
!pip install --quiet /kaggle/input/efficientnet-git
import warnings, glob
from tensorflow.keras import Sequential, Model
import efficientnet.tfkeras as efn
from cassava_scripts import *
seed = 0
seed_everything(seed)
warnings.filterwarnings('ig... | github_jupyter |
```
#import libraries
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
warnings.filterwarnings('ignore')
#import data
train_df = pd.read_csv("../Dataset/tra... | github_jupyter |
# Quantum Machine Learning and TTN
Let's look at the Tree Tensor Network as a model for quantum machine learning.
## What you will learn
1. TTN model
2. Optimization
## Install Blueqat
```
!pip install blueqat
```
The model we are going to build is called TTN. The quantum circuit is as follows.
<img src="../tutori... | github_jupyter |
```
# Importing needed libraries
import datetime
import pandas as pd
# Fetching the data from official site of Ministry of Health and Family Welfare | Government of India
try:
url = "https://www.mohfw.gov.in/"
dfs = pd.read_html(url)
for i in range(len(dfs)):
df = dfs[i]
if (len(df.columns... | github_jupyter |
# Artificial Intelligence Nanodegree
## Machine Translation Project
In this notebook, sections that end with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully!
## Introduction
I... | github_jupyter |
```
%matplotlib inline
import numpy as np
import pandas as pd
import math
from scipy import stats
import pickle
from causality.analysis.dataframe import CausalDataFrame
from sklearn.linear_model import LinearRegression
import datetime
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-seri... | github_jupyter |
```
import git_access,api_access,git2repo
import json
from __future__ import division
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import networkx as nx
import re
import git2data
import social_interaction
access_token = '--'
repo_owner = 'jankotek'
source_type = 'github_repo'
git_u... | github_jupyter |
# `aiterutils` tutorial
A functional programming toolkit for manipulation of asynchronous iterators in python >3.5
It has two types of operations:
1. Iterator functions
* `au.map(fn, aiter): aiter`
* `au.each(fn, aiter): coroutine`
* `au.filter(fn, aiter): aiter`
* `au.merge([aiter...]): aiter`
* `au.... | github_jupyter |
```
# Solve a linear system using 3 different approaches : Gaussian elimination, Inverse , PLU factorization & measure times.
import numpy as np
from scipy.linalg import solve_triangular
from numpy.linalg import inv
from scipy.linalg import lu
import time
def gaussElim(Matrix):
j = 1
num_rows, num_cols = Mat... | github_jupyter |
# 数据抓取:
> # Beautifulsoup简介
***
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
# 需要解决的问题
- 页面解析
- 获取Javascript隐藏源数据
- 自动翻页
- 自动登录
- 连接API接口
```
import urllib2
from bs4 import BeautifulSoup
```
- 一般的数据抓取,使用urllib2和beautifulsoup配合就可以了。
- 尤其是对于翻页时url出现规则变化的网页,只需要处理规则化的url就可以了。
- 以简单的例子是... | github_jupyter |
# 导入必要的库
我们需要导入一个叫 [captcha](https://github.com/lepture/captcha/) 的库来生成验证码。
我们生成验证码的字符由数字和大写字母组成。
```sh
pip install captcha numpy matplotlib tensorflow-gpu pydot tqdm
```
```
from captcha.image import ImageCaptcha
import matplotlib.pyplot as plt
import numpy as np
import random
%matplotlib inline
%config InlineBac... | github_jupyter |
```
!unzip "/content/drive/MyDrive/archive.zip" -d archive
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
from tensorflow import keras
from keras.layers import Input, Lambda, Dense, Flatten
from keras.models import Model
from keras.applications.vgg16 import VGG16
from keras.applications.v... | github_jupyter |
# Library
```
import numpy as np
import torch
import torch.nn as nn
from utils import *
from dataset import TossingDataset
from torch.utils.data import DataLoader
```
# Model
```
class NaiveMLP(nn.Module):
def __init__(self, in_traj_num, pre_traj_num):
super(NaiveMLP, self).__init__()
self.hidd... | github_jupyter |
<center>
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Module%202/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
</center>
# Data Wrangling
Estimated time needed: **30** minutes
## Objectives
After completing... | github_jupyter |
```
import numpy
import matplotlib.pyplot as plt
```
## Plot up tanker fuel capacity by vessel length
```
# SuezMax: 5986.7 m3 (4,025/130 m3 for HFO/diesel)
# Aframax: 2,984 m3 (2,822/162 for HFO/diesel)
# Handymax as 1,956 m3 (1,826/130 m3 for HFO/diesel)
# Small Tanker: 740 m3 (687/53 for HFO/diesel)
# SuezMax... | github_jupyter |
# Convolutional Neural Networks
## Project: Write an Algorithm for a Dog Identification App
---
In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond ... | github_jupyter |
## Appendix 1: Optional Refresher on the Unix Environment
### A1.1) A Quick Unix Overview
In Jupyter, many of the same Unix commands we use to navigate in the regular terminal can be used. (However, this is not true when we write standalone code outside Jupyter.) As a quick refresher, try each of the following:
```
l... | github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
from malaya_speech.train.model import hubert, ctc
from malaya_speech.train.model.conformer.model import Model as ConformerModel
import malaya_speech
import tensorflow as tf
import numpy as np
import json
from glob import glob
import string
unique_vocab = [''] + lis... | github_jupyter |
# Class Project
## GenePattern Single Cell Analysis Workshop
<div class="alert alert-info">
<p class="lead"> Instructions <i class="fa fa-info-circle"></i></p>
Log in to GenePettern with your credentials.
</div>
```
# Requires GenePattern Notebook: pip install genepattern-notebook
import gp
import genepattern
# User... | github_jupyter |
```
import gym
import random
import numpy as np
import time
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from gym.envs.registration import registry, register
from IPython.display import clear_output
try:
register(
id='FrozenLakeNoSlip-v0',
entry_point='gym.envs.toy_text:FrozenLakeEnv',... | github_jupyter |
<h1> Logistic Regression using Spark ML </h1>
Set up bucket
```
BUCKET='cloud-training-demos-ml' # CHANGE ME
os.environ['BUCKET'] = BUCKET
# Create spark session
from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext('local', 'logistic')
spark = SparkSession \
.builder \
.... | github_jupyter |
```
import pandas as pd
import warnings
import altair as alt
from urllib import request
import json
# fetch & enable a Spanish timeFormat locale.
with request.urlopen('https://raw.githubusercontent.com/d3/d3-time-format/master/locale/es-ES.json') as f:
es_time_format = json.load(f)
alt.renderers.set_embed_options(tim... | github_jupyter |
```
%cd ~/NetBeansProjects/ExpLosion/
from notebooks.common_imports import *
from gui.output_utils import *
from gui.user_code import pairwise_significance_exp_ids
query = {'expansions__decode_handler': 'SignifiedOnlyFeatureHandler',
'expansions__vectors__dimensionality': 100,
'expansions__vectors__r... | github_jupyter |
# Lussen
Looping `for` a `while`
## `for` lussen
```
for i in [0, 1, 2]:
print("i is", i)
for i in range(0, 3):
print("i is", i)
for x in [10, 15, 2020]:
print("x is", x)
```
```python
for i in ...:
print("Gefeliciteerd")
```
Hoe kan dit 10 keer worden uitgevoerd? Hier is een reeks aan oplossingen ... | github_jupyter |
```
import numpy as np
import pandas as pd
import gc
import matplotlib.pyplot as plt
import seaborn as sns
```
#### <font color='darkblue'> Doing these exercises, we had to be very careful about managing the RAM of our personal computers. We had to run this code with the 8gb RAM of our computers. So we tried to dele... | github_jupyter |
# Here I will deal mostly with extracting data from PDF files
### In accompanying scripts, I convert SAS and mutli-sheet Excel files into csv files for easy use in pandas using sas7bdat and pandas itself
```
# Necessary imports
import csv
import matplotlib.pyplot as plt
import numpy as np
import os
import openpyxl
im... | github_jupyter |
```
# Setup directories
from pathlib import Path
basedir = Path().absolute()
libdir = basedir.parent.parent.parent
# Other imports
import pandas as pd
import numpy as np
from datetime import datetime
from ioos_qc.plotting import bokeh_plot_collected_results
from bokeh import plotting
from bokeh.io import output_note... | github_jupyter |
# Overview
This notebook implements fourier series simualtions.
# Dependencies
```
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
```
# 1.3: Periodicity: Definitions, Examples, and Things to Come
A function $f(t)$ is said to be period of period $t$ if there exists a number $T > 0$... | github_jupyter |
# INPUT / OUTPUT
## open file handle function
`open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`
- file : filename (or file path)
- mode :
- r : read mode (default)
- w : write mode, truncating the file first
- x : open for exclusive creation, failin... | github_jupyter |
<div style="width: 100%; overflow: hidden;">
<div style="width: 150px; float: left;"> <img src="data/D4Sci_logo_ball.png" alt="Data For Science, Inc" align="left" border="0"> </div>
<div style="float: left; margin-left: 10px;"> <h1>NLP with Deep Learning for Everyone</h1>
<h1>Foundations of NLP</h1>
<p>... | github_jupyter |
Early stopping of model simulations
===================
For certain distance functions and certain models it is possible to calculate the
distance on-the-fly while the model is running. This is e.g. possible if the distance is calculated as a cumulative sum and the model is a stochastic process. For example, Markov Ju... | github_jupyter |
### This notebook covers how to get statistics on videos returned for a list of search terms on YouTube with the use of YouTube Data API v3.
First go to [Google Developer](http://console.developers.google.com/) and enable YouTube Data API v3 by clicking on the button "+ ENABLE APIS AND SERVICES" and searching for YouT... | github_jupyter |
```
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import sys
import time
import tensorflow as tf
TRAIN_FILE = 'train.tfrecords'
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example ... | 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 |
```
import plotly
plotly.offline.init_notebook_mode(connected=True)
from scipy.optimize import minimize
def objective_function_test(parameters):
a, b = parameters
return float(a + b)
minimize(objective_function_test, (8, 8), bounds=((0, None), (0, None)))
import numpy as np
import ccal
np.random.seed(seed=c... | github_jupyter |
<a href="https://colab.research.google.com/github/bakkiaraj/AIML_CEP_2021/blob/main/Sentiment_Analysis_TA_session_Dec_11.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
We will work with the IMDB dataset, which contains movie reviews from IMDB. Each... | github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 10)
df = pd.read_csv('data/final_cohort.csv')
df.head()
```
## Make Timeline in Python
```
names = df... | github_jupyter |
```
import numpy as np
import pandas as pd
import json
import requests
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
```
## Loading Labeled Dataset with hate tweets IDs
```
df = pd.read_csv('../data/hate_add.csv')
df = df[(df['racism']=='racism') | (df['racism']=='sexism')]
df.head()
d... | github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import numpy as np
from numpy.random import default_rng
import random
import collections
import re
import tensorflow as tf
from tqdm import tqdm
max_seq_length_encoder = 512
max_seq_length_decoder = 128
masked_lm_prob = 0.2
max_predictions_per_seq = int(masked_lm_p... | github_jupyter |
# Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need.
**Instructions:**
- You will be using Python 3.
- Avoid using for-loops and while-lo... | github_jupyter |
```
import os, json, sys, time, random
import numpy as np
import torch
from easydict import EasyDict
from math import floor
from easydict import EasyDict
from steves_utils.vanilla_train_eval_test_jig import Vanilla_Train_Eval_Test_Jig
from steves_utils.torch_utils import get_dataset_metrics, independent_accuracy_as... | github_jupyter |
# Saving and Loading Models
In this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data.
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
i... | github_jupyter |
# Explore the generated data
Here we explore the data that is generated with the [generate-data.ipynb](generate-data.ipynb) notebook.
You can either run the simulations or download the data set. See [README.md](README.md) for the download link and instructions.
### Joining the seperate data files of one simulation tog... | github_jupyter |
## In this notebook, images and their corresponding metadata are organized. We take note of the actual existing images, combine with available metadata, and scraped follower counts. After merging and dropping image duplicates, we obtain 7702 total images.
```
import pandas as pd
import numpy as np
import os
from PIL i... | github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# In addition to the imports, we'll also import some constants
# And also define our own
from scipy.constants import gravitational_constant, au
year = 365.25*24*3600
mass_sun = 1.989e30
mars_distance = 227.9*1.... | github_jupyter |
# Residual Networks
Welcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](h... | github_jupyter |
# Road Following - Live demo (TensorRT)
In this notebook, we will use model we trained to move JetBot smoothly on track.
# TensorRT
```
import torch
device = torch.device('cuda')
```
Load the TRT optimized model by executing the cell below
```
import torch
from torch2trt import TRTModule
model_trt = TRTModule()
m... | github_jupyter |
<img src='https://www.iss.nus.edu.sg/Sitefinity/WebsiteTemplates/ISS/App_Themes/ISS/Images/branding-iss.png' width=15% style="float: right;">
<img src='https://www.iss.nus.edu.sg/Sitefinity/WebsiteTemplates/ISS/App_Themes/ISS/Images/branding-nus.png' width=15% style="float: right;">
---
```
import IPython.display
IPy... | github_jupyter |
# Sequence to Sequence attention model for machine translation
This notebook trains a sequence to sequence (seq2seq) model with two different attentions implemented for Spanish to English translation.
The codes are built on TensorFlow Core tutorials: https://www.tensorflow.org/tutorials/text/nmt_with_attention
```
i... | github_jupyter |
# QCoDeS Example with DynaCool PPMS
This notebook explains how to control the DynaCool PPMS from QCoDeS.
For this setup to work, the proprietary `PPMS Dynacool` application (or, alternatively `Simulate PPMS Dynacool`) must be running on some PC. On that same PC, the `server.py` script (found in `qcodes/instrument_dri... | github_jupyter |
# Sentiment analysis
```
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
df=pd.read_csv("train.csv")
df.head()
df.shape
df_clean=df.drop(['ID','Place','location','date','status','job_title','summary','advice_to_mgmt','score_1','score_2','score_3','score_4','score_5','score_6','overall'... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.