text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# Matplotlib
**Matplotlib** is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python interpreter and IPython shell, the jupyter notebook, web application servers, and g... | github_jupyter |
# Deep Reinforcement Learning for Stock Trading from Scratch: Multiple Stock Trading
Tutorials to use OpenAI DRL to trade multiple stocks in one Jupyter Notebook | Presented at NeurIPS 2020: Deep RL Workshop
* This blog is based on our paper: FinRL: A Deep Reinforcement Learning Library for Automated Stock Trading in... | github_jupyter |
<a href="https://colab.research.google.com/github/joymaxnascimento/python/blob/master/bootcamp_igti/01_fundamentos/aula_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#mostrando o funcionamento do garbage collection
import sys #módulo utiliz... | github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
import csv
from scipy.optimize import minimize
import cvxpy as cvx
import osqp
import transactive_control.agents as agents
from transactive_control.simulation import Office
def price_signal(day = 45):
"""
Utkarsha's work on price signal from a building with d... | github_jupyter |
```
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from scipy import optimize
filenames = ["galaxy1.fits", "galaxy2.fits"]
galaxy_1_coords_pixels = (1833.88, 647.17)
galaxy_2_coords_pixels = (1347.92, 946.57)
coords_pixels = [galaxy_1_coords_pixels, galaxy_2_coords_pixels]
```
# Plot data... | github_jupyter |
A lot of Pandas' design is for speed and efficiency.
Unfortunately, this sometimes means that is it easy to use Pandas incorrectly, and so get results that you do not expect.
This page has some rules we suggest you follow to stay out of trouble when using Pandas.
As your understanding increases, you may find that yo... | github_jupyter |
```
%matplotlib inline
from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words = 10000)
len(train_data)
len(test_data)
def decode_words(data):
word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_ind... | github_jupyter |
# Comparing qubits
In this exercise we will show a real comparison between the different qubits in one of the machines.
We will run the same Bell state quantum program on three different setups:
- an ideal quantum computer (qasm_simulator)
- the 'best' and the 'worst' qubit pair on a five qubit least busy IBM Q machi... | github_jupyter |
# Embedding and Filtering Inference
Set default input and output directories according to local paths for data
```
import os
os.environ['TRKXINPUTDIR']="/global/cfs/cdirs/m3443/data/trackml-kaggle/train_10evts"
os.environ['TRKXOUTPUTDIR']= "/global/cfs/projectdirs/m3443/usr/caditi97/iml2020/misaligned/new_mis/shift_x... | github_jupyter |
# Create 7777 video - 'everyday' alignment 2nd attempt
This notebook shows the full code base needed to align all of Noah's images from the 'everyday' project and create the video [7777](https://www.youtube.com/watch?v=DC1KHAxE7mo).
```
from IPython.lib.display import YouTubeVideo
YouTubeVideo('DC1KHAxE7mo')
```
In ... | github_jupyter |
# Deep Learning - Hidden Layers
https://www.youtube.com/watch?v=UCG1FuKmIOs
## Why do we stack layers
(adapted from http://stats.stackexchange.com/questions/63152/what-does-the-hidden-layer-in-a-neural-network-compute)
Let's call the input vector $x$, the hidden layer activations $h$, and the output activation $y$.... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/search_by_buffer_distance.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a t... | github_jupyter |
```
# check if there are duplictaes in the clinical notes
import numpy as np
from collections import Counter
import pickle
df_train = pickle.load(open('/home/thetaphipsi/MasterAI/src/CNEP/src/data/mimic3/full_train_data.pickle', 'rb'))
df_val = pickle.load(open('/home/thetaphipsi/MasterAI/src/CNEP/src/data/mimic3/ful... | github_jupyter |
# Preview
In this example, we are going to use our toolbox to write the [PETS](https://arxiv.org/pdf/1805.12114.pdf) algorithm (Chua at al., 2018), and use it to solve a continuous version of the cartpole environment. PETS is a model-based algorithm that consists of two main components: an ensemble of probabilistic mo... | github_jupyter |
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.text import *
import numpy as np
import pickle
import sentencepiece as spm
from tqdm import tqdm
import fastai, torch
fastai.__version__ , torch.__version__
!nvidia-smi
torch.cuda.set_device(0)
!pwd
path = Path('/home/gaurav/PycharmProjects/code-mi... | github_jupyter |
# T81-558: Applications of Deep Neural Networks
**Module 12: Deep Learning and Security**
* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)
* For more information visit the [cl... | github_jupyter |
# Data Augmentation for Homegrown models
This generates augmented data for using with the homegrown models
```
import csv
import time
```
# Config Params
Update {IMAGE PATH}
```
image_basepath = '{IMAGE PATH}'
feature_basepath = '{IMAGE PATH}/resnet50_features_vectors/'
augmented_image... | github_jupyter |
# Data Augmentation
This process includes the following procedures;
- Data Mathcing
- Data Augmentation
- Data Shuffling
```
import pandas as pd
import numpy as np
df = pd.read_excel("data/dialog_200226.xlsx")
df.head(3)
df = df.rename(columns={"대분류": "major", '소분류':'minor', "상황":'situation','Set Nr.':'scenario', '발화자... | github_jupyter |
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
# # PyTorch Lightning
import pytorch_lightning as pl
# from pytorch_lightning import Trainer
# from pytorch_lightning.loggers import WandbLogger
# # from pytorch_lightning... | github_jupyter |
```
import pickle, os
import numpy as np
import scvelo as scv
import scanpy
import torch
from veloproj import *
scv.settings.verbosity = 1
parser = get_parser()
args = parser.parse_args(args=['--lr', '1e-5',
'--n-epochs', '20000',
'--g-rep-dim', '100',
... | github_jupyter |
# Identify missing residues
The goal of this script will be to generate a $(13\times L\times 3)$ coordinate tensor given a PDB entry ID as well as a $(13\times L)$ mask identifying which atoms are missing.
```
import sys
sys.path.append('/home/jok120/protein-transformer/protein')
import Sidechains
import numpy as np
... | github_jupyter |
<a href="https://colab.research.google.com/github/apache/beam/blob/master/examples/notebooks/documentation/transforms/python/elementwise/values-py.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a>
<table align="left"><td><a target="_blank" href="https... | github_jupyter |
# Scan
## In short
* Mechanism to perform loops in a Theano graph
* Supports nested loops and reusing results from previous iterations
* Highly generic
## Implementation
You've previous seen that a Theano function graph is composed of two types of nodes; Variable nodes which represent data and Apply node which app... | github_jupyter |
```
import pandas as pd
import numpy as np
import os
from glob import glob
import random
import matplotlib.pylab as plt
import keras.backend as K
from sklearn.model_selection import train_test_split
import tensorflow as tf
import keras
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
... | github_jupyter |
# Errors and Exceptions
Every programmer encounters errors, both those who are just beginning, and those
who have been programming for years. Encountering errors and exceptions can be
very frustrating at times, and can make coding feel like a hopeless endeavour.
However, understanding what the different types of error... | github_jupyter |
# Building a Bitstream
In this step we will be creating a FPGA Bitstream with your HLS core from **[Creating a Vivado HLS Core](2-Creating-A-Vivado-HLS-Core.ipynb)**. We will be using Vivado to create a block diagram, export it as a `.tcl` file, and compiling it into a `.bit` file.
PYNQ uses this `.tcl` file to match... | github_jupyter |
```
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#df = pd.read_csv("data/1.32.csv")
df100 = pd.read_csv("data/1.0.csv")
df131 = pd.read_csv("data/1.31.csv")
#df132 = pd.read_csv("data/1.32.csv")
df132 = pd.read_csv("data/2016-01-26-hc-1.32.csv")
dfte... | github_jupyter |
```
import sys, os
if 'google.colab' in sys.modules and not os.path.exists('.setup_complete'):
!wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash
!wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/week09_policy_II/runners.p... | github_jupyter |
# Assignment 4: Word Embeddings
Welcome to the fourth (and last) programming assignment of Course 2!
In this assignment, you will practice how to compute word embeddings and use them for sentiment analysis.
- To implement sentiment analysis, you can go beyond counting the number of positive words and negative words... | github_jupyter |
#### New to Plotly?
Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).
<br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-fo... | github_jupyter |
# Betaseries extraction
This script combines calculated whole brain trial beta-maps with brain parcellation and extracts trial beta-series for predefined set of brain regions. This analysis step has to be conducted separately for each parcellation. `NiftiSpheresMasker` is used for signal extraction with parameters:
- ... | github_jupyter |
# Datafaucet
Datafaucet is a productivity framework for ETL, ML application. Simplifying some of the common activities which are typical in Data pipeline such as project scaffolding, data ingesting, start schema generation, forecasting etc.
```
import datafaucet as dfc
from datafaucet import logging
```
## Logging
... | github_jupyter |
```
# default_exp parser
```
# Parser
> Este módulo processa o arquivo bin e extrai os metadados e dados do espectro dos blocos, além de criar estatísticas das medições.
en: This module process the bin file extracting its metadata and spectrum levels besides extracting useful statistics.
fr: Ce module traite le fi... | github_jupyter |
# API Rest cliente
```
from unittest import TestCase
import json, requests
from jsonschema import validate
import socket
import unittest
ipServer = socket.gethostbyname(socket.gethostname())
URLBASE = "http://127.0.1.1:10000"
URISOBA = "/api/soba/v1/occupants"
URISEBA = "/api/seba/v1/occupants"
URIFIRE = "/api/seb... | github_jupyter |
```
# This mounts your Google Drive to the Colab VM.
from google.colab import drive
drive.mount('/content/drive')
# TODO: Enter the foldername in your Drive where you have saved the unzipped
# assignment folder, e.g. 'cs231n/assignments/assignment1/'
FOLDERNAME = None
assert FOLDERNAME is not None, "[!] Enter the fold... | github_jupyter |
# NanoEvents tutorial
This is a rendered copy of [nanoevents.ipynb](https://github.com/CoffeaTeam/coffea/blob/master/binder/nanoevents.ipynb). You can optionally run it interactively on [binder at this link](https://mybinder.org/v2/gh/coffeateam/coffea/master?filepath=binder%2Fnanoevents.ipynb)
NanoEvents is a Coffea... | github_jupyter |
```
import pandas as pd
import re
import os
from email.parser import Parser
emails= pd.read_csv(r'D:\My Personal Documents\Learnings\Data Science\Data Sets\emails.csv')
msg=[]
emailmsg= list(emails.message[0:500000])
for i in emailmsg:
msg.append(re.split(r'\n\n',re.split(r'FileName:',i)[1],maxsplit=1))
#print(... | github_jupyter |
# Effect of the sample size in cross-validation
In the previous notebook, we presented the general cross-validation framework
and how to assess if a predictive model is underfiting, overfitting, or
generalizing. Besides these aspects, it is also important to understand how
the different errors are influenced by the nu... | github_jupyter |
Before you begin, execute this cell to import numpy and packages from the D-Wave Ocean suite, and all necessary functions for the gate-model framework you are going to use, whether that is the Forest SDK or Qiskit. In the case of Forest SDK, it also starts the qvm and quilc servers.
```
%run -i "assignment_helper.py"
... | github_jupyter |
# Homework #2: Music Genre Classification
Music genre classification is an important task that can be used in many musical applications such as music search or recommender systems. Your mission is to build your own Convolutional Neural Network (CNN) model to classify audio files into different music genres. Specificall... | github_jupyter |
```
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("dark")
plt.rcParams['figure.figsize'] = 16, 12
import pandas as pd
from tqdm import tqdm_notebook
import io
from PIL import Image
from glob import glob
from collections import defaultdict
imp... | github_jupyter |
# Anonymize JupyterHub Logs
This notebooks extracts anonymized, publishable user session information from JupyterHub logs.
## Extract user session information from the log
We only care about server starts & stops, so we extract lines related to this from the JupyterHub log. We might pre-filter the log with something... | github_jupyter |
***
* [Outline](../0_Introduction/0_introduction.ipynb)
* [Glossary](../0_Introduction/1_glossary.ipynb)
* [1. Building the Concepts](01_00_introduction.ipynb)
* Previous: Next: [1.7 Manipulating Fits Files and Data with PyFITS, Numpy and Scipy](01_07_manipulating_fits_files_and_data_with_pyfits,_numpy,_and_scip... | github_jupyter |
# Regression, adjusting training parameters, and cross-validation
All MNEflow models can be used for classification and regression. The type of task can be specified during building mnfelow dataset.
```
#Handle imports and suppress verbosity
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import... | github_jupyter |
```
import pandas as pd
import plotly.graph_objects as go
import numpy as np
from datetime import datetime
region_name = "PuertoRico"
xlim = (-68, -65)
ylim = (17, 19)
zlim = (-30, 0)
size = 1
region_name = "Ridgecrest"
xlim = (-117.8, -117.3)
ylim = (35.5, 36.0)
zlim = (-15, 0)
size = 2
region_name = "Hawaii"
xlim =... | github_jupyter |
```
import gzip
from xml.dom import minidom
from utils.list_files import get_stem
import os
import json
from utils.imutil import imshow
import numpy as np
with gzip.open('data/Siren_063021_NoPec_MoreReverb_SideEntrance+Lighting.als') as f:
raw = minidom.parseString(f.read())
def get_attribute(elt, attrib_name)... | github_jupyter |
```
import sys
import os
niftynet_path = '/home/tom/phd/NiftyNet-Generator-PR/NiftyNet'
sys.path.append(niftynet_path)
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from niftynet.io.image_reader import ImageReader
from niftynet.io.... | github_jupyter |
# Visualisation
The `visualisation` module provides visualisation capabilities for Underworld modelling. It provides a higher level interface to the rendering capabilities provided by [LavaVu](https://github.com/OKaluza/LavaVu), but also performs all the required collation of parallel data back to the root process, wh... | github_jupyter |
# Primerjava pristopov za luščenje ključnih fraz na povzetkih člankov s ključno besedo "Longevity"
V tem zvezku predstavljamo primerjavo pristopov za luščenje ključnih besed iz nabora povzetkov člankov s ključno besedo "Longevity" v zbirki PubMed.
Predstavili bomo objektivno primerjavo pristopov za luščenje besed. Pr... | github_jupyter |
# Commodity price forecasting using RNN
```
import pandas as pd
import numpy as np
import os
import time
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# preprocessing methods
from sklearn.preprocessing import StandardScaler
# accuracy measures and data spliting
from sklearn.metrics import... | github_jupyter |
```
%tensorflow_version 2.x
import tensorflow as tf # WELL...
import numpy as np # data manipulation
import pandas as pd # data manipulation
import matplotlib.pyplot as plt # visualise the results
from sklearn.datasets import load_wine # dataset
from sklearn.preprocessing import StandardScaler # Scaler for Normalizati... | github_jupyter |
**[SQL Home Page](https://www.kaggle.com/learn/intro-to-sql)**
---
*This exercise involves you writing code, and we check it automatically to tell you if it's right. We're having a temporary problem with out checking infrastructure, causing a bar that says `None` in some cases when you have the right answer. We're so... | github_jupyter |
# dense_2_Concatenate_20_embeddings_25_epochs
# Deep recommender on top of Amason’s Clean Clothing Shoes and Jewelry explicit rating dataset
Frame the recommendation system as a rating prediction machine learning problem and create a hybrid architecture that mixes the collaborative and content based filtering approac... | github_jupyter |
# Collecting weather data from an API
This notebook contains the code that was used to collect the data for this chapter. Note that if you overwrite the data that came with this chapter by saving the data you collect here, your results in the remaining notebooks may not match the book due to changes in the NCEI API's ... | github_jupyter |
# Widget List
```
import ipywidgets as widgets
```
## Numeric widgets
There are 10 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point co... | github_jupyter |
```
from sage.all import *
rho = var('rho')
rhomaxvar = var('rhomax')
eps = var('eps')
avar = var('avar')
avecvar = vector(var('avarx, avary, avarz'))
n = vector(var('nsrcx, nsrcy, nsrcz'))
assume(rhomaxvar > 0)
assume(eps > 0)
assume(avar > 0)
r2 = eps ** 2 + avar ** 2 * rho ** 2
r = sqrt(r2)
r3 = r2 ** (3 / 2)
r4 = r... | github_jupyter |
**1**. Make a list of consisting of the square of the numbers between 1 and 100 (inclusive) that are not divisible by 3 or 5
- Use a for loop
- Use map and filter
- using `numpy` arrays and vectorized operations
```
xs = []
for i in range(1, 101):
if (i % 3) and (i % 5):
xs.append(i**2)
xs[:10]
xs = list(... | github_jupyter |
```
# welcome to Aestheta's getting started guide!
# Here we'll jump in, grab a tile and do some basic array manipulations
# <-- see that big button over there? thats how we run code blocks in googler colab!
# go ahead and hit it! (or you can also press shift+ENTER)
print('Oh hello there!')
# our session on google ... | github_jupyter |
```
## tensorflow-gpu==2.3.0 bug to load_weight after call inference
!pip install tensorflow-gpu==2.2.0
import yaml
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow_tts.inference import AutoConfig
from tensorflow_tts.inference import TFAutoModel
from tensorflow_tts.inference ... | github_jupyter |
# Finding (Problem Statement) Signal in Sentence Phrasing
Here we look at intersecting (low signal) and exclusive (only in one class aka high signal) [n-grams](https://en.wikipedia.org/wiki/N-gram) of positive and negative labeled sentences.
If there are n-grams that *almost* exclusively appear in one class (0 or 1) ... | github_jupyter |
```
import pandas as pd
df = pd.read_csv('general_data.csv').dropna().drop_duplicates()
df.head()
df.columns
df.isnull()
df.duplicated()
df.drop_duplicates()
```
### Original data
```
df[['Age','DistanceFromHome','Education','MonthlyIncome',
'NumCompaniesWorked', 'PercentSalaryHike','TotalWorkingYears', 'TrainingTi... | github_jupyter |
<a href="https://www.pieriandata.com"><img src="../Pierian_Data_Logo.PNG"></a>
<strong><center>Copyright by Pierian Data Inc.</center></strong>
<strong><center>Created by Jose Marcial Portilla.</center></strong>
# Keras TF 2.0 - Code Along Classification Project
Let's explore a classification task with Keras API for... | github_jupyter |
# Classifying urban sounds using deep learning models.
## Data preprocessing
### Properties to be normalized:
During exploration it was found that the following properties needed normalization:
- Audio channel number.
- Sample Rate
- Bit Depth
Much of the preprocessing can be done via Librosa's load() function. T... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
%autoreload
## massey
import pandas as pd
import numpy as np
import itertools
import pickle
import matplotlib.pyplot as plt
from math import ceil
from tqdm import tqdm
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from pathlib import ... | github_jupyter |
# Semanlink automatic tagging and evaluation
This notebook present how to evaluate a neural search pipeline using pairs of query and answers. We will try to automatically tag arXiv papers that were manually automated by François-Paul Servant as part of the [Semanlink](http://www.semanlink.net/sl/home?lang=fr) Knowledg... | github_jupyter |
```
### Load necessary libraries ###
import glob
import os
import librosa
import numpy as np
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow import keras
### Define helper functions ###
def extract_features(parent_dir,sub_dirs,file_ext="*.wav... | github_jupyter |
# SIRモデル
## 記号の定義
* $S(t)$ : 時点$t$における未感染者数
* $I(t)$ : 時点$t$における感染者数
* $R(t)$ : 時点$t$における感染済かつ回復者数(免疫保持者数)
* $S(t)+I(t)+R(t) \equiv N(t)=N$ :総人口(死亡者数を含め保存されるものとする)
* $\beta$ : 未感染者が感染者と1回の接触で感染する確率
* $\gamma$ : 感染者が1日の内に回復し感染力を失う確率
(※)便宜的に各パラメータを定義する際,時間軸の単位を日としている
## 感染ダイナミクス
時点$t$において,未感染者1人がのべ$j$人と接触したと... | github_jupyter |
## Thinking About Causality
One of the main assumptions that we make when doing causal inference is that the treatment is at least conditionally independent of the potential outcomes.
$
(Y_0, Y_1) \perp T | X
$
This means that we are able to measure an effect on the outcome that is solely due to the treatment, and n... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder,MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split, ParameterGrid
from sklearn.metrics import accuracy_score, confusion_matrix, mean_squared_error, log_loss
from sklea... | github_jupyter |
```
'''
Get the transaction history of the ERC20 tokens.
Author: Jinhua Wang
License: MIT
Powered by Etherscan.io APIs
'''
from bs4 import BeautifulSoup
import urllib3
import urllib
#disable the annoying security warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import sys
import json
import... | github_jupyter |
# IMAGE SEGMENTATION USING K MEANS CLUSTERING
<p align="center">
<img width="700" height="350" src="https://miro.medium.com/max/1000/1*wbaUQkYzRhvmd7IjKJjjCg.gif">
</p>
Image segmentation is an important step in image processing, and it seems everywhere if we want to analyze what’s inside the image. For example, if ... | github_jupyter |
# Twitter bot Detection
## -Aayush Tyagi 2013206
```
# Import Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
#To check Performances
from sklearn.metrics import accuracy_score
f... | github_jupyter |
# Training analysis for DeepRacer
This notebook has been built based on the `DeepRacer Log Analysis.ipynb` provided by the AWS DeepRacer Team. It has been reorganised and expanded to provide new views on the training data without the helper code which was moved into utility `.py` files.
## Usage
I have expanded this... | github_jupyter |
# Python tutorial part 2
In the part 2 we explore lists.
```
# these are lists. In them can be any object. With any length.
mylist_number = [3, 5]
mylist_sting = ["apple", "banana", "banana"]
mylist_everything = ["apple", 120, "cherry", 120]
mylist_long = ["apple", -10, "cherry", 5, "banana", "apple", "banana", 28,... | github_jupyter |
```
# Copyright 2020 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 writi... | github_jupyter |
```
import pandas as pd
import numpy as np
import os, re, ast
from fuzzywuzzy import process
def convert_to_list(df,columns):
df.fillna('', inplace=True)
for col in columns:
if isinstance(df[col][0], str):
df[col] = [ast.literal_eval(s) for s in df[col]]
return df
def find... | github_jupyter |
```
import sys, os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
doubling_time=18
ncells1=800
tmax=7*doubling_time
ncells2=600
fig, ax = plt.subplots(1,2, figsize=(15,5),sharex=True,sharey=True)
data1=pd.read_csv("./SingleStep/data/data2Pop.csv")
smparr=data1.Sample.unique()
smparr.sort(... | github_jupyter |
# 雑草の生育期間を区別して分類器を作る(芽生え)
雑草の生育期間が芽生えのデータを用いて分類器を作成します。 育成した雑草の種類はハキダメギク、ホソアオゲイトウ、イチビ、イヌビエ、コセンダングサ、マメアサガオ、メヒシバ、オヒシバ、オイヌタデ、シロザの10種類です
### ■データのダウンロード
・cluster.zipをダウンロードします。
```
#グーグルドライブからファイルをダウンロードする方法
#ファイル限定
import requests
def download_file_from_google_drive(id, destination):
URL = "https://docs.google.... | github_jupyter |
# Practical 3: Modules and Functions - Introducing Numpy!
<div class="alert alert-block alert-success">
<b>Objectives:</b> In this practical the overarching objective is for you to practice using modules and functions. Following on from a discussion in class, this will be done through 4 sections in this notebook, each... | github_jupyter |
# Unsupervised Learning: Clustering
## World Happiness Report 2021
## Index
1. Load and Explore Data
2. Correlation Analysis
3. Dimensionality Reduction
- PCA
- PCs Dependencies
- PCA Variance Ratio
4. Clustering: apply 3 different approaches
- By partitioning: K-means
- By Hierarchy: Hierarchical Agglomera... | github_jupyter |
# Module 4. Personalize 캠페인과 실시간 상호 작용 하기
이 노트북은 사용자의 실시간 행동에 반응하는 기능을 추가하는 과정을 안내합니다. 영화를 탐색하는 동안 사용자의 의도가 변경되면, 해당 동작에 따라 수정된 추천 영화 목록들이 표시됩니다.
또한 추천 결과가 반환되기 전, 영화를 선택하는 사용자 행동을 시뮬레이션하기 위한 데모 코드를 보여줍니다.
우선, Personalize에 필요한 라이브러리를 가져 오는 것부터 시작합니다.
```
# Imports
import boto3
import json
import numpy as np
import ... | github_jupyter |
# Writing Down Qubit States
```
from qiskit import *
```
In the previous chapter we saw that there are multiple ways to extract an output from a qubit. The two methods we've used so far are the z and x measurements.
```
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0);
# x measureme... | github_jupyter |
# Lab 13: Linear regression
This lab covers both simple and multiple linear regression.</B>
Below is our typical list of imports.
```
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.stats as st
from scipy.stats import multivariate_normal
import csv
print ('Module... | github_jupyter |
# Chaînes de caractères (string)
Une **chaine de caractères** est une *séquence de lettres*. Elle est délimité par des guillemets
* simples
* doubles.
## Un index dans une chaîne
Chaque élement peut être accédé par un **indice** entre crochets.
```
fruit = 'banane'
fruit[0]
fruit[-1]
```
L'indexation commence avec... | github_jupyter |
# Teleportation - Cirq
I will use the Google cirq framework to implement the teleportation protocol.
```
import cirq
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
# Teleportation
In order to verify that measurements statistics are accurately simulated, I will use a rangle of initial states... | 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 |
# Compare pairs of lineages w.r.t. mutational profiles and determinants of transmissibility
```
import pickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import torch
from pyrocov import pangolin
import pandas as pd
matplotlib.rcParams["figure.dpi"] = 200
matplotlib.rcParams["axes.edgecolor"]... | github_jupyter |
### Iterating Collections
We saw how sequence types support iteration by being able to access elements by index. We could even write our custom sequence types by implementing the `__getitem__` method.
But there are some limitations:
* items must be numerically indexable, with indexing starting at `0`
* cannot be use... | github_jupyter |
<small><small><i>
All the IPython Notebooks in **Python Introduction** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/01_Python_Introduction)**
</i></small></small>
# Python Input, Output and Import
This class focuses on two built-in functions **`print()`** and **`input()`**... | github_jupyter |
```
# Allow reload of objects
%load_ext autoreload
%autoreload
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import colors
from mpl_toolkits.mplot3d import Axes3D
from scipy import stats
from scipy.signal import savgol_filter
from tqdm import tqdm
from pelenet.utils import Utils
... | github_jupyter |
### Secure Operations with EC2 and AWS Systems Manger

In this session, we will be creating an EC2 instance using CloudFormation to show you how to automate your [Infrastructure as Code](https://en.wikipedia.org/wiki/Infrastructure_as_code). We will also be leveraging AWS S... | github_jupyter |
# Programming onboard peripherals
## LEDs, switches and buttons
This notebook can be run with the PYNQ-Z1 or PYNQ-Z2. Both boards have four green LEDs (LD0-3), 2 multi color LEDs (LD4-5), 2 slide-switches (SW0-1) and 4 push-buttons (BTN0-3) that are connected to the Zynq’s programmable logic.
Note that there are addi... | github_jupyter |
```
!nvidia-smi
USE_CUDA = torch.cuda.is_available()
print(USE_CUDA)
#Set GPU
import os
import random
os.environ['CUDA_VISIBLE_DEVICES'] = '0' #Set GPU number
#Load Packages
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import imageio
from IPython.display import HT... | github_jupyter |
# 深度卷积神经网络(AlexNet)
:label:`sec_alexnet`
在LeNet提出后,卷积神经网络在计算机视觉和机器学习领域中很有名气。但卷积神经网络并没有主导这些领域。这是因为虽然 LeNet 在小数据集上取得了很好的效果,但是在更大、更真实的数据集上训练卷积神经网络的性能和可行性还有待研究。事实上,在上世纪90年代初到2012年之间的大部分时间里,神经网络往往被其他机器学习方法超越,如支持向量机(support vector machines)。
在计算机视觉中,直接将神经网络与其他机器学习方法进行比较也许不公平。这是因为,卷积神经网络的输入是由原始像素值或是经过简单预处理(例如居中、缩放)的像素值组成的。但... | github_jupyter |
# SageMaker PySpark XGBoost MNIST Example
1. [Introduction](#Introduction)
2. [Setup](#Setup)
3. [Loading the Data](#Loading-the-Data)
4. [Training and Hosting a Model](#Training-and-Hosting-a-Model)
5. [Inference](#Inference)
6. [More on SageMaker Spark](#More-on-SageMaker-Spark)
## Introduction
This notebook will s... | github_jupyter |
<center><h1>Cultural Analytics: Homework #2</h1></center>
<center><b>Due</b> 11:59PM 10/04/2019</center>
---
```
import os
import csv
import numpy as np
import sklearn
input_data = list()
row_count = 0
with open('data/na-slave-narratives/data/toc.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
for row i... | github_jupyter |
# Where would you open a Turkish Restaurant in Berlin?
## 1. Introduction <a name="introduction"></a>
### 1.1 Background
Berlin is the capital and largest city of Germany by both area and population. Its 3,769,495 inhabitants as of 31 December 2019 make it the most populous city of the European Union, according to ... | github_jupyter |
# Householder Similarity Transforms
Copyright (C) 2020 Andreas Kloeckner
<details>
<summary>MIT License</summary>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including wi... | github_jupyter |
# Prelab: Introduction to R #
# Table of Contents #
1. Preamble
2. Using R in CoCalc
3. Basic usage
4. Getting help
5. Loading files
6. T-test
7. Appendix
**1. Preamble**:
Thus far you've been running a lot of command line tools. These are programs that are already written. Now that you're becoming comfortable with... | github_jupyter |
```
# Import libs
import pandas as pd
import numpy as np
import keras
import nltk
import string
import re
from nltk.corpus import stopwords
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.preprocessing import text, sequence
from keras import utils
from keras.preproce... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.