code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
;; ---
;; jupyter:
;; jupytext:
;; text_representation:
;; extension: .scm
;; format_name: light
;; format_version: '1.5'
;; jupytext_version: 1.14.4
;; kernelspec:
;; display_name: Calysto Scheme 3
;; language: scheme
;; name: calysto_scheme
;; ---
;; # Lec22 `#30/11`
;; ### Exercise 1
;;
;; - Syntatic Sugar
;;
;; ### Exercise 2
;;
;; - Tracking a call through our metacircular evaluator
;; ## Lexical vs Dynamic Scope
;;
;; - **Variable Scope**: What part of program is a variable visible
;; - **Lexical Scope**: What env model imlements
;;
;; ### Lexical Scope Example:
;;
;; ```scheme
;; (define (make-person fname lname) ; fname, lname are only defined below
;; (let ((age 9)) ; age is only defined below
;; (lambda (msg) ; msg is only defined below
;; ...
;; ...)))
;; ```
;; ### Dynamic Scope Example:
;;
;; ```scheme
;; (define (pooh x) (bear 20))
;; (define (bear y) (+ x y))
;; (pooh 9)
;; ```
;;
;; - Error in lexical scope
;; - 29 in dynamic scope
| Lectures/Lec22.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] nbgrader={"grade": false, "grade_id": "q3_prompt", "locked": true, "schema_version": 1, "solution": false}
# # Question 3
#
# In this question, we'll focus on looping.
# + [markdown] nbgrader={"grade": false, "grade_id": "q3a_prompt", "locked": true, "schema_version": 1, "solution": false}
# ### Part A
#
# In the question below, you'll write code that generates a new list, `reverse`, that is the same as the input list except with its elements backwards relative to the original.
#
# As an example, if the input list is `[1, 2, 3]`, the output list `reverse` should be `[3, 2, 1]`.
#
# **You have to use loops** to answer this question! `[::-1]` is a neat trick that you should definitely use, and `reversed` is a great function you should also definitely use, but you just can't use them here.
# + nbgrader={"grade": false, "grade_id": "q3a", "locked": false, "schema_version": 1, "solution": true}
def reverse_list(inlist):
reverse = []
### BEGIN SOLUTION
### END SOLUTION
return reverse
# + nbgrader={"grade": true, "grade_id": "q3a_test1", "locked": true, "points": 7, "schema_version": 1, "solution": false}
t1 = [1, 2, 3]
t2 = [3, 2, 1]
assert t2 == reverse_list(t1)
# + nbgrader={"grade": true, "grade_id": "q3a_test2", "locked": true, "points": 7, "schema_version": 1, "solution": false}
t1 = [2, 6, 52, 64, 3.4, "something", 3, 6.2]
t2 = [6.2, 3, "something", 3.4, 64, 52, 6, 2]
assert t1 == reverse_list(t2)
# + [markdown] nbgrader={"grade": false, "grade_id": "q3b_prompt", "locked": true, "schema_version": 1, "solution": false}
# ### Part B
#
# This time, you'll implement a method for computing the average value of a list of numbers. Remember how to compute an average: add up all the values, then divide that sum by the number of values you initially added together.
#
# Example Input: [2, 1, 4, 3]
#
# Example Output: 2.5
#
# Aside from `len()`, you **cannot** use built-in functions like `sum()` or import any packages to help you out. You have to write this on your own!
# + nbgrader={"grade": false, "grade_id": "q3b", "locked": false, "schema_version": 1, "solution": true}
def average(numbers):
avg_val = 0.0
### BEGIN SOLUTION
### END SOLUTION
return avg_val
# + nbgrader={"grade": true, "grade_id": "q3b_test1", "locked": true, "points": 7, "schema_version": 1, "solution": false}
import numpy as np
inlist = np.random.randint(10, 100, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))
# + nbgrader={"grade": true, "grade_id": "q3b_test2", "locked": true, "points": 7, "schema_version": 1, "solution": false}
inlist = np.random.randint(10, 1000, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))
# + [markdown] nbgrader={"grade": false, "grade_id": "q3c_prompt", "locked": true, "schema_version": 1, "solution": false}
# ### Part C
#
# In this question, the function below `first_negative` takes a list of numbers (creatively-named `numbers`). Your goal is to write a `while` loop that searches for the **first negative number** in the list.
#
# You should set the variable `num` equal to that negative number.
#
# If there is no negative number in the list (all the numbers are `>= 0`), just return 0.
# + nbgrader={"grade": false, "grade_id": "q3c", "locked": false, "schema_version": 1, "solution": true}
def first_negative(numbers):
num = 0
### BEGIN SOLUTION
### END SOLUTION
return num
# + nbgrader={"grade": true, "grade_id": "q3c_test1", "locked": true, "points": 5, "schema_version": 1, "solution": false}
inlist1 = [1, 4, -22, -39, 1, 8, 27, 6, 27, -12]
a1 = -22
assert a1 == first_negative(inlist1)
# + nbgrader={"grade": true, "grade_id": "q3c_test2", "locked": true, "points": 2, "schema_version": 1, "solution": false}
inlist2 = [-29, -1, 49, -33, 49, -40, -7, 33, 36, 41]
a2 = -29
assert a2 == first_negative(inlist2)
| assignments/A1/A1_Q3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Import libraries and Packages
import pandas as pd
from pandas import DataFrame
import numpy as np
import datetime as dt
from datetime import datetime,tzinfo
from pytz import timezone
import time
import pytz
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import pprint as pp
#
# ## Filter news by marker
# This notebook is intended to perform the following processes:
#
# 1.1 Creates marks for mapping statistically significant price changes to news articles within a window of time
#
# ___
marker= pd.read_csv('markerNega.csv')
marker.head()
mark=marker['Date'] #create a new column of dates to track events
mark.head(5)
# __Modify datestamp for mapping purposes__
# create list of timestamps according to given datetime parameters
array_mark = []
for i in range(len(mark)):
date = datetime.strptime(mark[i],'%Y-%m-%d')
array_mark.append(date)
pp.pprint(array_mark[0:5])
# __Allows for a given date range of consideration (+- N days from statistically significant price change)__
N = 3
days_before=[]
days_after=[]
for i in range(len(mark)):
date = datetime.strptime(mark[i],'%Y-%m-%d')
days_before.append((date-timedelta(days=N)).isoformat())
days_after.append((date+timedelta(days=N)).isoformat())
# appends additional days to list -- used for mapping of articles
for i in range(len(mark)):
date = datetime.strptime(mark[i],'%Y-%m-%d')
array_mark.append(date-timedelta(days=1))
array_mark.append(date+timedelta(days=1))
array_mark.append(date-timedelta(days=2))
array_mark.append(date+timedelta(days=2))
array_mark.append(date-timedelta(days=3))
array_mark.append(date+timedelta(days=3))
pp.pprint(array_mark[:10])
# 1x8 array of 1's
np.ones(8)
# __Mark 'significant' dates__
# Marking of dates with statistically significant price changes
date_mark=pd.DataFrame({'Date':array_mark,
'Mark':np.ones(len(array_mark))})
pp.pprint(date_mark.head())
date_mark.to_csv('positive_marked_dates.csv')
# +
## checking variable types ##
#type(date_mark['Date'][0]) # .Timestamp
#type(date_mark['Mark'][0]) # float type
# -
# __Prepare articles for marking__
df= pd.read_csv('article_data_and_price_labeled_publisher.csv').drop('Unnamed: 0', axis = 1)
df
# +
#Convert Timestamp into separate Date and Time
#df['Date'] = pd.to_datetime(df['timeStamp']).dt.date
del df['timeStamp'] #Delete original datetime column
df.head()
print(date_mark)
# -
# __Additional Pre-Processing__
# datatype coercion of features
df.date = df.date.astype(str)
date_mark.Date = date_mark.Date.astype(str)
# __Mark articles according to statistically significant price changes__
marked = pd.merge(df,date_mark, how='left', left_on='date',right_on='Date')
# handle missing marks
marked.Mark = marked.Mark.fillna(0)
marked[marked['Mark']==1]
marked.to_csv('1027_negative_marked_news.csv')
# ___
| past-team-code/Fall2018Team1/Exploration/negative_filter_news_by_marker.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.8 64-bit (''base'': conda)'
# name: python3
# ---
# # RAPA Walkthrough
# This tutorial is meant to cover multiple RAPA use cases, including starting from scratch or using a previous DataRobot project.
#
# ### Overview
# 1. Initialize the DataRobot API
# - Save a pickled dictionary for DataRobot API Initialization
# - Use the pickled dictionary to initialize the DataRobot API
# - **(Optional)**: Skip this if the DataRobot API is previously initialized
# 2. Submit data as a project to DataRobot
# - Create a submittable `pandas` dataframe
# - Submit the data using RAPA
# - **(Optional)**: If parsimonious feature reduction is required on an existing project, it is possible to load the project instead of creating a new one.
# 3. Perform parsimonious feature reduction
#
# <a href="https://life-epigenetics-rapa.readthedocs-hosted.com/en/latest/">[Link to the documentation]</a>
import rapa
print(rapa.__version__)
# ## 1. Initialize DataRobot the API
# import pickle
import pickle
import os
# On the <a href="app.datarobot.com"> DataRobot website </a>, find the developer tools and retrieve an API key. Once you have a key, make sure to run the next block of code with your api key replacing the value in the dictionary. Here is a <a href="https://docs.datarobot.com/en/docs/api/api-quickstart/api-qs.html">detailed article on DataRobot API keys</a>.
#
# **Make sure to remove code creating the pickled dataframe and the pickled dataframe itself from any public documents, such as GitHub.**
#
os.listdir()
# +
# save a pickled dictionary for datarobot api initialization
api_dict = {'tutorial':'APIKEYHERE'}
if 'data' in os.listdir('.'):
print('data folder already exists, skipping folder creation...')
else:
print('Creating data folder in the current directory.')
os.mkdir('data')
if 'dr-tokens.pkl' in os.listdir('data'):
print('dr-tokens.pkl already exists.')
else:
with open('data/dr-tokens.pkl', 'wb') as handle:
pickle.dump(api_dict, handle)
# -
# Use the pickled dictionary to initialize the DataRobot API
rapa.utils.initialize_dr_api('tutorial')
# The majority of this tutorial uses the DataRobot API, so if the API is not initialized, it will not run.
# ## 2. Submit data as a project to DataRobot
# This tutorial uses the Breast cancer wisconsin (diagnostic) dataset as an easily accessible example set for `rapa`, as it easily loaded with `sklearn`.
#
# This breast cancer dataset has **30 features** extracted from digitized images of aspirated breast mass cells. A few features are the mean radius of the cells, the mean texture, mean perimater The **target** is whether the cells are from a malignant or benign tumor, with 1 indicating benign and 0 indicating malignant. There are 357 benign and 212 malignant samples, making 569 samples total.
from sklearn import datasets # data used in this tutorial
import pandas as pd # used for easy data management
# loads the dataset (as a dictionary)
breast_cancer_dataset = datasets.load_breast_cancer()
# puts features and targets from the dataset into a dataframe
breast_cancer_df = pd.DataFrame(data=breast_cancer_dataset['data'], columns=breast_cancer_dataset['feature_names'])
breast_cancer_df['benign'] = breast_cancer_dataset['target']
print(breast_cancer_df.shape)
breast_cancer_df.head()
# When using `rapa` to create a project on DataRobot, the number of features is reduced using on of the sklearn functions `sklearn.feature_selection.f_classif`, or `sklearn.feature_selection.f_regress` depending on the `rapa` instance that is called. In this tutorial's case, the data is a binary classification problem, so we have to create an instance of the `rapa.RAPAClassif` class.
#
# As of now, `rapa` only supports classification and regression problems on DataRobot. Additionally, `rapa` has only been tested on tabular data.
# Creates a rapa classifcation object
depression_classification = rapa.rapa.RAPAClassif()
# creates a datarobot submittable dataframe with cross validation folds stratified for the target (benign)
sub_df = depression_classification.create_submittable_dataframe(breast_cancer_df, target_name='benign')
print(sub_df.shape)
sub_df.head()
# submits a project to datarobot using our dataframe, target, and project name.
project = depression_classification.submit_datarobot_project(input_data_df=sub_df, target_name='benign', project_name='TUTORIAL_breast_cancer')
project
# if the project already exists, the `rapa.utils.find_project` function can be used to search for a project
project = rapa.utils.find_project("TUTORIAL_breast_cancer")
project
# ## 3. Perform parsimonious feature reduction
#
# `rapa`'s main function is `perform_parsimony`. Requiring a *feature_range* and a *project*, this function recursively removes features by their relative feature impact scores across all models in a featurelist, creating a new featurelist and set of models with DataRobot each iteration.
#
# * **feature_range:** a list of desired featurelist lengths as integers (Ex: [25, 20, 15, 10, 5, 4, 3, 2, 1]), or of desired featurelist sizes (Ex: [0.9, 0.7, 0.5, 0.3, 0.1]). This tells `rapa` how many features remain after each iteration of feature reduction.
# * **project:** either a `datarobot` project, or a string of it’s id or name. `rapa.utils.find_project` can be used to find a project already existing in DataRobot, or `submit_datarobot_project` can be used to submit a new project.
# * **featurelist_prefix:** provides `datarobot` with a prefix that will be used for all the featurelists created by the `perform_parsimony` function. If running `rapa` multiple times in one DataRobot project, make sure to change the **featurelist_prefix** each time to avoid confusion.
# * **starting_featurelist_name:** the name of the featurelist you would like to start parsimonious reduction from. It defaults to 'Informative Features', but can be changed to any featurelist name that exists within the project.
# * **lives:** number of times allowed for reducing the featurelist and obtaining a worse model. By default, ‘lives’ are off, and the entire ‘feature_range’ will be ran, but if supplied a number >= 0, then that is the number of ‘lives’ there are. (Ex: lives = 0, feature_range = [100, 90, 80, 50] RAPA finds that after making all the models for the length 80 featurelist, the ‘best’ model was created with the length 90 featurelist, so it stops and doesn’t make a featurelist of length 50.) This is similar to DataRobot’s <a href="https://www.datarobot.com/blog/using-feature-importance-rank-ensembling-fire-for-advanced-feature-selection/">Feature Importance Rank Ensembling for advanced feature selection (FIRE)</a> package’s ‘lifes’.
# * **cv_average_mean_error_limit**: limit of cross validation mean error to help avoid overfitting. By default, the limit is off, and the each ‘feature_range’ will be ran. Limit exists only if supplied a number >= 0.0.
# * **to_graph**: a list of keys choosing which graphs to produce. Current graphs are *feature_performance* and *models*. *feature_performance* graphs a stackplot of feature impacts across many featurelists, showing the change in impact over different featurelist lengths. *models* plots `seaborn` boxplots of some metric of accuracy for each featurelist length. These plots are created after each iteration.
#
# Additional arguments and their effects can be found <a href="https://life-epigenetics-rapa.readthedocs-hosted.com/en/latest/">in the API documentation</a>, or within the functions.
ret = depression_classification.perform_parsimony(project=project,
featurelist_prefix='TEST_0.0',
starting_featurelist_name='Informative Features',
feature_range=[25, 20, 15, 10, 5, 4, 3, 2, 1],
lives=5,
cv_average_mean_error_limit=.8,
to_graph=['feature_performance', 'models'])
| tutorials/general_tutorial.ipynb |
# -*- coding: utf-8 -*-
# ## C Integration Examples
#
# Notes:
#
# - SwiftSox package requires sox to be installed: `sudo apt install libsox-dev libsox-fmt-all sox`
# - SwiftVips package requires vips to be installed: see `SwiftVips/install.sh` for steps
%install-extra-include-command pkg-config --cflags vips
%install-location $cwd/swift-install
%install '.package(path: "$cwd/SwiftVips")' SwiftVips
%install '.package(path: "$cwd/SwiftSox")' SwiftSox
%install '.package(path: "$cwd/FastaiNotebook_08_data_block")' FastaiNotebook_08_data_block
import Foundation
import Path
import FastaiNotebook_08_data_block
# ### Sox
import sox
# +
public func InitSox() {
if sox_format_init() != SOX_SUCCESS.rawValue { fatalError("Can not init SOX!") }
}
public func ReadSoxAudio(_ name:String)->UnsafeMutablePointer<sox_format_t> {
return sox_open_read(name, nil, nil, nil)
}
# -
InitSox()
let fd = ReadSoxAudio("SwiftSox/sounds/chris.mp3")
let sig = fd.pointee.signal
(sig.rate,sig.precision,sig.channels,sig.length)
var samples = [Int32](repeating: 0, count: numericCast(sig.length))
sox_read(fd, &samples, numericCast(sig.length))
#if canImport(PythonKit)
import PythonKit
#else
import Python
#endif
%include "EnableIPythonDisplay.swift"
let plt = Python.import("matplotlib.pyplot")
let np = Python.import("numpy")
let display = Python.import("IPython.display")
IPythonDisplay.shell.enable_matplotlib("inline")
let t = samples.makeNumpyArray()
plt.figure(figsize: [12, 4])
plt.plot(t[2000..<4000])
plt.show()
display.Audio(t, rate:sig.rate).display()
# So here we're using numpy, matplotlib, ipython, all from swift! 😎
#
# Why limit ourselves to Python? There's a lot out there that's not in Python yet!
# [next slide](https://docs.google.com/presentation/d/1dc6o2o-uYGnJeCeyvgsgyk05dBMneArxdICW5vF75oU/edit#slide=id.g512a2e238a_144_16)
# ### Vips
import TensorFlow
import SwiftVips
import CSwiftVips
import vips
vipsInit()
let path = downloadImagenette()
let allNames = fetchFiles(path: path/"train", recurse: true, extensions: ["jpeg", "jpg"])
let fNames = Array(allNames[0..<256])
let ns = fNames.map {$0.string}
let imgpath = ns[0]
let img = vipsLoadImage(imgpath)!
func vipsToTensor(_ img:Image)->Tensor<UInt8> {
var sz = 0
let mem = vipsGet(img, &sz)
defer {free(mem)}
let shape = TensorShape(vipsShape(img))
return Tensor(shape: shape, scalars: UnsafeBufferPointer(start: mem, count: sz))
}
show_img(vipsToTensor(img))
# ## fin
| swift/c_interop_examples.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import hypernetx as hnx
from networkx import fruchterman_reingold_layout as layout
from itertools import combinations
import matplotlib.pyplot as plt
# %matplotlib inline
# +
#global variables
node_nb = 0
#gates
X = np.array([[0, 1],
[1, 0]],dtype=np.complex_)
Z = np.array([[1, 0],
[0, -1]],dtype=np.complex_)
I = np.array([[1, 0],
[0, 1]],dtype=np.complex_)
H = np.array([[1/np.sqrt(2), 1/np.sqrt(2)],
[1/np.sqrt(2), -1/np.sqrt(2)]],dtype=np.complex_)
CX = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]],dtype=np.complex_)
CZ = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, -1]],dtype=np.complex_)
CCZ = np.array([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, -1]],dtype=np.complex_)
SWAP = np.array([[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]],dtype=np.complex_)
initial_state = np.array([1, 0],dtype=np.complex_)
excited_state = np.array([0, 1],dtype=np.complex_)
def getUID(prefix='id'):
global node_nb
node_nb = node_nb + 1
return prefix+"_"+str(node_nb - 1)
def getNodeLabels(system):
labels = {}
for n in system.nodes:
labels[n] = system.nodes[n].uid + ' [' + system.nodes[n].qubit + '] ' + str(np.around(system.nodes[n].state,3))
return labels
def getEdgeLabels(system):
labels = {}
for n in system.edges:
labels[n] = n+' '+str(np.around(system.edges[n].amplitude,3))
return labels
def P2R(radii, angles):
return radii * np.exp(1j*angles)
def R2P(x):
return np.abs(x), np.angle(x)
class Node:
def __init__(self,qubit,state):
self.uid = getUID('node')
self.qubit = qubit
self.state = state
self.edge_uid = None
class Hyperedge:
def __init__(self,amplitude,uid=None):
self.node_uids = []
if (uid is None):
self.uid = getUID('edge')
else:
self.uid = uid
self.amplitude = amplitude
class Hypergraph:
def __init__(self,nb_qubits, sv=[]):
self.nodes = {}
self.edges = {}
if (len(sv) > 0):
for i in range(0,len(sv)):
prob = sv[i].real**2 + sv[i].imag**2
if (prob):
e = Hyperedge(sv[i])
self.edges[e.uid] = e
#create nodes
bits = [(i >> bit) & 1 for bit in range(nb_qubits - 1, -1, -1)]
j = 0
for bit in bits:
p = Node("q"+str(j),(excited_state if bit == 1 else initial_state))
#add nodes to hgraph
self.nodes[p.uid] = p
#add nodes to edge
self.addNodeToEdge(p.uid,e.uid)
j = j + 1
else:
for i in range(0,nb_qubits):
node = Node("q"+str(i),np.array([1, 0],dtype=np.complex_))
self.nodes[node.uid] = node
def normalize_complex_arr(self,a):
norm = np.linalg.norm(a)
return a / norm
def getQubitNodeIds(self,qubit):
uids = []
for n in self.nodes:
if (self.nodes[n].qubit == qubit):
uids.append(self.nodes[n].uid)
return uids
def getQubitNodeIdInEdge(self,qubit,edge_uid):
for n in self.nodes:
if (self.nodes[n].qubit == qubit):
if ((self.nodes[n].edge_uid is None and edge_uid is None) or (self.nodes[n].edge_uid == edge_uid)):
return self.nodes[n].uid
return None
def getQubitNodeId(self,qubit,edge):
uids = []
for n in self.edges[edge].node_uids:
if (self.nodes[n].qubit == qubit):
return self.nodes[n].uid
return None
def getQubitEdgeIds(self,qubit):
uids = []
for e in self.edges:
node_uids = self.edges[e].node_uids
for node_uid in node_uids:
if (self.nodes[node_uid].qubit == qubit):
uids.append(e)
return uids
def addNodeToEdge(self, node_uid, edge_uid):
#assume edge and node exist
if (self.nodes[node_uid].edge_uid == None):
self.nodes[node_uid].edge_uid = edge_uid
self.edges[edge_uid].node_uids.append(node_uid)
def deleteNode(self, node_uid):
#assuming nodes only belong to one element
if (node_uid in self.nodes.keys()):
e_uid = self.nodes[node_uid].edge_uid
self.nodes.pop(node_uid)
if (e_uid in self.edges.keys()):
i = self.edges[e_uid].node_uids.index(node_uid)
self.edges[e_uid].node_uids.pop(i)
def deleteEdge(self, edge_uid):
if ((edge_uid in self.edges.keys()) and len(self.edges[edge_uid].node_uids) == 0):
self.edges.pop(edge_uid)
def applyGate(self, qubit, gate):
for n in self.nodes:
if (self.nodes[n].qubit == qubit):
#we apply the gate
self.nodes[n].state = np.dot(gate,self.nodes[n].state)
#We must conbine them in distributabliy
def combineEdges(self, a_edge_ids, b_edge_ids):
for a_id in a_edge_ids:
for b_id in bedge_ids:
a_edge = self.edges[a_id]
b_edge = self.edges[b_id]
e = Hyperedge(a_edge.amplitude*b_edge.amplitude)
self.edges[e.uid] = e
#recrerate the nodes of a inside the new edge
for n_id in a_edge.node_uids:
p = Node(self.nodes[n_id].qubit,self.nodes[n_id].state)
self.nodes[p.uid] = p
self.addNodeToEdge(p.uid,e.uid)
#recrerate the nodes of b inside the new edge
for n_id in b_edge.node_uids:
p = Node(self.nodes[n_id].qubit,self.nodes[n_id].state)
self.nodes[p.uid] = p
self.addNodeToEdge(p.uid,e.uid)
#Cleanup and delete the old nodes and edges
for e_id in a_edge_ids:
edge = self.edges[e_id]
for n_id in edge.node_uids:
self.deleteNode(n_id)
self.deleteEdge(e_id)
for e_id in b_edge_ids:
edge = self.edges[e_id]
for n_id in edge.node_uids:
self.deleteNode(n_id)
self.deleteEdge(e_id)
#We assume a != b
def apply2QubitGate(self, a, b, gate):
#if one of the qubits is not entangled but the other is we need to add the qubit to all corresponding edges before we start with the operation (sort of decompress)
#preprocessing NOT tested
a_edge_ids = self.getQubitEdgeIds(a)
b_edge_ids = self.getQubitEdgeIds(b)
if (len(a_edge_ids) == 0 and len(b_edge_ids) != 0):
a_node_ids = self.getQubitNodeIds(a)
a_node = self.nodes[a_node_ids[0]]
for edge_id in b_edge_ids:
#create node
p = Node(a_node.qubit,a_node.state)
#add nodes to hgraph
self.nodes[p.uid] = p
#add nodes to edge
self.addNodeToEdge(p.uid,edge_id)
#delete original node
#did nt belong t any edge anyway
self.deleteNode(a_node.uid)
elif (len(b_edge_ids) == 0 and len(a_edge_ids) != 0):
b_node_ids = self.getQubitNodeIds(b)
b_node = self.nodes[b_node_ids[0]]
for edge_id in a_edge_ids:
#create node
p = Node(b_node.qubit,b_node.state)
#add nodes to hgraph
self.nodes[p.uid] = p
#add nodes to edge
self.addNodeToEdge(p.uid,edge_id)
#delete original node
#did nt belong t any edge anyway
self.deleteNode(b_node.uid)
#if both entangled but in different edges we need to do some preprocessing as well
shared_edges = list(set(a) & set(b))
#tbh, if edges are not shared they, the intersection must be empty. Any other set-up it's just not a valid state
if (len(shared_edges) == 0):
self.combineEdges(a_edge_ids,b_edge_ids)
# From here on we assume both are either not entangled or share the same edges
a_node_ids = self.getQubitNodeIds(a)
b_node_ids = self.getQubitNodeIds(b)
for a_id in a_node_ids:
for b_id in b_node_ids:
if ((a_id in self.nodes.keys()) and (b_id in self.nodes.keys())):
if (self.nodes[a_id].edge_uid == self.nodes[b_id].edge_uid):
parent_amplitude = 1
if (self.nodes[a_id].edge_uid != None):
parent_amplitude = self.edges[self.nodes[a_id].edge_uid].amplitude
#get local 2 qubit state vector
sv = np.kron(self.nodes[a_id].state, self.nodes[b_id].state)
#apply the gate
new_sv = np.dot(gate, sv)
#this is hard coded for 2 (00,01,10,11)
#for garbage collection afterwards
gc_n = [a_id, b_id]
#for garbage collection afterwards
gc_e = self.nodes[a_id].edge_uid
#process result
for i in range(0,4):
prob = new_sv[i].real**2 + new_sv[i].imag**2
if (prob):
#TODO This is used in many places and can be abstracted
e = Hyperedge(parent_amplitude*new_sv[i])
self.edges[e.uid] = e
#create nodes
p = Node(a,(excited_state if i>1 else initial_state))
q = Node(b,(excited_state if i%2 else initial_state))
#add nodes to hgraph
self.nodes[p.uid] = p
self.nodes[q.uid] = q
#add nodes to edge
self.addNodeToEdge(p.uid,e.uid)
self.addNodeToEdge(q.uid,e.uid)
#If they were inside an edge, this edge can have nodes from other qubits
#These nodes should also be replicated and the original ones deleted afterwards
e_id = self.nodes[a_id].edge_uid
if (e_id is not None):
for n_id in self.edges[e_id].node_uids:
if (n_id != a_id and n_id != b_id):
n = self.nodes[n_id]
#create nodes
p = Node(n.qubit,n.state)
#add nodes to hgraph
self.nodes[p.uid] = p
#add nodes to edge
self.addNodeToEdge(p.uid,e.uid)
gc_n.append(n_id)
#Collect garbage
for g_id in gc_n:
self.deleteNode(g_id)
#All belong to same edge
if (gc_e is not None):
self.deleteEdge(gc_e)
def getGlobalPhase(self, state):
for s in state:
(val, angle) = R2P(s)
#TODO is this a good convention?
if (val != 0):
return angle
return None
def correctPhase(self, state):
angle = self.getGlobalPhase(state)
for i, s in enumerate(state):
(absi, angi) = R2P(s)
state[i] = P2R(absi,angi-angle)
return state
def stateEq(self, state1, state2):
#Correct for global phase
state1 = self.correctPhase(state1)
state2 = self.correctPhase(state2)
return np.array_equal(state1,state2)
#Transforms the full system
def toStateVector(self):
sv = np.array([])
#First we deal with edges and entangled qubits
for edge in self.edges:
parent_amplitude = self.edges[edge].amplitude
tmp_sv = np.array([])
for node_uid in self.edges[edge].node_uids:
if (len(tmp_sv) == 0):
tmp_sv = self.nodes[node_uid].state
else:
tmp_sv = np.kron(self.nodes[node_uid].state,tmp_sv)
tmp_sv = parent_amplitude * tmp_sv
if (len(sv) == 0):
sv = tmp_sv
else:
sv = sv + tmp_sv
#Then we deal with the non-entangled ones
#Kroenecker product of all nodes
for node_uid in self.nodes:
if (self.nodes[node_uid].edge_uid is None):
if (len(sv) == 0):
sv = self.nodes[node].state
else:
sv = np.kron(self.nodes[node].state,sv)
return sv
# m Hyperedge matrix
# runs one merge
# m isdict with edges and qubits
# a is dictionary with edge amplitudes
#TODO: See inline
def simplifyRec(self, m, amps):
if (len(m.keys()) == 1):
return (m,amps)
res = {}
processed = []
#do one run
for e1 in m:
processed.append(e1)
for e2 in m:
if (e2 not in processed):
#can we merge e1 and e2
nb_diff = 0
a = None
b = None
e = None
x = amps[e1]
y = amps[e2]
nodes = {}
for n in m[e1]:
if (not self.stateEq(m[e1][n],m[e2][n])):
nb_diff += 1
nodes[n] = self.normalize_complex_arr((amps[e1]*m[e1][n]) + (amps[e2]*m[e2][n]))
a = np.reshape(m[e1][n],(len(m[e1][n]),1))
b = np.reshape(m[e2][n],(len(m[e2][n]),1))
e = np.reshape(nodes[n],(len(nodes[n]),1))
else:
nodes[n] = m[e1][n]
#TODO: We are missing the case where nb_diff == 0
#If nb_diff == 0
# -> should I resimplify the edge amplitudes?
if (nb_diff == 1):
res[e1+'_'+e2] = nodes
te = np.transpose(e)
amps[e1+'_'+e2] = np.dot(te,(x*a + y*b))[0]
for e3 in m:
if (e3 != e1 and e3 != e2):
res[e3] = m[e3]
#recursive step
return self.simplifyRec(res,amps)
#If we end up here it means we havent simplified anything
return (m,amps)
#m Hyperedge dict
def deleteEdges(self,m):
for e in m:
for q in m[e]:
self.deleteNode(self.getQubitNodeId(q,e))
self.deleteEdge(e)
#m Hyperedge dict
def createEdges(self,m, amps):
if (len(m.keys()) <= 1):
for e in m:
for q in m[e]:
node = Node(q,m[e][q])
self.nodes[node.uid] = node
else:
t = {}
for e in m:
for q in m[e]:
if (q not in t.keys()):
t[q] = {}
t[q][e] = m[e][q]
#Check which qubits are entangled
non_entangled = []
for q in t:
q_first = None
all_equal = True
for e in t[q]:
if (q_first is None):
q_first = t[q][e]
else:
all_equal = all_equal and (self.stateEq(t[q][e],q_first))
if (all_equal):
non_entangled.append(q)
for e in m:
edge = Hyperedge(amps[e],e)
self.edges[edge.uid] = edge
for q in m[edge.uid]:
node = Node(q,m[edge.uid][q])
self.nodes[node.uid] = node
if (q not in non_entangled):
self.addNodeToEdge(node.uid,edge.uid)
#Move all node global phases are bubbled up to the corresponding edges!
def factorPhases(self, qubits):
for node_uid in self.nodes:
edge_uid = self.nodes[node_uid].edge_uid
if (edge_uid is not None):
angle_n = self.getGlobalPhase(self.nodes[node_uid].state)
print("angle",angle_n)
print("old_state",self.nodes[node_uid].state)
self.nodes[node_uid].state = self.correctPhase(self.nodes[node_uid].state)
print("new_state",self.nodes[node_uid].state)
print("old_amp",self.edges[edge_uid].amplitude)
(val_e, angle_e) = R2P(self.edges[edge_uid].amplitude)
print("angle",angle_e)
self.edges[edge_uid].amplitude = P2R(val_e, angle_e + angle_n)
print("new_amp",self.edges[edge_uid].amplitude)
def simplify(self, qubits):
#preprocessing: Make sure all node global phases are bubbled up to the crresponding edges!
self.factorPhases(qubits)
#build matrix and check if exactly all the qubits are in hyperedges
m = {}
amps = {}
error = False
for q in qubits:
edge_ids = self.getQubitEdgeIds(q)
if (len(edge_ids) == 0):
error = 'qubit ' + q + ' is not entangled'
for e in edge_ids:
if (e not in m.keys() and qubits.index(q) == 0):
m[e] = {}
amps[e] = self.edges[e].amplitude
elif (e not in m.keys()):
error = 'The qubits are not entangled all together'
for n in self.edges[e].node_uids:
if (self.nodes[n].qubit not in qubits):
error = 'The qubits are entangled with others not specified in the input'
if (self.nodes[n].qubit == q):
m[e][q] = self.nodes[n].state
if (error):
print(error)
return
#call recursive part
(m_simp,amps_simp) = self.simplifyRec(m,amps)
#process output dict
self.deleteEdges(m)
self.createEdges(m_simp,amps_simp)
def print_raw(self):
print("nodes:")
for n in self.nodes:
print(self.nodes[n].state)
print("edges:")
for e in self.edges:
print(self.edges[e].amplitude)
def draw(self):
s = hnx.Entity('system', elements=[], amplitude=1)
hg = hnx.Hypergraph()
hg.add_edge(s)
empty_system = True
for i in self.edges:
edge = hnx.Entity(i+' '+str(np.around(self.edges[i].amplitude,3)))
hg.add_edge(edge)
for i in self.nodes:
node = hnx.Entity(str(self.nodes[i].uid) + ' [' + str(self.nodes[i].qubit) + '] ' + str(np.around(self.nodes[i].state,3)))
if (self.nodes[i].edge_uid == None):
hg.add_node_to_edge(node,'system')
empty_system = False
else:
euid = self.nodes[i].edge_uid
l_euid = euid+' '+str(np.around(self.edges[euid].amplitude,3))
hg.add_node_to_edge(node,l_euid)
if (empty_system):
hg.remove_edge("system")
'''hnx.drawing.rubber_band.draw(hg,
node_labels=getNodeLabels(hg),
edge_labels=getEdgeLabels(hg),
node_radius=2.0,
label_alpha=1.0
)'''
hnx.drawing.two_column.draw(hg)
# +
system = Hypergraph(3)
system.applyGate("q0",H)
system.apply2QubitGate("q0","q1",CX)
system.apply2QubitGate("q1","q2",CX)
system.applyGate("q2",H)
system.apply2QubitGate("q2","q1",CX)
system.simplify(["q0","q1","q2"])
print(system.toStateVector())
system.draw()
# +
sv = np.array([0.707+0j, 0+0j, 0+0j, 0.707+0j],dtype=np.complex_)
system = Hypergraph(2,sv)
system.applyGate("q1",Z)
system.simplify(["q0","q1"])
system.draw()
# +
sv = np.array([0.35+0j, 0.35+0j, 0.35+0j, 0.35+0j, 0.35+0j, 0.35+0j, 0.35+0j, 0.35+0j],dtype=np.complex_)
system = Hypergraph(3,sv)
system.simplify(["q0","q1","q2"])
system.draw()
#print(system.toStateVector(["q0","q1"]))
# -
a = -0.5+0j
np.angle(a, deg=True)
| prototype-Copy1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
l = [3, 6, 7, -1, 23, -10, 18]
print(max(l))
print(min(l))
ld = sorted(l, reverse=True)
print(ld)
print(ld[:3])
la = sorted(l)
print(la)
print(la[:3])
print(sorted(l, reverse=True)[:3])
print(sorted(l)[:3])
print(l)
l.sort(reverse=True)
print(l[:3])
print(l)
l.sort()
print(l[:3])
print(l)
| notebook/max_min_sorted.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.9.2 64-bit (''stock-price-prediction'': conda)'
# name: python39264bitstockpricepredictioncondad3d836eb614a4dd49be4ca55d4687f95
# ---
# +
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# +
import sys, site
from pathlib import Path
import stock_price_prediction
import glob
import pandas as pd
import matplotlib.pyplot as plt
scripts_dir = Path.cwd().parent.joinpath("scripts")
if not scripts_dir.joinpath("download_data.py").exists():
# download get_data.py script
scripts_dir = Path("~/tmp/qlib_code/scripts").expanduser().resolve()
scripts_dir.mkdir(parents=True, exist_ok=True)
import requests
with requests.get("https://raw.githubusercontent.com/jgehunter/stock_price_prediction/main/scripts/download_data.py") as resp:
with open(scripts_dir.joinpath("download_data.py"), "wb") as fp:
fp.write(resp.content)
# -
# Download data
file_name = "AAPL.parquet"
target_dir = "~/OneDrive - Santander Office 365/Projects/stock_price_prediction/Data/"
tickers = "AAPL"
start_date = "2015-01-01"
from stock_price_prediction.download.ticker_download import GetData
GetData()._download_data(file_name, target_dir, tickers, start=start_date)
# Load data in df
data_path = glob.glob(str(Path(target_dir + "/*_" + file_name).expanduser()))
stock_df = pd.read_parquet(data_path)
stock_df["Open"].plot()
from stock_price_prediction.models.sfm_model import SFM
sfm_model = SFM(d_feat=1)
import random
x_train = []
y_train = []
random_index = random.randint(0,len(stock_df)-1)
x_train_sample = stock_df[:random_index]["Open"]
y_train_sample = stock_df.iloc[random_index+1]["Open"]
x_train.append(x_train_sample)
y_train.append(y_train_sample)
x_val = []
y_val = []
random_index = random.randint(0,len(stock_df)-1)
x_val_sample = stock_df[:random_index]["Open"]
y_val_sample = stock_df.iloc[random_index+1]["Open"]
x_val.append(x_val_sample)
y_val.append(y_val_sample)
y_train_sample
sfm_model.fit(x_train_sample, x_train_sample.shift(), x_val_sample, x_val_sample.shift())
| examples/worflow_example.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 1-4.3 Intro Python Practice
# ## Conditionals
# <font size="5" color="#00A0B2" face="verdana"> <B>Student will be able to</B></font>
# - **control code flow with `if`... `else` conditional logic**
# - using Boolean string methods (`.isupper(), .isalpha(), .startswith()...`)
# - using comparision (`>, <, >=, <=, ==, !=`)
# - using Strings in comparisons
# ## `if else`
#
# +
# [ ] input avariable: age as digit and cast to int
# if age greater than or equal to 12 then print message on age in 10 years
# or else print message "It is good to be" age
age = input("Age:")
if int(age) >= 12:
print("Age in 10 years:",int(age)+10)
else:
print("It is good to be",age)
# +
# [ ] input a number
# if number IS a digit string then cast to int
# print number "greater than 100 is" True/False
# if number is NOT a digit string then message the user that "only int is accepted"
number = input("Number:")
if number.isdigit() == True:
print(number,"greater than 100 is",int(number)>100)
else:
print("only int is accepted")
# -
# ### Guessing a letter A-Z
# **check_guess()** takes 2 string arguments: **letter and guess** (both expect single alphabetical character)
# - if guess is not an alpha character print invalid and return False
# - test and print if guess is "high" or "low" and return False
# - test and print if guess is "correct" and return True
# +
# [ ] create check_guess()
# call with test
letter = "r"
guess = input("Guess a letter:")
def check_guess(letter,guess):
if guess.isalpha() == False:
print("Invalid")
elif guess == letter:
print("True")
elif guess >= letter:
print("False. Too high.")
elif guess <= letter:
print("False. Too low.")
# -
# [ ] call check_guess with user input
guess = input("Guess a letter:")
check_guess(letter,guess)
# ### Letter Guess
# **create letter_guess() function that gives user 3 guesses**
# - takes a letter character argument for the answer letter
# - gets user input for letter guess
# - calls check_guess() with answer and guess
# - End letter_guess if
# - check_guess() equals True, return True
# - or after 3 failed attempts, return False
# +
# [ ] create letter_guess() function, call the function to test
def letter_guess(letter):
guess1 = input("1st Guess:")
if check_guess(letter,guess1) == True:
print("True")
else:
guess2 = input("2nd Guess:")
if check_guess(letter,guess2) == True:
print("True")
else:
guess3 = input("3rd Guess:")
if check_guess(letter,guess3) == True:
print("True")
else:
print("False")
letter_guess("c")
# -
# ### Pet Conversation
# **ask the user for a sentence about a pet and then reply**
# - get user input in variable: about_pet
# - using a series of **if** statements respond with appropriate conversation
# - check if "dog" is in the string about_pet (sample reply "Ah, a dog")
# - check if "cat" is in the string about_pet
# - check if 1 or more animal is in string about_pet
# - no need for **else**'s
# - finish with thanking for the story
# +
# [ ] complete pet conversation
about_pet = input("Tell me a story about your pet")
if "dog" in about_pet.lower():
print("Nice dog!")
elif "cat" in about_pet.lower():
print("That's neat. I have a cat too.")
elif "crab" in about_pet.lower():
print("Hermit crabs are pretty cool.")
print("Thanks for the story.")
# -
# [Terms of use](http://go.microsoft.com/fwlink/?LinkID=206977) [Privacy & cookies](https://go.microsoft.com/fwlink/?LinkId=521839) © 2017 Microsoft
| Python Absolute Beginner/Module_3_Practice_1_IntroPy.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# *Based on a blog post by [<NAME>](http://jakevdp.github.io/blog/2018/09/13/waiting-time-paradox/)*
#
# ### Introduction
#
# Bit of a lighter post after the MCMC series. Came across this article on the waiting time paradox, and I thought it would be a good chance to dosomething light-hearted amidst this COVID outbreak.
#
# We all know that gnawing irritation we feel when, somehow, things are not as rosy as advertised. Bus schedules say that buses come every 10 minutes on average, but why does it always feel like you just missed the bus? Schools say that their average class size is around 20, but how do you always end up in a sardine-packed class? Why do your friends on Facebook always have more friends than you do?
#
# <!--  <br> -->
# <!-- <span style="color: grey; font-style: italic;">Lies</span> -->
#
# Welcome to the inspection paradox, or as the cited post puts it, the "why is my bus always late" paradox.
#
# ### What is the inspection paradox?
# The inspection paradox occurs when the probability of observing a quantity is related to the quantity being observed. This definition is pretty convoluted on it's own, so let's talk about an intuitive example - class size.
#
# Imagine a university cohort of 100 students with 3 different classes in each semester. Class 1 has 70 students, class 2 has 20, and class 3 has 10. From the university's perspective, the average class size is a straightforward $\frac{100}{3} = 33$.
#
# What happens if the students are surveyed? Now the story is completely different! By definition, the class size of 70 is experienced by 70 students, which biases the sample average! Instead of $\frac{100}{3} = 33$, we now have a weighted average of class size $(0.7 \cdot 70) + (0.2 \cdot 20) + (0.1 \cdot 10) = 54$ instead.
#
# In other words, the probability of an individual observing a class size of 70 is directly related to the probability of him/her being in that class!
#
# ### Seeing this in practice
# Let's see this for ourselves using a very relatable example: bus arrival timings. First, let's simulate the arrival time of 100000 bus arrivals with 10 minutes as the average waiting time between buses. The timeline below shows the first 10 simulated bus arrivals assuming the arrivals are random.
# +
import numpy as np
import matplotlib.pyplot as plt
simulated_bus_count = 100000
time_between_buses = 10
random = np.random.RandomState(1)
bus_arrival_times = simulated_bus_count * time_between_buses * np.sort(random.random(simulated_bus_count))
fig, ax = plt.subplots()
plt.plot(bus_arrival_times[:10], [0]*10, '-o', color = 'blue')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
tmp = 1
for i in range(10):
ax.annotate(round(bus_arrival_times[i], 1), (bus_arrival_times[i], 0.01*tmp))
tmp *= -1
plt.yticks([])
plt.title(f'Time of Bus Arrivals ({time_between_buses} minute average)')
plt.show()
# -
# Great! Let's just make sure that, on average, the time between arrivals is 10 minutes.
np.diff(bus_arrival_times).mean()
# Next, we simulate the arrival of passengers randomly along this range.
# +
random = np.random.RandomState(123)
num_passengers = 100000
# Get passenger arrival time
passenger_arrival_times = simulated_bus_count * time_between_buses * np.sort(random.random(num_passengers))
fig, ax = plt.subplots()
plt.plot(bus_arrival_times[:20], [0]*20, '-o', color = 'blue')
plt.plot(passenger_arrival_times[:10], [0]*10, '-o', color = 'red')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
tmp = 1
for i in range(0, 20, 3):
ax.annotate(round(bus_arrival_times[i], 1), (bus_arrival_times[i], 0.01*tmp))
ax.annotate(round(passenger_arrival_times[i], 1), (bus_arrival_times[i], 0.01*-tmp))
plt.yticks([])
plt.title(f'Time of Bus and Passenger Arrivals')
plt.show()
# -
# We overlay our randomly generated passengers on our bus timeline. Using the np.searchsorted() function, we input the array of bus and passenger arrivals, and the function returns an `index` of bus_arrival_times for which inserting each passenger_arrival_times[i] preserves the ordering of the array. Since side = 'right', it returns the largest possible value of the index, or the nearest possible bus arrival for each passenger. Using this, we compute the average waiting time for each passenger.
i = np.searchsorted(bus_arrival_times, passenger_arrival_times, side='right')
average_waiting_time = (bus_arrival_times[i] - passenger_arrival_times).mean()
print(average_waiting_time)
# This is a surprising result! Although the average time between buses is 10 minutes, passengers experience a 10 minute waiting time on average instead of 5mins, which you would expect if you can arrive randomly at any time between 2 buses.
#
# Like the class size example above, this result arises because you have a higher chance of 'catching' in a time period where the time between buses is large (since it takes up a longer stretch of the number line), and this biases average waiting time upwards!
#
# ### Conclusion
# This was a really interesting result to me, because it's a prime example of how our statistical heuristics can end up working horrendously. Yes, I know that bus arrivals don't actually follow a uniform distribution, but I found this instructive an example to illustrate the problem of our heuristics in statistical reasoning.
| _jupyter/2020-04-02-the-inspection-paradox.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model, ensemble, svm, tree, neural_network
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error, make_scorer
from sklearn.model_selection import cross_val_score, train_test_split, GridSearchCV
import warnings
warnings.filterwarnings("ignore")
# -
result = {}
# +
#hhids=[86, 59, 77, 26, 93, 101, 114, 171, 1086, 1403]
hhids=[26, 59, 77, 86, 93, 94, 101, 114, 171, 187]
for hhid in hhids:
result[hhid] = []
print('Start :: Process on household {}...'.format(hhid))
df = pd.read_csv('data_added2/added_hhdata_{}_2.csv'.format(hhid), index_col=0)
df = df.dropna()
st = []
ct = 0
for idx, row in df.iterrows():
if row.GH < 2000 and row.GH > -1000:
st.append(row)
else:
ct += 1
df = pd.DataFrame(data=st, columns=df.columns)
features = [ 'GH', 'use_hour','use_week', 'temperature', 'cloud_cover','wind_speed','is_weekday','month','hour']
Y = list(df.use)[1:]
try:
Y.append(df.use.iloc[0])
except:
break
Y = np.array(Y)
X = df[features]
X = np.array(X)
X.shape
# temp_df = pd.DataFrame(data=X, columns=features)
# temp_df['y_use'] = Y
# values = temp_df.values
# # normalize features
# scaler = MinMaxScaler()
# y_gt = values[:,-1:]
# scaled = scaler.fit_transform(values)
# values = scaled
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=0.10,
random_state=666)
classifiers = [
linear_model.Ridge(alpha=1.0, random_state=0),
linear_model.Lasso(alpha=0.55, random_state=0),
linear_model.BayesianRidge(alpha_1=1e-06, alpha_2=1e-06),
linear_model.LassoLars(alpha=0.55),
linear_model.LinearRegression(),
ensemble.RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None,
max_features='sqrt', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=75, n_jobs=1,
oob_score=False, random_state=0, verbose=0, warm_start=False),
tree.DecisionTreeRegressor(),
neural_network.MLPRegressor(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,
beta_2=0.999, early_stopping=False, epsilon=1e-08,
hidden_layer_sizes=(50, 50), learning_rate='constant',
learning_rate_init=0.001, max_iter=200, momentum=0.9,
nesterovs_momentum=True, power_t=0.5, random_state=0, shuffle=True,
solver='adam', tol=0.0001, validation_fraction=0.1, verbose=False,
warm_start=False)
]
print('Start :: Find the best model for this household...')
for clf in classifiers:
clf.fit(X_train, Y_train)
# print(clf)
yhat = clf.predict(X_test)
scores = cross_val_score(clf, X_train, Y_train)
rmse = np.sqrt(mean_squared_error(Y_test, yhat))
mae = mean_absolute_error(Y_test, yhat)
# print('RMSE =>', rmse)
# print('MAE =>', mae)
# print('CV Score =>', scores)
model_dict = {
'name': clf.__class__.__name__,
'rmse': rmse,
'mae': mae,
}
result[hhid].append(model_dict)
# print('')
# -
result
final = []
for k, v in result.items():
for i in result[k]:
final.append([str(k), i['name'], i['rmse'], i['mae']])
col = ['household_id', 'alg', 'RMSE', 'MAE']
final = pd.DataFrame(data=final, columns=col)
final.to_csv('HL.csv')
final = pd.read_csv('HL.csv', index_col=0)
final
gb = final.groupby('alg')
N = 8
ind = range(N)
mean = list(gb['RMSE'].describe()['mean'])
std = list(gb['RMSE'].describe()['std'])
ind, mean, std
# +
# fig = plt.figure()
# ax = fig.add_subplot(111)
# # ax2 = ax.twinx()
# ax.set_ylabel('RMSE1')
# # ax2.set_ylabel('RMSE2')
# # ax.bar(ind, ghi_mean, 0.3, yerr=ghi_std, color='red', align='center')
# # ax.autoscale(tight=True)
# plt.show()
plt.bar(ind, mean, 0.4, yerr=std, align='center')
plt.ylabel('Home Energy Consumption ($KWh$)')
plt.xlabel('Model')
plt.title('Prediction RMSE of different models')
plt.xticks(ind, ('Ridge', 'Lasso','BR' ,'LasLar', 'LR', 'RF', 'DTR', 'MLP'))
# plt.yticks(np.arange(0, 2))
plt.axhline(y=gb['RMSE'].describe()['mean']['RandomForestRegressor'], linewidth=0.15)
plt.savefig('hl.png')
# -
fig = plt.figure()
| data_processing/hl_model_fig.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # When do the hands of the clock face each other?
# At which times are the hour and the minute hand of the clock located exaclty opposite of each other?
# Imports
# %matplotlib inline
from pylab import *
from scipy.optimize import fmin
rcParams['figure.figsize'] = [9.0, 6.0]
# ## Positionen der Zeiger
# ### Stundenzeiger
# Der Winkel $\varphi$ beschreibt die Position des Stundenzeigers.
# ### Minutenzeiger
# Die Position des Minutenzeigers $\varphi_m$ ist abhängig von $\varphi$: Bei einer Drehung des Stundenzeigers, dreht er sich 12 mal im Kreis:
#
# $ \phi_m = \phi * 12 $.
#
# Durch Modulorechnung mit $2 \pi$ wird ein Winkel $< 2 \pi$ bestimmt:
#
phim = lambda phi: np.mod(phi*12.0, 2*np.pi)
# ### Gegenüberliegende Richtung
# Die einem Zeiger gegenüberliegende Winkelposition wird durch Verdrehen um $\pi$ und eine erneute Modulorechnung bestimmt:
gegenueber = lambda p: np.mod(p+np.pi, 2*np.pi)
# ## Grob bestimmte Zeitpunkte
# Zur Bestimmung der ungefähren Zeitpunkte werden die Zeigerpositionen für 500 Zeitpunkte ausgewertet:
phi = np.linspace(-0.1, 2*np.pi+0.1, 500)
# Die interessierenden Zeitpunkte sind die, bei denen die Stundenzeigerposition gleich der dem
# Minutenzeiger gegeüberliegenden ist:
#
# $\varphi$ == gegenueber($\varphi_m$).
#
# Es weden die Indices des Vektors *phi* gesucht, bei denen sich die beiden Funktionswerte schneiden, d.h. die Indices $i$ bei denen
#
# $phi_i >= gegenueber(phim_i)$
#
# ist und
#
# $phi_{i+1} < gegenueber(phim_{i+1})$.
idc = np.where((phi[:-1]>=gegenueber(phim(phi[:-1])))*
(phi[1:]<gegenueber(phim(phi[1:]))))[0]
print('Stundenzeigerpositionen: ', phi[idc])
# Dartstellung der Winkelverläufe und der grob bestimmten Schnittpunkte:
plot(phi, phi, label='$phi$')
plot(phi, phim(phi), ':', label='$phi_m$')
plot(phi, gegenueber(phim(phi)), label='$phi_m^g$')
plot(phi[idc], phi[idc], '*', label='phi_X')
legend()
grid(True)
# ## Numerische Optimierung: Bestimmung der Schnittpunkte
# +
fun = lambda p: (p-gegenueber(phim(p)))**2
phi_X = [fmin(fun, np.array([phi[i]]), disp=False, ftol=1e-12)[0]
for i in idc]
print(phi[idc]-phi_X)
# -
plot(phi, phi, label='$phi$')
plot(phi, gegenueber(phim(phi)), label='$phi_m^g$')
plot(phi[idc], phi[idc], 'o', label='phi_X')
plot(phi[idc], phi_X, '*', label='phi_Xopt')
legend()
for p in phi_X:
hf = p/2/np.pi*12
h = int(hf)
m = int((hf-h)*60)
s = (hf-h-m/60)*60*60
print('{h:02d}:{m:02d}\'{s:2.4f}'.format(h=h, m=m, s=s))
# Gütefunktion:
plot(phi, fun(phi))
plot(phi, phi*12+np.pi, label='$phi_{gegenüber}$')
for offs in range(12):
plot(phi, phi+offs*2*np.pi, 'g', label='$phi$')
plot(phi[idc], phi[idc]*12+np.pi, 'o', label='phi_Xopt')
legend(('gegenüber Minutenzeiger', 'Stundenzeiger + $n\pi$'))
xlabel('Winkel des Stundenzeigers')
ylabel('Winkel')
grid(True)
# # Symbolisch: Einfacher?
from sympy import *
init_printing()
phi, phim, n, h = symbols('varphi, varphi_m, n, h')
# $ h = phi/{2\pi} *12$
#
# $\varphi == gegenueber(\varphi_m) - n * 2\pi$
#
# $\varphi == 12 \varphi + \pi - n 2\pi$
#
# $\varphi - 12 \varphi - \pi + n 2\pi == 0$
#
phi = h/12 * 2 * pi
phim = 12 * phi
eq = phi + n*2*pi-phim+pi
pprint(eq)
h_eq = solve(eq, h)[0]
h_eq
for val in range(1, 12):
hS = (h_eq).subs(n, val).n(20)
print('{org:015.12f}: {h:02.0f}:{m:02.0f}\'{s:08.5f}"'.format(
org=float(hS),
h=float(np.floor(hS)),
m=float(np.floor(np.mod(hS, 1.0)*60)),
s=float(np.mod((np.mod(hS, 1.0)*60), 1.0)*60)))
# ## Zeiger in die gleiche Richtung
phi = h/12 * 2 * pi
phim = 12 * phi
eq = phi + n*2*pi - phim
pprint(eq)
h_eq = solve(eq, h)[0]
h_eq
for val in range(1, 12):
hS = (h_eq).subs(n, val).n(20)
print('{org:015.12f}: {h:02.0f}:{m:02.0f}\'{s:08.5f}"'.format(
org=float(hS),
h=float(np.floor(hS)),
m=float(np.floor(np.mod(hS, 1.0)*60)),
s=float(np.mod((np.mod(hS, 1.0)*60), 1.0)*60)))
| clock-hands.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Análisis de la base de datos "earthquake"
# En este notebook realizaremos una exploración de la base de datos earthquake obtenida en [kaggle](https://www.kaggle.com/usgs/earthquake-database). Esta contiene el histórico de sismos relevantes (con magnitud mayor o igual a 5.5) desde 1965 hasta 2016.
# +
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
# -
sismo = pd.read_csv('../data/earthquake.csv')
# +
print(' Dimensión del DataFrame:')
print(sismo.shape)
print('\nNombre de las columnas de nuestro data frame: \n')
print(sismo.columns.tolist())
print('\nData frame:')
sismo.head(4)
# -
print('Porcentaje de NAs:')
sismo.isna().sum()*100/sismo.shape[0]
sismo = (sismo.loc[:,['Date', 'Time', 'Latitude', 'Longitude', 'Type', 'Depth', 'Magnitude',
'Magnitude Type', 'ID', 'Source', 'Location Source', 'Magnitude Source', 'Status']]
.rename(index=str, columns={'Location Source': 'Location_Source', 'Magnitude Source': 'Magnitude_Source',
'Magnitude Type': 'Magnitude_Type'}))
sismo.sample(5)
sismo.plot('Depth', 'Magnitude', kind='scatter', figsize=(10,8))
sismo.Date.unique()
| notebooks/earthquake.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:py27]
# language: python
# name: conda-env-py27-py
# ---
# # Linearly non-separable classes
#
# The main limitation of perceptrons is that they only work with linearly separable classes.
#
# This is a variation of a previous exercise, with a slightly different dataset.
# +
import numpy as np
import sklearn.linear_model
import matplotlib.pyplot as plt
from packages.plot import plot_decision_boundary, plot_data
# %matplotlib inline
# -
# ## Load in the data
#
# Again, there are two classes of dots (red and black), and each dot is defined by two features as before. So the structure of the dataset is exactly the same, consising of a matrix `x` with as many rows as dots, and two columns, and the vector `y` with as many elements as dots. The value of `y[i]` is 0 for red dots and 1 for black dots.
#
# In fact, the values in `x` are exactly the same as in the previous exercise, but you must define the values in `y` so that the data points become linealy non-separable.
x = np.array([[2,2],[1,3],[2,3],[5,3],[7,3],[2,4],[3,4],\
[6,4],[1,5],[2,5],[5,5],[4,6],[6,6],[5,7]])
y = np.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1])
# ## Plot the data
#
# Let's represent graphically the data. Here you can see that the classes can't be separated by a single straight line.
plot_data(x, y)
plt.axis([0,8,0,8]);
# ## Build the model
# Create a [perceptron object](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html).
net = sklearn.linear_model.Perceptron(n_iter=1, warm_start=True)
# ## Train
# Repeat the following cell (`Ctrl+Enter`) until the model converges (or you are tired).
net.fit(x,y)
print("Coefficient 0: %6.3f" % net.coef_[0,0])
print("Coefficient 1: %6.3f" % net.coef_[0,1])
print(" Bias: %6.3f" % net.intercept_)
plot_data(x, y)
plt.axis([0,8,0,8]);
plot_decision_boundary(net)
print(' Target: %s' % np.array_str(y))
print('Prediction: %s' % np.array_str(net.predict(x)))
# The model can't converge because this is a linearly non-separable problem, just like the XOR function.
| perceptron/non-separable_Solution.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Plotting with Matplotlib
# IPython works with the [Matplotlib](http://matplotlib.org/) plotting library, which integrates Matplotlib with IPython's display system and event loop handling.
# ## matplotlib mode
# To make plots using Matplotlib, you must first enable IPython's matplotlib mode.
#
# To do this, run the `%matplotlib` magic command to enable plotting in the current Notebook.
#
# This magic takes an optional argument that specifies which Matplotlib backend should be used. Most of the time, in the Notebook, you will want to use the `inline` backend, which will embed plots inside the Notebook:
# + jupyter={"outputs_hidden": false}
# %matplotlib inline
# -
# You can also use Matplotlib GUI backends in the Notebook, such as the Qt backend (`%matplotlib qt`). This will use Matplotlib's interactive Qt UI in a floating window to the side of your browser. Of course, this only works if your browser is running on the same system as the Notebook Server. You can always call the `display` function to paste figures into the Notebook document.
# ## Making a simple plot
# With matplotlib enabled, plotting should just work.
# + jupyter={"outputs_hidden": false}
import matplotlib.pyplot as plt
import numpy as np
# + jupyter={"outputs_hidden": false}
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
# -
# These images can be resized by dragging the handle in the lower right corner. Double clicking will return them to their original size.
# One thing to be aware of is that by default, the `Figure` object is cleared at the end of each cell, so you will need to issue all plotting commands for a single figure in a single cell.
# ## Loading Matplotlib demos with %load
# IPython's `%load` magic can be used to load any Matplotlib demo by its URL:
# + jupyter={"outputs_hidden": false}
# # %load http://matplotlib.org/mpl_examples/showcase/integral_demo.py
"""
Plot demonstrating the integral as the area under a curve.
Although this is a simple example, it demonstrates some important tweaks:
* A simple line plot with custom color and line width.
* A shaded region created using a Polygon patch.
* A text label with mathtext rendering.
* figtext calls to label the x- and y-axes.
* Use of axis spines to hide the top and right spines.
* Custom tick placement and labels.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85
a, b = 2, 9 # integral limits
x = np.linspace(0, 10)
y = func(x)
fig, ax = plt.subplots()
plt.plot(x, y, 'r', linewidth=2)
plt.ylim(ymin=0)
# Make the shaded region
ix = np.linspace(a, b)
iy = func(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)
plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
horizontalalignment='center', fontsize=20)
plt.figtext(0.9, 0.05, '$x$')
plt.figtext(0.1, 0.9, '$y$')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])
plt.show()
# -
# Matplotlib 1.4 introduces an interactive backend for use in the notebook,
# called 'nbagg'. You can enable this with `%matplotlib notebook`.
#
# With this backend, you will get interactive panning and zooming of matplotlib figures in your browser.
# + jupyter={"outputs_hidden": true}
# %matplotlib notebook
# + jupyter={"outputs_hidden": false}
plt.figure()
x = np.linspace(0, 5 * np.pi, 1000)
for n in range(1, 4):
plt.plot(np.sin(n * x))
plt.show()
| 001-Jupyter/001-Tutorials/001-Basic-Tutorials/001-IPython-Kernel/Plotting in the Notebook with Matplotlib.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.8.5 64-bit
# language: python
# name: python3
# ---
# # Incremental Evolution
#
# There are some problems where the solution can be described as a set of small solutions that add up. In these cases, it may be interesting to carry out an incremental evolution. In it, a part of the individuals is blocked, while its other part evolves. After a few generations the blocked part is then released to evolve, evolving another piece of the solution.
#
# Let's implement an evolutionary algorithm that performs incremental evolution.
import evolvepy as ep
import numpy as np
from matplotlib import pyplot as plt
# # Fitness Function
#
# Our problem will be to find the coefficients of a polynomial, in this case $y = 10 x^3 + 25 x^2$. This is not a problem that would need incremental evolution, but let's use it as an example.
#
# The fitness function will be the error of our individual represented polynomial and the target:
#
# $$error(individual) = \sqrt{\sum_{x=-100}^{100} (polynomial(x) - individual(x))^2}$$
#
# Since we want to maximize the fitness, we will use $-error$.
# +
import numba
@numba.jit
def f(x):
return 10*np.power(x, 3) + 25*np.power(x, 2)
def fitness_function(individuals):
individual = individuals[0]
x = np.arange(-100, 100, 1)
y = f(x)
y_individual = individual["chr0"]*np.power(x, 3) + individual["chr1"]*np.power(x, 2)
score = np.linalg.norm(y-y_individual)/1E7
return -score
evaluator = ep.evaluator.FunctionEvaluator(fitness_function)
# -
# # Generator
#
# Let's define a generator with elitism. Note that, unlike the previous examples, we are defining layers of type "FirstGenLayer". These layers generate the initial individuals and are normally created automatically by the Generator. We created two of these layers: the first will run in the first generation as expected, but it will just randomly generate the first chromosome, the second will be initialized with zeros. The second layer will be used to initialize the second chromosome in the middle of evolution (the parameter "run=False" indicates that it will not be executed right at the beginning).
#
# We are also using "Block" layer. This layer will prevent our second chromosome from being altered by mutations or other operators.
# +
descriptor = ep.generator.Descriptor([1, 1], [(-100.0, 100.0), (-100.0, 100.0)], types=[np.float32, np.float32])
# Blocks the second chromosome
block = ep.generator.Block("chr1")
mutation = ep.generator.mutation.NumericMutationLayer(ep.generator.mutation.sum_mutation, 1.0, 0.0, (-10.0, 10.0))
combine = ep.generator.CombineLayer(ep.generator.selection.tournament, ep.generator.crossover.one_point)
filter0 = ep.generator.FilterFirsts(95)
sort = ep.generator.Sort()
filter1 = ep.generator.FilterFirsts(5)
concat = ep.generator.Concatenate()
# The FirstGenLayers
first_gen0 = ep.generator.FirstGenLayer(descriptor, initialize_zeros=True, chromosome_names="chr0") #Generate only the first chromosome.
first_gen1 = ep.generator.FirstGenLayer(descriptor, chromosome_names="chr1", run=False) #Generate the second chromosome.
block.next = sort
sort.next = filter1
filter1.next = concat
block.next = mutation
mutation.next = combine
combine.next = filter0
filter0.next = concat
concat.next = first_gen0
first_gen0.next = first_gen1
gen = ep.generator.Generator(first_layer=block, last_layer=first_gen1)
# -
# # Evolver and Incremental Evolution
#
# Here we are creating an Evolver with a dynamic mutation callback and the incremental evolution. The incremental evolution receives the generation in which the chromosome will be unlocked, the Block layer and the FirstGenLayer. It can also receive callbacks to block the execution before the unlock generation. We use this to prevent the dynamic mutation of changing mutation rates before we have all the chromosomes initially evolved.
# +
dyn_mut = ep.callbacks.DynamicMutation([mutation.name], patience=3, refinement_steps=5, exploration_patience=0, exploration_steps=0, exploration_multiplier=1)
inc_evol = ep.callbacks.IncrementalEvolution(15, block_layer=block, first_gen_layer=first_gen1, callbacks=[dyn_mut])
evolver = ep.Evolver(gen, evaluator, 100, [inc_evol, dyn_mut])
# -
# # Results
#
# Let's evolve for some generation and see the results
hist, last_pop = evolver.evolve(30)
# +
print("Best individual: ", last_pop[np.argmax(hist[-1])])
plt.plot(hist.max(axis=1))
plt.xlabel("Generation")
plt.ylabel("Fitness")
plt.title("Evolution history")
plt.legend(["Best"])
plt.show()
# -
# Looking at the evolution history, we can see how fitness took a leap in generation 15, in which we unlocked the second individual. After that, the generation is stuck for a few generations before activating the dynamic mutation.
#
# 
#
| examples/Incremental Evolution.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import pandas as pd
import quandl
# -
# # Load Data from Quandl
# +
quandl.ApiConfig.api_key = 'API_KEY'
start_date = '1993-01-01'
end_date = '2021-06-30'
sigs_ticks = ["MULTPL/SP500_DIV_YIELD_MONTH","MULTPL/SP500_EARNINGS_YIELD_MONTH","YC/USA10Y"]
sigs_names = ['DP','EP', 'US10Y']
sigs_info = pd.DataFrame({'Name':sigs_names,'Ticker':sigs_ticks}).set_index('Name')
signals = pd.DataFrame()
for idx,tick in enumerate(sigs_info['Ticker']):
temp = quandl.get(tick, start_date=start_date, end_date=end_date)
temp.columns = [sigs_info.index[idx]]
signals = signals.join(temp,rsuffix='_',how='outer')
# some monthly data reported at start of month--assume we do not have it until end of month
signals = signals.resample('M').last()
signals.columns.name = 'SP500 Multiples'
signals
# +
spy_tick = 'EOD/SPY'
spy = quandl.get(spy_tick, start_date=start_date, end_date=end_date)[['Adj_Close']]
spy_rets = spy.resample('M').last().pct_change()
spy_rets.columns = ['SPY']
rf_tick = 'YC/USA3M'
rf = quandl.get(rf_tick, start_date=start_date, end_date=end_date)
rf = rf.resample('M').last()/(12*100)
rf.rename(columns={'Rate':'US3M'},inplace=True)
# -
rets = spy_rets.join(rf,how='inner')
retsx = rets['SPY'].sub(rets['US3M']).to_frame().rename(columns={0:'SPY'})
# # Save Data to Excel
with pd.ExcelWriter('sp500_fundamentals.xlsx') as writer:
signals.to_excel(writer, sheet_name= 'fundamentals')
rets.to_excel(writer, sheet_name='total returns')
#retsx.to_excel(writer, sheet_name='excess returns')
| build_data/Build_Forecasting_Data_Quandl.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import os
os.environ["NUMBA_NUM_THREADS"] = str(24)
import sys
import matplotlib.pyplot as plt
sys.path += ["../"]
# +
import hepaccelerate
import uproot
import numpy as np
import cupy as cp
import pandas
import copy
import hepaccelerate.kernels as kernels
import hepaccelerate.backend_cuda as backend_cuda
import hepaccelerate.backend_cpu as backend_cpu
# +
# #!curl http://opendata.atlas.cern/release/samples/Data/DataMuons.root -o DataMuons.root
# #!curl http://opendata.atlas.cern/release/samples/MC/mc_147771.Zmumu.root -o mc_147771.Zmumu.root
# -
uproot.open("DataMuons.root").get("mini").keys()
def load_file(filename):
fi = uproot.open(filename)
tt = fi.get("mini")
#Load arrays from ROOT file
arrdata = {
str(k, "ascii"): tt.array(k) for k in [
b"jet_pt", b"jet_eta", b"jet_phi", b"jet_m",
b"lep_pt", b"lep_eta", b"lep_phi", b"lep_E", b"lep_type", b"lep_charge",
b"pvxp_n",
b"scaleFactor_PILEUP",
]
}
numev = len(tt)
return arrdata, numev
arrdata_d, numev_d = load_file("DataMuons.root")
arrdata_m, numev_m = load_file("mc_147771.Zmumu.root")
def compute_inv_mass(offsets, pt, eta, phi, m, mask_content, nplib, backend):
#Convert all the jet momenta to cartesian
px, py, pz, e = backend.spherical_to_cartesian(
pt, eta, phi, m
)
#Add up the jet momenta on a per-event basis
pxtot = kernels.sum_in_offsets(
backend,
offsets, px, mask_content=mask_content
)
pytot = kernels.sum_in_offsets(
backend,
offsets, py, mask_content=mask_content
)
pztot = kernels.sum_in_offsets(
backend,
offsets, pz, mask_content=mask_content
)
ptot2 = (pxtot**2 + pytot**2 + pztot**2)
etot = kernels.sum_in_offsets(
backend,
offsets, e, mask_content=mask_content
)
etot2 = etot**2
diff = etot2 - ptot2
diff[diff<0] = 0.0
return nplib.sqrt(diff)
#Copy to GPU device in case cupy is specified, otherwise do nothing
def to_device(arr, nplib):
if nplib == cp:
return cp.array(arr)
return arr
def process_array_data(arrdata, numev, nplib, backend, parameters):
#Move arrays to GPU if applicable
jet_pt = to_device(arrdata["jet_pt"].content/1000.0, nplib)
jet_m = to_device(arrdata["jet_m"].content/1000.0, nplib)
jet_eta = to_device(arrdata["jet_eta"].content, nplib)
jet_phi = to_device(arrdata["jet_phi"].content, nplib)
jet_offsets = to_device(arrdata["jet_pt"].offsets, nplib)
lep_pt = to_device(arrdata["lep_pt"].content/1000.0, nplib)
lep_e = to_device(arrdata["lep_E"].content/1000.0, nplib)
lep_eta = to_device(arrdata["lep_eta"].content, nplib)
lep_phi = to_device(arrdata["lep_phi"].content, nplib)
lep_type = to_device(arrdata["lep_type"].content, nplib)
lep_charge = to_device(arrdata["lep_charge"].content, nplib)
lep_offsets = to_device(arrdata["lep_pt"].offsets, nplib)
#Set the lepton masses to the experimental values
lep_m = nplib.zeros_like(lep_pt)
lep_m[lep_type==11] = 0.510/1000.0
lep_m[lep_type==13] = 105.658/1000.0
#Lepton selection
sel_leps = lep_pt > parameters["lep_pt_cut"]
leps_opposite_charge = kernels.select_opposite_sign(backend, lep_offsets, lep_charge, sel_leps)
sel_leps = sel_leps & leps_opposite_charge
num_leps = kernels.sum_in_offsets(backend, lep_offsets, sel_leps, dtype=nplib.int8)
inv_mass_leps = compute_inv_mass(lep_offsets, lep_pt, lep_eta, lep_phi, lep_m, sel_leps, nplib, backend)
#Find jets that pass the selection cuts
sel_jets = (
(jet_pt > parameters["jet_pt_cut"]) &
(nplib.abs(jet_eta) < parameters["jet_eta_cut"])
)
#Mask the jets that are closer than a certain dR value to selected leptons
jet_dr_masked = kernels.mask_deltar_first(
backend,
{"eta": jet_eta, "phi": jet_phi, "offsets": jet_offsets}, sel_jets,
{"eta": lep_eta, "phi": lep_phi, "offsets": jet_offsets}, sel_leps,
parameters["jet_lepton_dr"]
)
sel_jets = sel_jets & jet_dr_masked
#Find events with a minimum number of jets
num_jets = kernels.sum_in_offsets(backend, jet_offsets, sel_jets, dtype=nplib.int8)
sel_ev = (num_jets >= parameters["min_num_jet"]) * (num_leps >= 2)
#Compute the total pt of jets for all events that pass the selection
sum_pt = kernels.sum_in_offsets(backend, jet_offsets, jet_pt, mask_rows=sel_ev, mask_content=sel_jets)
#Create per-event weights
weights_ev = nplib.ones(numev, dtype=nplib.float32)
if parameters["is_mc"]:
weights_ev *= nplib.array(arrdata["scaleFactor_PILEUP"])
#Create a per-jet array of the event weights using broadcasting
weights_jet = nplib.ones(len(jet_pt), dtype=nplib.float32)
kernels.broadcast(backend, jet_offsets, weights_ev, weights_jet)
#Prepare histograms of jet properties
hists_jet = kernels.histogram_from_vector_several(
backend,
[
(jet_pt, nplib.linspace(0, 500, 100, dtype=nplib.float32)),
(jet_eta, nplib.linspace(-5, 5, 100, dtype=nplib.float32)),
(jet_phi, nplib.linspace(-4, 4, 100, dtype=nplib.float32)),
],
weights_jet,
mask=sel_jets
)
#Compute the invariant mass of the jets in the event
inv_mass_jets = compute_inv_mass(jet_offsets, jet_pt, jet_eta, jet_phi, jet_m, sel_jets, nplib, backend)
hists_ev = kernels.histogram_from_vector_several(
backend,
[
(sum_pt, nplib.linspace(0, 1000, 100, dtype=nplib.float32)),
(inv_mass_jets, nplib.linspace(0, 1000, 40, dtype=nplib.float32)),
(inv_mass_leps, nplib.linspace(0, 200, 40, dtype=nplib.float32)),
],
weights_ev,
mask=sel_ev
)
return {
"numev": numev,
"hist_jet_pt": hists_jet[0],
"hist_jet_eta": hists_jet[1],
"hist_sum_pt": hists_ev[0],
"hist_inv_mass_jets": hists_ev[1],
"hist_inv_mass_leps": hists_ev[2],
}
def process_analysis(pars, nplib, backend):
p_d = copy.deepcopy(pars)
p_d["is_mc"] = False
r_d = process_array_data(arrdata_d, numev_d, nplib, backend, p_d)
p_m = copy.deepcopy(pars)
p_m["is_mc"] = True
r_m = process_array_data(arrdata_m, numev_m, nplib, backend, p_m)
return {
"data": r_d,
"mc": r_m
}
pars = {
"lep_pt_cut": 40.0, "jet_lepton_dr": 0.4,
"jet_pt_cut": 20, "jet_eta_cut": 2.5, "min_num_jet": 3
}
r = process_analysis(pars, cp, backend_cuda)
plt.plot(r["data"]["hist_jet_pt"][2][:-1], r["data"]["hist_jet_pt"][0])
plt.plot(r["mc"]["hist_jet_pt"][2][:-1], r["mc"]["hist_jet_pt"][0])
plt.plot(r["data"]["hist_inv_mass_leps"][2][:-1], r["data"]["hist_inv_mass_leps"][0], lw=0, marker="o", color="black")
plt.plot(r["mc"]["hist_inv_mass_leps"][2][:-1], r["mc"]["hist_inv_mass_leps"][0])
# tr = %timeit -o process_analysis(pars, cp, backend_cuda)
numev = r["data"]["numev"] + r["mc"]["numev"]
print("Event processing speed: {0:.2f} MHz".format(numev/tr.average/1e6))
# tr = %timeit -o process_analysis(pars, np, backend_cpu)
print("Event processing speed: {0:.2f} MHz".format(numev/tr.average/1e6))
| notebooks/atlas.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
import category_encoders as ce
from sklearn.preprocessing import LabelBinarizer
from sklearn.externals import joblib
from sklearn.preprocessing import OneHotEncoder
data_path = "../data/notebooks/4_merged_data.csv"
df = pd.read_csv(data_path)
df_raw = df.copy()
target_encoding_cols = ['location_country' , 'currency' , 'category', 'sub_category']
# +
model_oh = joblib.load('estimators/model_oh.sav')
model_hel = joblib.load('estimators/model_hel.sav')
encoder_oh = joblib.load('estimators/encoder_oh.sav')
encoder_hel = joblib.load('estimators/encoder_hel.sav')
binarizer = joblib.load('estimators/encoder_label.sav')
# +
pred_dic = {
"launched_at":'2019-11-06',
"deadline":"2019-12-06",
"goal":1000,
"sub_category":"comic books",
"category":"comics",
"currency":"GBP",
"location_country":"the United Kingdom",
"blurb":"A multimedia journalistic trip to a culture different than my own in order to explore & document a radically different way of life.",
"rewards":"[10,20, 50, 250, 500 , 1000 ]",
}
pred_df = {
"days_to_deadline":[],
"goal":[],
"blurb_length":[],
"rewards_mean":[],
"rewards_median":[],
"rewards_variance":[],
"rewards_SD":[],
"rewards_MIN":[],
"rewards_MAX":[],
"rewards_NUM":[],
"launch_year":[],
"launch_month":[],
"deadline_year":[],
"deadline_month":[],
"location_country":[],
"currency":[],
"category":[],
"sub_category":[],
}
# +
def getMean(x):
lis = eval(x)
return np.array(lis).mean()
def getMedian(x):
lis = eval(x)
return np.median(lis)
def getVariance(x):
lis = eval(x)
return np.array(lis).var()
def getSD(x):
lis = eval(x)
return np.std(lis)
def getMIN(x):
lis = eval(x)
return min(lis)
def getMAX(x):
lis = eval(x)
return max(lis)
def getNUM(x):
lis = eval(x)
return len(lis)
def get_blurb_length(x):
return len(x)
# +
pred_df["rewards_mean"].append(getMean(pred_dic['rewards']))
pred_df["rewards_median"].append(getMedian(pred_dic['rewards']))
pred_df["rewards_variance"].append(getVariance(pred_dic['rewards']))
pred_df["rewards_SD"].append(getSD(pred_dic['rewards']))
pred_df["rewards_MIN"].append(getMIN(pred_dic['rewards']))
pred_df["rewards_MAX"].append(getMAX(pred_dic['rewards']))
pred_df["rewards_NUM"].append(getNUM(pred_dic['rewards']))
pred_df['launch_year'].append(pd.to_datetime(pred_dic['launched_at']).year)
pred_df['launch_month'].append(pd.to_datetime(pred_dic['launched_at']).month)
pred_df['deadline_year'].append(pd.to_datetime(pred_dic['deadline']).year)
pred_df['deadline_month'].append(pd.to_datetime(pred_dic['deadline']).month)
pred_df['days_to_deadline'].append((pd.to_datetime(pred_dic['deadline']) - pd.to_datetime(pred_dic['launched_at'])).days)
pred_df['blurb_length'].append(get_blurb_length(pred_dic['blurb']))
pred_df['goal'].append(pred_dic['goal'])
pred_df['category'].append(pred_dic['category'])
pred_df['sub_category'].append(pred_dic['sub_category'])
pred_df['currency'].append(pred_dic['currency'])
pred_df['location_country'].append(pred_dic['location_country'])
# -
df_pred = pd.DataFrame.from_dict(pred_df )
def transform_onehot(df , cols , encoder):
df_temp = pd.DataFrame(encoder.transform(df[cols]) , columns = [x for sublist in encoder.categories_ for x in sublist])
df = pd.concat([df , df_temp] , axis=1)
df_resp = df.copy()
df_resp.drop(cols , axis=1 , inplace=True)
return df_resp
def transform_helmert(df , cols , encoder):
df_temp = encoder.transform(df[cols])
df = pd.concat([df , df_temp] , axis=1)
df_resp = df.copy()
df_resp.drop(cols , axis=1 , inplace=True)
return df_resp
df_pred_oh = transform_onehot(df_pred , target_encoding_cols , encoder_oh)
df_pred_hel = transform_helmert(df_pred , target_encoding_cols , encoder_hel)
# # ELI5
import eli5
# **Required columns are selected based on the features which the user are seeking to tune one's that are excluded are the one's which can not be changed associated with a campaign, for ex after we developed a product we can not change the category it fit's into just because the change would increase the probability of a successful campaign**
categ_cols =[pred_df['category'][0] , pred_df['sub_category'][0] , pred_df['currency'][0] , pred_df['location_country'][0]]
required_columns = ['blurb_length', 'goal' ,'rewards_variance','rewards_median', 'rewards_SD', 'rewards_MIN', 'rewards_MAX', 'rewards_NUM'
,'days_to_delivery', 'days_to_deadline', 'launch_year', 'deadline_year']
all_cols =required_columns+categ_cols
def func(x , s):
return x in required_columns
# ## Model_OH
# +
eli5.explain_prediction_xgboost(model_oh.get_booster() , df_pred_oh.iloc[0] , feature_filter=func)
# -
# **Feature Importance of Model_OH**
eli5.explain_weights_xgboost(model_oh.get_booster())
# ## Model_hel
# +
eli5.explain_prediction_xgboost(model_hel.get_booster() , df_pred_hel.iloc[0] , feature_filter=func)
# -
# **Feature Importance of Model_Hel**
eli5.explain_weights_xgboost(model_hel.get_booster())
# ### Conclusion
# **We will be using the model with helmert encoding even though variables which are subjected to the encoding become uninterpretable and the reason is variables which are transformed are fixed variables which would not be interpreted any way in our final dashboard.**
| notebooks/6_Model_Interpretation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.6.13 64-bit (''chemvae'': conda)'
# name: python3
# ---
import numpy as np
import scipy as sp
import scipy.linalg
import scipy.stats
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
from scipy import sparse
import os.path
from scipy.interpolate import splrep, splev
def ALS_solve(M, Ω, r, mu, epsilon=1e-3, max_iterations=100, debug = False):
"""
Solve probabilistic matrix factorization using alternating least squares.
Since loss function is non-convex, each attempt at ALS starts from a
random initialization and returns a local optimum.
[ <NAME> Mnih 2008 ]
[ <NAME>, and Volinksy 2009 ]
Parameters:
-----------
M : m x n array
matrix to complete
Ω : m x n array
matrix with entries zero (if missing) or one (if present)
r : integer
how many factors to use
mu : float
hyper-parameter penalizing norm of factored U, V
epsilon : float
convergence condition on the difference between iterative results
max_iterations: int
hard limit on maximum number of iterations
Returns:
--------
X: m x n array
completed matrix
"""
#logger = logging.getLogger(__name__)
n1, n2 = M.shape
U = np.random.randn(n1, r)
V = np.random.randn(n2, r)
prev_X = np.dot(U, V.T)
def solve(M, U, Ω):
V = np.zeros((M.shape[1], r))
mu_I = mu * np.eye(U.shape[1])
for j in range(M.shape[1]):
X1 = Ω[:, j:j+1].copy() * U
X2 = X1.T @ X1 + mu_I
#V[j] = (np.linalg.pinv(X2) @ X1.T @ (M[:, j:j+1].copy())).T
#print(M[:, j:j+1].shape)
V[j] = np.linalg.solve(X2, X1.T @ (M[:, j:j+1].copy())).reshape(-1)
return V
for _ in range(max_iterations):
U = solve(M.T, V, Ω.T)
V = solve(M, U, Ω)
X = np.dot(U, V.T)
mean_diff = np.linalg.norm(X - prev_X) / np.linalg.norm(X)
#if _ % 1 == 0:
# logger.info("Iteration: %i; Mean diff: %.4f" % (_ + 1, mean_diff))
if (debug):
print("Iteration: %i; Mean diff: %.4f" % (_ + 1, mean_diff))
if mean_diff < epsilon:
break
prev_X = X
return X
def noise_to_signal(X, M, Ω):
return np.sqrt(np.sum((Ω*X - Ω*M)**2) / np.sum((Ω*M)**2))
def abs_mean(X, M, Ω):
return np.sum(np.abs((X-M)*Ω)) / np.sum(Ω)
## least-squares solved via single SVD
def SVD(M,r): #input matrix M, approximating with rank r
u,s,vh = np.linalg.svd(M, full_matrices=False) #s is diag
X = u[:,:r].dot(np.diag(np.sqrt(s[:r])))
Y = vh[:r,:].T.dot(np.diag(np.sqrt(s[:r])))
return X.dot(Y.T), X, Y## least-squares solved via single SVD
def low_rank_matrix_generation(n1, n2, r, gamma_shape, gamma_scale, mean_M):
'''
generate a low-rank matrix M0
low rank components are entry-wise Gamma distribution
mean_M: the mean value of M0
'''
U = np.random.gamma(shape = gamma_shape, scale = gamma_scale, size = (n1, r))
V = np.random.gamma(shape = gamma_shape, scale = gamma_scale, size = (n2, r))
M0 = U.dot(V.T)
M0 = M0 / np.mean(M0) * mean_M
return M0
# ### Compute Sigma
# +
def compute_Sigma_Poisson(M0, r, p_observe):
'''
Compute the standard deviation of least-square estimator for Poisson noise
The formula is specified in the paper
'''
u,s,vh = np.linalg.svd(M0, full_matrices=False)
U = u[:, :r]
V = vh[:r, :].T
sigmaS = ((U.dot(U.T))**2).dot(M0) + M0.dot((V.dot(V.T))**2)
sigmaS /= p_observe
sigmaS = np.sqrt(sigmaS)
return sigmaS
def compute_Sigma_Bernoulli(M0, r, p_observe):
u,s,vh = np.linalg.svd(M0, full_matrices=False)
U = u[:, :r]
V = vh[:r, :].T
sigmaS = ((U.dot(U.T))**2).dot(M0*(1-M0)) + (M0*(1-M0)).dot((V.dot(V.T))**2)
sigmaS /= p_observe
sigmaS = np.sqrt(sigmaS)
return sigmaS
def compute_Sigma_adpative(Mhat, E, r, p_observe):
u,s,vh = np.linalg.svd(Mhat, full_matrices=False)
U = u[:, :r]
V = vh[:r, :].T
sigmaS = ((U.dot(U.T))**2).dot(E**2) + (E**2).dot((V.dot(V.T))**2)
sigmaS /= (p_observe**2)
sigmaS = np.sqrt(sigmaS)
return sigmaS
# -
# ## Simulation: Single Entry Distribution Plot
# + tags=[]
np.random.seed(1)
n = 300
r = 2
M0 = low_rank_matrix_generation(n1=n, n2=n, r=r, gamma_shape=2, gamma_scale=1, mean_M=20)
index_i = 0
index_j = 0
u,s,vh = np.linalg.svd(M0, full_matrices=False)
U = u[:, :r]
V = vh[:r, :].T
#print(U, V)
num_experiment = 1000 #set to >= 10000 for the plot in the paper
p_observe = 0.6
exp_list = []
for i in range(num_experiment):
X = np.random.poisson(M0)
#X = np.random.binomial(1, np.minimum(M0, 1))
Ω = np.random.rand(n, n) <= p_observe
Mhat = ALS_solve(X, Ω, r, 0)
while (np.linalg.norm(Mhat-M0) / np.linalg.norm(M0) > 1):
Mhat = ALS_solve(X, Ω, r, 0)
exp_list.append((Mhat - M0)[index_i, index_j])
#print(np.mean(np.abs(Mhat - M0)))
# +
sigmaS = compute_Sigma_Poisson(M0, r, p_observe)
thm_list = np.zeros(2000)
for i in range(2000):
thm_list[i] = np.random.normal(loc=0, scale=sigmaS[index_i, index_j])
from scipy.stats import norm
def CDF(points):
points = np.sort(points)
Y = np.arange(1, len(points)+1, 1) / len(points)
return points, Y
def pdf(samples):
samples = np.array(samples) / sigmaS[index_i, index_j]
#hist, bined = np.histogram(samples, bins = 300, density=True)
#plt.plot((bined[:-1]/2+bined[1:]/2), hist)
pos_guassian = np.linspace(min(samples), max(samples), 1000)
pdf_guassian = norm.pdf(pos_guassian, loc=0, scale=1)
#plt.plot(pos_guassian, pdf_guassian)
#plt.show()
g = sns.displot(data=samples, kind='hist', stat='density', bins=50)
g.set(xlim=(-4, 4))
g.set(ylim=(0.0, 0.45))
plt.plot(pos_guassian, pdf_guassian, label=r'$N(0, 1)$', color='r')
plt.legend(fontsize = 17)
plt.ylabel('Density', fontsize = 18)
plt.tight_layout()
plt.savefig('distribution.eps')
plt.show()
X1, Y1 = CDF(exp_list)
X2, Y2 = CDF(thm_list)
plt.plot(X1, Y1, X2, Y2)
plt.xlim([X2.min(), -X2.min()])
plt.legend(['Experiment', 'Theory'])
plt.xlabel(r'$M^{d} - M$')
plt.ylabel('CDF')
plt.show()
pdf(exp_list)
# -
# ## Simulation: Coverage Rate 95% Verification
def compute_coverage_rate_with_CI(M0, Mhat, sigmaS, CI, Ω=None):
if (Ω is None):
Ω = np.ones_like(M0)
delta = (1-CI)/2
mul = norm.ppf(CI+delta)
return np.sum((np.abs(M0-Mhat) <= sigmaS * mul)*Ω) / np.sum(Ω)
# +
#np.random.seed(1)
n = 500
for r in [3, 6]:
for p in [0.3, 0.6]:
for mean_M in [5, 20]:
num_experiment = 10 # set to >= 100 for the results in the paper
results = []
for i in range(num_experiment):
M0 = low_rank_matrix_generation(n1=n, n2=n, r=r, gamma_shape=2, gamma_scale=1, mean_M=mean_M)
p_observe = p
sigmaS = compute_Sigma_Poisson(M0, r, p_observe)
X = np.random.poisson(M0)
Ω = np.random.rand(n, n) <= p_observe
Mhat = ALS_solve(X, Ω, r, 0)
while (np.linalg.norm(Mhat-M0) / np.linalg.norm(M0) > 1):
Mhat = ALS_solve(X, Ω, r, 0)
results.append(compute_coverage_rate_with_CI(M0, Mhat, sigmaS, CI=0.95))
print(np.mean(results), np.std(results))
# -
# ## Sales data: Maximizing Coverage Rate with Limited Budgets
# +
import pickle
sale_matrix = pickle.load(open('drug_sale.p', 'rb'))
sale_matrix = sale_matrix.fillna(0).to_numpy()
print(sale_matrix.shape)
remaining_cols = np.sum(sale_matrix==0, axis = 0) < 200 #filtering cols
remaining_rows = np.sum(sale_matrix==0, axis = 1) < 200 #filtering rows
sale_matrix = sale_matrix[:, remaining_cols]
sale_matrix = sale_matrix[remaining_rows, :]
O = sale_matrix
O = np.maximum(O, 0)
# +
def Inverse_Gaussian(t, S):
A = -2 * (t + np.log(S * np.sqrt(2*np.pi))) * (S**2)
A = np.maximum(A, 0)
return np.sqrt(A)
def compute_coverage_rate_with_budget(M0, Mhat, sigmaS, budget, eps = 1e-6, Omega=None):
if (Omega is None):
Omega = np.ones_like(M0)
l_bound = 0
sigma = np.min(sigmaS)
r_bound = 1 / sigma / np.sqrt(2*np.pi)
while (r_bound - l_bound > eps):
mid = (r_bound + l_bound) / 2
cost = 0
A = Inverse_Gaussian(np.log(mid), sigmaS)
cost = 2 * np.sum(A)
if (cost > budget):
l_bound = mid
else:
r_bound = mid
return np.sum((np.abs(M0-Mhat) <= A)*Omega) / np.sum(Omega)
def budget_coverage_rate(M0, Mhat, sigmaS, Omega=None, s = None):
if (Omega is None):
Omega = np.ones_like(M0)
cost = []
coverage = []
if (s is None):
s = np.arange(-30, np.log(1 / np.min(sigmaS) / np.sqrt(2*np.pi))+0.1, 0.1)
for t in s:
A = Inverse_Gaussian(t, sigmaS)
cost.append(np.sum(A*Omega) * 2)
coverage.append(np.sum((np.abs(M0-Mhat) <= A)*Omega) / np.sum(Omega))
return s, cost, coverage
# +
r = 4
n1 = O.shape[0]
n2 = O.shape[1]
num_experiment = 1
p_observe = 0.95
exp_list = []
for i in range(num_experiment):
X = O
Ω = (np.random.rand(n1, n2) <= p_observe)
M0 = X
u,s,vh = np.linalg.svd(M0, full_matrices=False)
U = u[:, :r]
V = vh[:r, :].T
X_r = (U*s[:r]).dot(V.T)
Mhat = ALS_solve(X, Ω, r, 0)
#print(np.sqrt(np.sum(M0)) / np.linalg.norm(M0))
#print(np.linalg.norm((Mhat-X)*(1-Ω)) / np.linalg.norm(X*(1-Ω)))
while (np.linalg.norm(Mhat-M0) / np.linalg.norm(M0) > 1):
Mhat = ALS_solve(X, Ω, r, 0)
#Mhat = np.maximum(Mhat, 0)
sigmaS = compute_Sigma_Poisson(Mhat, r, p_observe)
u,s,vh = np.linalg.svd(Mhat, full_matrices=False)
Uhat = u[:, :r]
Vhat = vh[:r, :].T
gaussianS = np.zeros_like(M0)
gaussianS = np.ones((n1,1)).dot(np.sum(Vhat**2, axis=1).reshape(1, -1)) + np.sum(Uhat**2, axis=1).reshape(-1, 1).dot(np.ones((1, n2)))
gaussianS /= p_observe
gaussianS = np.sqrt(gaussianS)
sigma = np.sqrt(np.sum(((Mhat-X)**2)*Ω)/np.sum(Ω))
# -
_, cost_A, coverage_A = budget_coverage_rate(X_r, Mhat, sigmaS, 1-Ω, np.arange(-35, np.log(1 / np.min(sigmaS) / np.sqrt(2*np.pi))+0.1, 0.2))
_, cost_B, coverage_B = budget_coverage_rate(X_r, Mhat, gaussianS*sigma, 1-Ω, np.arange(-20, np.log(1 / np.min(sigmaS) / np.sqrt(2*np.pi))+0.1, 0.1))
plt.plot(cost_A, coverage_A, color='r')
plt.plot(cost_B, coverage_B, color='g')
plt.xlim([0, cost_A[0]])
plt.legend(['Poisson Formula', 'Homogeneous Gaussian Formula'], fontsize=14)
plt.xlabel('Budget', fontsize=14)
plt.ylabel('Coverage Rate', fontsize=14)
plt.title(r'$p$={}'.format(p_observe), fontsize=14)
plt.savefig('real-data-coverage-rate-comparison.eps')
plt.show()
| main.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Think Bayes
#
# This notebook presents example code and exercise solutions for Think Bayes.
#
# Copyright 2018 <NAME>
#
# MIT License: https://opensource.org/licenses/MIT
# +
# Configure Jupyter so figures appear in the notebook
# %matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
# %config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import classes from thinkbayes2
from thinkbayes2 import Hist, Pmf, Suite
# -
# ## The cookie problem
#
# Here's the original statement of the cookie problem:
#
# > Suppose there are two bowls of cookies. Bowl 1 contains 30 vanilla cookies and 10 chocolate cookies. Bowl 2 contains 20 of each.
#
# > Now suppose you choose one of the bowls at random and, without looking, select a cookie at random. The cookie is vanilla. What is the probability that it came from Bowl 1?
#
# If we only draw one cookie, this problem is simple, but if we draw more than one cookie, there is a complication: do we replace the cookie after each draw, or not?
#
# If we replace the cookie, the proportion of vanilla and chocolate cookies stays the same, and we can perform multiple updates with the same likelihood function.
#
# If we *don't* replace the cookie, the proportions change and we have to keep track of the number of cookies in each bowl.
#
# **Exercise:**
#
# Modify the solution from the book to handle selection without replacement.
#
# Hint: Add instance variables to the `Cookie` class to represent the hypothetical state of the bowls, and modify the `Likelihood` function accordingly.
#
# To represent the state of a Bowl, you might want to use the `Hist` class from `thinkbayes2`.
# +
# Solution
# We'll need an object to keep track of the number of cookies in each bowl.
# I use a Hist object, defined in thinkbayes2:
bowl1 = Hist(dict(vanilla=30, chocolate=10))
bowl2 = Hist(dict(vanilla=20, chocolate=20))
bowl1.Print()
# +
# Solution
# Now I'll make a Pmf that contains the two bowls, giving them equal probability.
pmf = Pmf([bowl1, bowl2])
pmf.Print()
# +
# Solution
# Here's a likelihood function that takes `hypo`, which is one of
# the Hist objects that represents a bowl, and `data`, which is either
# 'vanilla' or 'chocolate'.
# `likelihood` computes the likelihood of the data under the hypothesis,
# and as a side effect, it removes one of the cookies from `hypo`
def likelihood(hypo, data):
like = hypo[data] / hypo.Total()
if like:
hypo[data] -= 1
return like
# +
# Solution
# Now for the update. We have to loop through the hypotheses and
# compute the likelihood of the data under each hypothesis.
def update(pmf, data):
for hypo in pmf:
pmf[hypo] *= likelihood(hypo, data)
return pmf.Normalize()
# +
# Solution
# Here's the first update. The posterior probabilities are the
# same as what we got before, but notice that the number of cookies
# in each Hist has been updated.
update(pmf, 'vanilla')
pmf.Print()
# +
# Solution
# So when we update again with a chocolate cookies, we get different
# likelihoods, and different posteriors.
update(pmf, 'chocolate')
pmf.Print()
# +
# Solution
# If we get 10 more chocolate cookies, that eliminates Bowl 1 completely
for i in range(10):
update(pmf, 'chocolate')
print(pmf[bowl1])
| solutions/cookie_soln.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from pathlib import Path
from sklearn import tree
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
my_file = Path("/Users/bharu/CS690-PROJECTS/ActivityAnalyzer/activity_analyzer/DecisionTreeClassifier/FeaturesCsvFile/featuresfile.csv")
df = pd.read_csv(my_file)
X = df.values[:, 1:44]
Y = df.values[:, 44]
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.3)
logistic = LogisticRegression(C=1e5,random_state=1)
logistic
logistic.fit(X_train,Y_train)
lg_score_train_Data = logistic.score(X_train,Y_train)
lg_score_train_Data
lg_score_test_Data = logistic.score(X_test,Y_test)
lg_score_test_Data
| LogisticRegression-Try/Classifier/Log_regrsn.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Learning Objectives
#
# At the end of this class, you will be able to...
#
# - Compute probability density functions and cumulative density functions
#
# - Use the `scipy.stats` package to compute the Survaival Value or CDF Value for a known distribution
# +
import numpy as np
import pandas as pd
df = pd.read_csv('./Datasets/titanic.csv')
# -
# ## Normalizing
#
# In statistics and applications of statistics, normalization can have a range of meanings. In the simplest cases, normalization means adjusting values measured on different scales to a notionally common scale, often prior to averaging. In our example we will use normalization to make values be between 0 and 1.
# ## Probability Distribution Function (PDF)
#
# - PDFs have a similar pattern to histogram. The only difference is that we _normalize the value of histograms_
#
# - Let's plot the histogram for Age in our Titanic dataset
#
# - To visualize this data, we'll use the [seaborn](https://seaborn.pydata.org/) library
import seaborn as sns
#kde: Whether to plot a gaussian kernel density estimate.
#a cool website explaining kernel density explanation: https://mathisonian.github.io/kde/
sns.distplot(df['Age'].dropna(), hist=True, kde=False, bins=16)
# - Now let's plot the PDF of Age in Titanic
import seaborn as sns
sns.distplot(df['Age'].dropna(), hist=True, kde=True, bins=16)
# ## Activity: In PDFs, where does the y axes numbers come from?
#
# For example, at Age 20, why is the y-value around 0.030?
#
# To normalize we will take counts / total counts / bin size
# ## Activity: What percent of passengers are younger than 40?
# Find the number of passengers younger than 40
How_many_younger_40 = df[df['Age'] <= 40]
# Find the percentage of passengers who are younger than 40
# Do this by dividing the number of passengers younger than 40 by the total number of passengers (with an age)
pr_below_40 = len(How_many_younger_40)/len(df['Age'].dropna())
pr_below_40
# ## It is not easy to calculate this percentage from PDFs as we need to compute the area under the curve
# ## Cumulative Density Function (CDF)
#
# - In above example, we could not easily obtain the percentage from a PDF, although it is possible.
#
# - This is much easier if we use a CDF. A CDF calculates the probability that a random variable is less than a threshold value
#
# - Let's learn CDF by example: given an array of numbers (our random variable) and a threshold value as input:
#
# 1. Find the minimum value in the array
# 1. Set the threshold to be the minimum value of the array
# 1. For a given array of numbers and a given threshold, count all of the elements in the array that are less than the threshold, and divide that count by the length of the array
# 1. Repeat step three, increasing the threshold by one, until you go through step three where threshold is equail to the maximum value in the array
#
#
# +
ls_age = df['Age'].dropna().values
def calculate_cdf(x, threshold):
return np.sum(x <= threshold)
# Create an array cdf_age where each value is the cdf of the age for each threshold
cdf_age = [calculate_cdf(ls_age, r)/len(ls_age) for r in range(int(np.min(ls_age)), int(np.max(ls_age)))]
print(cdf_age)
# +
import matplotlib.pyplot as plt
plt.plot(range(int(np.min(ls_age)), int(np.max(ls_age))), cdf_age)
# -
# ## Normal Distribution
#
# - It is possible that when we plot a histogram or PDF of an array, it has a Bell Shape
#
# - The name of this histogram is **Normal**
# +
import numpy as np
import seaborn as sns
# Generate 1000 samples with 60 as its mean and 10 as its std
a = np.random.normal(60, 10, 1000)
sns.distplot(a, hist=True, kde=True, bins=20)
# -
# ## Normal Distribution Properties:
#
# When the data is Normally distributed:
#
# - 68% of the data is captured within one standard deviation from the mean.
# - 95% of the data is captured within two standard deviations from the mean.
# - 99.7% of the data is captured within three standard deviations from the mean.
# <br><img src="http://www.oswego.edu/~srp/stats/images/normal_34.gif" /><br>
# ## Activity:
#
# - Show that about 68% of the values are in the [50, 70] range
#
norm.cdf(70, loc=60, scale=10) - norm.cdf(50, loc=60, scale=10)
# ## Z-Distribution
#
# - Z-distribution is another name for _standard Normal distribution_
#
# - When the samples of our numerical array are Normal with an arbitrary mean and std
#
# - If scale each element by subtracting elements from the mean, and divide over the std, then the new array would be a Normal distribution with zero mean, and std 1
| site/public/courses/DS-1.1/Notebooks/PDF_CDF_Normal.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from lrcurve import PlotLearningCurve
import sklearn.model_selection
import sklearn.metrics
import torch
import torch.nn as nn
from torch import optim
from torch.utils import data as D
from tqdm.notebook import tqdm
from neural_caissa.data.load import ChessDataset
from neural_caissa.model.chess_conv_net import ChessConvNet
_PIECES = 12
_BOARD_DIM = 8
_EPOCHS = 100
_BATCH_SIZE = 256
plot = PlotLearningCurve(
mappings = {
'loss': { 'line': 'train', 'facet': 'loss' },
'val_loss': { 'line': 'validation', 'facet': 'loss' },
},
facet_config = {
'loss': { 'name': 'MSE-loss', 'limit': [0, None], 'scale': 'linear' },
},
xaxis_config = { 'name': 'Epoch', 'limit': [0, 500] }
)
input_data_file='../data/serialized_data/dataset_1k.npz'
output_model='../nets/neural_score_1k.pth'
checkpoint_path='../nets/neural_score_1k_checkpoint.pth'
chess_dataset = ChessDataset(input_data_file)
train_length = int(len(chess_dataset) * 0.8)
train, test = D.random_split(chess_dataset, lengths=[train_length , len(chess_dataset) - train_length])
train_loader = torch.utils.data.DataLoader(train, batch_size=_BATCH_SIZE, shuffle=True)
test_loader = torch.utils.data.DataLoader(test, batch_size=1, shuffle=True)
model = ChessConvNet()
optimizer = optim.Adam(model.parameters())
loss_function = nn.MSELoss()
recorded_epoch = 0
checkpoint = False
if checkpoint_path and checkpoint:
checkpnt = torch.load(checkpoint_path)
model.load_state_dict(checkpnt['model_state_dict'])
optimizer.load_state_dict(checkpnt['optimizer_state_dict'])
recorded_epoch = checkpnt['epoch']
recorded_loss = checkpnt['loss']
print(f'recorded current loss: {recorded_loss}')
model.train()
with plot:
for epoch in range(_EPOCHS-recorded_epoch):
all_loss = 0
num_loss = 0
test_all_loss = 0
test_num_loss = 0
for batch_idx, (data_origin, data_move, data_random, target) in enumerate(train_loader):
for test_data, data_move, data_random, test_target in test_loader:
test_target = test_target.unsqueeze(-1)
test_data = test_data.float()
test_target = test_target.float()
test_output = model(test_data)
test_loss = loss_function(test_output, test_target)
test_all_loss += test_loss.item()
test_num_loss += 1
optimizer.zero_grad()
target = target.unsqueeze(-1)
data_origin = data_origin.float()
target = target.float()
optimizer.zero_grad()
train_output = model(data_origin)
loss_train = loss_function(train_output, target)
loss_train.backward()
optimizer.step()
all_loss += loss_train.item()
num_loss += 1
current_loss = all_loss / num_loss
print("Train loss: %3d: %f" % (epoch, current_loss))
current_test_loss = test_all_loss / test_num_loss
print("Test loss: %3d: %f" % (epoch, current_test_loss))
plot.append(epoch, {
'loss': current_loss,
'val_loss': current_test_loss,
})
plot.draw()
torch.save(model.state_dict(), output_model)
if checkpoint_path:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': current_loss,
}, checkpoint_path)
| scripts/Train NeuralCaissa.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # 数据预处理
#
#
# 在模型训练过程中有时会遇到过拟合的问题,其中一个解决方法就是对训练数据做数据增强处理。通过对数据进行特定的处理,如图像的裁剪、翻转、调整亮度等处理,以增加样本的多样性,从而增强模型的泛化能力。
#
# 本节以图像数据为例,介绍数据预处理的方法。
#
# ## 一、paddle.vision.transforms 介绍
#
# 飞桨框架在 [paddle.vision.transforms](../../api/paddle/vision/Overview_cn.html#about-transforms) 下内置了数十种图像数据处理方法,可以通过以下代码查看:
import paddle
print('图像数据处理方法:', paddle.vision.transforms.__all__)
# 包括图像随机裁剪、图像旋转变换、改变图像亮度、改变图像对比度等常见操作,各个操作方法的简介可参考 [API 文档](../../api/paddle/vision/Overview_cn.html#about-transforms)。
#
#
#
# 对于飞桨框架内置的数据预处理方法,可以单个调用,也可以将多个数据预处理方法进行组合使用,具体使用方式如下:
#
# * 单个使用
# +
from paddle.vision.transforms import Resize
# 定义一个待使用的数据处理方法,这里定义了一个调整图像大小的方法
transform = Resize(size=28)
# -
# * 多个组合使用
#
# 这种使用模式下,需要先定义好每个数据处理方法,然后用`Compose` 进行组合。
# +
from paddle.vision.transforms import Compose, RandomRotation
# 定义待使用的数据处理方法,这里包括随机旋转、改变图片大小两个组合处理
transform = Compose([RandomRotation(10), Resize(size=32)])
# -
# ## 二、在数据集中应用数据预处理操作
#
# 定义好数据处理方法后,可以直接在数据集 Dataset 中应用,下面介绍两种数据预处理应用方式:一种是在框架内置数据集中应用,一种是在自定义的数据集中应用。
#
# ### 2.1 在框架内置数据集中应用
#
# 前面已定义好数据处理的方法,在加载内置数据集时,将其传递给 `transform` 字段即可。
#
# 通过 transform 字段传递定义好的数据处理方法,即可完成对框架内置数据集的增强
train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
# ### 2.2 在自定义的数据集中应用
#
# 对于自定义的数据集,可以在数据集中将定义好的数据处理方法传入 `__init__` 函数,将其定义为自定义数据集类的一个属性,然后在 `__getitem__` 中将其应用到图像上,如下述代码所示:
# 下载 MNIST 数据集并解压
# ! wget https://paddle-imagenet-models-name.bj.bcebos.com/data/mnist.tar
# ! tar -xf mnist.tar
# +
import os
import cv2
import numpy as np
from paddle.io import Dataset
class MyDataset(Dataset):
"""
步骤一:继承 paddle.io.Dataset 类
"""
def __init__(self, data_dir, label_path, transform=None):
"""
步骤二:实现 __init__ 函数,初始化数据集,将样本和标签映射到列表中
"""
super(MyDataset, self).__init__()
self.data_list = []
with open(label_path,encoding='utf-8') as f:
for line in f.readlines():
image_path, label = line.strip().split('\t')
image_path = os.path.join(data_dir, image_path)
self.data_list.append([image_path, label])
# 2. 传入定义好的数据处理方法,作为自定义数据集类的一个属性
self.transform = transform
def __getitem__(self, index):
"""
步骤三:实现 __getitem__ 函数,定义指定 index 时如何获取数据,并返回单条数据(样本数据、对应的标签)
"""
image_path, label = self.data_list[index]
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = image.astype('float32')
# 3. 应用数据处理方法到图像上
if self.transform is not None:
image = self.transform(image)
label = int(label)
return image, label
def __len__(self):
"""
步骤四:实现 __len__ 函数,返回数据集的样本总数
"""
return len(self.data_list)
# 1. 定义随机旋转和改变图片大小的数据处理方法
transform = Compose([RandomRotation(10), Resize(size=32)])
custom_dataset = MyDataset('mnist/train','mnist/train/label.txt', transform)
# -
# 在以上示例代码中,定义了随机旋转和改变图片大小数据处理方法,并传入 `__init__` 函数,然后在 `__getitem__` 中将其应用到图像上。
# ## 三、数据预处理的几种方法介绍
#
# 通过可视化的方法,可方便地对比飞桨内置数据处理方法的效果,下面介绍其中几个方法的对比示例。
#
# 首先下载示例图片
# 下载示例图片
# ! wget https://paddle-imagenet-models-name.bj.bcebos.com/data/demo_images/flower_demo.png
# ### CenterCrop:
#
# 对输入图像进行裁剪,保持图片中心点不变。
# +
import cv2
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from paddle.vision.transforms import CenterCrop
transform = CenterCrop(224)
image = cv2.imread('flower_demo.png')
image_after_transform = transform(image)
plt.subplot(1,2,1)
plt.title('origin image')
plt.imshow(image[:,:,::-1])
plt.subplot(1,2,2)
plt.title('CenterCrop image')
plt.imshow(image_after_transform[:,:,::-1])
# -
# ### RandomHorizontalFlip
#
# 基于概率来执行图片的水平翻转。
# +
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from paddle.vision.transforms import RandomHorizontalFlip
transform = RandomHorizontalFlip(0.5)
image = cv2.imread('flower_demo.png')
image_after_transform = transform(image)
plt.subplot(1,2,1)
plt.title('origin image')
plt.imshow(image[:,:,::-1])
plt.subplot(1,2,2)
plt.title('RandomHorizontalFlip image')
plt.imshow(image_after_transform[:,:,::-1])
# -
# ### ColorJitter
#
# 随机调整图像的亮度、对比度、饱和度和色调。
# +
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from paddle.vision.transforms import ColorJitter
transform = ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
image = cv2.imread('flower_demo.png')
image_after_transform = transform(image)
plt.subplot(1,2,1)
plt.title('origin image')
plt.imshow(image[:,:,::-1])
plt.subplot(1,2,2)
plt.title('ColorJitter image')
plt.imshow(image_after_transform[:,:,::-1])
# -
# 更多数据处理方法介绍可以参考 [paddle.vision.transforms API 文档](../../api/paddle/vision/Overview_cn.html#about-transforms)。
# ## 四、总结
#
# 本节介绍了数据预处理方法在数据集中的使用方式,可先将一个或多个方法组合定义到一个实例中,再在数据集中应用,总结整个流程和用到的关键 API 如下图所示。
#
# 
#
# 图 1:数据预处理流程
#
#
# 图像、文本等不同类型的数据预处理方法不同,关于文本的数据预处理可以参考 [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/docs/data_prepare/overview.rst)。
| docs/guides/02_paddle2.0_develop/03_data_preprocessing_cn.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import sys
sys.path.append('../')
# +
test_roots = {
'깨닫', '불', '묻', '눋', '겯', '믿', '묻', '뜯', # ㄷ 불규칙
'구르', '무르', '마르', '누르', '나르', '모르', '이르', # 르 불규칙
'아니꼽', '우습', '더럽', '아름답', '잡', '뽑', '곱', '돕', # ㅂ 불규칙
'낫', '긋', '붓', '뭇', '벗', '솟', '치솟', '씻', '손씻', '뺏', # ㅅ 불규칙
'똥푸', '주', '좀주', '푸', # 우 불규칙
'끄', '크', '트', # ㅡ 탈락 불규칙
'삼가', '가', '들어가', # 거라 불규칙
'돌아오', '오', # 너라 불규칙
'이르', '푸르', '누르', # 러 불규칙
'하', # 여 불규칙
'가', '노랗', '퍼렇', '놀라', # 어미 ㄴ
'시퍼렇', '파랗', # ㅎ 불규칙
'먹',
'보', '뵈', '뵙', '그렇'
}
test_eomis = {
'',
'아', '어나다', '어', '워', '웠다', '워서', '왔다', '와주니', '었다', '었어', '았어', '데',
'라', '라니까', '너라', '았다', '러', '였다', '았다', '면', '다', '거라', '고', '는', '니'
}
testset = [
('깨달' ,'아'),
('굴' ,'러'),
('더러' ,'워서'),
('도' ,'왔다'),
('부' ,'었다'),
('똥퍼' ,''),
('퍼' ,''),
('줬' ,'어'),
('꺼' ,''),
('텄' ,'어'),
('가' ,'거라'),
('돌아오' ,'거라'),
('돌아왔' ,'다'),
('이르' ,'러'),
('파라' ,'면'),
('시퍼렜' ,'다'),
('파랬' ,'다'),
('파래' ,''),
('간' ,''),
('푸른' ,''),
('한' ,''),
('이른' ,''),
('불', '어'),
('부', '어'),
('일', '러'),
('이르', '니'),
('이른', ''),
('뵈', '고'),
('뵙', '고'),
('뵙', '는'),
('그래', ''),
]
from _lemmatizer import Lemmatizer
lemmatizer = Lemmatizer(test_roots, test_eomis)
for l,r in testset:
print('({}, {}) -> {}'.format(l,r,lemmatizer.lemmatize(l+r)))
# -
| SoyNLP/test/lemmatizer_test.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: VPython
# language: python
# name: vpython
# ---
import numpy as np
import astropy
import scipy
import math
import matplotlib.pyplot as plt
from scipy import constants
from astropy.io import ascii
from astropy import cosmology
from astropy import units as u
from astropy.units import astrophys as astro
from vpython import *
from vpython import graph
#window for the progrom if it's run on a computer
scene = display(title = 'Planets Orbiting K2 - 266', width = 800,
height = 800, range = (25000,25000,25000), center = (1000,0,0))
# +
#getting file from directory
filename = 'C://Users/Janel/Documents/ASTRO_200_Python/K2-266.txt'
#reading data from the file into an ascii table
data = ascii.read(filename)
#indexing raw values for mathematical calculation
planet_letter= data['pl_letter'] #planet letter
#print(planet_letter)
P = data['pl_orbper'] #planets orbital period in days
#print(P)
i_deg = data['pl_orbincl'] #planets inclincation
#print(i_deg)
pl_massj= data['pl_bmassj'] #planets mass in jupiter units
#print(pl_massj)
pl_rad= data['pl_radj'] #planet radius in jupiter radii
#print(pl_rad)
St_dist= data['st_dist'] #distance of star from us in parsecs
#print(St_dist)
St_M= data['st_mass'] #stellar mass in solar mass
#print(St_M)
St_R= data['st_rad'] #stellar radius in solar radii
#print(St_R)
e = data['pl_orbeccen'] #orbital eccentricity
#print(e)
semi_ax = data['pl_orbsmax'] #semi - major axis of each planet in AU
#print(semi_ax)
orb_peri = data['pl_orbper']
V_star = data['st_rad']
#print(orb_peri)
# -
#defining constants
G = scipy.constants.gravitational_constant *1e-9 #gravitational constant from scipy database #changed from m^3 to kilometers^3
#print(G)
pi = scipy.constants.pi # pi constant from data bate
#print(pi)
pi_2 = pi**2 #pi squared
#print(pi_2)
au_km = (1.496e8) # 1au in kilometers
#print(au_km)
Mjup_kg= (1.8981872e27) #jupiter masses in kilograms, conversion factor
#print(Mjup_kg)
Msol_kg = (1.9884754e30) #solar masses in kilograms, conversion factor
#print(Msol_kg)
Rjup_km = (71492.0) #jupiter radii in kilometers
#print(Rjup_km)
Rsol_km = (695700.0) #star radii in kilometers
#print(Rsol_km)
#change from integer to real number
# +
#indexing raw extracted raw data
Mstar = St_M[0] * Msol_kg #multiplying indexed raw stellar mass data by solar constant
#print(Mstar)
Rstar = St_R[0]*Rsol_km #indexing Rstar value which is in km
#print(Rstar)
v_star = V_star[0]
Mp = pl_massj*Mjup_kg #multiplying indexed raw planet masses by jupiter masses to get kg
#print(Mp)
Rp = pl_rad*Rjup_km #multiplying indexed raw planet radii by jupiter radians to get km
#print(Rp)
ap = semi_ax*au_km #multiplying indexed raw planet obital radius by 1au in km to get the ap from au to km
#print(ap)
i_rad = (i_deg)*(pi/180)
#print(i_rad)
Wop = orb_peri
#print(Wop)
#print(ap)
#print(planet_letter)
#------------Planet Masses in kg -----------#
#bmass = Mp[0:1]
bmass = Mp[0]
#print(bmass)
cmass = Mp[1]
#print(cmass)
dmass = Mp[2]
#print(dmass)
emass = Mp[3]
#print(emass)
print(bmass)
print(cmass)
print(dmass)
#----------Planet Period in days ----------#
P_b = P[0]
#print(P_b)
P_c = P[1]
#print(P_c)
P_d = P[2]
#print(P_d)
P_e = P[3]
#print(P_e)
#--------Planet Orbital Semimajor axis in km ------#
ap_b = ap[0]
#print(ap_b)
ap_c = ap[1]
#print(ap_c)
ap_d = ap[2]
#print(ap_d)
ap_e = ap[3]
#print(ap_e)
#---------------Planet Radii in km ---------------#
Rb = Rp[0]
#print(Rb)
Rc = Rp[1]
#print(Rc)
Rd = Rp[2]
#print(Rd)
Re = Rp[3]
#print(Re)
#--------------Planet Inclincation in radians -------------#
i_b = i_rad[0]
#print(i_b)
i_c = i_rad[1]
#print(i_c)
i_d = i_rad[2]
#print(i_d)
i_e = i_rad[3]
#print(i_e)
#-------------Planet Orbital Eccentricity ---------------#
e_b = .044
#print(e_b)
e_c = e[1]
#print(e_c)
e_d = e[2]
#print(e_d)
e_e = e[3]
#print(e_e)
#----------Planet Long. Periastrian angle in deg----------------#
Wob = 88.00 #abitrarily chosen due to missing values
#print(Wob)
Woc = Wop[1]
Wod = Wop[2]
#print(Wod)
Woe = Wop[3]
#print(Woe)
#----------------FORCE on the planets------------------#
F_b = (G*(bmass*Mstar))/(ap_b**2)
#print(F_b)
F_c = (G*(cmass*Mstar))/(ap_c**2)
#print(F_c)
F_d = (G*(dmass*Mstar))/(ap_d**2)
#print(F_d)
F_e = (G*(emass*Mstar))/(ap_e**2)
#print(F_e)
#------------Angular Velocity of the planets, the initial velocity-----------------#
wb = math.sqrt(F_b/(bmass*ap_b))
wc = math.sqrt(F_c/(cmass*ap_c))
wd = math.sqrt(F_d/(dmass*ap_d))
we = math.sqrt(F_e/(emass*ap_e))
#------------Initial Velocities of the planets-----------------#
vb = wb*ap_b
vc = wc*ap_c
vd = wd*ap_d
ve = we*ap_e
#print(vb)
#print(vc)
#print(vd)
#print(ve)
# +
#this defines the inital position, size, and velocity of the objects
rsc = 10
star = sphere(pos = vector(0,0,0), radius = Rstar, color = color.red, make_trail = True ) # star's starting position at the origin
star.velocity= vector(0,0,0)
b = sphere(pos = vector(ap_b,0,0), radius = Rb*rsc, color = color.orange, make_trail = True ) # star's starting position at the origin of the simulation
b.velocity = vector(0,vb,0)
c = sphere(pos = vector(ap_c,0,0), radius = Rc*rsc, color = color.green, make_trail = True ) # star's starting position at the origin ''
c.velocity = vector(0,vc,0)
d = sphere(pos = vector(ap_d,0,0), radius = Rd*rsc, color = color.blue, make_trail = True ) # star's starting position at the origin ''
d.velocity = vector(0,vd,0)
e = sphere(pos = vector(ap_e,0,0), radius = Re*rsc, color = color.purple, make_trail = True ) # star's starting position at the origin ''
e.velocity = vector(0,ve,0)
# +
#---------Initializing Graphics Curve -----------------------#
f1 = gcurve(color=color.orange) # a graphics curve
f2 = gcurve(color = color.green)
f3 = gcurve(color = color.blue)
f4 = gcurve(color = color.purple)
f5 = gcurve(color = color.black)
t = 0
# +
t = 0 #inital time
dt = 10 #timestep
while t <= 1e50:
rate(1000)
dist_b = mag(b.pos)
unvec_b = (b.pos - star.pos)/dist_b
fgrav_b_mag = -(G*(bmass*Mstar))/(dist_b**2)
fgrav_b = fgrav_b_mag * unvec_b
b.velocity = b.velocity + (np.divide(fgrav_b,bmass))*dt
b.pos = b.pos + b.velocity*dt
# f1.plot(t,b.pos.y)
dist_c = mag(c.pos)
unvec_c = (c.pos - star.pos)/dist_c
fgrav_c_mag = -(G*(cmass*Mstar))/(dist_c**2)
fgrav_c = fgrav_c_mag * unvec_c
c.velocity = c.velocity + (np.divide(fgrav_c,cmass))*dt
c.pos = c.pos + c.velocity*dt
# f2.plot(t,c.pos.y)
dist_d = mag(d.pos)
unvec_d = (d.pos - star.pos)/dist_d
fgrav_d_mag = -(G*(dmass*Mstar))/(dist_d**2)
fgrav_d = fgrav_d_mag * unvec_d
d.velocity = d.velocity + (np.divide(fgrav_d,dmass))*dt
d.pos = d.pos + d.velocity*dt
# f3.plot(t,d.pos.y)
dist_e = mag(e.pos)
unvec_e = (e.pos - star.pos)/dist_e
fgrav_e_mag = -(G*(emass*Mstar))/(dist_e**2)
fgrav_e = fgrav_e_mag*unvec_e
e.velocity = e.velocity + (np.divide(fgrav_e,emass))*dt
e.pos = e.pos + e.velocity*dt
# f4.plot(t,e.pos.y)
mratio_b = bmass/Mstar
mratio_c = cmass/Mstar
mratio_d = dmass/Mstar
mratio_e = emass/Mstar
star.pos.y = star.pos.y + (b.velocity.y*mratio_b + c.velocity.y*mratio_c + d.velocity.y*mratio_d + e.velocity.y*mratio_e)*dt
star.pos.x = star.pos.x + (b.velocity.x*mratio_b + c.velocity.x*mratio_c + d.velocity.x*mratio_d + e.velocity.x*mratio_e)*dt
star.pos.z = star.pos.z + (b.velocity.z*mratio_b + c.velocity.z*mratio_c + d.velocity.z*mratio_d + e.velocity.z*mratio_e)*dt
#print(star.pos.y)
#plotting the y compnent of the velocity over time
f1.plot(t,b.velocity.y)
f2.plot(t,c.velocity.y)
f3.plot(t,d.velocity.y)
f4.plot(t,e.velocity.y)
# f5.plot(t,star.pos)
f5.plot(t,star.pos.y)
#plotting the magnitiudes of the gravitional force on the planets over time
t+=dt
# -
| ASTRO_200_Presentation_Orbital_Simulations_K2-266_Williams.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="6WX0OhSMEi5N"
# # Introduction to Pandas
#
# You may have used a program like Microsoft Excel or Google Sheets to record data or perform calculations for school. Datasets are often organized in rows and columns. Here's an example of a table:
#
# | Product | Price | Quantity Sold |
# |--------------|-------------|------------------------|
# | Apples | \$ 1.50 | 26 |
# | Bananas | \$ 0.50 | 32 |
# | Lemons | \$ 1.99 | 17 |
#
# In this case, we have prices of fruit from a grocery store. Each row in this dataset corresponds to a type of fruit, and each column is an observation or measurement about that fruit. What measurements do we have here?
# + [markdown] colab_type="text" id="_90Q12UnL4Tj"
# **Measurements**: Price, Quantity Sold
# + [markdown] colab_type="text" id="WtJhbr1nL2qu"
# To handle table data in Python, we use a package called called `pandas`. (Despite the name, it actually doesn't have anything to do with panda bears - disappointing, we know.)
#
# Before we can use the package, we need to import it. Try writing a line of code to import the `pandas` package:
# + colab={} colab_type="code" id="-q4BsNy9Er34"
# write the code to import the package
import pandas
# + [markdown] colab_type="text" id="Dx6txgMkMYv3"
# We're going to be using `pandas` a lot. To save us some time typing, let's tell Python to rename the package for us to something a little shorter:
# + colab={} colab_type="code" id="xZSsmJy-MPXn"
import pandas as pd
# + [markdown] colab_type="text" id="bu8qnXXwOLOJ"
# Adding "`as pd`" to our import statement tells Python that every time we use `pd`, we actually mean `pandas`. It's like giving the package a nickname! Most people use this same nickname for `pandas`, so if you see other people's code, you'll know that `pd` means `pandas`.
#
# Now that we've imported `pandas`, we're ready to use it. Datasets are stored in `pandas` in a special container called a `DataFrame`. `DataFrames` help us handle data that are organized in rows and columns, just like the grocery store dataset above. We can create that `DataFrame` by calling the `DataFrame` function:
# + colab={"base_uri": "https://localhost:8080/", "height": 142} colab_type="code" executionInfo={"elapsed": 823, "status": "ok", "timestamp": 1563148382350, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WQsOgn6cXFg/AAAAAAAAAAI/AAAAAAAAAVA/ol7X28qyOHc/s64/photo.jpg", "userId": "07259925140867310896"}, "user_tz": 240} id="6oILyPBHOunF" outputId="9ab6633f-60f2-47b9-e570-954a9362a0f9"
pd.DataFrame({'Product': ['Apples', 'Bananas', 'Lemons'],
'Price': [1.50, 0.50, 1.99],
'QuantitySold': [26, 32, 17]})
# + [markdown] colab_type="text" id="jsOzQKKhPAdY"
# There are a few things to notice:
#
# 1. Python helpfully showed us what our `DataFrame` looks like with rows and columns.
# 1. Python gave each row in the `DataFrame` a number, starting from zero. Does that remind you of something about lists?
#
# When we ran that cell, Python showed us what the `DataFrame` looks like, but it didn't save the `DataFrame` anywhere. If we want to do more things with it, we'll need to save it to a variable - the same way we learned to save integers or strings to variables. In the below cell, save the same `DataFrame` to a variable called `fruit_data`:
# + colab={} colab_type="code" id="nggCk6-xTwQL"
# save the DataFrame to a variable called fruit_data
fruit_data = pd.DataFrame({'Product': ['Apples', 'Bananas', 'Lemons'],
'Price': [1.50, 0.50, 1.99],
'QuantitySold': [26, 32, 17]})
# + [markdown] colab_type="text" id="EjhJ8RvtT25R"
# When we run the above cell, does anything happen?
#
# Since we saved the `DataFrame` to a variable, Python assumed that we don't want to take a peek at it. If we do want to see what our `DataFrame` looks like, we can write the variable on a line by itself like this:
# + colab={"base_uri": "https://localhost:8080/", "height": 142} colab_type="code" executionInfo={"elapsed": 803, "status": "ok", "timestamp": 1563148382357, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WQsOgn6cXFg/AAAAAAAAAAI/AAAAAAAAAVA/ol7X28qyOHc/s64/photo.jpg", "userId": "07259925140867310896"}, "user_tz": 240} id="FiwHIyIdUjyn" outputId="7febdca8-e736-436b-da53-4c5b9c5f0c1d"
# print out fruit_data
fruit_data
# + [markdown] colab_type="text" id="kAHbv9J6UnkI"
# Sometimes we don't want to see all of the data at once. To view just the first few rows of a `DataFrame`, we use a method called `head`.
#
# Recall: methods are special functions that belong to certain types of variables. They only work with the type of variable that they belong to, so running `head` on a variable that isn't a `DataFrame` will not work.
#
# Let's use the `head` method to view only the first two rows of our fruit data:
# + colab={"base_uri": "https://localhost:8080/", "height": 111} colab_type="code" executionInfo={"elapsed": 782, "status": "ok", "timestamp": 1563148382359, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WQsOgn6cXFg/AAAAAAAAAAI/AAAAAAAAAVA/ol7X28qyOHc/s64/photo.jpg", "userId": "07259925140867310896"}, "user_tz": 240} id="allPAW1nVn6L" outputId="0ea894c0-9e11-48e1-ef09-d8dcdb46219b"
fruit_data.head(2)
# + [markdown] colab_type="text" id="YfQSfKheWTN8"
# After typing `head`, the name of the method, we wrote the number `2` between the parentheses. This told `head` that we wanted to see only the first two lines of our `DataFrame`. What would you do if you only wanted to see the first line of `fruit_data`?
# + colab={"base_uri": "https://localhost:8080/", "height": 80} colab_type="code" executionInfo={"elapsed": 758, "status": "ok", "timestamp": 1563148382360, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WQsOgn6cXFg/AAAAAAAAAAI/AAAAAAAAAVA/ol7X28qyOHc/s64/photo.jpg", "userId": "07259925140867310896"}, "user_tz": 240} id="8P09FlUXXPoG" outputId="a34ea6f5-d1fb-4585-a6eb-659fd477abc8"
# write the code to see only the first line of the DataFrame
fruit_data.head(1)
# + [markdown] colab_type="text" id="oKD81ZM9YXkn"
# Great! What if instead of viewing the first few lines, we wanted to see the last few lines? For that we will use another method called `tail`. It is very similar to `head`, except it will show us the last few lines instead of the first few. Try writing a line of code to view the very last line of `fruit_data`:
# + colab={"base_uri": "https://localhost:8080/", "height": 80} colab_type="code" executionInfo={"elapsed": 748, "status": "ok", "timestamp": 1563148382362, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/-WQsOgn6cXFg/AAAAAAAAAAI/AAAAAAAAAVA/ol7X28qyOHc/s64/photo.jpg", "userId": "07259925140867310896"}, "user_tz": 240} id="nAZAPhwyZBjg" outputId="f1080349-051a-4bad-c0b9-990ec86f0e85"
# write the code to see only the last line of the DataFrame
fruit_data.tail(1)
# + [markdown] colab_type="text" id="lcQomTMvYnHv"
# `head` and `tail` are especially useful for big datasets with many rows so you can get a sense for what the `DataFrame` looks like without flooding your notebook with too much information. They will come in handy later!
#
# Now let's talk about the types of variables we have in the `fruit_data` `DataFrame`. What are some of the types of variables we've learned about in Python?
# + [markdown] colab_type="text" id="X_QgfriidxZF"
# **Types:** string, int, float, list
# + [markdown] colab_type="text" id="amfeRkLneFMN"
# Based on what you know about these types of variables, what `type` do you think the values in each of the columns belong to in `fruit_data`?
# + [markdown] colab_type="text" id="9ydMKRmffKmU"
# **Type of the `Product` column:** string (explanation: the names of the fruit are words)
#
# **Type of the `Price` column:** float (explanation: the prices have decimal points)
#
# **Type of the `QuantitySold` column:** int (explanation: quantity sold is a count. stores won't sell only half a banana.)
# + [markdown] colab_type="text" id="elTWh0Whf3Yg"
# Notice how each of the columns in `fruit_data` have different types. That's one of the many cool things about `pandas` -- it let's us store many different types of data in `DataFrames`.
| Lessons/_Keys/KEY_Lesson14_Pandas-Intro.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # QCoDeS Example with the Stahl Bias Sources
#
# This notebook provides an example to how to set voltages with the Stahl Bias Sources.
from qcodes.instrument_drivers.stahl import Stahl
stahl = Stahl("stahl", "ASRL3")
stahl.channel[4].voltage(2)
v = stahl.channel[4].voltage()
print(v)
stahl.channel[4].voltage(-2)
v = stahl.channel[4].voltage()
print(v)
stahl.channel[4].voltage(0)
v = stahl.channel[4].voltage()
print(v)
stahl.channel[0].current()
stahl.channel[0].current.unit
stahl.temperature()
stahl.channel[1].is_locked()
stahl.output_type
| docs/examples/driver_examples/Qcodes example with Stahl.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Trades Example
# Use with the following artifacts:
# 1) trades.xml
# 2) traders.xml
# 3) trades.csv
# 4) traders.csv
# 5) eventgenerator.xml
# The first step is to import the ESPPy package.
import esppy
# Start an ESP server before running the next cell. Enter the appropriate ('http:host:port') as the argument to the ESP constructor.
server=esppy.ESP('<host>:<port>')
server
server.server_info
# List any projects that are active on the server. If you have not loaded projects to the server, this returns an empty dictionary.
server.get_projects()
# List windows within the project. If you have not loaded projects to the server, this returns an empty dictionary.
server.get_windows()
project_path = '<path>/trades.xml'
project_xml = project_path
# Load the project 'trades_proj' into the esppy server session
trades_project = server.load_project(project_xml, name='trades_proj')
# Confirm that the project 'trades_proj' has been successfully uploaded to the esp server
server.get_projects()
server.get_windows()
# List only the windows that are contained in the 'trades_proj' project
trades_project.get_windows()
# Output a list of only the continuous queries that are in the 'trades_project' project
trades_project.queries
# List all windows that are a part of the continuous query, 'trades_cq'
trades_project.queries['trades_cq'].windows
# Produce a graphical representation of the continuous query, 'trades_cq'
trades_project.queries['trades_cq']
# Display the XML of the project
print(trades_project.to_xml(pretty=True))
# Create a new project named 'my_proj'
my_project=server.create_project('my_proj')
my_project
# Add a continuous query called 'trades_cq' to the project
my_query = my_project.add_query('trades_cq')
my_query
# Continue to build your project by adding a source window called 'Trades' to the project.
#
# Specify any input variables in the schema along with their datatype. You may choose to add a key to a variable by placing a * after its name.
#
# After creating the window, display an image of it.
# +
source_trades = server.SourceWindow(name='Trades',
schema=('tradeID*:string', 'security:string', 'quantity:int32', 'price:double', 'traderID:int64', 'time:stamp'),
index_type='pi_RBTREE')
source_trades
# -
# Add the source window'Trades' to the continuous query 'trades_cq'. Then display an image of the project so far.
# +
my_query.add_window(source_trades)
my_project
# -
# Create another source window that receives data about the Traders. Name this new window 'Traders'.
# Note that the input variable tradesID is specified to be a key. Then display an image of the Source window 'Traders'.
# +
source_traders = server.SourceWindow(name='Traders', schema=('tradeID*:string', 'name:string'))
source_traders
# -
# Make a FilterWindow called 'Large Trades'. Add an expression to the FilterWindow, that defines what data passes through it. In this case, let Large trades that have a quantity that is at least 100 pass through.
# +
filter_large = server.FilterWindow(name='LargeTrades')
filter_large.set_expression('quantity >= 100')
# -
# Create a JoinWindow called 'AddTraderName' and specify the type of join as well as the join conditions.
# Define field selections and specify the variable pairs to be joined.
# Place 'l_' before all variables that come from the left join, and 'r_' before those from the right join.
# Display the field selections. Then run a loop to perform the actual join.
# +
join = server.JoinWindow(name='AddTraderName', type='leftouter', conditions=[('tradeID', 'tradeID')])
field_selections = [['security', 'l_security'], ['quantity', 'l_quantity'], ['price', 'l_price'], ['traderID', 'l_traderID'], ['time', 'l_time'], ['name', 'r_name']]
field_selections
for i in range(len(field_selections)):
join.add_field_selection(field_selections[i][0], field_selections[i][1])
# -
# Add a compute window to the project called 'TotalCost' to calculate price*quantity.
# Though the variable totalCost does not exist yet, you must specify it in the output schema.
# Additionally, in the schema you must include any variables that are needed to perform the calculation
# Then, add field expressions that define how each variable in your output schema is created.
# Notice that variables are created in the order that they were specified in your output schema.
# +
compute = server.ComputeWindow(name='TotalCost',
schema=('tradeID*:string', 'security:string', 'quantity:int32',
'price:double', 'totalCost:double', 'traderID:int64',
'time:stamp', 'name:string'))
compute.add_field_expressions('security', 'quantity', 'price', 'price*quantity', 'traderID', 'time', 'name')
compute
# -
# Add an aggregate window to our project, and call it 'BySecurity'. In this window you compute quantityTotal and costTotal. Most importantly, the calculations are done by the specified key value, security*.
# Add field expressions to the calculate window to declare how the values in the output schema are computed. Here, you calculate the 'quantityTotal' by 'ESP_aSum(quantity)', and 'costTotal' by 'ESP_aSum(totalCost)'. Then display the aggregate window along with its schema.
# +
aggregate = server.AggregateWindow(name='BySecurity', schema=('security*:string', 'quantityTotal:double',
'costTotal:double'))
aggregate.add_field_expressions('ESP_aSum(quantity)', 'ESP_aSum(totalCost)')
aggregate
# -
# Assemble the project by defining edges between each of the windows.
# Create an edge between the 'Trades' Source window and the 'LargeTrades' Filter window with the data role.
# Create an edge between the filterWindow 'LargeTrades' and the the join window 'AddTraderName' with the role 'left', specifying the left join.
# Create an edge between the source window, 'Traders' and the join window 'AddTraderName' with the role 'right', specifying the right join.
# Create an edge between the join window 'AddTraderName' and the compute window, 'TotalCost' with the data role.
# Create an edge between the aggregate window, 'BySecurity' and the compute window, 'TotalCost' with the data role.
source_trades.add_target(filter_large, role='data')
filter_large.add_target(join, role='left')
source_traders.add_target(join, role='right')
join.add_target(compute, role='data')
compute.add_target(aggregate, role='data')
# +
my_query.add_windows(source_trades, source_traders, filter_large, join, compute, aggregate)
my_project
# -
server.load_project(my_project)
server.get_projects()
print(my_project.to_xml(pretty=True))
trades_project['trades_cq'].to_graph(schema=True)
print(trades_project['trades_cq']['Traders'].to_xml(pretty=True))
# The code that follows explores two methods for publishing data into the project.
# The first publishes data from a .csv file into a source window.
# Begin by opening and reading a file that contains trades data.
trades_csv = open('<path>/trades.csv').read()
# Next, open and read a file that contains traders data.
traders_csv = open('<path>/traders.csv').read()
# Use print to confirm that the data on trades has been read
print(trades_csv)
# Isolate the two source windows('Trades' and 'Traders') into which data is published.
w_trades = trades_project['trades_cq']['Trades']
w_traders = trades_project['trades_cq']['Traders']
# Publish data into the 'Trades' and 'Traders' source windows
w_trades.publish_events(trades_csv, dateformat='%d/%b/%Y:%H:%M:%S', format='csv')
w_traders.publish_events(traders_csv, format='csv')
# Confirm that the data has been published into the 'Trades' source window
w_trades.get_events()
# The second method to publish data is through a pre-defined event generator.
# Define and read a separate xml file that contains the definitions for that is used to create the event generator
EventGenerator_Path = '<path>/eventgenerator.xml'
EventGenerator_xml = open(EventGenerator_Path).read()
# Use print to ensure that the event generator has been loaded
# Notice that this event generator is designed to inject events into the 'Trades' source window
print(EventGenerator_xml)
# Formally create an event generator using the XML that was loaded.
trades_generator = esppy.evtgen.EventGenerator.from_xml(str(EventGenerator_xml))
trades_generator
# In order to run an event generator, make sure that it is running in the same session as the model. After assigning the session, save the event generator. Then initialize and start it.
# +
trades_generator.session = server.session
trades_generator.save()
trades_generator.initialize()
trades_generator.start(rate=10)
# -
# After events begin to stream in, retrieve them from the 'Trades' source window
w_trades2 = trades_project['trades_cq']['Trades']
w_trades2.get_events()
# When you specify a streaming chart, it creates an independent subscriber to the associated window. Thus, you do not need to subscribe to that window on a separate line of code beforehand.
# +
from esppy.plotting import StreamingChart
w_BySecurity=trades_project['trades_cq']['BySecurity']
streamChart = w_BySecurity.streaming_bar('security', 'quantityTotal', title='Total Quantity Sold By Security')
streamChart
# -
w_trades2 = trades_project['trades_cq']['Trades']
w_trades2.subscribe()
w_trades2
w_trades2.info()
w_trades2.head()
w_trades2.describe()
# +
# %matplotlib inline
w_trades2.plot(y='quantity')
# -
w_trades2.streaming_bar(x='time', y=['quantity', 'price'])
trades_generator.stop()
trades_generator.delete()
| examples/TradesExample.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %load_ext autoreload
# %autoreload 2
# %matplotlib inline
# -
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import KFold
import lightgbm as lgb
path=Path('/kaggle/data_science_bowl')
path
# ### Read Data
def read_data():
train_df = pd.read_csv(path/'train.csv')
test_df = pd.read_csv(path/'test.csv')
train_labels_df = pd.read_csv(path/'train_labels.csv')
return train_df, test_df, train_labels_df
train_df, test_df, train_labels_df = read_data()
train_df.head()
test_df.head()
train_labels_df.head()
# ## Feature Engineering
main_key = 'installation_id'
merge_args = {'left_index':True, 'right_index':True}
agg_stats = ['mean', 'sum', 'min', 'max', 'std', 'skew', 'median', pd.Series.kurt, 'count']
def get_event_id_count(df):
df = df.groupby([main_key]).agg({'event_id': ['count']})
df.columns = ['event_id_count']
return df
# +
import json
def process_event_code(x, is_correct):
count = 0
for xi in x:
fields = json.loads(xi)
if 'event_code' in fields and fields['event_code'] in [4100, 4110] and 'correct' in fields and fields['correct'] == is_correct:
count += 1
return count
def process_correct_event_code(x):
return process_event_code(x, True)
def process_incorrect_event_code(x):
return process_event_code(x, False)
def extract_correct_incorrect(df, field_name, func):
key = ['installation_id']
event_code_count = df[:].groupby(key)['event_data'].agg(func)
event_code_count = event_code_count.reset_index()
event_code_count.columns = [*key, field_name]
return event_code_count
def extract_correct(df):
return extract_correct_incorrect(df, 'num_correct', process_correct_event_code)
def extract_incorrect(df):
return extract_correct_incorrect(df, 'num_incorrect', process_incorrect_event_code)
# +
def get_object_columns(df, column):
df = df.groupby([main_key, column])['event_id'].count().reset_index()
df = df.pivot_table(index = main_key, columns = [column], values = 'event_id')
df.columns = list(df.columns)
df.fillna(0, inplace = True)
return df
def get_numeric_columns(df, column):
df = df.groupby('installation_id').agg({f'{column}': agg_stats})
df[column].fillna(df[column].mean(), inplace = True)
df.columns = [f'{column}_{stat}' for stat in agg_stats]
df.rename(columns={ df.columns[7]: f'{column}_kurt' }, inplace = True)
df.fillna(0, inplace = True)
return df
def get_numeric_columns_add(df, agg_column, column):
df = df.groupby([main_key, agg_column]).agg({f'{column}': agg_stats}).reset_index()
df = df.pivot_table(index = main_key, columns = [agg_column], values = [col for col in df.columns if col not in [main_key, agg_column]])
df[column].fillna(df[column].mean(), inplace = True)
df.columns = list(df.columns)
return df
def process_correct_incorrect(comp_train_df, comp_test_df, func, field):
comp_train_df = comp_train_df.merge(func(train_df), on=main_key, how='left')
comp_test_df = comp_test_df.merge(func(test_df), on=main_key, how='left')
comp_train_df[field].fillna(0.0, inplace=True)
comp_test_df[field].fillna(0.0, inplace=True)
return comp_train_df, comp_test_df
def feature_engineering(train_df, test_df, train_labels_df):
numerical_columns = ['game_time']
categorical_columns = ['type', 'world']
comp_train_df = pd.DataFrame({main_key: train_df[main_key].unique()})
comp_train_df.set_index(main_key, inplace = True)
comp_test_df = pd.DataFrame({main_key: test_df[main_key].unique()})
comp_test_df.set_index(main_key, inplace = True)
for i in numerical_columns:
comp_train_df = comp_train_df.merge(get_numeric_columns(train_df, i), **merge_args)
comp_test_df = comp_test_df.merge(get_numeric_columns(test_df, i), **merge_args)
for i in categorical_columns:
comp_train_df = comp_train_df.merge(get_object_columns(train_df, i), **merge_args)
comp_test_df = comp_test_df.merge(get_object_columns(test_df, i), **merge_args)
for i in categorical_columns:
for j in numerical_columns:
comp_train_df = comp_train_df.merge(get_numeric_columns_add(train_df, i, j), **merge_args)
comp_test_df = comp_test_df.merge(get_numeric_columns_add(test_df, i, j), **merge_args)
comp_train_df.reset_index(inplace = True)
comp_test_df.reset_index(inplace = True)
comp_train_df, comp_test_df = process_correct_incorrect(comp_train_df, comp_test_df, extract_correct, 'num_correct')
comp_train_df, comp_test_df = process_correct_incorrect(comp_train_df, comp_test_df, extract_incorrect, 'num_incorrect')
print(f'Our training set has {comp_train_df.shape[0]} rows and {comp_train_df.shape[1]} columns')
print(f'Our test set has {comp_test_df.shape[0]} rows and {comp_test_df.shape[1]} columns')
# get the mode of the title
labels_map = dict(train_labels_df.groupby('title')['accuracy_group'].agg(lambda x:x.value_counts().index[0]))
# merge target
labels = train_labels_df[[main_key, 'title', 'accuracy_group']]
# replace title with the mode
labels.loc[:,'title'] = labels['title'].map(labels_map)
# get title from the test set
comp_test_df.loc[:,'title'] = test_df.groupby(main_key).last()['title'].map(labels_map).reset_index(drop = True)
# join train with labels
comp_train_df = labels.merge(comp_train_df, on = main_key, how = 'left')
print(f'We have {comp_train_df.shape[0]} training rows')
return comp_train_df, comp_test_df
# -
comp_train_df, comp_test_df = feature_engineering(train_df, test_df, train_labels_df)
pd.options.display.max_columns = None
comp_train_df
list(comp_test_df.columns)
# ## Normalize
import re
comp_train_df.columns = [c if type(c) != tuple else '_'.join(c) for c in comp_train_df.columns]
comp_test_df.columns = [c if type(c) != tuple else '_'.join(c) for c in comp_test_df.columns]
comp_train_df.columns = [re.sub(r'\W', '_', s) for s in comp_train_df.columns]
comp_test_df.columns = [re.sub(r'\W', '_', s) for s in comp_test_df.columns]
list(comp_train_df.columns)
# ## Training
# quadratic weighted kappa
def qwk3(a1, a2, max_rat=3):
'''
a1 - ground truth
a2 - predicted values
'''
assert(len(a1) == len(a2))
a1 = np.asarray(a1, dtype=int)
a2 = np.asarray(a2, dtype=int)
hist1 = np.zeros((max_rat + 1, ))
hist2 = np.zeros((max_rat + 1, ))
o = 0
for k in range(a1.shape[0]):
i, j = a1[k], a2[k]
hist1[i] += 1
hist2[j] += 1
o += (i - j) * (i - j)
e = 0
for i in range(max_rat + 1):
for j in range(max_rat + 1):
e += hist1[i] * hist2[j] * (i - j) * (i - j)
e = e / a1.shape[0]
return 1 - o / e
# +
features = [i for i in comp_train_df.columns if i not in ['accuracy_group', 'installation_id']]
target = 'accuracy_group'
num_splits = 10
params = {
'learning_rate': 0.007,
'metric': 'multiclass',
'objective': 'multiclass',
'num_classes': 4,
'feature_fraction': 0.75,
"bagging_fraction": 0.8,
"bagging_seed": 42,
'max_depth': 11
}
early_stopping_rounds = 100
def train_model(comp_train_df, comp_test_df):
kf = KFold(n_splits=num_splits, shuffle=True)
oof_pred = np.zeros((len(comp_train_df), 4))
models = []
for fold, (tr_ind, val_ind) in enumerate(kf.split(comp_train_df)):
print(f'Fold: {fold+1}')
x_train, x_val = comp_train_df[features].iloc[tr_ind], comp_train_df[features].iloc[val_ind]
y_train, y_val = comp_train_df[target][tr_ind], comp_train_df[target][val_ind]
train_set = lgb.Dataset(x_train, y_train)
val_set = lgb.Dataset(x_val, y_val)
model = lgb.train(params, train_set, num_boost_round = 10000, early_stopping_rounds = early_stopping_rounds,
valid_sets=[train_set, val_set], verbose_eval = early_stopping_rounds)
oof_pred[val_ind] = model.predict(x_val)
models.append(model)
val_crt_fold = qwk3(y_val, oof_pred[val_ind].argmax(axis = 1))
print(f'Fold: {fold+1} quadratic weighted kappa score: {np.round(val_crt_fold,4)}')
res = qwk3(comp_train_df['accuracy_group'], oof_pred.argmax(axis = 1))
print(f'Quadratic weighted score: {np.round(res,4)}')
return models
# -
models = train_model(comp_train_df, comp_test_df)
# ## Inference
def add_missing_columns(comp_train_df: pd.DataFrame, comp_test_df: pd.DataFrame):
missing: set = set(comp_train_df.columns) - set(comp_test_df.columns)
for col in missing:
comp_test_df[col] = 0.
print(f'Added missing colums: {missing}')
add_missing_columns(comp_train_df, comp_test_df)
def run_predictions(models):
y_pred = np.zeros((len(comp_test_df), 4))
for model in models:
y_pred += model.predict(comp_test_df[features])
return y_pred / num_splits
y_pred = run_predictions(models)
np.unique(y_pred.argmax(-1), return_counts=True)
assert comp_test_df.shape[0] == y_pred.shape[0]
def prepare_submission(comp_test_df, y_pred):
comp_test_df = comp_test_df.reset_index()
comp_test_df = comp_test_df[['installation_id']]
comp_test_df['accuracy_group'] = y_pred.argmax(axis = 1)
sample_submission_df = pd.read_csv(path/'sample_submission.csv')
sample_submission_df.drop('accuracy_group', inplace = True, axis = 1)
sample_submission_df = sample_submission_df.merge(comp_test_df, on = 'installation_id')
sample_submission_df.to_csv('submission.csv', index = False)
prepare_submission(comp_test_df, y_pred)
# !head submission.csv
# !cat submission.csv | wc -l
| nbs_gil/data_science_bowl/data_science_bowl_training_10.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scinet import *
import scinet.ed_oscillator as edo
from sklearn.feature_selection import mutual_info_regression
# ### Helper functions for plots
# +
def osc_eqn(A_0, delta_0, b, kappa, t):
return np.real(A_0 * np.exp(-b / 2. * t) * np.exp(1 / 2. * np.sqrt(b**2 - 4 * kappa + 0.j) * t + 1.j * delta_0))
def gen_input(A_0, delta_0, b, kappa, tt_predicted):
tt_in = np.linspace(0, 5, 50)
in1 = np.array([osc_eqn(A_0, delta_0, b, kappa, tt_in) for _ in tt_predicted])
in2 = np.reshape(tt_predicted, (-1, 1))
out = in2 #dummy filler
return [in1, in2, out]
# -
blue_color='#000cff'
orange_color='#ff7700'
def pendulum_prediction(net, b, kappa):
tt_given = np.linspace(0, 10, 250)
tt_predicted = np.linspace(0, 10, 250)
a_given = osc_eqn(1, 0, b, kappa, tt_given)
a_precicted = net.run(gen_input(1, 0, b, kappa, tt_predicted), net.output).ravel()
fig = plt.figure(figsize=(3.4, 2.1))
ax = fig.add_subplot(111)
ax.plot(tt_given, a_given, color=orange_color, label='True time evolution')
ax.plot(tt_predicted, a_precicted, '--', color=blue_color, label='Predicted time evolution')
ax.set_xlabel(r'$t$ [$s$]')
ax.set_ylabel(r'$x$ [$m$]')
handles, labels = ax.get_legend_handles_labels()
lgd=ax.legend(handles, labels,loc='upper center', bbox_to_anchor=(0.6, 1.3), shadow=True, ncol=1)
fig.tight_layout()
return fig
def osc_representation_plot(net, b_range, kappa_range, step_num=100, eval_time=7.5):
bb = np.linspace(*b_range, num=step_num)
kk = np.linspace(*kappa_range, num=step_num)
B, K = np.meshgrid(bb, kk)
out = np.array([net.run(gen_input(1, 0, b, kappa, [eval_time]), net.mu)[0] for b, kappa in zip(np.ravel(B), np.ravel(K))])
fig = plt.figure(figsize=(net.latent_size*3.9, 2.1))
for i in range(net.latent_size):
zs = out[:, i]
ax = fig.add_subplot('1{}{}'.format(net.latent_size, i + 1), projection='3d')
Z = np.reshape(zs, B.shape)
surf = ax.plot_surface(B, K, Z, rstride=1, cstride=1, cmap=cm.inferno, linewidth=0)
ax.set_xlabel(r'$b$ [$kg/s$]')
ax.set_ylabel(r'$\kappa$ [$kg/s^2$]')
ax.set_zlabel('Latent activation {}'.format(i + 1))
if (i==2):
ax.set_zlim(-1,1) #Fix the scale for the third plot, where the activation is close to zero
ax.set_zticks([-1,-0.5,0,0.5,1])
fig.tight_layout()
return fig
# ## Load pre-trained model
#
# ### Parameters
# - `latent_size: 2`
# - `input_size: 50`
# - `input2_size: 1`
# - `output_size: 1`
# - `encoder_num_units: [500, 100]`
# - other parameters: default values
# ### Data
# - Only kappa and b are varied (in the default intervals), A_0 and delta_0 are fixed
# - `t_sample: np.linspace(0, 5, 50)` (fed into the network)
# - `t_meas_interval: (0, 10)` (time interval in which prediction times lie)
# - training data: 95000 samples
# - validation data: 5000 samples
#
# ### Training
# - `epoch_num: 1000`, `batch_size: 512`, `learning_rate: 1e-3`, `beta: 1e-3`
net_2_latent = nn.Network.from_saved('oscillator')
pendulum_prediction(net_2_latent, 0.5, 5.);
# %matplotlib tk
osc_representation_plot(net_2_latent, [0.5, 1], [5, 10]);
# ## Load pre-trained model
#
# ### Parameters
# - `latent_size: 3`
# - Rest as for `net_2_latent`
net_3_latent = nn.Network.from_saved('oscillator_3_latent')
pendulum_prediction(net_3_latent, 0.5, 5.);
# %matplotlib tk
osc_representation_plot(net_3_latent, [0.5, 1], [5, 10]);
# ## Calculate L2 norm of error
data, states, params = edo.oscillator_data(50000, t_meas_interval=(0, 10))
np.sqrt(net_3_latent.run(data, net_3_latent.recon_loss))
# ## Calculate mutual information between latent neurons
data, states, params = edo.oscillator_data(200000, t_meas_interval=(0, 10))
# Calculate the mutual information between two latent neurons
def mi(net, data, latent_neuron_1, latent_neuron_2):
mu = net_3_latent.run(data, net_3_latent.mu)
mi_estimate = mutual_info_regression(mu[:,latent_neuron_1].reshape(-1, 1), mu[:,latent_neuron_2], discrete_features = False)
return mi_estimate[0]
mi(net_3_latent, data, 0, 0)
mi(net_3_latent, data, 0, 1)
| analysis/oscillator.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import pytesseract
from sklearn.feature_extraction.text import CountVectorizer
# +
##############
# file paths #
##############
path_fiveg_images = "../dataset/tweets/hydrated/5G/images/"
path_nocon_images = "../dataset/tweets/hydrated/Non/images/"
path_other_images = "../dataset/tweets/hydrated/Other/images/"
path_test_images = "../dataset/tweets/hydrated/Test/images/"
# +
#######################
# cv helper functions #
#######################
# from https://nanonets.com/blog/ocr-with-tesseract/
# see also https://github.com/bloomberg/scatteract/blob/master/tesseract.py
def thresholding(image):
return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
def canny(image):
return cv2.Canny(image, 100, 200)
def deskew(image):
coords = np.column_stack(np.where(image > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
# +
#############################
# create english dictionary #
#############################
# from https://inventwithpython.com/hacking/chapter12.html
dictionary = []
with open('./output/dictionary.txt', 'r') as f:
dictionary.extend(f.read().split('\n'))
# add special terms
dictionary.extend(['5G','COVID','CORONAVIRUS','COVID19','COVID-19','19'])
# +
########################
# get text from images #
########################
img_text = dict()
# config options:
# oem 3 - use best available engine
# psm 12 - greedy grab sparse text
custom_config = r'--oem 3 --psm 12'
# tokenizer used in with nlp classifier
tokenize = CountVectorizer().build_tokenizer()
# output image text to csv
f = open('image_terms_test.csv','w')
# headers
f.write('filename,terms\n')
for filename in os.listdir(path_test_images):
path = os.path.join(path_test_images, filename)
if os.path.isfile(path):
# print(f'\n--- {path} ---\n')
text = ""
# we want the best processing possible per image, so
# we try multiple types of processing
orig_img = cv2.imread(path)
text = pytesseract.image_to_string(img, config=custom_config)
img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2GRAY)
text += pytesseract.image_to_string(img, config=custom_config)
try:
img = deskew(img)
text += pytesseract.image_to_string(img, config=custom_config)
except Exception:
pass
img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
text += pytesseract.image_to_string(img, config=custom_config)
text = text.upper()
tokens = tokenize(text)
# creating a set of words, will lose repeats
english_words = set([x.lower() for x in tokens if x in dictionary])
#plt.figure()
#plt.imshow(orig_img)
#plt.show()
#print(img_text[filename])
terms = ' '.join(english_words)
f.write(f'{filename},{terms}\n')
f.close()
| lexical/utils/OCR.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.7.0 64-bit (''DSPT7-Twitoff'': pipenv)'
# metadata:
# interpreter:
# hash: f81506ac7cc087dab0ed262a83b64ea07622c46958e46757d8ddba2fe4c6f543
# name: 'Python 3.7.0 64-bit (''DSPT7-Twitoff'': pipenv)'
# ---
# + [markdown] toc=true
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#DSPT6---Unit-3-Module-2---Consuming-Data-from-an-API" data-toc-modified-id="DSPT6---Unit-3-Module-2---Consuming-Data-from-an-API-1"><span class="toc-item-num">1 </span>DSPT6 - Unit 3 Module 2 - Consuming Data from an API</a></span></li><li><span><a href="#SpaCy-Embeddings" data-toc-modified-id="SpaCy-Embeddings-2"><span class="toc-item-num">2 </span>SpaCy Embeddings</a></span></li><li><span><a href="#Bringing-it-all-together" data-toc-modified-id="Bringing-it-all-together-3"><span class="toc-item-num">3 </span>Bringing it all together</a></span></li></ul></div>
# + [markdown] colab={"base_uri": "https://localhost:8080/", "height": 155} colab_type="code" id="SGPLRW-t1ECX" outputId="f774218a-8e3e-46b3-80ec-8eb1667ddd33"
# ### DSPT6 - Unit 3 Module 2 - Consuming Data from an API
#
# The purpose of this notebook is to demonstrate:
# - Connect to the Twitter API (and twitter_scraper) to query for tweets and user information by various parameters
# - Convert tweet text using SpaCy into numerical embeddings that can be use in a predictive model
# + colab={} colab_type="code" id="vS_A9hjG1HGD"
import tweepy
# + colab={} colab_type="code" id="ntkRF7mp8zqp"
TWITTER_CONSUMER_API_KEY = '<KEY>'
TWITTER_CONSUMER_API_SECRET = 'jObB3HIRoVBMFtToJvaL062FmA3sg8anTf4oS03xhviMYOoEwS'
TWITTER_ACCESS_TOKEN = '<KEY>'
TWITTER_ACCESS_TOKEN_SECRET = '<KEY>'
# + colab={} colab_type="code" id="6F65yM5G1gP1"
TWITTER_AUTH = tweepy.OAuthHandler(TWITTER_CONSUMER_API_KEY, TWITTER_CONSUMER_API_SECRET)
TWITTER_AUTH.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)
TWITTER = tweepy.API(TWITTER_AUTH)
# -
dir(TWITTER)
twitter_user = TWITTER.get_user('elonmusk')
twitter_user
twitter_user.id
elon_tweets = twitter_user.timeline()
elon_tweets
elon_tweets[0].text
len(elon_tweets)
elon_tweets = twitter_user.timeline(count=200,
exclude_replies=True,
include_rts=False,
# max_id='1303802636827799555',
tweet_mode='extended')
len(elon_tweets)
elon_tweets[1].full_text
# ### SpaCy Embeddings
import spacy
nlp = spacy.load('en_core_web_md', disable=['tagger', 'parser'])
# + tags=[]
tokens = nlp("dog cat banana daslkfjsalkjf")
for token in tokens:
print(token.text, token.has_vector, token.is_oov)
# -
dog = nlp('dog')
dog.vector
tweet_embedding = nlp(elon_tweets[1].full_text)
tweet_embedding.vector
# ### Bringing it all together
def vectorize_tweet(nlp, tweet_text):
return nlp(tweet_text).vector
def add_or_update_user(username, nlp):
try:
twitter_user = TWITTER.get_user(username)
tweets = twitter_user.timeline(count=200,
exclude_replies=True,
include_rts=False,
tweet_mode='extended')
embeddings = vectorize_tweet(nlp, tweets[0].full_text)
except Exception as e:
print('Error processing {}: {}'.format(username, e))
return tweets, embeddings
# +
import spacy
import en_core_web_sm
nlp = en_core_web_sm.load()
nlp.to_disk('../spacy_sm_model/')
# -
nlp2 = spacy.load('../spacy_sm_model')
nlp2('Tjos os a sample').vector
| notebooks/LS332_DSPT7_APIs_Demo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# QDA
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[-1, -1], [-2,1], [-3,2],[1,1], [2,1], [3,2]])
y = np.array([1,1,1,2,2,2])
plt. scatter(X.T[0], X.T[1], c = y, s = 100)
plt.show()
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
model = QuadraticDiscriminantAnalysis().fit(x,y)
# +
x = [[0, 0]]
p = model.predict_proba(x)[0]
plt.subplot(211)
plt.scatter(X.T[0], X.T[1], c=y, s=100)
plt.scatter(x[0][0], x[0][1], c='r', s=100)
plt.title("data")
plt.subplot(212)
plt.bar(model.classes_, p, align="center")
plt.title("conditional probability")
plt.axis([0, 3, 0, 1])
plt.gca().xaxis.grid(False)
plt.xticks(model.classes_)
plt.tight_layout()
plt.show()
# -
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
# +
news = fetch_20newsgroups(subset="all")
model = Pipeline([
('vect', TfidfVectorizer(stop_words="english")),
('nb', MultinomialNB()),
])
model.fit(news.data, news.target)
x = news.data[:1]
y = model.predict(x)[0]
# -
plt.subplot(211)
plt.bar(model.classes_, model.predict_proba(x)[0], align="center")
plt.xlim(-1, 20)
plt.gca().xaxis.grid(False)
plt.xticks(model.classes_)
plt.subplot(212)
plt.bar(model.classes_, model.predict_log_proba(x)[0], align="center")
plt.xlim(-1, 20)
plt.gca().xaxis.grid(False)
plt.xticks(model.classes_)
plt.show()
# multi-class
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
iris = load_iris()
model = LogisticRegression().fit(iris.data, iris.target)
from sklearn.metrics import roc_curve
fpr0, tpr0, thresholds0 = roc_curve(iris.target, model.decision_function(iris.data)[:, 0], pos_label=0)
fpr1, tpr1, thresholds1 = roc_curve(iris.target, model.decision_function(iris.data)[:, 1], pos_label=1)
fpr2, tpr2, thresholds2 = roc_curve(iris.target, model.decision_function(iris.data)[:, 2], pos_label=2)
fpr0, tpr0, thresholds0
| Practice/04-24.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# 
# <center><em>Copyright! This material is protected, please do not copy or distribute. by:<NAME></em></center>
# ***
# <h1 align="center">Udemy course : Python Bootcamp for Data Science 2021 Numpy Pandas & Seaborn</h1>
#
# ***
# ## 12.2 Reshaping by Melting (Wide to Long)
# First we import pandas library:
# + hide_input=false
import pandas as pd
# -
# As an example, we will read a dataframe from a csv file using the function **pd.read_csv()**:
# + hide_input=false
data1 = pd.read_csv('data/ex7.csv')
data1
# -
# We can reshape this dataframe by transforming the values of all columns into a single column using the function **melt()**:
# ***Notice:** the column that is assigned in the argument **id_vard** will not be transformed.
# + hide_input=false
data2 = data1.melt(id_vars= 'year')
data2
# -
# We can rename the newly created columns ourselves by using the arguments **var_name** and **value_name**, instead of the default names (variable and value):
# + hide_input=false
data2 = data1.melt(id_vars= 'year', var_name= 'sales', value_name = 'amount')
data2
# -
# Another example, lets read this dataframe:
# + hide_input=false
data3 = pd.read_csv('data/ex8.csv', index_col = 'date')
data3
# -
# We can move the prices of google and apple into one column using the function **melt()**:
#
# ***Notice**: the index is automatically removed after melting.
# + hide_input=false
data3.melt(var_name='company', value_name='closing price')
# -
# To keep the original index after melting: we need to add the argument **ignore_index = False**:
# + hide_input=false
data4 = data3.melt( var_name='company', value_name='closing price', ignore_index =False)
data4
# -
# It is better to sort the index after melting, and we do that using the function **sort_index()**:
# + hide_input=false
data4.sort_index()
# -
# ***
#
# <h1 align="center">Thank You</h1>
#
# ***
| 12.2 Reshaping by Melting (Wide to Long).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pennylane as qml
from pennylane import numpy as np
dev = qml.device(name = 'default.qubit', wires = 5, shots = 1000)
# +
@qml.qnode(dev)
# RYRZ linear entanglement
def circuit(param, wires):
for w in range(wires):
qml.RY(param [0, w], wires = w)
qml.RZ(param[1, w], wires = w)
for w in range(wires-1):
qml.CNOT(wires = [w, w+1])
for w in range(wires):
qml.RY(param [0, w+5], wires = w)
qml.RZ(param[1, w+5], wires = w)
for w in range(wires-1):
qml.CNOT(wires = [w, w+1])
return qml.expval(qml.PauliZ(wires = 0))
# -
def psr(qnode, param, wires, i, j):
shift_param_f = param.copy()
shift_param_b = param.copy()
shift = np.pi/2
# Forward
shift_param_f[i, j] = shift_param_f[i, j] + shift
forward = qnode(shift_param_f, wires)
# Backward
shift_param_b[i, j] = shift_param_b[i, j] - shift
backward = qnode(shift_param_b, wires)
gradient = (forward - backward) / (2*np.sin(shift))
return gradient
# +
wires = 5
np.random.seed(100)
param = np.random.uniform(low = -np.pi/2, high = np.pi, size = (2, 10))
gradient = np.zeros_like(param)
# print(gradient)
# print(param)
# print(param[0])
# [[np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi], [np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi, np.pi]]
print(circuit(param, wires))
print(circuit.draw())
for i in range(2):
for j in range(len(param)):
gradient[i, j] = psr(circuit, param, wires, i, j)
print(gradient)
# print(circuit(gradient, wires))
# print(circuit.draw())
# -
| pennylane-xanadu/Parameter_Shift_Rule.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.8.5 64-bit ('endsars')
# language: python
# name: python38564bitendsarsd73fdd1e91f242ed966f5421b7ebc3bf
# ---
# import fastText
import sys
import os
import nltk
# nltk.download('punkt')
import csv
import datetime
from bs4 import BeautifulSoup
import re
import itertools
import emoji
import fasttext
# + jupyter={"source_hidden": true}
#####################################################################################
#
# DATA CLEANING
#
#####################################################################################
def load_dict_smileys():
return {
":‑)":"smiley",
":-]":"smiley",
":-3":"smiley",
":->":"smiley",
"8-)":"smiley",
":-}":"smiley",
":)":"smiley",
":]":"smiley",
":3":"smiley",
":>":"smiley",
"8)":"smiley",
":}":"smiley",
":o)":"smiley",
":c)":"smiley",
":^)":"smiley",
"=]":"smiley",
"=)":"smiley",
":-))":"smiley",
":‑D":"smiley",
"8‑D":"smiley",
"x‑D":"smiley",
"X‑D":"smiley",
":D":"smiley",
"8D":"smiley",
"xD":"smiley",
"XD":"smiley",
":‑(":"sad",
":‑c":"sad",
":‑<":"sad",
":‑[":"sad",
":(":"sad",
":c":"sad",
":<":"sad",
":[":"sad",
":-||":"sad",
">:[":"sad",
":{":"sad",
":@":"sad",
">:(":"sad",
":'‑(":"sad",
":'(":"sad",
":‑P":"playful",
"X‑P":"playful",
"x‑p":"playful",
":‑p":"playful",
":‑Þ":"playful",
":‑þ":"playful",
":‑b":"playful",
":P":"playful",
"XP":"playful",
"xp":"playful",
":p":"playful",
":Þ":"playful",
":þ":"playful",
":b":"playful",
"<3":"love"
}
def load_dict_contractions():
return {
"ain't":"is not",
"amn't":"am not",
"aren't":"are not",
"can't":"cannot",
"'cause":"because",
"couldn't":"could not",
"couldn't've":"could not have",
"could've":"could have",
"daren't":"dare not",
"daresn't":"dare not",
"dasn't":"dare not",
"didn't":"did not",
"doesn't":"does not",
"don't":"do not",
"e'er":"ever",
"em":"them",
"everyone's":"everyone is",
"finna":"fixing to",
"gimme":"give me",
"gonna":"going to",
"gon't":"go not",
"gotta":"got to",
"hadn't":"had not",
"hasn't":"has not",
"haven't":"have not",
"he'd":"he would",
"he'll":"he will",
"he's":"he is",
"he've":"he have",
"how'd":"how would",
"how'll":"how will",
"how're":"how are",
"how's":"how is",
"I'd":"I would",
"I'll":"I will",
"I'm":"I am",
"I'm'a":"I am about to",
"I'm'o":"I am going to",
"isn't":"is not",
"it'd":"it would",
"it'll":"it will",
"it's":"it is",
"I've":"I have",
"kinda":"kind of",
"let's":"let us",
"mayn't":"may not",
"may've":"may have",
"mightn't":"might not",
"might've":"might have",
"mustn't":"must not",
"mustn't've":"must not have",
"must've":"must have",
"needn't":"need not",
"ne'er":"never",
"o'":"of",
"o'er":"over",
"ol'":"old",
"oughtn't":"ought not",
"shalln't":"shall not",
"shan't":"shall not",
"she'd":"she would",
"she'll":"she will",
"she's":"she is",
"shouldn't":"should not",
"shouldn't've":"should not have",
"should've":"should have",
"somebody's":"somebody is",
"someone's":"someone is",
"something's":"something is",
"that'd":"that would",
"that'll":"that will",
"that're":"that are",
"that's":"that is",
"there'd":"there would",
"there'll":"there will",
"there're":"there are",
"there's":"there is",
"these're":"these are",
"they'd":"they would",
"they'll":"they will",
"they're":"they are",
"they've":"they have",
"this's":"this is",
"those're":"those are",
"'tis":"it is",
"'twas":"it was",
"wanna":"want to",
"wasn't":"was not",
"we'd":"we would",
"we'd've":"we would have",
"we'll":"we will",
"we're":"we are",
"weren't":"were not",
"we've":"we have",
"what'd":"what did",
"what'll":"what will",
"what're":"what are",
"what's":"what is",
"what've":"what have",
"when's":"when is",
"where'd":"where did",
"where're":"where are",
"where's":"where is",
"where've":"where have",
"which's":"which is",
"who'd":"who would",
"who'd've":"who would have",
"who'll":"who will",
"who're":"who are",
"who's":"who is",
"who've":"who have",
"why'd":"why did",
"why're":"why are",
"why's":"why is",
"won't":"will not",
"wouldn't":"would not",
"would've":"would have",
"y'all":"you all",
"you'd":"you would",
"you'll":"you will",
"you're":"you are",
"you've":"you have",
"Whatcha":"What are you",
"luv":"love",
"sux":"sucks"
}
# +
def strip_accents(text):
if 'ø' in text or 'Ø' in text:
#Do nothing when finding ø
return text
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text)
def tweet_cleaning_for_sentiment_analysis(tweet):
#Escaping HTML characters
tweet = BeautifulSoup(tweet).get_text()
#Special case not handled previously.
tweet = tweet.replace('\x92',"'")
#Removal of hastags/account
tweet = ' '.join(re.sub("(@[A-Za-z0-9]+)|(#[A-Za-z0-9]+)", " ", tweet).split())
#Removal of address
tweet = ' '.join(re.sub("(\w+:\/\/\S+)", " ", tweet).split())
#Removal of Punctuation
tweet = ' '.join(re.sub("[\.\,\!\?\:\;\-\=]", " ", tweet).split())
#Lower case
tweet = tweet.lower()
#CONTRACTIONS source: https://en.wikipedia.org/wiki/Contraction_%28grammar%29
CONTRACTIONS = load_dict_contractions()
tweet = tweet.replace("’","'")
words = tweet.split()
reformed = [CONTRACTIONS[word] if word in CONTRACTIONS else word for word in words]
tweet = " ".join(reformed)
# Standardizing words
tweet = ''.join(''.join(s)[:2] for _, s in itertools.groupby(tweet))
#Deal with smileys
#source: https://en.wikipedia.org/wiki/List_of_emoticons
SMILEY = load_dict_smileys()
words = tweet.split()
reformed = [SMILEY[word] if word in SMILEY else word for word in words]
tweet = " ".join(reformed)
#Deal with emojis
tweet = emoji.demojize(tweet)
#Strip accents
tweet= strip_accents(tweet)
tweet = tweet.replace(":"," ")
tweet = ' '.join(tweet.split())
# DO NOT REMOVE STOP WORDS FOR SENTIMENT ANALYSIS - OR AT LEAST NOT NEGATIVE ONES
return tweet
# +
def transform_instance(row):
cur_row = []
#Prefix the index-ed label with __label__
label = "__label__" + row[4]
cur_row.append(label)
cur_row.extend(nltk.word_tokenize(tweet_cleaning_for_sentiment_analysis(row[2].lower())))
return cur_row
def preprocess(input_file, output_file, keep=1):
i=0
with open(output_file, 'w') as csvoutfile:
csv_writer = csv.writer(csvoutfile, delimiter=' ', lineterminator='\n')
with open(input_file, 'r', newline='') as csvinfile: #,encoding='latin1'
csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='"')
for row in csv_reader:
if row[4]!="MIXED" and row[4].upper() in ['POSITIVE','NEGATIVE','NEUTRAL'] and row[2]!='':
row_output = transform_instance(row)
csv_writer.writerow(row_output )
i=i+1
if i%10000 ==0:
print(i)
# + jupyter={"outputs_hidden": true}
preprocess('betsentiment-EN-tweets-sentiment-teams.csv', 'tweets.train')
# + jupyter={"outputs_hidden": true}
def upsampling(input_file, output_file, ratio_upsampling=1):
# Create a file with equal number of tweets for each label
# input_file: path to file
# output_file: path to the output file
# ratio_upsampling: ratio of each minority classes vs majority one. 1 mean there will be as much of each class than there is for the majority class
i=0
counts = {}
dict_data_by_label = {}
# GET LABEL LIST AND GET DATA PER LABEL
with open(input_file, 'r', newline='') as csvinfile:
csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='"')
for row in csv_reader:
counts[row[0].split()[0]] = counts.get(row[0].split()[0], 0) + 1
if not row[0].split()[0] in dict_data_by_label:
dict_data_by_label[row[0].split()[0]]=[row[0]]
else:
dict_data_by_label[row[0].split()[0]].append(row[0])
i=i+1
if i%10000 ==0:
print("read" + str(i))
# FIND MAJORITY CLASS
majority_class=""
count_majority_class=0
for item in dict_data_by_label:
if len(dict_data_by_label[item])>count_majority_class:
majority_class= item
count_majority_class=len(dict_data_by_label[item])
# UPSAMPLE MINORITY CLASS
data_upsampled=[]
for item in dict_data_by_label:
data_upsampled.extend(dict_data_by_label[item])
if item != majority_class:
items_added=0
items_to_add = count_majority_class - len(dict_data_by_label[item])
while items_added<items_to_add:
data_upsampled.extend(dict_data_by_label[item][:max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))])
items_added = items_added + max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))
# WRITE ALL
i=0
with open(output_file, 'w') as txtoutfile:
for row in data_upsampled:
txtoutfile.write(row+ '\n' )
i=i+1
if i%10000 ==0:
print("writer" + str(i))
upsampling( 'tweets.train','uptweets.train')
# +
training_data_path ='uptweets.train'
validation_data_path ='tweets.validation'
model_path ='\\model\\'
model_name="model-en"
def train():
print('Training start')
try:
hyper_params = {"lr": 0.01,
"epoch": 20,
"wordNgrams": 2,
"dim": 20}
print(str(datetime.datetime.now()) + ' START=>' + str(hyper_params) )
# Train the model.
model = fasttext.train_supervised(input=training_data_path, **hyper_params)
print("Model trained with the hyperparameter \n {}".format(hyper_params))
# CHECK PERFORMANCE
print(str(datetime.datetime.now()) + 'Training complete.' + str(hyper_params) )
result = model.test(training_data_path)
# validation = model.test(validation_data_path)
# DISPLAY ACCURACY OF TRAINED MODEL
# text_line = str(hyper_params) + ",accuracy:" + str(result[1]) + ",validation:" + str(validation[1]) + '\n'
# print(text_line)
#quantize a model to reduce the memory usage
model.quantize(input=training_data_path, qnorm=True, retrain=True, cutoff=100000)
print("Model is quantized!!")
model.save_model('model.ftz')
##########################################################################
#
# TESTING PART
#
##########################################################################
model.predict(['why not'],k=3)
model.predict(['this player is so bad'],k=1)
except Exception as e:
print('Exception during training: ' + str(e) )
# Train your model.
train()
# -
| training_for_transfer_learning.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Clustering using k-means and GMM
#
# Clustering is the task of grouping a set of objects without known their labels. It is one of the most fundamental methods for unsupervised learning. We will start with the simple k-means method and then progress to the Gaussian Mixture Method (GMM).
#
# This notebook is based on a blog post by [<NAME>](https://jakevdp.github.io/PythonDataScienceHandbook/05.12-gaussian-mixtures.html) on clustering with [scikit-learn](https://scikit-learn.org/stable/index.html), an excerpt from his book [*Python Data Science Handbook*](https://www.oreilly.com/library/view/python-data-science/9781491912126/).
# +
# sklearn
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture as GMM
from sklearn.datasets import make_moons
from sklearn import metrics
import sklearn.datasets
# helpers
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib as mpl
plt.style.use('ggplot')
# -
# ---
# # K-means
#
# K-means is probably the most popular clustering method. It clusters the data by minimising the within-cluster sum of squares (WCSS), i.e., given data $\mathbf{x}$ and the number of clusters $k$, to find a set of clusters $\mathbf{S}=\{S_1, S_2, \cdots, S_k\}$ by
#
# $$\operatorname*{arg\,min}_\mathbf{S} \sum_{i=1}^k \sum_{\mathbf{x}\in S_i}\lVert\mathbf{x}-\mathbf{\mu}_i\rVert^2,$$
#
# where $\mathbf{\mu}_i$ is the mean of points in cluster $S_i$.
#
#
# ## Data generation
#
# First, similar to [01_classification_decision_tree.ipynb](01_classification_decision_tree.ipynb), we use a dataset generated by the `make_blobs` method from `sklearn`. It has 400 samples with 2 features, 4 centres and a standard deviation of 0.6. Note that we flip the axes (2nd feature as $x$-axis) in the plot for better visualisation.
# +
# generate Gaussian blobs
X, y_true = make_blobs(n_samples=400, n_features=2, centers=4,
cluster_std=0.6, random_state=0)
# plot data points with true labels
plt.figure(dpi=100)
scat = plt.scatter(X[:, 1], X[:, 0], c=y_true, s=20, alpha=0.7, edgecolors='k')
plt.xlabel('Feature 1')
plt.ylabel('Feature 0')
plt.gca().add_artist(plt.legend(*scat.legend_elements(),
title='True labels', bbox_to_anchor=(1.25, 1.)))
plt.gca().set_aspect(1)
plt.show()
# -
# ## Clustering using k-means
#
# With `sklearn`, clustering using k-means is only a few lines:
# +
# create k-means and fit
kmeans = KMeans(4, random_state=0).fit(X)
# make predictions
y_kmeans = kmeans.predict(X)
# -
# Now we can plot the resultant clusters. For better visualisation, we add the "range circles" to the plot, centred at the cluster means (`kmeans.cluster_centers_`) and having radii from the means to the farthest points.
# plot data points with predicted labels
plt.figure(dpi=100)
scat = plt.scatter(X[:, 1], X[:, 0], c=y_kmeans, s=20,
alpha=0.7, edgecolors='k', cmap='viridis')
# add the range circles
for icenter, center in enumerate(kmeans.cluster_centers_):
radius = np.max(np.linalg.norm(X[y_kmeans == icenter] - center, axis=1))
circle = plt.Circle((center[1], center[0]), radius, alpha=.3,
color=cm.get_cmap('viridis', kmeans.n_clusters)(icenter))
plt.gca().add_artist(circle)
plt.xlabel('Feature 1')
plt.ylabel('Feature 0')
plt.gca().add_artist(plt.legend(*scat.legend_elements(),
title='Clusters', bbox_to_anchor=(1.2, 1.)))
plt.gca().set_aspect(1)
plt.show()
# With `cluster_std=0.6`, k-means yields a prediction exactly the same as the ground truth; the only difference is the order of labels (which is reasonable because k-means takes in no information about the true labels). We can compute the following score for the clustering, all independent of the label orders:
#
# * Homogeneity score: a clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class;
# * Completeness score: a clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster;
# * V-measure score: the harmonic mean between homogeneity and completeness.
#
# For, `cluster_std=0.6`, the scores should all be 1. Try a larger `cluster_std`.
# print scores
print('Homogeneity score = %.3f' % metrics.homogeneity_score(y_true, y_kmeans))
print('Completeness score = %.3f' % metrics.completeness_score(y_true, y_kmeans))
print('V-measure score = %.3f' % metrics.v_measure_score(y_true, y_kmeans))
# ---
# # Gaussian Mixture Method
#
# In k-means, the objective function (the WCSS) is isotropic; for example, it defines a circle in 2D (2 features) and a sphere in 3D (3 features). If the data distribution is anisotropic along the dimensions (e.g., all the data points lie on the $x$-axis), k-means will suffer from over-expanded cluster ranges along the minor dimensions.
#
# The Gaussian Mixture Method (GMM) can overcome this difficulty. In GMM, each cluster is defined by a normal distribution rather than a single point (i.e., the centres in k-means), as shown in the following figure ([source](https://towardsdatascience.com/gaussian-mixture-models-explained-6986aaf5a95)). In a multivariate problem, each cluster is characterised by a series of Gaussian bells along each of the dimensions, forming an ellipsoidal range that can handle anisotropic data.
#
# <img src="https://i.ibb.co/HVD4MjH/gmm.png" width=60% height=60% />
#
# In GMM, clustering is conducted by maximising the likelihood of each Gaussian fitting the data points belonging to each cluster, so the solution is a maximum likelihood (ML) estimate. Further, variational inference can be introduced to GMM, giving rise to the Bayesian GMM, of which the solution is a maximum a posteriori probability (MAP) estimate.
#
#
#
#
#
# ## Data transformation
#
# To create an anisotropic data distribution, we stretch the previous dataset by applying a random transformation matrix to the coordinates:
# +
# stretch the data
# for reproducibility, we fix the random seed here
rng = np.random.RandomState(13)
X_stretch = np.dot(X, rng.randn(2, 2))
# plot data points with true labels
plt.figure(dpi=100)
scat = plt.scatter(X_stretch[:, 1], X_stretch[:, 0], c=y_true, s=20,
alpha=0.7, edgecolors='k')
plt.xlabel('Feature 1')
plt.ylabel('Feature 0')
plt.gca().add_artist(plt.legend(*scat.legend_elements(),
title='True labels', bbox_to_anchor=(1.35, 1.)))
plt.gca().set_aspect(1)
plt.show()
# -
# Let us try k-means with this stretched dataset -- the result clearly reflects the difficulty described above:
# +
# create k-means and fit
kmeans_stretch = KMeans(4, random_state=0).fit(X_stretch)
# make predictions
y_kmeans_stretch = kmeans_stretch.predict(X_stretch)
# plot data points with predicted labels
plt.figure(dpi=100)
scat = plt.scatter(X_stretch[:, 1], X_stretch[:, 0], c=y_kmeans_stretch, s=20,
alpha=0.7, edgecolors='k', cmap='viridis')
# add the range circles
for icenter, center in enumerate(kmeans_stretch.cluster_centers_):
radius = np.max(np.linalg.norm(X_stretch[y_kmeans_stretch == icenter] - center, axis=1))
circle = plt.Circle((center[1], center[0]), radius, alpha=.3,
color=cm.get_cmap('viridis', kmeans_stretch.n_clusters)(icenter))
plt.gca().add_artist(circle)
plt.xlabel('Feature 1')
plt.ylabel('Feature 0')
plt.gca().add_artist(plt.legend(*scat.legend_elements(),
title='Clusters', bbox_to_anchor=(1.3, 1.)))
plt.gca().set_aspect(1)
plt.show()
# print scores
print('Homogeneity score = %.3f' % metrics.homogeneity_score(y_true, y_kmeans_stretch))
print('Completeness score = %.3f' % metrics.completeness_score(y_true, y_kmeans_stretch))
print('V-measure score = %.3f' % metrics.v_measure_score(y_true, y_kmeans_stretch))
# -
# ## Clustering using GMM
#
# With `sklearn`, using GMM involves nothing more complicated than using k-means except for a few more hyperparameters (see [the documentation](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture)). The number of clusters is given by the argument `n_components`. To guarantee that we always reach the global optimal solution, here we specify `n_init=20`, the number of initial random states from which the best result will be chosen.
# +
# create GMM and fit
gmm = GMM(n_components=4, n_init=20).fit(X_stretch)
# make predictions
y_gmm = gmm.predict(X_stretch)
# -
# Next, we plot the resultant clusters with the "range ellipses" and print the scores:
# +
# function to add ellipses of a GMM to a plot
def add_ellipses(gmm, ax, cmap):
for n in range(gmm.n_components):
# get covariances
if gmm.covariance_type == 'full':
covariances = gmm.covariances_[n][:2, :2]
elif gmm.covariance_type == 'tied':
covariances = gmm.covariances_[:2, :2]
elif gmm.covariance_type == 'diag':
covariances = np.diag(gmm.covariances_[n][:2])
elif gmm.covariance_type == 'spherical':
covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
# compute ellipse geometry
v, w = np.linalg.eigh(covariances)
u = w[0] / np.linalg.norm(w[0])
angle = np.degrees(np.arctan2(u[0], u[1]))
v = 4. * np.sqrt(2.) * np.sqrt(v)
ell = mpl.patches.Ellipse((gmm.means_[n, 1], gmm.means_[n, 0]), v[1], v[0],
90 + angle, color=cmap(n), alpha=.3)
ax.add_artist(ell)
# plot data points with predicted labels
plt.figure(dpi=100)
scat = plt.scatter(X_stretch[:, 1], X_stretch[:, 0], c=y_gmm,
s=20, alpha=0.7, edgecolors='k', cmap='viridis')
add_ellipses(gmm, plt.gca(), cm.get_cmap('viridis', gmm.n_components))
plt.xlabel('Feature 1')
plt.ylabel('Feature 0')
plt.gca().add_artist(plt.legend(*scat.legend_elements(),
title='Clusters', bbox_to_anchor=(1.3, 1.)))
plt.gca().set_aspect(1)
plt.show()
# print scores
print('Homogeneity score = %.3f' % metrics.homogeneity_score(y_true, y_gmm))
print('Completeness score = %.3f' % metrics.completeness_score(y_true, y_gmm))
print('V-measure score = %.3f' % metrics.v_measure_score(y_true, y_gmm))
# -
# In addition, because GMM contains a probabilistic model under the hood, it is also possible to find the probabilistic cluster assignments, which is implemented by the `predict_proba` method in `sklearn`. It returns a matrix of size `[n_samples, n_components]`, which measures the probability that a point belongs to a cluster.
# +
# predict probability
probs = gmm.predict_proba(X)
# show the last 5 samples
print(probs[:5].round(3))
# -
# ## Tune the number of clusters
# It seems a little frustrating that we need to choose the number of clusters by hand. Is there any automatic way of selecting this? The answer is yes. Because the GMM yields a distribution of probabilities, it can be used to generate new samples within that distribution. We can then estimate the likelihood that the data we have observed would be generated by a particular GMM. Therefore, we can generate a set of GMMs with different numbers of clusters and find which one has the maximum likelihood of generating (reproducing) our observed data.
#
# First, we make a set of GMMs with `n_components` ranging from 1 to 10:
# +
# a set of numbers of clusters
n_components = np.arange(1, 11)
# create the GMM models
models = [GMM(n, n_init=20).fit(X_stretch) for n in n_components]
# -
# The GMM in `sklearn` has a couple of built-in methods to estimate how well the model matches the data, such as the Akaike information criterion (AIC) and the Bayesian information criterion (BIC):
# +
# Akaike information criterion
aics = [m.aic(X_stretch) for m in models]
# Bayesian information criterion
bics = [m.bic(X_stretch) for m in models]
# -
# Plotting AIC and BIC against `n_components`, we find that 4 is the optimal number of clusters:
plt.figure(dpi=100)
plt.plot(n_components, aics, label='AIC')
plt.plot(n_components, bics, label='BIC')
plt.legend(loc='best')
plt.xlabel('n_components')
plt.ylabel('AIC or BIC')
plt.show()
# ---
# ## Exercises:
#
# 1. The famous `two-moons` dataset can be generated by `sklearn`. Work out the best number of GMM clusters for replicating this data.
# load the two-moons dataset
Xmoon, ymoon = make_moons(200, noise=.05, random_state=0)
plt.scatter(Xmoon[:, 0], Xmoon[:, 1])
# 2. Use k-means or GMM to cluster one or some of the standard "toy" datasets we have used to practice classification, such as `iris` (`n_features=4`) and `wine` (`n_features=13`). You may notice that the complexity of the problem rapidly grows with the number of features. In [06_autoencoder_basics.ipynb](06_autoencoder_basics.ipynb), we will train an autoencoder to reduce the input dimensionality for clustering.
# load iris dataset
iris = sklearn.datasets.load_iris()
print(iris['DESCR'])
| course_2.0_with_solutions/02_clustering_kmeans_GMM.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Testing Tesseract OCR performance on custom fonts
#
# The interactive notebook and necessary files are available on GitHub:
#
# `https://github.com/byewokko/tesseract-font-test`
# +
import matplotlib.pyplot as plt
import matplotlib.axes
import numpy as np
import os
import pandas as pd
# %matplotlib inline
from utils import *
# -
# ## Introduction
#
# Humans are able to read text written in various typefaces or scripts and usually they don't even realize the differences between them. For a computer vision however, those small differences are crucial and a single decorative curl can cause a letter to be completely unrecognizable.
#
# In this task I perform two experiments in order to evaluate Tesseract software on text set in different typefaces.
#
# To keep this notebook less bulky, I have removed all my custom functions to `utils.py`.
# ## Sample experiment
#
# Because of licensing issues I cannot freely redistribute many of the font files I use in the main experiments below. Here I provide a sample experiment to demonstrate my pipeline (without the data visualization) using the _Gentium Plus_ fonts which are licensed under SIL Open Font License and are included in this repository. Hence this experiment is fully reproducible.
preview_fonts(get_font_names("."))
# For this experiment, we use both _Gentium_ fonts found in cwd to render file `en-eisenhower.txt` in two sizes (20 and 30 points) and save them in `test` folder. The we pass them to the Tesseract engine and evaluate its output. The steps are shown in the following snippet. Both main experiments follow the same procedure.
# +
outdir = "test" # directory for storing generated files
fontdir = "." # directory with font files
ptsizes = [20,30] # list of font sizes to generate
textfile = "en-eisenhower.txt" # file with sample text
language = "eng" # Tesseract language model
# Read example text file
with open(textfile, "r") as fin:
rawtext = fin.read()[:500]
# Break long lines
text = breaklines(rawtext)
# Read font data of files in fontdir
fontdata = get_font_names(fontdir)
# Setup the experiment, store metadata in a dataframe
setup = make_experiment_setup(fontdata, ptsizes, outdir)
# Render text as images
batch_render_text(text, setup, fontdata)
# OCR the images
batch_ocr_images(setup, language)
# Evaluate OCR output
results = batch_evaluate(setup, fontdata, text)
# -
results
# # Experiment 1
# ## OCRing different sizes, weights and widths of one typeface
# We explore the OCR performance on different fonts of the same typeface superfamily _Helvetica Neue_ by Linotype foundry. It classifies as a transitional modern sans-serif, similarly to Helvetica or Arial. The family uses convenient number coding for different fonts: weights from _Ultra Light_ to _Black_ are coded with numbers from 2 to 9. Similarly the widths _Extended_, _Regular_ and _Condensed_ are coded with 3, 5 and 9 respectively. So for example 47 represents _Light Condensed_. Here we use 6 different weights and 3 widths. We render each of them in 5 sizes: 10, 16, 22, 28 and 34 points.
#
# We use an excerpt from [Czech news article](https://denikn.cz/31964) as our source text. Accordingly, we use the `ces` language model for OCR in Tesseract.
outdir = "helvetica" # directory for storing generated files
fontdir = "fonts/helvetica" # directory with font files
ptsizes = [10,16,22,28,34] # list of font sizes to generate
textfile = "cz-news.txt" # file with sample text
language = "ces" # Tesseract language model
# +
# Prepare data and preview fonts
# This step requires having the font files in fontdir!
fontdata = get_font_names(fontdir)
setup = make_experiment_setup(fontdata, ptsizes, outdir)
fontdata.to_csv(os.path.join(outdir, "fontdata.csv"))
setup.to_csv(os.path.join(outdir, "setup.csv"))
preview_fonts(fontdata)
# +
# Batch process all files, write results
# This step requires having the font files in fontdir!
with open(textfile, 'r') as file:
orig_text = file.read()
orig_text = breaklines(orig_text, 60)
batch_render_text(orig_text, setup, fontdata)
batch_ocr_images(setup, "ces")
results = batch_evaluate(setup, fontdata, orig_text)
results.to_csv(os.path.join(outdir, "results.csv"))
# -
# ## Visualising the results
#
# First we extract the width and weight numbers from font names and save them as new variables in the dataframe.
outdir = "helvetica"
fontdata = pd.read_csv(os.path.join(outdir, "fontdata.csv"))
results = pd.read_csv(os.path.join(outdir, "results.csv"))
results["Weight"] = pd.to_numeric(results["Font"].str[22])
results["Width"] = pd.to_numeric(results["Font"].str[23])
results = results.set_index(["Weight", "Width", "Point size"])[["WER","CER","Font"]]
# Now we plot average error rates per point size, weight and width.
# +
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(16,5), sharey=True)
fig.suptitle("Average error rates")
results.groupby("Point size").mean().plot.bar(y=["WER","CER"], ax=axes[0])
results.groupby("Weight").mean().plot.bar(y=["WER","CER"], ax=axes[1])
results.groupby("Width").mean().plot.bar(y=["WER","CER"], ax=axes[2])
for x in axes:
x.grid(True, axis="y")
x.set_axisbelow(True)
plt.show()
# -
# In all three cases, WER and CER follow the same curve. It shows that Tesseract is very sensitive to point size and weight, but much less to font width. Not surprisingly it performs better at bigger sizes. Similarly it works better with fonts of thicker weights. There is also a slight preference of extended over condensed weights.
# +
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(16,5), sharey=True)
fig.suptitle("Average word error rate")
results.groupby(["Width", "Weight"]).mean()["WER"].unstack(0).plot.bar(ax=axes[0]);
results.groupby(["Point size", "Weight"]).mean()["WER"].unstack(0).plot.bar(ax=axes[1]);
results.groupby(["Width", "Point size"]).mean()["WER"].unstack(0).plot.bar(ax=axes[2]);
for x in axes:
x.grid(True, axis="y")
x.set_axisbelow(True)
# -
# Here we plotted average CER by grouped parameters. The middle plot shows that thinner weights are not legible at all. This is mainly a rendering problem, because even in large sizes some strokes are too thin to be displayed.
results.nsmallest(5,"CER")
# The three best results are tied at the same WER and CER and they are all extended weights. Interestingly, they are all also sizes 28. I have no explanation why the same fonts in size 34 yielded worse results.
# # Experiment 2
# ## OCRing different typefaces
# In this experiment we compare OCR error rates on 16 different typefaces rendered at 2 point sizes. This can give us a crude idea about which typefaces work better in smaller sizes and which ones work well generally.
#
# The typefaces we chose can be seen below in the preview.
outdir = "assorted" # directory for storing generated files
fontdir = "fonts/assorted" # directory with font files
ptsizes = [16,32] # list of font sizes to generate
textfile = "cz-news.txt" # file with sample text
language = "ces" # Tesseract language model
# +
# Prepare data and preview fonts
fontdata = get_font_names(fontdir)
setup = make_experiment_setup(fontdata, ptsizes, outdir)
setup.to_csv(os.path.join(outdir, "setup.csv"))
preview_fonts(fontdata)
# -
# We chose mostly different types of common "non-decorative" text typefaces plus three "decorative" ones with substantially different letterforms. Even though we preview all of them in the same point size, some of them are apparently smaller, because of other design parameters, such as x-height.
#
# We add some basic classification to the font data:
# +
fontdata["Proportional"] = "proportional"
fontdata["Serif"] = "sans"
fontdata["Slanted"] = "upright"
fontdata["Decorative"] = "normal"
fontdata.loc[[1,4,11], "Proportional"] = "monospaced"
fontdata.loc[[1,2,3,6,7,15], "Serif"] = "serif"
fontdata.loc[[3,7,9,11,13], "Slanted"] = "slanted"
fontdata.loc[[0,12,13], "Decorative"] = "decorative"
fontdata.to_csv(os.path.join(outdir, "fontdata.csv"))
fontdata
# +
# Batch process all files, write results
# This takes several minutes and requires the font files!
with open(textfile, 'r') as file:
orig_text = file.read()
orig_text = breaklines(orig_text, 60)
batch_render_text(orig_text, setup, fontdata)
batch_ocr_images(setup, "ces")
results = batch_evaluate(setup, fontdata, orig_text)
results.to_csv(os.path.join(outdir, "results.csv"))
# -
# ## Visualising the results
# +
outdir = "assorted"
fontdata = pd.read_csv(os.path.join(outdir, "fontdata.csv"))
results = pd.read_csv(os.path.join(outdir, "results.csv"))
# Merge results with fontdata
results = pd.merge(results, fontdata[["id","Proportional","Serif","Slanted","Decorative"]],
left_on="Font id", right_on="id", how="left").drop(columns=[list(results)[0], "id", "txt"])
# -
results.groupby(["Font"])["WER","CER"].mean().sort_values("WER").plot.barh(title="Average error rates");
plt.grid(True, axis="both")
# This plot show the error rates for each font averaged over the two sizes. It is sorted by WER. At the top, with the highest error rates there are two of our decorative typefaces: _Plagwitz_, a modern adaptation of German blackletter, and _Petit Formal Script_, which is a connected script. It is followed by the italic weight of _Fell DW Pica_, _Courier New_ and the last decorative font _Orange Kid_. All of them have very distinct letterforms, which explains why they are hard to OCR correctly.
#
# On the other end we find _Consolas_, a monospaced sans with occasional serifs on critical narrow characters like `I, l` or `i`. It is followed by _Museo Slab_ and _Sans_, _Helvetica Neue_ from the previous experiment and the _Times New_.
results.groupby(["Point size","Font"])["WER"].mean().unstack(0).sort_values(32).plot.barh(title="Word error rate by point size");
plt.grid(True, axis="both")
# This figure shows that fonts that work in large sizes do not always work as well in small sizes. This is the case of _Times New Roman Italic_. On the other hand _Comic Sans MS_ does not work as good as Times New in the large size, but outperforms it in the small size.
# +
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(16,4), sharey=True)
fig.suptitle("Average word error rate by font types")
results.groupby(["Point size", "Serif"]).mean()["WER"].unstack(0).plot.bar(ax=axes[0]);
results.groupby(["Point size", "Slanted"]).mean()["WER"].unstack(0).plot.bar(ax=axes[1]);
results.groupby(["Point size", "Proportional"]).mean()["WER"].unstack(0).plot.bar(ax=axes[2]);
results.groupby(["Point size", "Decorative"]).mean()["WER"].unstack(0).plot.bar(ax=axes[3]);
for x in axes:
x.grid(True, axis="y")
x.set_axisbelow(True)
x.tick_params("x",labelrotation=0)
# -
# There is no big difference between the results for sans serif and serif fonts in our collection, although there is a slight preference for sans serif fonts. Upright typefaces show better results than slanted ones. The biggest difference is between decorative and non-decorative types, which we have already observed above. Mono typefaces work slightly better than proportional in 16 pt but slightly worse in 32 pt.
#
# # Conclusion
#
# We have found that Tesseract can be very sensitive to recognizing text set in certain typefaces, but also their size and weight.
#
# **However**, for all the comparisons we made it is important to take into account that our type classes are **not equally represented** and our **data is very small**. To get representative results, we would have to choose the fonts systematically, collect more of them and test them on multiple texts.
| tesseract-fonts.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
from sklearn.ensemble import RandomForestClassifier
import pickle
with open('data/census.pkl', 'rb') as f:
X_census_treinamento, X_census_teste, y_census_treinamento, y_census_teste = pickle.load(f)
X_census_treinamento.shape, y_census_treinamento.shape
X_census_teste.shape, y_census_teste.shape
random_forest_census = RandomForestClassifier(n_estimators=100, criterion='entropy', random_state=0)
random_forest_census.fit(X_census_treinamento, y_census_treinamento)
previsoes = random_forest_census.predict(X_census_teste)
previsoes
y_census_teste
from sklearn.metrics import accuracy_score, classification_report
accuracy_score(y_census_teste, previsoes)
from yellowbrick.classifier import ConfusionMatrix
cm = ConfusionMatrix(random_forest_census)
cm.fit(X_census_treinamento, y_census_treinamento)
cm.score(X_census_teste, y_census_teste)
print(classification_report(y_census_teste, previsoes))
| estudo/aprendizagem-random-forest/random-forest-censo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python (venv_data_science)
# language: python
# name: venv_data_science
# ---
# ## 2.1 Pandas Series
import pandas as pd
# %matplotlib inline
# +
scientists = pd.DataFrame(
data={'Occupation': ['Chemist', 'Statistician'],
'Born': ['1920-07-25', '1876-06-13'],
'Died': ['1958-04-16', '1937-10-16'],
'Age': [37, 61]},
index=['<NAME>', '<NAME>'],
columns=['Occupation', 'Born', 'Died', 'Age'])
scientists
# -
first_row = scientists.loc["<NAME>"]
first_row
# +
first_row.index
# or using a method
first_row.keys()
# -
first_row.values
# `Pandas Series` are similar to `numpy.ndarray`
age = scientists["Age"]
age.mean()
age.min()
age.max()
age.std()
age.describe()
# ### 2.1.1 Boolean Indexing
scientists = pd.read_csv('../data/scientists.csv')
scientists
ages = scientists['Age']
ages
ages[ages > ages.mean()]
# ### 2.1.2 Vector Operations
# Operations Are Automatically Aligned and Vectorized (Broadcasting)
ages + ages
ages * ages
# ages is still the same
ages
# #### 2.1.2.1 Vectors and Scalars
ages + 100
# #### 2.1.2.2 Vectors with Different Lengths
# Broadcasting will be done if both are Pandas Series
ages + pd.Series([1, 100])
import numpy as np
ages + np.array([1, 100])
# ### 2.1.3 Automatic Alignment
rev_ages = ages.sort_index(ascending=False)
rev_ages
# if you add ages and rev_ages, the vectors will be aligned first before the operation is carried out.
ages + rev_ages
# same with
ages * 2
# ## 2.2 Pandas DataFrames
# Same concepts and operations applies as with the Pandas Series
# ### 2.2.1 Adding and Manipulating Columns
scientists.dtypes
scientists.head()
# +
born_dt = pd.to_datetime(scientists['Born'], format='%Y-%m-%d')
died_dt = pd.to_datetime(scientists['Died'], format='%Y-%m-%d')
scientists['born_dt'], scientists['died_dt'] = (born_dt, died_dt)
scientists.head()
# -
scientists.dtypes
scientists['age_days_dt'] = (scientists['died_dt'] - scientists['born_dt'])
scientists.head()
# convert days to years
scientists['age_years_dt'] = scientists['age_days_dt'].astype('timedelta64[Y]')
scientists.head()
# ### 2.2.2 Dropping Columns
# +
scientists = scientists.drop(['Born'], axis=1)
scientists = scientists.drop(['Died'], axis=1)
# columns after dropping our column
print(scientists.columns)
# -
scientists.head()
# ## 2.3 Exporting and Importing Data
scientists.to_pickle('../output/scientists.pickle')
scientists_from_pickle = pd.read_pickle('../output/scientists.pickle')
scientists_from_pickle.head()
# ### 2.3.1 To CSV
scientists.to_csv('../output/scientists.csv')
scientists.to_csv('../output/scientists.tsv', sep='\t')
# removing row numbers from output
scientists.to_csv('../output/scientists_no_index.csv', index=False)
scientists_from_csv = pd.read_csv('../output/scientists_no_index.csv')
scientists_from_csv.head()
# ### 2.3.2 To Excel
scientists.to_excel('../output/scientists_df.xlsx',sheet_name='scientists',index=False)
# Series does not have to_excel method, convert it first to DataFrame
age = scientists["Age"]
type(age)
age_df = age.to_frame()
age_df.to_excel('../output/age_df.xlsx',sheet_name='age',index=False)
| 01_Intro/02 Pandas Data Structures.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="Ud2ivjvQJx-b" executionInfo={"status": "ok", "timestamp": 1604802374598, "user_tz": 300, "elapsed": 590, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="edaa0313-4c47-496a-81bc-13797293f5cb" colab={"base_uri": "https://localhost:8080/"}
# %cd /content/drive/My Drive/Colab Notebooks/playing with btc
# + id="3Arq8nPfBc-t"
# !pip install backtrader
# !pip install pyfolio
# For plotting capabilities
# !pip install backtrader[plotting]
# + id="ZKzrkh27Vfhj" executionInfo={"status": "ok", "timestamp": 1604802390120, "user_tz": 300, "elapsed": 16087, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# %matplotlib inline
import pandas as pd
import backtrader as bt
import backtrader.indicators as btind
import backtrader.analyzers as btanalyzers
import datetime
from backtrader.feeds import PandasData
# + id="AK90LRVgVZbk" executionInfo={"status": "ok", "timestamp": 1604802391867, "user_tz": 300, "elapsed": 17817, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="b413fb43-aad8-4a57-8559-757993b24aa1" colab={"base_uri": "https://localhost:8080/", "height": 424}
df = pd.read_csv('bitcoin/btc_4h_2017_2020.csv')
names = ['open', 'high', 'low', 'close', 'volume', 'open_time']
df = df[names]
df
# + [markdown] id="Cf32E7NTuinJ"
# # ticker and the start and end dates for testing
# + id="xZpGXmAgXz8m" executionInfo={"status": "ok", "timestamp": 1604802391872, "user_tz": 300, "elapsed": 17809, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="df27f1ce-552b-49fd-96a8-15582af162a6" colab={"base_uri": "https://localhost:8080/", "height": 143}
format = '%Y-%m-%d %H:%M:%S.%f'
df['open_time'] = pd.to_datetime(df['open_time'], format=format)
df.set_index('open_time', inplace=True)
df.head(2)
# + id="gzJxd9SjX0HR" executionInfo={"status": "ok", "timestamp": 1604802391875, "user_tz": 300, "elapsed": 17805, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# class to define the columns we will provide
class SignalData(PandasData):
"""
Define pandas DataFrame structure
"""
OHLCV = ['open', 'high', 'low', 'close', 'volume']
cols = OHLCV
# create lines
lines = tuple(cols)
# define parameters
params = {c: -1 for c in cols}
params.update({'datetime': None})
params = tuple(params.items())
# + [markdown] id="1NkwZyMRX0Kq"
# # Strategy
#
# Use two moving averages and buy in the cross of the moving average, but the RSI must be above a certain range.
#
# Then sell the position when the RSI is too high or when we achieve a certain value.
# + id="ZZy_YkfeX0Qm" executionInfo={"status": "ok", "timestamp": 1604802391878, "user_tz": 300, "elapsed": 17803, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# define backtesting strategy class
class Strategy(bt.Strategy):
params = dict()
def __init__(self):
self.btc = self.datas[0]
self.close = self.btc.close
self.ema_20 = btind.ExponentialMovingAverage(self.btc.close, period=20)
self.ema_40 = btind.ExponentialMovingAverage(self.btc.close, period=40)
# 1 if 20 crosses up 40 -1 if 20 crosses down 40
self.cross = btind.CrossOver(self.ema_20, self.ema_40)
self.order = None
# logging function
def log(self, txt):
'''Logging function'''
dt = self.datas[0].datetime.date(0).isoformat()
print(f'{dt}, {txt}')
def next(self):
# not in the market
if not self.position: # not in the market
if self.cross[0] > 0:
self.order = self.buy()
self.log(f'Buy at {self.btc.close[0]}')
self.order = 'buying'
elif self.order == 'buying': # position in market
if self.cross[0] < 0:
self.order = self.sell()
self.log(f'Sell at {self.btc.close[0]}')
# + id="KyC2W280X0TJ" executionInfo={"status": "ok", "timestamp": 1604802391880, "user_tz": 300, "elapsed": 17800, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# instantiate SignalData class
data = SignalData(dataname=df)
# + id="LEX4i14sX0Wf" executionInfo={"status": "ok", "timestamp": 1604802391884, "user_tz": 300, "elapsed": 17799, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# instantiate Cerebro, add strategy, data, initial cash, commission and pyfolio for performance analysis
cerebro = bt.Cerebro(stdstats = False)
cerebro.addstrategy(Strategy)
cerebro.adddata(data, name='BTC/USDT')
cerebro.broker.setcash(20000.0)
cerebro.broker.setcommission(commission=0.001)
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
# + [markdown] id="Uh2uaSIxYuHQ"
# # Analizers
# + id="63S_7wCwYxGv" executionInfo={"status": "ok", "timestamp": 1604802391884, "user_tz": 300, "elapsed": 17794, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
# Analyzer
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='ta')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe', riskfreerate=0.0, annualize=True, timeframe=bt.TimeFrame.Minutes)
cerebro.addanalyzer(bt.analyzers.VWR, _name='vwr')
cerebro.addanalyzer(bt.analyzers.SQN, _name='sqn')
cerebro.addanalyzer(bt.analyzers.Transactions, _name='txn')
# + [markdown] id="N3xMkZ2DpQdN"
# # Observers
#
# + id="5q4wkiGmpQ4O" executionInfo={"status": "ok", "timestamp": 1604802391886, "user_tz": 300, "elapsed": 17791, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}}
cerebro.addobserver(bt.observers.TimeReturn)
cerebro.addobserver(bt.observers.BuySell)
cerebro.addobserver(bt.observers.Value)
cerebro.addobserver(bt.observers.DrawDown)
cerebro.addobserver(bt.observers.Trades)
# + id="Uabrf7T0h439" executionInfo={"status": "ok", "timestamp": 1604802396163, "user_tz": 300, "elapsed": 22063, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="2cfced77-0e83-413b-a5f0-0ec5fc9af459" colab={"base_uri": "https://localhost:8080/"}
# run the backtest
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
backtest_result = cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
# + id="RVXVXj9UY0hX" executionInfo={"status": "ok", "timestamp": 1604802396165, "user_tz": 300, "elapsed": 22060, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="c6ae8225-a8ff-4207-b844-08b2ae5d9bec" colab={"base_uri": "https://localhost:8080/"}
strat = backtest_result[0]
from pprint import pprint
drawdown = strat.analyzers.drawdown.get_analysis()
pprint(drawdown)
sharpe_ratio = strat.analyzers.sharpe.get_analysis()
pprint(sharpe_ratio)
transactions = strat.analyzers.txn.get_analysis()
pprint(transactions)
# + id="GXSDgl7Fh5KT" executionInfo={"status": "ok", "timestamp": 1604802397006, "user_tz": 300, "elapsed": 22889, "user": {"displayName": "<NAME>\u00e9rrez", "photoUrl": "", "userId": "11854874717100226645"}} outputId="14736bfb-85ac-456a-be0c-d147226f9e02" colab={"base_uri": "https://localhost:8080/", "height": 35}
cerebro.plot()
| examples/simple_strategy.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# [View in Colaboratory](https://colab.research.google.com/github/keshan/neural_style_transfer/blob/master/Neural_Style_Transfer.ipynb)
# + [markdown] id="zuvU0ICeypup" colab_type="text"
# Download VGG-19, Content image and Style image to the workspace.
# + id="70MahdLQbfQp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 578} outputId="07ba15a1-b6d4-4bbe-80b8-4ff80c5337fd"
# !wget http://www.vlfeat.org/matconvnet/models/imagenet-vgg-verydeep-19.mat
# !wget https://www.travellingpearllanka.com/wp-content/uploads/2015/04/featured-discover-srilanka-18d-17n-tour-400x300.jpg
# !wget http://www.goldenedgetravels.com/img/goldenedgetravels/img18.jpg
# + id="OIe3g48tbj0X" colab_type="code" colab={}
import os
import sys
import scipy.io
import scipy.misc
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
import numpy as np
import tensorflow as tf
# %matplotlib inline
# + [markdown] id="elvjKpo1y49J" colab_type="text"
# Defining the VGG-19 model, Loading the downloaded pre-trained weights This model is based on "Very Deep Convolutional Networks for Large-Scale Image Recognition" by <NAME> and <NAME> https://arxiv.org/pdf/1409.1556.pdf
# + id="KQhXsDNbcW3k" colab_type="code" colab={}
class CONFIG:
IMAGE_WIDTH = 400
IMAGE_HEIGHT = 300
COLOR_CHANNELS = 3
NOISE_RATIO = 0.6
MEANS = np.array([123.68, 116.779, 103.939]).reshape((1,1,1,3))
VGG_MODEL = 'imagenet-vgg-verydeep-19.mat'
STYLE_IMAGE = 'featured-discover-srilanka-18d-17n-tour-400x300.jpg'
CONTENT_IMAGE = 'img18.jpg'
def load_vgg_model(path):
"""
Returns a model for the purpose of 'painting' the picture.
Takes only the convolution layer weights and wrap using the TensorFlow
Conv2d, Relu and AveragePooling layer. VGG actually uses maxpool but
the paper indicates that using AveragePooling yields better results.
The last few fully connected layers are not used.
Here is the detailed configuration of the VGG model:
0 is conv1_1 (3, 3, 3, 64)
1 is relu
2 is conv1_2 (3, 3, 64, 64)
3 is relu
4 is maxpool
5 is conv2_1 (3, 3, 64, 128)
6 is relu
7 is conv2_2 (3, 3, 128, 128)
8 is relu
9 is maxpool
10 is conv3_1 (3, 3, 128, 256)
11 is relu
12 is conv3_2 (3, 3, 256, 256)
13 is relu
14 is conv3_3 (3, 3, 256, 256)
15 is relu
16 is conv3_4 (3, 3, 256, 256)
17 is relu
18 is maxpool
19 is conv4_1 (3, 3, 256, 512)
20 is relu
21 is conv4_2 (3, 3, 512, 512)
22 is relu
23 is conv4_3 (3, 3, 512, 512)
24 is relu
25 is conv4_4 (3, 3, 512, 512)
26 is relu
27 is maxpool
28 is conv5_1 (3, 3, 512, 512)
29 is relu
30 is conv5_2 (3, 3, 512, 512)
31 is relu
32 is conv5_3 (3, 3, 512, 512)
33 is relu
34 is conv5_4 (3, 3, 512, 512)
35 is relu
36 is maxpool
37 is fullyconnected (7, 7, 512, 4096)
38 is relu
39 is fullyconnected (1, 1, 4096, 4096)
40 is relu
41 is fullyconnected (1, 1, 4096, 1000)
42 is softmax
"""
vgg = scipy.io.loadmat(path)
vgg_layers = vgg['layers']
def _weights(layer, expected_layer_name):
"""
Return the weights and bias from the VGG model for a given layer.
"""
wb = vgg_layers[0][layer][0][0][2]
W = wb[0][0]
b = wb[0][1]
layer_name = vgg_layers[0][layer][0][0][0][0]
assert layer_name == expected_layer_name
return W, b
return W, b
def _relu(conv2d_layer):
"""
Return the RELU function wrapped over a TensorFlow layer. Expects a
Conv2d layer input.
"""
return tf.nn.relu(conv2d_layer)
def _conv2d(prev_layer, layer, layer_name):
"""
Return the Conv2D layer using the weights, biases from the VGG
model at 'layer'.
"""
W, b = _weights(layer, layer_name)
W = tf.constant(W)
b = tf.constant(np.reshape(b, (b.size)))
return tf.nn.conv2d(prev_layer, filter=W, strides=[1, 1, 1, 1], padding='SAME') + b
def _conv2d_relu(prev_layer, layer, layer_name):
"""
Return the Conv2D + RELU layer using the weights, biases from the VGG
model at 'layer'.
"""
return _relu(_conv2d(prev_layer, layer, layer_name))
def _avgpool(prev_layer):
return tf.nn.avg_pool(prev_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# Constructs the graph model.
graph = {}
graph['input'] = tf.Variable(np.zeros((1, CONFIG.IMAGE_HEIGHT, CONFIG.IMAGE_WIDTH, CONFIG.COLOR_CHANNELS)), dtype = 'float32')
graph['conv1_1'] = _conv2d_relu(graph['input'], 0, 'conv1_1')
graph['conv1_2'] = _conv2d_relu(graph['conv1_1'], 2, 'conv1_2')
graph['avgpool1'] = _avgpool(graph['conv1_2'])
graph['conv2_1'] = _conv2d_relu(graph['avgpool1'], 5, 'conv2_1')
graph['conv2_2'] = _conv2d_relu(graph['conv2_1'], 7, 'conv2_2')
graph['avgpool2'] = _avgpool(graph['conv2_2'])
graph['conv3_1'] = _conv2d_relu(graph['avgpool2'], 10, 'conv3_1')
graph['conv3_2'] = _conv2d_relu(graph['conv3_1'], 12, 'conv3_2')
graph['conv3_3'] = _conv2d_relu(graph['conv3_2'], 14, 'conv3_3')
graph['conv3_4'] = _conv2d_relu(graph['conv3_3'], 16, 'conv3_4')
graph['avgpool3'] = _avgpool(graph['conv3_4'])
graph['conv4_1'] = _conv2d_relu(graph['avgpool3'], 19, 'conv4_1')
graph['conv4_2'] = _conv2d_relu(graph['conv4_1'], 21, 'conv4_2')
graph['conv4_3'] = _conv2d_relu(graph['conv4_2'], 23, 'conv4_3')
graph['conv4_4'] = _conv2d_relu(graph['conv4_3'], 25, 'conv4_4')
graph['avgpool4'] = _avgpool(graph['conv4_4'])
graph['conv5_1'] = _conv2d_relu(graph['avgpool4'], 28, 'conv5_1')
graph['conv5_2'] = _conv2d_relu(graph['conv5_1'], 30, 'conv5_2')
graph['conv5_3'] = _conv2d_relu(graph['conv5_2'], 32, 'conv5_3')
graph['conv5_4'] = _conv2d_relu(graph['conv5_3'], 34, 'conv5_4')
graph['avgpool5'] = _avgpool(graph['conv5_4'])
return graph
# + [markdown] id="sp3hmnUe0kK3" colab_type="text"
# Let's have a look at the model.
# + id="F5WwmCXuccnl" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="70b117d6-58b1-442f-c9ee-95fe6175b436"
model = load_vgg_model(CONFIG.VGG_MODEL)
print(model)
# + [markdown] id="WbSBD7kV0szS" colab_type="text"
# Fun part starts from here. The implementations are based on "A Neural Algorithm of Artistic Style" by <NAME> et al. https://arxiv.org/pdf/1508.06576.pdf
# + id="13Lo7JJ9czdN" colab_type="code" colab={}
def compute_content_cost(a_C, a_G):
m, n_H, n_W, n_C = a_G.get_shape().as_list()
# Reshape a_C and a_G
a_C_unrolled = tf.reshape(a_C,[-1])
a_G_unrolled = tf.reshape(a_G,[-1])
J_content = tf.reduce_sum(tf.square(a_C_unrolled-a_G_unrolled))/(4*n_H*n_W*n_C)
return J_content
# + id="7PB03dz0c2nt" colab_type="code" colab={}
def gram_matrix(A):
GA = tf.matmul(A,tf.transpose(A))
return GA
# + id="Tbf2cFbKc5uK" colab_type="code" colab={}
def compute_layer_style_cost(a_S, a_G):
m, n_H, n_W, n_C = a_G.get_shape().as_list()
# Reshape the images to have them of shape (n_H*n_W, n_C)
a_S = tf.reshape(a_S, [n_H*n_W, n_C])
a_G = tf.reshape(a_G, [n_H*n_W, n_C])
# Computing gram_matrices for both images S and G
GS = gram_matrix(tf.transpose(a_S)) # the input of gram_matrix is A: matrix of shape (n_C, n_H*n_W)
GG = gram_matrix(tf.transpose(a_G))
J_style_layer = tf.reduce_sum(tf.square(GS-GG)) / (4 * n_C**2 * (n_W * n_H)**2)
return J_style_layer
# + id="oqZcN319dcjD" colab_type="code" colab={}
STYLE_LAYERS = [
('conv1_1', 0.2),
('conv2_1', 0.2),
('conv3_1', 0.2),
('conv4_1', 0.2),
('conv5_1', 0.2)]
# + id="e8d4TD6-dmQo" colab_type="code" colab={}
def compute_style_cost(model, STYLE_LAYERS):
J_style = 0
for layer_name, coeff in STYLE_LAYERS:
# output tensor of the currently selected layer
out = model[layer_name]
# a_S the hidden layer activation from the layer we have selected
a_S = sess.run(out)
# a_G is the hidden layer activation from same layer.
a_G = out
J_style_layer = compute_layer_style_cost(a_S, a_G)
# Add coeff * J_style_layer of this layer to overall style cost
J_style += coeff * J_style_layer
return J_style
# + id="89a9ljtNdr7Z" colab_type="code" colab={}
def total_cost(J_content, J_style, alpha = 10, beta = 40):
J = alpha*J_content + beta*J_style
return J
# + id="JMjQeALbd0JB" colab_type="code" colab={}
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = load_vgg_model(CONFIG.VGG_MODEL)
# + id="uKQvgrAdd3HF" colab_type="code" colab={}
def reshape_and_normalize_image(image):
image = np.reshape(image, ((1,) + image.shape))
image = image - CONFIG.MEANS
return image
def save_image(path, image):
image = image + CONFIG.MEANS
image = np.clip(image[0], 0, 255).astype('uint8')
scipy.misc.imsave(path, image)
# + id="XwKzOL_DeZ1b" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 269} outputId="b0df8016-2c68-470b-e1c1-c959397169d4"
content_image = scipy.misc.imread(CONFIG.CONTENT_IMAGE)
imshow(content_image)
content_image = reshape_and_normalize_image(content_image)
# + id="z0R8ejXfecff" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 456} outputId="2c77d7da-76ab-4730-e4b2-31afdfed1d0c"
# #!wget http://lh3.googleusercontent.com/-AO-zg5FNkNw/VquzW0L4mxI/AAAAAAAAOv0/OTAnc-nRj5w/s640/blogger-image--389148106.jpg
style_image = scipy.misc.imread(CONFIG.STYLE_IMAGE)
#style_image = scipy.misc.imread("blogger-image--389148106.jpg")
imshow(style_image)
style_image = reshape_and_normalize_image(style_image)
# + id="N4UmLlvUegli" colab_type="code" colab={}
def generate_noise_image(content_image, noise_ratio=CONFIG.NOISE_RATIO):
noise_image = np.random.uniform(-20, 20,
(1, CONFIG.IMAGE_HEIGHT, CONFIG.IMAGE_WIDTH, CONFIG.COLOR_CHANNELS)).astype(
'float32')
input_image = noise_image * noise_ratio + content_image * (1 - noise_ratio)
return input_image
# + id="lAZ6CaBxent8" colab_type="code" colab={}
generated_image = generate_noise_image(content_image)
# + id="ywEinhSNe9A8" colab_type="code" colab={}
sess.run(model['input'].assign(content_image))
out = model['conv4_2']
a_C = sess.run(out)
a_G = out
J_content = compute_content_cost(a_C, a_G)
# + id="sDioJ4ogfMfj" colab_type="code" colab={}
sess.run(model['input'].assign(style_image))
J_style = compute_style_cost(model, STYLE_LAYERS)
J = total_cost(J_content,J_style,10,40)
optimizer = tf.train.AdamOptimizer(2.0)
train_step = optimizer.minimize(J)
# + id="jfPQaYyDfu2h" colab_type="code" colab={}
def model_nn(sess, input_image, num_iterations = 200):
sess.run(tf.global_variables_initializer())
sess.run(model['input'].assign(input_image))
for i in range(num_iterations):
sess.run(train_step)
generated_image = sess.run(model['input'])
if i%20 == 0:
Jt, Jc, Js = sess.run([J, J_content, J_style])
print("Iteration " + str(i) + " :")
print("total cost = " + str(Jt))
print("content cost = " + str(Jc))
print("style cost = " + str(Js))
save_image(str(i) + ".jpg", generated_image)
save_image('generated_image.jpg', generated_image)
return generated_image
# + id="RxHfrwWff0Io" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1530} outputId="540e04ab-ff4e-463a-fd19-2ed091cc858f"
model_nn(sess, generated_image)
# + id="Mxqwv3snhCiu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 317} outputId="f3e5d424-0619-450a-f294-28a7fb6eae15"
from IPython.display import Image
Image(filename="generated_image.jpg")
# + id="qoFlQJmkhpnD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 453} outputId="cf88e77e-9a7c-49a6-e520-dd87960308fc"
# !ls
Image(filename="40.jpg")
# + id="8bPSZGtVr8Qn" colab_type="code" colab={}
| Neural_Style_Transfer.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""""objective:
pridict the probability of a word occouring in a negative review with respect to posititve review
import nltk
import random
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.classify import ClassifierI
from statistics import mode
from nltk.tokenize import word_tokenize
import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.corpus import stopwords
from nltk.text import Text
import string, re
from nltk.corpus import stopwords
# +
import os
files_pos = os.listdir(r'C:/Users/dell/Desktop/train_pos')
files_neg = os.listdir(r'C:/Users/dell/Desktop/train_neg')
files_pos = [open(r'C:/Users/dell/Desktop/train_pos/'+f, 'r',encoding="utf8").read() for f in files_pos]
files_neg = [open(r'C:/Users/dell/Desktop/train_neg/'+f, 'r',encoding="utf8").read() for f in files_neg]
# -
stop_words = list(set(stopwords.words('english')))
print(stop_words)
#j is adjective, r is adverb, and v is verb
#allowed_word_types = ["J","R","V"]
allowed_word_types = ["J"]
all_words = []
documents = []
for p in files_pos:
#creating tuple
documents.append((p,"pos"))
#remove puntuations
cleaned = re.sub(r'[^(a-zA-Z)\s]','', p)
#tokenize
tokenized = word_tokenize(cleaned)
#"""Tokenize a string to split off punctuation other than periods"""
# remove stopwords
stopped = [w for w in tokenized if not w in stop_words]
# parts of speech tagging for each word
pos = nltk.pos_tag(stopped)
# make a list of all adjectives identified by the allowed word types list above
for w in pos:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
# +
# tagger This package contains classes and interfaces for part-of-speech tagging, or simply “tagging”.
# tagger A “tag” is a case-sensitive string that specifies some property of a token, such as its part of speech. Tagged tokens are encoded as tuples (tag, token). For example, the following tagged token combines the word 'fly' with a noun part of speech tag ('NN'):
# -
print(pos)
for w in pos:
print(w)
#last element saved in iteration
for w in pos:
print(w)
print(w[0][0])
print(w[1][0])
for p in files_neg:
# create a list of tuples where the first element of each tuple is a review
# the second element is the label
documents.append((p, "neg"))
# remove punctuations
cleaned = re.sub(r'[^(a-zA-Z)\s]','', p)
# tokenize
tokenized = word_tokenize(cleaned)
# remove stopwords
stopped = [w for w in tokenized if not w in stop_words]
# parts of speech tagging for each word
neg = nltk.pos_tag(stopped)
# make a list of all adjectives identified by the allowed word types list above
for w in neg:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
for i in tokenized:
print(i)
# creating a frequency distribution of each adjectives.
all_words = nltk.FreqDist(all_words)
# listing the 5000 most frequent words
word_features = list(all_words.keys())[:5000]
print(word_features)
# +
# function to create a dictionary of features for each review in the list document.
# The keys are the words in word_features
# The values of each key are either true or false for wether that feature appears in the review or not
def find_features(document):
words = word_tokenize(document) #tokenized.
for w in all_words:
features[w] = (w in words)
return features
# Creating features for each review
featuresets = [(find_features(rev), category) for (rev, category) in documents]
# -
count=0
for i in featuresets:
if count<1:
print(i)
print("***********")
count=count+1
# +
z=[]
x=[]
#Shuffling the dictionary
random.shuffle(featuresets)
train = 25000
test = 20000
training_set = featuresets[:25000]
testing_set = featuresets[20000:]
z.append(train/test)
x.append(test/train)
# +
y=[]
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
# -
#Shuffling the dictionary
random.shuffle(featuresets)
train = 20000
test = 20001
training_set = featuresets[:20000]
testing_set = featuresets[20001:]
z.append(train/test)
x.append(test/train)
# +
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
# -
#Shuffling the dictionary
random.shuffle(featuresets)
train = 30000
test = 20001
training_set = featuresets[:30000]
testing_set = featuresets[20001:]
z.append(train/test)
x.append(test/train)
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
# +
random.shuffle(featuresets)
train = 30000
test = 30001
training_set = featuresets[:30000]
testing_set = featuresets[30001:]
z.append(train/test)
x.append(test/train)
# -
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
# +
random.shuffle(featuresets)
train = 8000
test = 8001
training_set = featuresets[:8000]
testing_set = featuresets[8001:]
z.append(train/test)
x.append(test/train)
# -
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
# +
random.shuffle(featuresets)
train = 8000
test = 5001
training_set = featuresets[:8000]
testing_set = featuresets[5001:]
z.append(train/test)
x.append(test/train)
# -
classifier = nltk.NaiveBayesClassifier.train(training_set)
t=(nltk.classify.accuracy(classifier, testing_set))*100
y.append(t)
print("Classifier accuracy percent:",t)
classifier.show_most_informative_features(15)
import matplotlib.pyplot as plt
plt.plot( [1.25, 0.999950002499875, 1.4999250037498124, 0.9998750156230471, 1.5996800639872026],[85.1829,82.98,85.22,82.28823,83.405],'ro')
plt.label('train/test')
plt.ylabel('accuracy')
print(x)
| review.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # DataFlow API walkthrough
# <NAME> <br>
# 4/6/2022 <br>
# Oak Ridge National Laboratory
# ## 0. Prepare to use DataFlow's API:
#
# 1. Install the ``ordflow`` python package from PyPi via:
#
# ``pip install ordflow``
#
# 2. Generate an API Key from DataFlow's web interface
#
# **Note**: API Keys are not reusable across DataFlow servers (e.g. facility-local and central at https://dataflow.ornl.gov). You will need to get an API key to suit the specific instance of DataFlow you are communicating with
api_key = "<KEY>"
# 3. Encrypt password(s) necessary to activate Globus endpoints securely
#
# Here, the two Globus endpoints (DataFlow server and destination) use the same authentication (ORNL's XCAMS)
#
# **Note**: You will need to get your passwords encrypted by the specific deployment of DataFlow (central / facility-local) that you intend to use
enc_pwd = "V<KEY>
# 4. Import the ``API`` class from the ``dflow`` package.
from ordflow import API
# Instantiate the API object with your personal API Key:
# ## 1. Instantiate the API
api = API(api_key)
# ## 2. Check default settings
# Primarily pay attention to the ``destination_globus`` parameter since this is the only parameter that can be changed / has any significant effect
response = api.settings_get()
response
# ## 3. Update a default setting
#
# Here, we will switch the destination endpoint to ``olcf#dtn`` for illustration purposes
response = api.settings_set("globus.destination_endpoint",
"ef1a9560-7ca1-11e5-992c-22000b96db58")
response
# Switching back the destination endpoint to ``cades#CADES-OR`` which is the default
response = api.settings_set("globus.destination_endpoint",
"57230a10-7ba2-11e7-8c3b-22000b9923ef")
response
# ## 4. List and view registered instruments
#
# Contact a DataFlow server administrator to add an instrument for you.
response = api.instrument_list()
response
response = api.instrument_info(2)
response
# ## 5. Check to see if Globus endpoints are active:
response = api.globus_endpoints_active("57230a10-7ba2-11e7-8c3b-22000b9923ef")
response
# ## 6. Activate one or both endpoints as necessary:
# Because the destination wasn't already activated, we can activate that specific endpoint.
#
# **Note**: An encrypted password is being used in place of the conventional password for safety reasons.
response = api.globus_endpoints_activate("syz",
enc_pwd,
encrypted=True,
endpoint="destination")
response
response = api.globus_endpoints_active()
response
# ## 7. Create a measurement Dataset
# This creates a directory at the destination Globus Endpoint:
response = api.dataset_create("My new dataset with nested metadata",
metadata={"Sample": "PZT",
"Microscope": {
"Vendor": "Asylum Research",
"Model": "MFP3D"
},
"Temperature": 373
}
)
response
# Getting the dataset ID programmatically to use later on:
dataset_id = response['id']
dataset_id
# ## 8. Upload data file(s) to Dataset
response = api.file_upload("./AFM_Topography.PNG", dataset_id)
response
# Upload another data file to the same dataset:
response = api.file_upload("./measurement_configuration.txt", dataset_id, relative_path="foo/bar")
response
# ## 9. Search Dataset:
response = api.dataset_search("nested")
response
# Parsing the response to get the dataset of interest for us:
dset_id = response['results'][0]['id']
dset_id
# ## 10. View this Dataset:
# This view shows both the files and metadata contained in a dataset:
response = api.dataset_info(dset_id)
response
# ## 11. View files uploaded via DataFlow:
# We're not using DataFlow here but just viewing the destination file system.
#
# Datasets are sorted by date:
# ! ls -hlt ~/dataflow/untitled_instrument/
# There may be more than one dataset per day. Here we only have one
# !ls -hlt ~/dataflow/untitled_instrument/2022-04-06/
# Viewing the root directory of the dataset we just created:
# !ls -hlt ~/dataflow/untitled_instrument/2022-04-06/135750_atomic_force_microscopy_scan_of_pzt/
# We will very soon be able to specify root level metadata that will be stored in ``metadata.json``.
#
# We can also see the nested directories: ``foo/bar`` where we uploaded the second file:
# !ls -hlt ~/dataflow/untitled_instrument/2022-04-06/135750_atomic_force_microscopy_scan_of_pzt/foo/
# Looking at the inner most directory - ``bar``:
# !ls -hlt ~/dataflow/untitled_instrument/2022-04-06/135750_atomic_force_microscopy_scan_of_pzt/foo/bar
| notebooks/01_User_guide/DataFlow_API_Walkthrough.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:nf] *
# language: python
# name: conda-env-nf-py
# ---
# # Support Vector Machines
# ## External Resources
# [Data Science Handbook / 05.07-Support-Vector-Machines.ipynb](https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/05.07-Support-Vector-Machines.ipynb)
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# ## Dataset: Social Network Ads
# The original dataset can be found at Kaggle ([Social Network Ads](https://www.kaggle.com/rakeshrau/social-network-ads)).
# ## Importing the datasets
df = pd.read_csv('Social_Network_Ads.csv')
X = df.iloc[:, [2,3]].values
y = df.iloc[:, 4].values
df.head()
# ## Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# ## Feature Scaling
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# ## Fitting the classifier into the Training set
clf = SVC(kernel = 'linear', random_state = 0)
clf.fit(X_train, y_train)
# ## Predicting the test set results
y_pred = clf.predict(X_test)
# ## Making the Confusion Matrix
confusion_matrix(y_test, y_pred)
# ## Visualization
def visualize(features, target, title):
X_set, y_set = features, target
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1,
stop = X_set[:, 0].max() + 1,
step = 0.01),
np.arange(start = X_set[:, 1].min() - 1,
stop = X_set[:, 1].max() + 1,
step = 0.01))
plt.contourf(X1,
X2,
clf.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75,
cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0],
X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title(title)
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# ### Visualising the Training set results
visualize(X_train, y_train, 'Support Vector Machine (Training set)')
# ### Visualising the Test set results
visualize(X_test, y_test, 'Support Vector Machine (Test set)')
# As we can see due the linear nature of this classifier the model made some incorrect predictions(10 incorrect predictions as per the confusion matrix and graph). Now let's try to use different kernel type and see if it makes any better predictions.
clf = SVC(kernel='rbf',random_state=0)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
confusion_matrix(y_test, y_pred)
# ## Visualising the Training set results for `'rbf'` kernel
visualize(X_train, y_train, 'SVM (Training set)')
visualize(X_test, y_test, 'SVM (Test set)')
# As we can observe from the figure above, the classifier with kernel as rbf made better predictions with only 7 inocrrect predictions. Thus this ia still a better model compared to Logistic regression and K-NN in making useful predictions for the dependant variable.
# ## Sources
# The second part of the note book is based on the work of https://www.kaggle.com/farhanmd29/svm-model-for-social-network-ads.
| social_network_ads_notebook.ipynb |
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .cs
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: .NET (C#)
// language: C#
// name: .net-csharp
// ---
// # Convergence Study using the Meta Job Manager
//
// ## Initialization
//
// In order to execute the individual solver runs,
// we are going to employ the mini batch processor,
// for running the calculations on the local machine.
// We also have to initialize the workflow management system and create
// a database.
// + dotnet_interactive={"language": "csharp"}
#r "BoSSSpad.dll"
using System;
using System.Collections.Generic;
using System.Linq;
using ilPSP;
using ilPSP.Utils;
using BoSSS.Platform;
using BoSSS.Foundation;
using BoSSS.Foundation.Grid;
using BoSSS.Foundation.Grid.Classic;
using BoSSS.Foundation.IO;
using BoSSS.Solution;
using BoSSS.Solution.Control;
using BoSSS.Solution.GridImport;
using BoSSS.Solution.Statistic;
using BoSSS.Solution.Utils;
using BoSSS.Solution.Gnuplot;
using BoSSS.Application.BoSSSpad;
using BoSSS.Application.XNSE_Solver;
using static BoSSS.Application.BoSSSpad.BoSSSshell;
Init();
// + dotnet_interactive={"language": "csharp"}
using NUnit.Framework;
// + dotnet_interactive={"language": "csharp"}
BoSSSshell.WorkflowMgm.Init("ConvStudyTutorial");
// + dotnet_interactive={"language": "csharp"}
var db = CreateTempDatabase();
// -
// The following (deactivated) line would delete all Sessions (i.e. solver
// runs) which correspond to this project from the database.
// Hence, on every execution of the worksheet, all simulations would be
// re-done.
//
// Normally, without the following line, existing simulations from
// the database will be used; therefore, it is save to close and open
// the worksheet.
//
// This is handy e.g. when simulations are running on a cluster for a long
// time, and we usually don't want to re-submit the calculation
// every time we execute the worksheet.
//
// ```csharp
// BoSSSshell.WorkflowMgm.Sessions.ForEach(si => si.Delete(true));
// ```
// For sake of simplicity, we employ the Poisson solver
// **ipPoisson** which is just a benchmarking application, but sufficient
// for the purpose of this tutorial.
// + dotnet_interactive={"language": "csharp"}
using BoSSS.Application.SipPoisson;
// -
// We also instantiate a client for the **MiniBatchProcessor**:
// + dotnet_interactive={"language": "csharp"}
var myBatch = ExecutionQueues[0];
// + dotnet_interactive={"language": "csharp"}
myBatch
// -
// ## Mesh Creation
//
// We create multiple grids using resolutions of $2 \times 2$, $4 \times 4$ to $32 \times 32$
// cells:
// + dotnet_interactive={"language": "csharp"}
int[] resolutions = new int[] { 2, 4, 8, 16, 32};
// + dotnet_interactive={"language": "csharp"}
var grids = new GridCommons[resolutions.Length];
for(int iRes = 0; iRes < resolutions.Length; iRes++) {
// create nodes:
var Nodes = GenericBlas.Linspace(-Math.PI*0.5, Math.PI*0.5,
resolutions[iRes] + 1); // note: number of nodes = number of cells + 1!
// create grid:
GridCommons grd_i = Grid2D.Cartesian2DGrid(Nodes, Nodes);
// define all boundaries as Dirichlet:
grd_i.EdgeTagNames.Add(1, BoundaryType.Dirichlet.ToString());
grd_i.DefineEdgeTags(delegate (double[] X) {
byte ret = 1;
return ret;
});
// save grid in database
db.SaveGrid(ref grd_i);
// remenber reference to grid:
grids[iRes] = grd_i;
}
// -
// ## Setup and execution of solver runs
//
// First, we implement the exact expressions for the right-hand-side $$ f(x,y)= -2\cos(x)\cos(y)$$
// and the exact solution.
// $$ u_{sol} (x,y)=\cos(x) \cos(y) $$
//
// The exact solution will be used to compute the error of the simulation.
// Normally, the exact solution is not known; in those cases, we need to
// compute the experimental convergence against the solution on the finest
// grid.
// + dotnet_interactive={"language": "csharp"}
string formula_code =
"static class Expressions { " +
" public static double RHS(double[] X) { " +
" double x = X[0]; " +
" double y = X[1]; " +
" return -2.0*Math.Cos(x)*Math.Cos(y); " +
" } " +
" public static double Tex(double[] X) { " +
" double x = X[0]; " +
" double y = X[1]; " +
" return Math.Cos(x)*Math.Cos(y); " +
" } " +
"}";
// + dotnet_interactive={"language": "csharp"}
var RHSfunc = new Formula("Expressions.RHS", false, formula_code);
// + dotnet_interactive={"language": "csharp"}
var TexFunc = new Formula("Expressions.Tex", false, formula_code);
// -
// We compute 4 different polynomial orders:
// + dotnet_interactive={"language": "csharp"}
int[] Degrees = new int[] {1, 2, 3, 4};
// -
// Setup of all runs...
// + dotnet_interactive={"language": "csharp"}
var Runs = new List<SipControl>();
Runs.Clear(); // start with an empty run list
foreach(int pDeg in Degrees) { // loop over polynomial degrees
foreach(var grd in grids) { // loop over all grids
// create object and remember in list:
SipControl C = new SipControl();
Runs.Add(C);
// set polynomial degree and grid:
C.SetDGdegree(pDeg);
C.SetGrid(grd);
// specify RHS and exact solution (these are realized as initial values
// in the \code{ipPoisson} solver:
C.AddInitialValue("RHS", RHSfunc);
C.AddInitialValue("Tex", TexFunc);
// specify boundary condition:
C.AddBoundaryValue(BoundaryType.Dirichlet.ToString()); // for homogeneous
// boundary conditions, we don not need a value, since the default value
// zero is sufficient.
// the exact solution is a speciality of the SIP Poisson benchmark solver;
// in order to evaluate the exact solution, we have to set the following
// boolean:
C.ExactSolution_provided = true;
}
}
// -
// In the following, we check the correctness of the `Equals`-method for `SipControl`;
// This tutorial is part of the BoSSS test suit, the following is not required for the functionality of the example.
int NC = Runs.Count;
for(int i = 0; i < NC; i++) {
for(int j = 0; j < NC; j++) {
if(i == j)
Assert.IsTrue(Runs[i].Equals(Runs[j]), "Control is not self-equal");
else
Assert.IsFalse(Runs[i].Equals(Runs[j]), "Different Control are wrongly equal");
}
}
// ...and activate them:
// + dotnet_interactive={"language": "csharp"}
foreach(var C in Runs)
C.RunBatch(myBatch);
// -
// The following line ensures that all jobs are complete before
// post-processing analysis is started, although, there is a one-hour (3600-seconds )
// time-out.
// + dotnet_interactive={"language": "csharp"}
BoSSSshell.WorkflowMgm.BlockUntilAllJobsTerminate(3600*4);
// -
// Note that, in a larger production run study, where jobs may run days or
// weeks, blocking the worksheet is not really usefull.
// Instead, one might split process into two workseets
// (eactly at this line here), one for set-up and
// job sumbission and another one for the analysis.
// + dotnet_interactive={"language": "csharp"}
BoSSSshell.WorkflowMgm.AllJobs
// -
// We can take a closer inspection of anything that failed (should not be,
// anyway).
// + dotnet_interactive={"language": "csharp"}
foreach(var job in BoSSSshell.WorkflowMgm.AllJobs.Values) {
if(job.Status != JobStatus.FinishedSuccessful) {
Console.WriteLine("###############################################");
Console.WriteLine($"Job {job}");
Console.WriteLine("###############################################");
Console.WriteLine(job.Stdout);
Console.WriteLine("===============================================");
Console.WriteLine(job.Stderr);
Console.WriteLine("###############################################");
}
}
// -
//
// ## Convergence against exact solution
//
// As already noted, the computation of the $L^2$ error against the
// exact solution is handled specially in the **ipPoisson** solver.
// However, the following tutorial can serve as a general template of how to
// extract data from the session table and visualize it.
//
// We aquire a copy of the session table, and from all the columns in there...
//
// + dotnet_interactive={"language": "csharp"}
var Tab = BoSSSshell.WorkflowMgm.SessionTable;
// + dotnet_interactive={"language": "csharp"}
Tab.GetColumnNames().Take(7) // Take(7) is just to shorten the output. There are a total of 86 ColumnNames.
// -
// ...we extract those which sound interesting:
// + dotnet_interactive={"language": "csharp"}
Tab = Tab.ExtractColumns(
//"SessionName",
"DGdegree:T", "Grid:NoOfCells", "Grid:hMin", "DOFs",
//"ExactSolution_provided",
"SolL2err");
// + dotnet_interactive={"language": "csharp"}
Tab.Print();
// + [markdown] dotnet_interactive={"language": "csharp"}
//
// Note: the session table can also be exported, e.g. to Excel or
// Libre/Open Office Calc, by using the **ToCSVFile** function.
// + [markdown] dotnet_interactive={"language": "csharp"}
// The columns of the session table
// can be easily converted to a plot: the $x$-axis is determined
// by the cell width, the $y$-axis is determined by the $L^2$ error.
// Furthermore, we want to *group* our plots according
// to the DG degree, i.e. have one line for each polynomial degree;
// + dotnet_interactive={"language": "csharp"}
var ErrorPlot = Tab.ToPlot("Grid:hMin", "SolL2err", // column for x- and y
"DGdegree:T"); // column for group
// -
// We set logarithmic axes:
// + dotnet_interactive={"language": "csharp"}
ErrorPlot.LogX = true;
ErrorPlot.LogY = true;
// + dotnet_interactive={"language": "csharp"}
ErrorPlot.PlotNow()
// -
// Of course, we can adjust the plot styles:
// + dotnet_interactive={"language": "csharp"}
ErrorPlot.dataGroups[0].Format.PointType = PointTypes.Diamond;
ErrorPlot.dataGroups[1].Format.PointType = PointTypes.Box;
ErrorPlot.dataGroups[2].Format.PointType = PointTypes.LowerTriangle;
ErrorPlot.dataGroups[3].Format.PointType = PointTypes.Asterisk;
// + dotnet_interactive={"language": "csharp"}
foreach(var grp in ErrorPlot.dataGroups) {
grp.Format.PointSize = 0.8;
grp.Format.DashType = DashTypes.Dotted;
grp.Format.LineWidth = 2;
}
// + dotnet_interactive={"language": "csharp"}
ErrorPlot.PlotNow()
// -
// And we can compute the convergence order:
// + dotnet_interactive={"language": "csharp"}
ErrorPlot.Regression()
// + dotnet_interactive={"language": "csharp"}
/// BoSSScmdSilent
var reg1 = ErrorPlot.Regression();
double conv1 = reg1.Single(kv => kv.Key.Contains("T1")).Value;
double conv2 = reg1.Single(kv => kv.Key.Contains("T2")).Value;
double conv3 = reg1.Single(kv => kv.Key.Contains("T3")).Value;
double conv4 = reg1.Single(kv => kv.Key.Contains("T4")).Value;
Assert.IsTrue(Math.Abs(conv1 - (+2)) < 0.7, "experimental convergence failed on k = 1");
Assert.IsTrue(Math.Abs(conv2 - (+3)) < 0.7, "experimental convergence failed on k = 2");
Assert.IsTrue(Math.Abs(conv3 - (+4)) < 0.7, "experimental convergence failed on k = 3");
Assert.IsTrue(Math.Abs(conv4 - (+5)) < 0.7, "experimental convergence failed on k = 4");
// + [markdown] dotnet_interactive={"language": "csharp"}
//
// Note: these plots can also be exported to LaTeX, in a quality
// that is suitable for print publication:
// ```csharp
// ErrorPlot.ToGnuplot().PlotCairolatex().SaveTo("C:\\tmp\\errplt.tex");
// + dotnet_interactive={"language": "csharp"}
// + [markdown] dotnet_interactive={"language": "csharp"}
// ## experimental convergence plot
//
// If the exact solution is not known, one can only estimate the convergence
// behavior experimentally.
// **BoSSS** provides some utility for this, the **DGFieldComparison**
// class, which has a versatile, yet complex interface.
//
// However, there is a simple interface in the workflow management toolbox.
//
// We can augment the current session table with experimental errors:
// + dotnet_interactive={"language": "csharp"}
BoSSSshell.WorkflowMgm.hConvergence.Update();
// + dotnet_interactive={"language": "csharp"}
var Tab = BoSSSshell.WorkflowMgm.SessionTable;
// -
// We observe, that columns have been added to the session table,
// starting with a prefix **L2Error\_**
// + dotnet_interactive={"language": "csharp"}
Tab.GetColumnNames().Skip(46)
// + dotnet_interactive={"language": "csharp"}
Tab = Tab.ExtractColumns(
"DGdegree:T", "Grid:NoOfCells",
"SolL2err", "L2Error_T");
// -
// We observe that the \emph{experimental} $L^2$ error is approximately
// equal to the $L^2$ error against the exact solution,
// except for the highest resolutions. There, the error of the numerical
// solution is computed against itself, and thus the error is zero up
// to round-off errors.
//
// If we would like to extract convergence plots from this table, we need to
// exclude the rows with the finest solution using e.g. the
// **TableExtensions.ExtractRows** method.
// + dotnet_interactive={"language": "csharp"}
Tab.Print();
// -
// Rows could be extracted form a table using a selector function:
// this is an expression, which is true for all rows that we want to extract;
// + dotnet_interactive={"language": "csharp"}
Tab = Tab.ExtractRows(
(iRow, RowEntries) => Convert.ToInt32(RowEntries["Grid:NoOfCells"]) != 1024);
// + dotnet_interactive={"language": "csharp"}
Tab.Print();
// + [markdown] dotnet_interactive={"language": "csharp"}
// ## Working without the session table
//
// As an alternative to working with the session table, which is sometimes
// not versatile enough, we demonstrate a way to extract data
// from the sessions in the current project directly.
//
// Create a list in which we store a separate plot for each polynomial degree:
// + dotnet_interactive={"language": "csharp"}
var ExpPlotS = new List<Plot2Ddata>();
foreach(int pDeg in Degrees) { // loop over polynomial degrees
// extract sessions with DG degree pDeg
var pDegSessions = BoSSSshell.WorkflowMgm.Sessions.Where(
// function which is true on all sessions we are interested in:
Si => Convert.ToInt32(Si.KeysAndQueries["DGdegree:T"]) == pDeg
).ToArray();
// now, create a plot from the selected sessions:
// (we could also do other things)
Plot2Ddata pDegPlot =
pDegSessions.ToEstimatedGridConvergenceData("T",
xAxis_Is_hOrDof:false, // false selects DOFs for x-axis
normType:NormType.H1_approximate); // use the H1-Sobolev norm
// remember the freshly created plot object in a list:
ExpPlotS.Add(pDegPlot);
}
// -
// We adjust some plot style settings:
// + dotnet_interactive={"language": "csharp"}
ExpPlotS[0].dataGroups[0].Format.PointType = PointTypes.Diamond;
ExpPlotS[1].dataGroups[0].Format.PointType = PointTypes.Box;
ExpPlotS[2].dataGroups[0].Format.PointType = PointTypes.LowerTriangle;
ExpPlotS[3].dataGroups[0].Format.PointType = PointTypes.Asterisk;
ExpPlotS[0].dataGroups[0].Name = "$k = 1$";
ExpPlotS[1].dataGroups[0].Name = "$k = 2$";
ExpPlotS[2].dataGroups[0].Name = "$k = 3$";
ExpPlotS[3].dataGroups[0].Name = "$k = 4$";
foreach(var p in ExpPlotS) {
p.dataGroups[0].Format.PointSize = 0.8;
p.dataGroups[0].Format.DashType = DashTypes.Dotted;
p.dataGroups[0].Format.LineWidth = 2;
}
// -
// and we can merge all four plot objects into a singe one:
// + dotnet_interactive={"language": "csharp"}
var ExpPlot = ExpPlotS[0]; // select 0-th object
foreach(var p in ExpPlotS.Skip(1)) { // loop over other (skip 0-th entry)
ExpPlot = ExpPlot.Merge(p); // merge
}
// + dotnet_interactive={"language": "csharp"}
ExpPlot.PlotNow()
// -
// and we can also verify the slope of the error curves.
// Note that convergence order by using the $H^1$ norm is one degree lower
// compared to the $L^2$ norm..
// + dotnet_interactive={"language": "csharp"}
ExpPlot.Regression()
// + dotnet_interactive={"language": "csharp"}
/// BoSSScmdSilent
var regExp = ExpPlot.Regression();
double conv1 = regExp.Single(kv => kv.Key.Contains("1")).Value;
double conv2 = regExp.Single(kv => kv.Key.Contains("2")).Value;
double conv3 = regExp.Single(kv => kv.Key.Contains("3")).Value;
double conv4 = regExp.Single(kv => kv.Key.Contains("4")).Value;
Assert.IsTrue(Math.Abs(conv1 - (-1)) < 0.7, "experimental convergence failed on k = 1");
Assert.IsTrue(Math.Abs(conv2 - (-2)) < 0.7, "experimental convergence failed on k = 2");
Assert.IsTrue(Math.Abs(conv3 - (-3)) < 0.7, "experimental convergence failed on k = 3");
Assert.IsTrue(Math.Abs(conv4 - (-4)) < 0.7, "experimental convergence failed on k = 4");
// + [markdown] dotnet_interactive={"language": "csharp"}
// ## Multiplot demonstration
//
// If we have more than one plot object, we can arrange them in an array
// to realize multi-plots:
// + dotnet_interactive={"language": "csharp"}
var multiplot = new Plot2Ddata[2,2];
// + dotnet_interactive={"language": "csharp"}
multiplot[0,0] = ExpPlotS[0];
multiplot[0,1] = ExpPlotS[1];
multiplot[1,0] = ExpPlotS[2];
multiplot[1,1] = ExpPlotS[3];
// + [markdown] dotnet_interactive={"language": "csharp"}
// Now, we can draw an array of plots:
// + dotnet_interactive={"language": "csharp"}
multiplot.PlotNow()
// -
// this already looks neat, but a few
// formatting tweaks to make the multi-plot look nicer:
// + dotnet_interactive={"language": "csharp"}
multiplot[0,1].dataGroups[0].UseY2 = true; // label right on right column
multiplot[0,1].ShowYtics = false;
multiplot[0,1].ShowY2tics = true;
multiplot[1,1].dataGroups[0].UseY2 = true; // label right on right column
multiplot[1,1].ShowYtics = false;
multiplot[1,1].ShowY2tics = true;
multiplot[0,0].dataGroups[0].UseX2 = true; // label on top on top row
multiplot[0,0].ShowXtics = false;
multiplot[0,0].ShowX2tics = true;
multiplot[0,1].dataGroups[0].UseX2 = true; // label on top on top row
multiplot[0,1].ShowXtics = false;
multiplot[0,1].ShowX2tics = true;
// turn logarithm on for the secondary axis;
multiplot[0,0].LogX2 = true;
multiplot[0,1].LogX2 = true;
multiplot[1,0].LogX2 = true;
multiplot[1,1].LogX2 = true;
multiplot[0,0].LogY2 = true;
multiplot[0,1].LogY2 = true;
multiplot[1,0].LogY2 = true;
multiplot[1,1].LogY2 = true;
// set x ranges
multiplot[0,0].X2rangeMin = 1e0;
multiplot[0,0].X2rangeMax = 1e2;
multiplot[0,1].X2rangeMin = 1e0;
multiplot[0,1].X2rangeMax = 1e2;
multiplot[1,0].XrangeMin = 1e0;
multiplot[1,0].XrangeMax = 1e2;
multiplot[1,1].XrangeMin = 1e0;
multiplot[1,1].XrangeMax = 1e2;
// set y ranges
multiplot[0,0].YrangeMin = 1e-7;
multiplot[0,0].YrangeMax = 1e0;
multiplot[1,0].YrangeMin = 1e-7;
multiplot[1,0].YrangeMax = 1e0;
multiplot[0,1].Y2rangeMin = 1e-7;
multiplot[0,1].Y2rangeMax = 1e0;
multiplot[1,1].Y2rangeMin = 1e-7;
multiplot[1,1].Y2rangeMax = 1e0;
// reduce the whitespace in between the plots:
multiplot[0,0].rmargin = 2;
multiplot[0,1].lmargin = 2;
multiplot[1,0].rmargin = 2;
multiplot[1,1].lmargin = 2;
multiplot[0,0].bmargin = 0.5;
multiplot[1,0].tmargin = 0.5;
multiplot[0,1].bmargin = 0.5;
multiplot[1,1].tmargin = 0.5;
// + dotnet_interactive={"language": "csharp"}
multiplot.PlotNow()
// + [markdown] dotnet_interactive={"language": "csharp"}
// ## Summary
//
// This tutorial showed how to set-up a parameter study,
// by looping over a set of parameters (in this case, different grids
// and polynomial degrees), see sections about MeshCreation
// and about Setup-And-Execution.
// Finally, it only requires a simple loop to send all jobs to a
// compute resource.
//
// Afterwards, c.f. section about ExactConvergence,
// the **session table** was used to combine measurements
// taken in each session (here, the $L^2$ error against the exact solution)
// into a single table.
// This table can either be exported to spreadsheet analysis software
// or visualized internally.
// -
| doc/handbook/convergenceStudyTutorial/convStudy.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/jads-nl/intro-to-python/blob/develop/01_elements/02_exercises.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="FtYFqNo6Zz_0"
# # Chapter 1: Elements of a Program (Coding Exercises)
# + [markdown] id="o2SWZet1Zz_1"
# The exercises below assume that you have read the [first part <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/01_elements/00_content.ipynb) of Chapter 1.
#
# The `...`'s in the code cells indicate where you need to fill in code snippets. The number of `...`'s within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.
# + [markdown] id="WnYSWsUBZz_2"
# ## Simple `for`-loops
# + [markdown] id="mPUjTmmDZz_3"
# `for`-loops are extremely versatile in Python. That is different from many other programming languages.
#
# As shown in the first example in [Chapter 1 <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/01_elements/00_content.ipynb#Example:-Averaging-all-even-Numbers-in-a-List), we can create a `list` like `numbers` and loop over the numbers in it on a one-by-one basis.
# + id="glL2nwObZz_3"
numbers = [7, 11, 8, 5, 3, 12, 2, 6, 9, 10, 1, 4]
# + [markdown] id="KDgBo9OlZz_8"
# **Q1**: Fill in the *condition* of the `if` statement such that only numbers divisible by `3` are printed! Adjust the call of the [print() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#print) function such that the `for`-loop prints out all the numbers on *one* line of output!
# + id="PTJHTIEyZz_9"
for number in numbers:
if ...:
print(...)
# + [markdown] id="V5ki8MjOZz__"
# Instead of looping over an *existing* object referenced by a variable like `numbers`, we may also create a *new* object within the `for` statement and loop over it directly. For example, below we write out the `list` object as a *literal*.
#
# Generically, the objects contained in a `list` objects are referred to as its **elements**. We reflect that in the name of the *target* variable `element` that is assigned a different number in every iteration of the `for`-loop. While we could use *any* syntactically valid name, it is best to choose one that makes sense in the context (e.g., `number` in `numbers`).
#
# **Q2**: Fill in the condition of the `if` statement such that only numbers consisting of *one* digit are printed out! As before, print out all the numbers on *one* line of output!
# + id="48Bsv70xZ0AA"
for element in [7, 11, 8, 5, 3, 12, 2, 6, 9, 10, 1, 4]:
if ...:
print(...)
# + [markdown] id="Rne36wcWZ0AC"
# An easy way to loop over a `list` object in a sorted manner, is to wrap it with the built-in [sorted() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#sorted) function.
#
# **Q3**: Fill in the condition of the `if` statement such that only odd numbers are printed out! Put all the numbers on *one* line of output!
# + id="lVSsa_6SZ0AD"
for number in sorted(numbers):
if ...:
print(...)
# + [markdown] id="nzI33tDrZ0AG"
# Whenever we want to loop over numbers representing a [series <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1">](https://en.wikipedia.org/wiki/Series_%28mathematics%29) in the mathematical sense (i.e., a rule to calculate the next number from its predecessor), we may be able to use the [range() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#func-range) built-in.
#
# For example, to loop over the whole numbers from `0` to `9` (both including) in order, we could write them out in a `list` like below.
#
# **Q4**: Fill in the call to the [print() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#print) function such that all the numbers are printed on *one* line ouf output!
# + id="SoImdbEuZ0AG"
for number in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(...)
# + [markdown] id="B89KnggLZ0AJ"
# **Q5**: Read the documentation on the [range() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#func-range) built-in! It may be used with either one, two, or three expressions "passed" in. What do `start`, `stop`, and `step` mean? Fill in the calls to [range() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#func-range) and [print() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#print) to mimic the output of **Q4**!
# + id="p0X937yEZ0AJ"
for number in range(...):
print(...)
# + [markdown] id="yWaZfYw0Z0AN"
# **Q6**: Fill in the calls to [range() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#func-range) and [print() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#print) to print out *all* numbers from `1` to `10` (both including)!
# + id="l5ec50f5Z0AN"
for number in range(...):
print(...)
# + [markdown] id="Ny2ag4_jZ0AP"
# **Q7**: Fill in the calls to [range() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#func-range) and [print() <img height="12" style="display: inline-block" src="https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1">](https://docs.python.org/3/library/functions.html#print) to print out the *even* numbers from `1` to `10` (both including)! Do *not* use an `if` statement to accomplish this!
# + id="WTRMU8VgZ0AQ"
for number in range(...):
print(...)
| 01_elements/02_exercises.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Introduction
#
# This notebook includes
# - using a data generator to load data from a file structure
# - Example of the image augmentation
# - explanation of callback functions
# - Fitting the model
# - Analyzing the results
# - Saving the model
#
# # Importing libraries
# +
import tensorflow as tf
from tensorflow import keras
# Import libraries for preprocessing
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#Import other libraries
import numpy as np # nice library to work with data arrays and matrices
import itertools # loop optimizing tool. It creates itterators
import matplotlib.pyplot as plt # library for plotting graphs
# tell the plot to not open a seperate windows for each plot. # The % commands are called magic commands.
# %matplotlib inline
from PIL import Image # used for loading images
import os # used for navigating to image path. Os is generally for operating in the operation system (does not matter which one)
# -
# # Defining the **data preprocessing with ImageDataGenerator**
# We define the **ImageDataGenerator**, which later generates batches of augmented and standardized data as declared below.
#
# ***
#
#
# We try to explain the main features below in our own words, but you can also check the [official guide](https://keras.io/preprocessing/image/) as there are more features than here explained.
#
# Generally, the input data should be standardized. If you load all data at once, this has to be done separate. With the Data generator, this can happen on the fly within the data generator.
#
# - **rescale**
#
# In many tutorials you will find the point to rescale your images from 0-255 to 0 and 1 to merge the color resemblence of 255 differnet RGB combinations into a thight cheme between 0 and 1. The ImageDataGenerator can do that with the parameter `rescale=1./255.` or any other number. Rescale is applied after all the other augmentations.
#
#
#
#
# - **featurewise_center, samplewise_center**
#
# This parameters sets mean to zero. Together with the next parameter, those are the standard normalization steps which should be set to TRUE. Both reduce the optimization instability. Where 'samplewise' uses normalization within each image/data separate. Feature wise does this over the whole batch and is same as the known Batchnormalization.
# the difference is important to notice. Normally, each feature (e.g., temperature and body hight) are very different in their data range. Therefore we would like to normalize per feature, that the range for each feature does not intermix with other features.
#
# - **featurewise_std_normalization, samplewise_std_normalization**
#
# This parameters sets the standard derivation to 1. See also above
#
#
# - **zca_whitening**
#
# A whitening transform of an image is a linear algebra operation that reduces the redundancy in the matrix of pixel images.
#
# Less redundancy in the image is intended to better highlight the structures and features in the image to the learning algorithm.
#
# Typically, image whitening is performed using the Principal Component Analysis (PCA) technique. More recently, an alternative called sparce component analysis (ZCA) shows better results and results in transformed images that keeps all of the original dimensions and unlike PCA, resulting transformed images still look like their originals.
#
#
# - **width_shift_range=0.0, height_shift_range=0.0**
#
# As later real input data might not be always in the center of the image, you can apply random shift which randomly shifts images away from the center.
#
# The same principle holds for the following options:
# - **rotation_range**
# - **brightness_range**
# - **shear_range**
# - **zoom_range**
#
# All the above do not create new images but augment existing ones. You can save the augmented images to enlarge your dataset. This does not include using different background images. The saving can be done with the flow, flow_from_dataframe, or flow_from_directory command. We will get to this commands in a second.
#
# - **color_mode**
#
# It can be easier for a CNN to determine edges and recognize objects if the image is turned into a greyscale image. Therefore, it can be tried to use `color_mode='greyscale'` within flow, flow_from_dataframe, or flow_from_directory function. More of those functions later.
#
#
# - **preprocessing_function**
#
# If you want to use your own preprocessing function you can point to it with `preprocessing_function= yourfunction` The function will run after the image is resized and augmented. The function should take one argument: one image (Numpy tensor with rank 3), and should output a Numpy tensor with the same shape.
#
#
# - **validation_split**
#
# Important. The data you use have to be separated into train test sets for the model be able to update its weights without bias. You can either do that beforehand by sorting your data in train and test folders. But then the split is fixed. With this parameter you can split the data on the fly which is very handy if the data is all in one folder or loaded via a CSV file. the split is in percent so use a value between 0.0 and 1.
#
datagen =ImageDataGenerator(featurewise_center=True,
samplewise_center=False,
featurewise_std_normalization=True,
samplewise_std_normalization=False,
zca_whitening=False,
zca_epsilon=1e-06,
rotation_range=0.9,
width_shift_range=0.0,
height_shift_range=0.0,
brightness_range=None,
shear_range=0.0,
zoom_range=1.0,
channel_shift_range=0.0,
fill_mode='nearest',
cval=0.0,
horizontal_flip=False,
vertical_flip=False,
rescale=1./255.,
preprocessing_function=None,
data_format='channels_last',
validation_split=0.0)
# If you want to add your own function to alter the input images, you can follow [this guide](https://towardsdatascience.com/image-augmentation-for-deep-learning-using-keras-and-histogram-equalization-9329f6ae5085) (lower part of the page) or [this guide](https://jkjung-avt.github.io/keras-image-cropping/)
# ## Example
#
# Now lets try some image augmentations. Load a test image and use the ImageDataGenerator
# If you do not change the parameter data_format, the input should be of format: `(samples, height, width, channels)`
#
#
# <div class="alert alert-block alert-info">
# <b>Also important:</b>
#
# If you use flow_from_directory it is looking for at least one subdirectory in the root folder
#
# </div>
Test_image='./Data/Hands_orig_224_224/input/Train/' # singel images to show example
# +
batches =datagen.flow_from_directory(directory=Test_image, classes=['Faust', 'Offen'],
target_size=[224,224],
class_mode='categorical',
batch_size=1,
color_mode='rgb',
shuffle=False)
img_batch = next(batches)
display(img_batch[0].shape) # show the image shape
for i in range (0,1):
image = img_batch[i]#.transpose((2,1,3,0))
display(image.shape)
image=np.squeeze(image)
plt.imshow(image)
plt.show()
display(image.shape)
# image=np.squeeze(image, axis=3) # image=np.squeeze(image, axis=3)
# display(image.shape)
# plt.imshow(image,norm=NoNorm())
# plt.show()
# Load the image again to plot the original
idx = (batches.batch_index - 1) * batches.batch_size
print(batches.filenames[0])
im = Image.open(Test_image + batches.filenames[0])
pix = np.array(im)
plt.imshow(pix)
plt.show()
display(pix.shape)
# -
# ## Defining train and validation batches with flow functions
#
# After comparing the images, now create generator for train and validation data which is later needed to fit into the model.
# ***
#
# **Let's quickly check what the `flow` functions do:**
#
# Generally, the flow functions generate data on the fly.
#
# - **flow**
#
# if you have a small number of data which fits into your memory, then you can load all data at once and fit it into an numpy or pandas array. flow then calls an amount of data from that array to feed it to the model.
#
#
# - **flow_from_directory**
#
# this function reads the data from a directory. The directory expects at least one subfolder. The target are automatically named after the subfolders if not otherwise determined with `classes=['target1','target2']`
#
#
# - **flow_from_dataframe**
#
# This loads the data from a pandas dataframe (pandas is based on numpy). The datafram can be a transformed CSV file (quite common type). Within the CSV file the path has to be given to the file and the target.
#
# ***
#
# ### Parameters of the flow functions
#
# please also check the guides for [flow](https://keras.io/preprocessing/image/#flow), [flow_from_directory](https://keras.io/preprocessing/image/#flow_from_directory), and [flow_from_dataframe](https://keras.io/preprocessing/image/#flow_from_dataframe) as we will discuss only the main parameters here
#
#
# - **batch_size** Integer(default: 32)
#
# the batch size determines how many images are loaded at the same time. A batch size of 1 is called a minibatch. If you choose a minibatch, the gradient descent will be very fast as it is updated after every (very small) batch, but will mostly likely be more erratic as the direction of the gradient descent is based on only one example. If you choose the maximum size for the batch_size, which is the numbers of samples you have at hand (or fit into your memory), the gradient descent will be much slower but less erratic. Choosing something in between is suggested.
# We choose batch_size of 30 as we have a total of 180 training images at this point. If the batch_size does not fit into the amount of images ,images might be left out. For general data, this is not a problem as the last batch will just be smaller with padded values. To my knowledge that is not possible for images. I heard that it would be best to have the batch size as a multiple of 32 or 2^n. This is connected to the RAM-BUS operations which are based on 2^n. Using different sizes will reduce the efficiency of the system.
#
# - **class_mode**
#
# This is important depending on what is planned. If we have a binary problem use either `'binary'` or `'categorical'`. Categorical creates a [one-hot-encoded](https://hackernoon.com/what-is-one-hot-encoding-why-and-when-do-you-have-to-use-it-e3c6186d008f) target which is optimal to be handled by the model. `'input'` is used for generative adversarial Networks (GAN).
# If none is given, non is created. This can be used e.g. later for running inference without target information.
#
#
#
# - **shuffle** Boolean (default: True).
#
# to shuffle or not to shuffle. To increase generalization i would always choose shuffle true. Again, for time-series data using LSTMs this might not be advisable.
#
#
#
# - **sample_weight**
#
# If the data is heavily unbalanced, the unbalance can be tackled with sample eights. Increase the sample weights for the samples from the minority class. There are also other tricks to fight imbalance. but this is not the right place to talk about it.
#
#
# - **seed** Int (default: None)
#
# If you shuffle randomly but want to be able to recreate the shuffle use a number. Always use 42 for the obvious reason.
#
#
# - **save_to_dir**
#
# If you generate a lot of images they can be used to enlarge the dataset for later reuse. Or jsut to check on what data the model actually trained
#
#
# - **subset:**
#
# If you do not have a Train, validate structure from which you load the data, e.g., a CSV file with all files at once, you were able to determine the split earlier in the `ImageDataGenerator`. Now you can tell the flow what it is, a `'taining'` or `'validation'` batch generator.
#
#
#
# +
from tensorflow.keras.preprocessing.image import ImageDataGenerator
root_directory='./Data/Hands_orig_224_224/input/'
Tshape=[224,224]
train_batch_generator=ImageDataGenerator(rescale=1.0/255.0).flow_from_directory(root_directory + 'Train',
classes=['Faust', 'Offen'],
target_size=Tshape,
class_mode='categorical',
batch_size=20,
shuffle=True,
seed=42,
color_mode='rgb')
valid_batch_generator =ImageDataGenerator(rescale=1.0/255.0).flow_from_directory(root_directory + 'Test',
classes=['Faust', 'Offen'],
target_size=Tshape,
class_mode='categorical',
batch_size=10,
shuffle=True,
seed=42,
color_mode='rgb')
# -
# ## defining the model before we fit the data to the model
#
# Now it is time to talk about the model. Please check the jupyter file [Simple_CNN_model](http://localhost:8888/notebooks/Jupyter%20Notebook/Simple_CNN_model.ipynb) for explantions on the model structure and layers.
#
# +
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPool2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.regularizers import l1,l2,l1_l2
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.optimizers import SGD
#import libraries for model performance analysys
from tensorflow.keras.metrics import categorical_crossentropy
from sklearn.metrics import confusion_matrix
num_category=2
# img_width, img_height = 255, 170
# input_shape = (img_width, img_height, 3)
Ishape=[255,170,3]
#model building
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='elu', input_shape=Ishape))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.5, seed=42))
model.add(Conv2D(32, (3, 3), activation='elu',kernel_regularizer=l1_l2(0.01), activity_regularizer=l1_l2(0.1)))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.5, seed=42))
model.add(Conv2D(64, (3, 3), activation='elu',kernel_regularizer=l1_l2(0.01), activity_regularizer=l1_l2(0.1)))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.5, seed=42))
model.add(Conv2D(64, (3, 3), activation='elu',kernel_regularizer=l1_l2(0.01), activity_regularizer=l1_l2(0.1)))
model.add(BatchNormalization())
model.add(Dropout(0.5, seed=42))
model.add(Conv2D(128, (3, 3), activation='elu',kernel_regularizer=l1_l2(0.01), activity_regularizer=l1_l2(0.1)))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dense(128, activation='elu' ,kernel_regularizer=l1_l2(0.01), activity_regularizer=l1_l2(0.1)))
model.add(Dropout(0.5, seed=42))
model.add(Flatten())
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# -
# Instead of defining your model her you can also call other jupyter notebooks if you want to try different models
# +
# %run Simple_CNN_model.ipynb
model=sequential_CNN_Model(input_shape=Ishape,num_category=2)
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# -
# # Callback functions
#
# Callback functions can be used for multiple purposes.
#
# - Stopping your model when it does not improve anymore.
# - Save the best model automatically
# - Save history in CSV files
# - Reduce learning rate when a metric has stopped improving
# - ...
# - creating your own callback function defining what happens on_train_begin and on_batch_end
#
#
# +
import datetime, os
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks import EarlyStopping
logdir = ".\logs"
os.makedirs(logdir, exist_ok=True)
logdir = os.path.join(logdir, datetime.datetime.now().strftime("%d%m%Y-%H%M%S"))
modeldir = ".\models"
os.makedirs(modeldir, exist_ok=True)
filepath="models/" + datetime.datetime.now().strftime("%d%m%Y-%H%M%S") + "_modelchckpnt-{epoch:02d}-{val_accuracy:.2f}.hdf5"
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
Checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(filepath=filepath, monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=False,
mode='auto',
period=1)
stop_callback=keras.callbacks.EarlyStopping(monitor='val_loss',
min_delta=0,
patience=0,
restore_best_weights=True)
# -
# I prepared an own callbackfunction which is later explained to demonstrate how callback is set up
# # Fit function
# ## fit_generator
#
# the fit_generator function takes the previously defined model and fit the data to the model. The data is defined in the earlier `ImageDataGenerator` and generated via the `flow` functions.
#
# The guide can be found [here](https://keras.io/models/sequential/#fit_generator)
#
#
# `fit_generator(generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0)`
#
#
# ## Main parameters of fit_generator
#
#
# - **generator**
#
# Here we define which of the earlier defined generators is used to create the training data.
#
#
# - **steps_per_epoch** <font size="1"> credit to [Silpion](https://datascience.stackexchange.com/users/49704/silpion) </font>
#
# the default None is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined.
#
# The number of batch iterations before a training epoch is considered finished. If you have a training set of fixed size you can ignore it but it may be useful if you have a huge data set or if you are generating random data augmentations on the fly, i.e., if your training set has a (generated) infinite size. If you have the time to go through your whole training data set I recommend to skip this parameter.
#
# This parameter is most important when infinitive data is generated. Then the step size should be limited.
#
#
# - **validation_steps**
#
# similar to steps_per_epoch but on the validation data set instead on the training data. If you have the time to go through your whole validation data set I recommend to skip this parameter.
#
# - **verbose**
#
# you can set it to 1 or 2 if you want to see the training, otherwise 0
#
# - **callbacks**
#
# You can create own callback functions, or use [predefined ones ](https://keras.io/callbacks/)
#
#
#
# +
# %%time
step_size_train=train_batch_generator.n//train_batch_generator.batch_size
step_size_valid=valid_batch_generator.n//valid_batch_generator.batch_size
history=model.fit_generator(generator=train_batch_generator,
steps_per_epoch=step_size_train,
validation_data=valid_batch_generator,
epochs=3,
callbacks=[stop_callback,tensorboard_callback]
)
# -
# # Analyze the Results
# Open TensorBoard with `tensorboard --logdir= heregoesthePathtotheLogs`
# C:/Users/werth/Documents/GitHub/Workshop/logs
print(history.history.keys())
# +
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# -
# # Saving model
# ## as hdf5
#
# To save the model there are several steps possible.
#
# Generally you can use the callbackfunction `tf.keras.callbacks.ModelCheckpoint()` to save the best model of each run.
#
# alternatively the files can also be saved with the `tf.keras.models.save_model()` function.
# The model will be saved as a hdf5 file
#
# The saved model contains: - the model's configuration (topology) - the model's weights - the model's optimizer's state (if any).
#
# You can retreive the model weights with `model.load_weights(checkpoint_path)` and test the model (which has to have the same structure as the one from the saved model)as following:
#
# `loss,acc = model.evaluate(test_images, test_labels)`
#
# `print("Restored model, accuracy: {:5.2f}%".format(100*acc))`
#
# To save an entire model, just use: `model.save('my_model.h5')`
#
# This model can be simply loaded again for retraining, sending to your friends, using in inference. But hdf5 files are not optimized for inference runs. Faster are Tensorflow graphs (pb files). Therefore, we advice to save the model in pb format or transform the saved hdf5 file into a pb file later.
saved_model_path='./pb_models/'
pbModel=tf.contrib.saved_model.save_keras_model(model, saved_model_path)
# ## from hdf5 to pb (Protocol Buffers)
#
tf.saved_model(model,)
estimator_model = tf.keras.estimator.model_to_estimator(keras_model = model, model_dir = './models/estimatormodels')
# ## as pb (Protocol Buffers)
#
# [Alpha guide](https://www.tensorflow.org/api_docs/python/tf/contrib/saved_model/save_keras_model)
#
#
#
# A new way to save a model is by using tensorflow function `saved_model()` via Keras. This can change in the near future as it is in alpha state.
# Use:
# `saved_model_path = tf.contrib.saved_model.save_keras_model(model, "./saved_models")` To save your model.
#
# A SavedModel contains a complete TensorFlow program, including weights and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying (with TFLite, TensorFlow.js, TensorFlow Serving, or TFHub)
#
# Loading the model can be done via:
#
# `new_model = tf.contrib.saved_model.load_keras_model(saved_model_path)`
#
# `new_model.summary()`
#
# Then you have to compile the model again and can use evaluate to run inference in keras.
#
# From Guide:
#
#
# ---
#
# If the above **should not work** due to the alpha status, you can use the classic apporach via tensorflow:
#
# [Classic Tensorflow Guide](https://www.tensorflow.org/alpha/guide/saved_model)
#
# We can load the SavedModel back into Python with tf.saved_model.load. The model is imported as a dictionary named ["serving_default"]
#
# `loaded = tf.saved_model.load("modelpath")`
#
# `infer = loaded.signatures["serving_default"]`
#
# `labeling = infer(tf.constant(x))["reshape_2"]`
#
# `decoded = imagenet_labels[np.argsort(labeling)[0,::-1][:5]+1]` # :5 as example in the guide has five labels
#
#
#
saved_model_path = tf.contrib.saved_model.save_keras_model(model, "./saved_models")
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
| Deep learning using filestructure.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.9.7 64-bit (''conda-forge'': conda)'
# name: python3
# ---
# +
'''
Ref: https://plotly.com/python/figurewidget/
The github notebooks are simply too old (3 years+).
'''
import plotly.graph_objects as go
f = go.FigureWidget()
# -
f.add_scatter(y=[2, 1, 4, 3]);
f.add_bar(y=[1, 4, 3, 2]);
f
f.layout.title = 'Hello FigureWidget'
print(f)
# # Test with my own data
from IPython.display import display
import pandas as pd
df = pd.read_csv('../data/test_pred.csv')
display(df.columns)
trace = go.Scatter(x=df.found_helpful_percentage, y=df.pred_lstm2_untuned, \
mode='markers')
layout = go.Layout(title='Predicted Proportion of Positive Votes vs Truth')
figure = go.Figure(data=[trace], layout=layout)
f2 = go.FigureWidget(figure)
# +
'''
Ref: https://community.plotly.com/t/on-click-event-bar-chart-attributeerror-figureweidget-object-has-no-attribute-on-click/39294
'''
from ipywidgets import Output, VBox
out = Output()
@out.capture(clear_output=True)
def fetch_xy(trace, points, selector):
for i in points.point_inds:
df_sel = df[(df.found_helpful_percentage == perf_scatt.x[i]) & (df.pred_lstm2_untuned == perf_scatt.y[i])]
print(df_sel.iloc[0].review)
perf_scatt = f2.data[0]
perf_scatt.on_click(fetch_xy)
VBox([f2, out])
# +
import plotly.graph_objs as go
from ipywidgets import Output, VBox
fig = go.FigureWidget()
pie = fig.add_pie(values=[1, 2, 3])
pie2 = fig.data[0]
out = Output()
@out.capture(clear_output=True)
def handle_click(trace, points, state):
print(points.point_inds)
pie2.on_click(handle_click)
VBox([fig, out])
# -
| tests/figure_widget.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.9.2 64-bit
# name: python392jvsc74a57bd0aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49
# ---
# + [markdown] colab_type="text" id="EgiF12Hf1Dhs"
# **I recommend you run the first code cell of this notebook immediately, to start provisioning drake on the cloud machine, then you can leave this window open as you [read the textbook](manipulation.csail.mit.edu/pose.html).**
#
# # Notebook setup
#
# The following cell will:
# - on Colab (only), install Drake to `/opt/drake`, install Drake's prerequisites via `apt`, and add pydrake to `sys.path`. This will take approximately two minutes on the first time it runs (to provision the machine), but should only need to reinstall once every 12 hours. If you navigate between notebooks using Colab's "File->Open" menu, then you can avoid provisioning a separate machine for each notebook.
# - launch a server for our 3D visualizer (MeshCat) that will be used for the remainder of this notebook.
#
# You will need to rerun this cell if you restart the kernel, but it should be fast because the machine will already have drake installed.
# + colab={} colab_type="code" id="eeMrMI0-1Dhu"
import importlib
import sys
from urllib.request import urlretrieve
if 'google.colab' in sys.modules and importlib.util.find_spec('manipulation') is None:
urlretrieve(f"http://manipulation.csail.mit.edu/scripts/setup/setup_manipulation_colab.py",
"setup_manipulation_colab.py")
from setup_manipulation_colab import setup_manipulation
setup_manipulation(manipulation_sha='c1bdae733682f8a390f848bc6cb0dbbf9ea98602', drake_version='0.25.0', drake_build='releases')
from manipulation import running_as_notebook
# Setup rendering (with xvfb), if necessary:
import os
if 'google.colab' in sys.modules and os.getenv("DISPLAY") is None:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(1400, 900))
display.start()
# Start a single meshcat server instance to use for the remainder of this notebook.
from meshcat.servers.zmqserver import start_zmq_server_as_subprocess
server_args = []
if 'google.colab' in sys.modules:
server_args = ['--ngrok_http_tunnel']
proc, zmq_url, web_url = start_zmq_server_as_subprocess(server_args=server_args)
# Let's do all of our imports here, too.
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt, mpld3
import open3d
import pydot
from IPython.display import display, SVG, HTML
from pydrake.all import (
AddMultibodyPlantSceneGraph, BaseField, Box, ConnectMeshcatVisualizer, CsdpSolver,
DepthRenderCamera, RenderCameraCore, CameraInfo, ClippingRange, DepthRange,
DepthImageToPointCloud, DiagramBuilder, FindResourceOrThrow, FixedOffsetFrame,
ge, GeometryInstance, MakeRenderEngineVtk, MakePhongIllustrationProperties,
MathematicalProgram, MeshcatPointCloudVisualizer, Parser, RandomGenerator, RenderEngineVtkParams, RgbdSensor, RigidTransform,
RollPitchYaw, RotationMatrix, SpatialInertia, Solve, set_log_level, UniformlyRandomRotationMatrix, world_model_instance)
from pydrake.examples.manipulation_station import ManipulationStation
from manipulation.utils import FindResource
if running_as_notebook:
mpld3.enable_notebook()
# + [markdown] colab_type="text" id="7q0A14bAilIX"
# # Simulating an RGB-D camera
#
#
# + colab={} colab_type="code" id="ILYLouFTjv6e"
def DepthCameraDemoSystem():
builder = DiagramBuilder()
# Create the physics engine + scene graph.
plant, scene_graph = AddMultibodyPlantSceneGraph(builder, time_step=0.0)
# Add a single object into it.
X_Mustard = RigidTransform(RollPitchYaw(-np.pi/2., 0, -np.pi/2.), [0, 0, 0.09515])
parser = Parser(plant)
mustard = parser.AddModelFromFile(FindResourceOrThrow(
"drake/manipulation/models/ycb/sdf/006_mustard_bottle.sdf"))
plant.WeldFrames(plant.world_frame(),
plant.GetFrameByName("base_link_mustard", mustard),
X_Mustard)
# Add a rendering engine
renderer = "my_renderer"
scene_graph.AddRenderer(renderer,
MakeRenderEngineVtk(RenderEngineVtkParams()))
# Add a box for the camera in the environment.
X_Camera = RigidTransform(
RollPitchYaw(0, -0.2, 0.2).ToRotationMatrix().multiply(
RollPitchYaw(-np.pi/2.0, 0, np.pi/2.0).ToRotationMatrix()),
[.5, .1, .2])
camera_instance = parser.AddModelFromFile(FindResource("models/camera_box.sdf"))
camera = plant.GetBodyByName("base", camera_instance)
plant.WeldFrames(plant.world_frame(), camera.body_frame(), X_Camera)
plant.Finalize()
frames_to_draw = {"cameras": "camera"}
meshcat = ConnectMeshcatVisualizer(builder, scene_graph, zmq_url=zmq_url,
delete_prefix_on_load=False,
frames_to_draw=frames_to_draw)
meshcat.load()
depth_camera = DepthRenderCamera(RenderCameraCore(
renderer, CameraInfo(width=640, height=480, fov_y=np.pi / 4.0),
ClippingRange(near=0.1, far=10.0),
RigidTransform()),
DepthRange(0.1, 10.0))
camera = builder.AddSystem(
RgbdSensor(parent_id=plant.GetBodyFrameIdOrThrow(camera.index()),
X_PB=RigidTransform(),
depth_camera=depth_camera,
show_window=False))
camera.set_name("rgbd_sensor")
builder.Connect(scene_graph.get_query_output_port(),
camera.query_object_input_port())
# Export the camera outputs
builder.ExportOutput(camera.color_image_output_port(), "color_image")
builder.ExportOutput(camera.depth_image_32F_output_port(), "depth_image")
# Add a system to convert the camera output into a point cloud
to_point_cloud = builder.AddSystem(
DepthImageToPointCloud(camera_info=camera.depth_camera_info(),
fields=BaseField.kXYZs | BaseField.kRGBs))
builder.Connect(camera.depth_image_32F_output_port(),
to_point_cloud.depth_image_input_port())
builder.Connect(camera.color_image_output_port(),
to_point_cloud.color_image_input_port())
# Send the point cloud to meshcat for visualization, too.
meshcat_pointcloud = builder.AddSystem(MeshcatPointCloudVisualizer(meshcat, X_WP=X_Camera))
builder.Connect(to_point_cloud.point_cloud_output_port(), meshcat_pointcloud.get_input_port())
# Export the point cloud output.
builder.ExportOutput(to_point_cloud.point_cloud_output_port(),
"point_cloud")
diagram = builder.Build()
diagram.set_name("depth_camera_demo_system")
return diagram
# + colab={} colab_type="code" id="WCb1f0DmMUay" tags=[]
def plot_camera_images():
system = DepthCameraDemoSystem()
# Evaluate the camera output ports to get the images.
context = system.CreateDefaultContext()
system.Publish(context)
color_image = system.GetOutputPort("color_image").Eval(context)
depth_image = system.GetOutputPort("depth_image").Eval(context)
# Plot the two images.
plt.subplot(121)
plt.imshow(color_image.data)
plt.title('Color image')
plt.subplot(122)
plt.imshow(np.squeeze(depth_image.data))
plt.title('Depth image')
#mpld3.display()
plt.show()
plot_camera_images()
# + colab={} colab_type="code" id="Wya-_6_3MUa1" tags=[]
def draw_diagram():
system = DepthCameraDemoSystem()
display(SVG(pydot.graph_from_dot_data(system.GetGraphvizString(max_depth=1))[0].create_svg()))
draw_diagram()
# + colab={} colab_type="code" id="mFNDRsZ1MUa4" tags=[]
def plot_manipulation_station_camera_images():
station = ManipulationStation()
station.SetupManipulationClassStation()
# station.SetupClutterClearingStation()
station.Finalize()
context = station.CreateDefaultContext()
camera_names = station.get_camera_names()
index = 1
for name in camera_names:
color_image = station.GetOutputPort("camera_" + name +
"_rgb_image").Eval(context)
depth_image = station.GetOutputPort("camera_" + name +
"_depth_image").Eval(context)
plt.subplot(len(camera_names), 2, index)
plt.imshow(color_image.data)
index += 1
plt.title('Color image')
plt.subplot(len(camera_names), 2, index)
plt.imshow(np.squeeze(depth_image.data))
index += 1
plt.title('Depth image')
plt.show()
plot_manipulation_station_camera_images()
# + [markdown] colab_type="text" id="9QDyRMCyb_gL"
# # Point cloud registration with known correspondences
# + colab={} colab_type="code" id="vU_zEQJ_b1mv" tags=[]
def MakeRandomObjectModelAndScenePoints(
num_model_points=20,
noise_std=0,
num_outliers=0,
yaw_O=None,
p_O=None,
num_viewable_points=None,
seed=None):
""" Returns p_Om, p_s """
random_state = np.random.RandomState(seed)
# Make a random set of points to define our object in the x,y plane
theta = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_model_points)
l = 1.0 + 0.5*np.sin(2.0*theta) + 0.4*random_state.rand(1, num_model_points)
p_Om = np.vstack((l * np.sin(theta), l * np.cos(theta), 0 * l))
# Make a random object pose if one is not specified, and apply it to get the scene points.
if p_O is None:
p_O = [2.0*random_state.rand(), 2.0*random_state.rand(), 0.0]
if len(p_O) == 2:
p_O.append(0.0)
if yaw_O is None:
yaw_O = 0.5*random_state.random()
X_O = RigidTransform(RotationMatrix.MakeZRotation(yaw_O), p_O)
if num_viewable_points is None:
num_viewable_points = num_model_points
assert num_viewable_points <= num_model_points
p_s = X_O.multiply(p_Om[:,:num_viewable_points])
p_s[:2, :] += random_state.normal(scale=noise_std, size=(2, num_viewable_points))
if num_outliers:
outliers = random_state.uniform(low=-1.5, high=3.5, size=(3, num_outliers))
outliers[2,:] = 0
p_s = np.hstack((p_s, outliers))
return p_Om, p_s, X_O
def MakeRectangleModelAndScenePoints(
num_points_per_side=7,
noise_std=0,
num_outliers=0,
yaw_O=None,
p_O=None,
num_viewable_points=None,
seed=None):
random_state = np.random.RandomState(seed)
if p_O is None:
p_O = [2.0*random_state.rand(), 2.0*random_state.rand(), 0.0]
if len(p_O) == 2:
p_O.append(0.0)
if yaw_O is None:
yaw_O = 0.5*random_state.random()
X_O = RigidTransform(RotationMatrix.MakeZRotation(yaw_O), p_O)
if num_viewable_points is None:
num_viewable_points = 4*num_points_per_side
x = np.arange(-1, 1, 2/num_points_per_side)
half_width = 2
half_height = 1
top = np.vstack((half_width*x, half_height + 0*x))
right = np.vstack((half_width + 0*x, -half_height*x))
bottom = np.vstack((-half_width*x, -half_height + 0*x))
left = np.vstack((-half_width + 0*x, half_height*x))
p_Om = np.vstack((np.hstack((top, right, bottom, left)), np.zeros((1, 4*num_points_per_side))))
p_s = X_O.multiply(p_Om[:,:num_viewable_points])
p_s[:2, :] += random_state.normal(scale=noise_std, size=(2, num_viewable_points))
if num_outliers:
outliers = random_state.uniform(low=-1.5, high=3.5, size=(3, num_outliers))
outliers[2,:] = 0
p_s = np.hstack((p_s, outliers))
return p_Om, p_s, X_O
def PlotEstimate(p_Om, p_s, Xhat_O=RigidTransform(), chat=None, X_O=None, ax=None):
p_m = Xhat_O.multiply(p_Om)
if ax is None:
ax = plt.subplot()
Nm = p_Om.shape[1]
artists = ax.plot(p_m[0, :], p_m[1, :], 'bo')
artists += ax.fill(p_m[0, :], p_m[1, :], 'lightblue', alpha=0.5)
artists += ax.plot(p_s[0, :], p_s[1, :], 'ro')
if chat is not None:
artists += ax.plot(np.vstack((p_m[0, chat], p_s[0, :])), np.vstack((p_m[1, chat], p_s[1, :])), 'g--')
if X_O:
p_s = X_O.multiply(p_Om)
artists += ax.fill(p_s[0, :Nm], p_s[1, :Nm], 'lightsalmon')
ax.axis('equal')
return artists
def PrintResults(X_O, Xhat_O):
p = X_O.translation()
aa = X_O.rotation().ToAngleAxis()
print(f"True position: {p}")
print(f"True orientation: {aa}")
p = Xhat_O.translation()
aa = Xhat_O.rotation().ToAngleAxis()
print(f"Estimated position: {p}")
print(f"Estimated orientation: {aa}")
def PoseEstimationGivenCorrespondences(p_Om, p_s, chat):
""" Returns optimal X_O given the correspondences """
# Apply correspondences, and transpose data to support numpy broadcasting
p_Omc = p_Om[:, chat].T
p_s = p_s.T
# Calculate the central points
p_Ombar = p_Omc.mean(axis=0)
p_sbar = p_s.mean(axis=0)
# Calculate the "error" terms, and form the data matrix
merr = p_Omc - p_Ombar
serr = p_s - p_sbar
W = np.matmul(serr.T, merr)
# Compute R
U, Sigma, Vt = np.linalg.svd(W)
R = np.matmul(U, Vt)
if np.linalg.det(R) < 0:
print("fixing improper rotation")
Vt[-1, :] *= -1
R = np.matmul(U, Vt)
# Compute p
p = p_sbar - np.matmul(R, p_Ombar)
return RigidTransform(RotationMatrix(R), p)
p_Om, p_s, X_O = MakeRandomObjectModelAndScenePoints(num_model_points=20)
#p_Om, p_s, X_O = MakeRectangleModelAndScenePoints()
Xhat = RigidTransform()
c = range(p_Om.shape[1]) # perfect, known correspondences
fig, ax = plt.subplots(1, 2)
PlotEstimate(p_Om, p_s, Xhat, c, ax=ax[0])
Xhat = PoseEstimationGivenCorrespondences(p_Om, p_s, c)
ax[1].set_xlim(ax[0].get_xlim())
ax[1].set_ylim(ax[0].get_ylim());
PlotEstimate(p_Om, p_s, Xhat, c, ax=ax[1])
ax[0].set_title('Original Data')
ax[1].set_title('After Registration')
PrintResults(X_O, Xhat)
# + [markdown] colab_type="text" id="AHfxMwrvb1mz"
# # Iterative Closest Point (ICP)
# + colab={} colab_type="code" id="N2cYjTpub1m0" tags=[]
def FindClosestPoints(point_cloud_A, point_cloud_B):
"""
Finds the nearest (Euclidean) neighbor in point_cloud_B for each
point in point_cloud_A.
@param point_cloud_A A 3xN numpy array of points.
@param point_cloud_B A 3xN numpy array of points.
@return indices An (N, ) numpy array of the indices in point_cloud_B of each
point_cloud_A point's nearest neighbor.
"""
indices = np.empty(point_cloud_A.shape[1], dtype=int)
kdtree = open3d.geometry.KDTreeFlann(point_cloud_B)
for i in range(point_cloud_A.shape[1]):
nn = kdtree.search_knn_vector_3d(point_cloud_A[:,i], 1)
indices[i] = nn[1][0]
return indices
def IterativeClosestPoint(p_Om, p_s, X_O=None, animate=True):
Xhat = RigidTransform()
Nm = p_s.shape[1]
chat_previous = np.zeros(Nm)
fig, ax = plt.subplots()
frames = []
frames.append(PlotEstimate(p_Om=p_Om, p_s=p_s, Xhat_O=Xhat, chat=None, X_O=X_O, ax=ax))
while True:
chat = FindClosestPoints(p_s, Xhat.multiply(p_Om))
if np.array_equal(chat, chat_previous):
# Then I've converged.
break
chat_previous = chat
frames.append(PlotEstimate(p_Om=p_Om, p_s=p_s, Xhat_O=Xhat, chat=chat, X_O=X_O, ax=ax))
Xhat = PoseEstimationGivenCorrespondences(p_Om, p_s, chat)
frames.append(PlotEstimate(p_Om=p_Om, p_s=p_s, Xhat_O=Xhat, chat=None, X_O=X_O, ax=ax))
ani = animation.ArtistAnimation(fig, frames, interval=400, repeat=False)
display(HTML(ani.to_jshtml()))
plt.close()
if X_O:
PrintResults(X_O, Xhat)
return Xhat, chat
p_Om, p_s, X_O = MakeRandomObjectModelAndScenePoints(num_model_points=20)
IterativeClosestPoint(p_Om, p_s, X_O);
# + [markdown] colab_type="text" id="WLMLxAJJb1m2"
# Try increasing the standard deviation on yaw in the example above. At some point, the performance can get pretty poor!
#
# # ICP with messy point clouds
#
# Try changing the amount of noise, the number of outliers, and/or the partial views. There are not particularly good theorems here, but I hope that a little bit of play will get you a lot of intuition.
# + tags=[]
#p_Om, p_s, X_O = MakeRandomObjectModelAndScenePoints(
p_Om, p_s, X_O = MakeRectangleModelAndScenePoints(
yaw_O=0.1,
# noise_std=0.2,
# num_outliers=3,
num_viewable_points=14)
IterativeClosestPoint(p_Om, p_s, X_O);
# -
# # Non-penetration of a half-plane with convex optimization
# + tags=[]
def ConstrainedPoseEstimationGivenCorrespondences(p_Om, p_s, chat):
""" This version adds a non-penetration constraint (x,y >= 0) """
p_Omc = p_Om[:2, chat]
p_s = p_s[:2, :]
Ns = p_s.shape[1]
prog = MathematicalProgram()
[a,b] = prog.NewContinuousVariables(2)
# We use the slack variable as an upper bound on the cost of each point to make the objective linear.
slack = prog.NewContinuousVariables(Ns)
p = prog.NewContinuousVariables(2)
prog.AddBoundingBoxConstraint(0,1,[a,b]) # This makes Csdp happier
R = np.array([[a, -b],[b, a]])
prog.AddLorentzConeConstraint([1.0, a, b])
# Note: Could do this more efficiently, exploiting trace. But I'm keeping it simpler here.
prog.AddCost(np.sum(slack))
for i in range(Ns):
c = p + np.matmul(R,p_Omc[:,i]) - p_s[:,i]
# forall i, slack[i]^2 >= |c|^2
prog.AddLorentzConeConstraint([slack[i], c[0], c[1]])
# forall i, p + R*mi >= 0.
prog.AddConstraint(ge(p + np.matmul(R, p_Omc[:,i]), [0, 0]))
result = CsdpSolver().Solve(prog)
[a,b] = result.GetSolution([a,b])
Rsol = np.array([[a, -b, 0],[b, a, 0], [0,0,1]])
psol = np.zeros(3)
psol[:2] = result.GetSolution(p)
return RigidTransform(RotationMatrix(Rsol), psol)
p_Om, p_s, X_O = MakeRectangleModelAndScenePoints(
yaw_O=0.2,
p_O = [1.5, 1.2],
)
c = range(p_Om.shape[1]) # perfect, known correspondences
Xhat_O = ConstrainedPoseEstimationGivenCorrespondences(p_Om, p_s, c)
PlotEstimate(p_Om=p_Om, p_s=p_s, Xhat_O=Xhat_O, chat=c, X_O=X_O)
PrintResults(X_O, Xhat_O)
plt.gca().plot([0,0], [0, 2.5], 'g-', linewidth=3)
plt.gca().plot([0,4], [0, 0], 'g-', linewidth=3);
# -
| pose.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
import zipfile
import csv
import requests
def get_data():
return csv.DictReader((x for x in open("data/trim_fac/FacEneMar2020.csv",encoding = "utf-8-sig")), delimiter=";",)
def get_ratings():
return get_data()
def get_book_features():
return get_data()
# +
import json
from itertools import islice
ratings = get_data()
# -
for line in islice(ratings, 2):
print(json.dumps(line, indent=4))
# +
from lightfm.data import Dataset
dataset = Dataset()
dataset.fit((x['NIT'] for x in get_ratings()),
(x['ARTCOD'] for x in get_ratings()))
# -
num_users, num_items = dataset.interactions_shape()
print('Num users: {}, num_items {}.'.format(num_users, num_items))
# +
(interactions, weights) = dataset.build_interactions(((x['NIT'], x['ARTCOD'],float(x['NUM_VECES_COMP']))
for x in get_ratings()))
print(repr(interactions))
print(repr(weights))
# -
print(interactions)
print(weights)
# +
from lightfm import LightFM
model = LightFM(loss='bpr')
model.fit(weights)
# +
from lightfm.evaluation import precision_at_k
from lightfm.evaluation import auc_score
train_precision = precision_at_k(model, weights, k=3).mean()
print('Precision: train %.2f' % (train_precision))
# +
import os
import zipfile
import csv
dict_csv1 = csv.DictReader((x for x in open("data/NcAbr2020.csv",encoding = "utf-8-sig")), delimiter=";",)
dict_csv2 = csv.DictReader((x for x in open("data/FacAgo2020_f.csv",encoding = "utf-8-sig")), delimiter=";",)
# +
import json
from itertools import islice
for line in islice(dict_csv1, 2):
print(json.dumps(line, indent=4))
# +
from lightfm.data import Dataset
dataset = Dataset()
dataset.fit((x['User-ID'] for x in dict_csv1),
(x['PRODUCT-ID'] for x in dict_csv1))
# -
num_users, num_items = dataset1.interactions_shape()
print('Num users: {}, num_items {}.'.format(num_users, num_items))
(print(x) for x in dict_csv1)
| pruebaDS28abril.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
#
# +
import datetime, os, pathlib, platform, pprint, sys
import fastai
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sdv
import sklearn
import yellowbrick as yb
from fastai.tabular.data import TabularDataLoaders, TabularPandas
from fastai.tabular.all import FillMissing, Categorify, Normalize, tabular_learner, accuracy, ClassificationInterpretation, ShowGraphCallback, RandomSplitter, range_of
from sdv.tabular import TVAE
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from yellowbrick.model_selection import CVScores, LearningCurve, ValidationCurve
seed: int = 14
# set up pretty printer for easier data evaluation
pretty = pprint.PrettyPrinter(indent=4, width=30).pprint
# set up pandas display options
pd.set_option('display.max_colwidth', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 100)
# print library and python versions for reproducibility
print(
f'''
Last Execution: {datetime.datetime.now()}
python:\t{platform.python_version()}
\tfastai:\t\t{fastai.__version__}
\tmatplotlib:\t{mpl.__version__}
\tnumpy:\t\t{np.__version__}
\tpandas:\t\t{pd.__version__}
\tseaborn:\t{sns.__version__}
\tsdv:\t\t{sdv.__version__}
\tsklearn:\t{sklearn.__version__}
\tyellowbrick:\t{yb.__version__}
'''
)
# +
def get_file_path(directory: str):
'''
Closure that will return a function.
Function will return the filepath to the directory given to the closure
'''
def func(file: str) -> str:
return os.path.join(directory, file)
return func
def load_data(filePath):
'''
Loads the Dataset from the given filepath and caches it for quick access in the future
Function will only work when filepath is a .csv file
'''
p = pathlib.Path(filePath)
filePathClean: str = str(p.parts[-1])
pickleDump: str = f'./cache/{filePathClean}.pickle'
print(f'Loading Dataset: {filePath}')
print(f'\tTo Dataset Cache: {pickleDump}\n')
# check if data already exists within cache
if os.path.exists(pickleDump):
df = pd.read_pickle(pickleDump)
# if not, load data and clean it before caching it
else:
df = pd.read_csv(filePath, low_memory=True)
df.to_pickle(pickleDump)
return df
def features_with_bad_values(df: pd.DataFrame, datasetName: str) -> pd.DataFrame:
'''
Function will scan the dataframe for features with Inf, NaN, or Zero values.
Returns a new dataframe describing the distribution of these values in the original dataframe
'''
# Inf and NaN values can take different forms so we screen for every one of them
invalid_values: list = [ np.inf, np.nan, 'Infinity', 'inf', 'NaN', 'nan', 0 ]
infs : list = [ np.inf, 'Infinity', 'inf' ]
NaNs : list = [ np.nan, 'NaN', 'nan' ]
# We will collect stats on the dataset, specifically how many instances of Infs, NaNs, and 0s are present.
# using a dictionary that will be converted into a (3, 2+88) dataframe
stats: dict = {
'Dataset':[ datasetName, datasetName, datasetName ],
'Value' :['Inf', 'NaN', 'Zero']
}
i = 0
for col in df.columns:
i += 1
feature = np.zeros(3)
for value in invalid_values:
if value in infs:
j = 0
elif value in NaNs:
j = 1
else:
j = 2
indexNames = df[df[col] == value].index
if not indexNames.empty:
feature[j] += len(indexNames)
stats[col] = feature
return pd.DataFrame(stats)
def clean_data(df: pd.DataFrame, prune: list) -> pd.DataFrame:
'''
Function will take a dataframe and remove the columns that match a value in prune
Inf values will also be removed from Flow Bytes/s and Flow Packets/s
once appropriate rows and columns have been removed, we will return
the dataframe with the appropriate values
'''
# remove the features in the prune list
for col in prune:
if col in df.columns:
df.drop(columns=[col], inplace=True)
# drop missing values/NaN etc.
df.dropna(inplace=True)
# Search through dataframe for any Infinite or NaN values in various forms that were not picked up previously
invalid_values: list = [
np.inf, np.nan, 'Infinity', 'inf', 'NaN', 'nan'
]
for col in df.columns:
for value in invalid_values:
indexNames = df[df[col] == value].index
if not indexNames.empty:
print(f'deleting {len(indexNames)} rows with Infinity in column {col}')
df.drop(indexNames, inplace=True)
return df
# -
class SklearnWrapper(BaseEstimator):
'''
A wrapper for fastai learners for creating visualizations using yellowbrick
code sourced from:
forums.fast.ai/t/fastai-with-yellowbrics-how-to-get-roc-curves-more/79408
'''
_estimator_type = "classifier"
def __init__(self, model):
self.model = model
self.classes_ = list(self.model.dls.y.unique())
def fit(self, X, y):
pass
def score(self, X, y):
return accuracy_score(y, self.predict(X))
def get_new_preds(self, X):
new_to = self.model.dls.valid_ds.new(X)
new_to.conts = new_to.conts.astype(np.float32)
new_dl = self.model.dls.valid.new(new_to)
with self.model.no_bar():
preds,_,dec_preds = self.model.get_preds(dl=new_dl, with_decoded=True)
return (preds, dec_preds)
def predict_proba(self, X):
return self.get_new_preds(X)[0].numpy()
def predict(self, X):
return self.get_new_preds(X)[1].numpy()
# +
# This code is used to scale to processing numerous datasets
data_path_1: str = './phase1/'
data_path_2: str = './synthetic/vae/'
data_set_1: list = [ 'Darknet_reduced_features.csv' ]
data_set_2: list = [
'vae_balanced_traffic_dataset_1_all_labels.csv',
'vae_balanced_traffic_dataset_2_traffic_labels.csv',
'vae_balanced_traffic_dataset_3_traffic_3_labels.csv',
]
file_path_1 = get_file_path(data_path_1)
file_path_2 = get_file_path(data_path_2)
file_set_1 : list = list(map(file_path_1, data_set_1))
file_set_2 : list = list(map(file_path_2, data_set_2))
file_set : list = file_set_1 + file_set_2
data_set : list = data_set_1 + data_set_2
current_job: int = 0
# +
def examine_dataset(job_id: int) -> dict:
'''
Function will return a dictionary containing dataframe of the job_id passed in as well as that dataframe's
feature stats, data composition, and file name.
This dictionary is expected as the input for all of the other helper functions
'''
job_id = job_id - 1 # adjusts for indexing while enumerating jobs from 1
print(f'Dataset {job_id+1}/{len(data_set)}: We now look at {file_set[job_id]}\n\n')
# Load the dataset
df: pd.DataFrame = load_data(file_set[job_id])
# print the data composition
print(f'''
File:\t\t\t\t{file_set[job_id]}
Job Number:\t\t\t{job_id+1}
Shape:\t\t\t\t{df.shape}
Samples:\t\t\t{df.shape[0]}
Features:\t\t\t{df.shape[1]}
''')
# return the dataframe and the feature stats
data_summary: dict = {
'File': file_set[job_id],
'Dataset': df,
'Feature_stats': features_with_bad_values(df, file_set[job_id]),
}
return data_summary
# +
def package_data_for_inspection(df: pd.DataFrame) -> dict:
'''
Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats.
'''
# print the data composition
print(f'''
Dataset statistics:
Shape:\t\t\t\t{df.shape}
Samples:\t\t\t{df.shape[0]}
Features:\t\t\t{df.shape[1]}
''')
# return the dataframe and the feature stats
data_summary: dict = {
'File': '',
'Dataset': df,
'Feature_stats': features_with_bad_values(df, ''),
}
return data_summary
def package_data_for_inspection_with_label(df: pd.DataFrame, label: str) -> dict:
'''
Function will return a dictionary containing dataframe passed in as well as that dataframe's feature stats.
'''
# print the data composition
print(f'''
Shape:\t\t\t\t{df.shape}
Samples:\t\t\t{df.shape[0]}
Features:\t\t\t{df.shape[1]}
''')
# return the dataframe and the feature stats
data_summary: dict = {
'File': f'{label}',
'Dataset': df,
'Feature_stats': features_with_bad_values(df, f'{label}'),
}
return data_summary
def check_infs(data_summary: dict) -> pd.DataFrame:
'''
Function will return a dataframe of features with a value of Inf.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
inf_df = vals[vals['Value'] == 'Inf'].T
return inf_df[inf_df[0] != 0]
def check_nans(data_summary: dict) -> pd.DataFrame:
'''
Function will return a dataframe of features with a value of NaN.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
nan_df = vals[vals['Value'] == 'NaN'].T
return nan_df[nan_df[1] != 0]
def check_zeros(data_summary: dict) -> pd.DataFrame:
'''
Function will return a dataframe of features with a value of 0.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
zero_df = vals[vals['Value'] == 'Zero'].T
return zero_df[zero_df[2] != 0]
def check_zeros_over_threshold(data_summary: dict, threshold: int) -> pd.DataFrame:
'''
Function will return a dataframe of features with a value of 0.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
zero_df = vals[vals['Value'] == 'Zero'].T
zero_df_bottom = zero_df[2:]
return zero_df_bottom[zero_df_bottom[2] > threshold]
def check_zeros_over_threshold_percentage(data_summary: dict, threshold: float) -> pd.DataFrame:
'''
Function will return a dataframe of features with all features with
a frequency of 0 values greater than the threshold
'''
vals: pd.DataFrame = data_summary['Feature_stats']
size: int = data_summary['Dataset'].shape[0]
zero_df = vals[vals['Value'] == 'Zero'].T
zero_df_bottom = zero_df[2:]
return zero_df_bottom[zero_df_bottom[2] > threshold*size]
def remove_infs_and_nans(data_summary: dict) -> pd.DataFrame:
'''
Function will return the dataset with all inf and nan values removed.
'''
df: pd.DataFrame = data_summary['Dataset'].copy()
df = clean_data(df, [])
return df
def rename_columns(data_summary: dict, columns: list, new_names: list) -> dict:
'''
Function will return the data_summary dict with the names of the columns in the dataframe changed
'''
df: pd.DataFrame = data_summary['Dataset'].copy()
for x, i in enumerate(columns):
df.rename(columns={i: new_names[x]}, inplace=True)
data_summary['Dataset'] = df
return data_summary
def rename_values_in_column(data_summary: dict, replace: list) -> pd.DataFrame:
'''
Function will return a dataframe with the names of the columns changed
replace: [('column', {'old_name': 'new_name', ...}), ...]
'''
length: int = len(replace)
df: pd.DataFrame = data_summary['Dataset'].copy()
for i in range(length):
df[replace[i][0]].replace(replace[i][1], inplace=True)
return df
def prune_dataset(data_summary: dict, prune: list) -> pd.DataFrame:
'''
Function will return the dataset with all the columns in the prune list removed.
'''
df: pd.DataFrame = data_summary['Dataset'].copy()
df = clean_data(df, prune)
return df
def create_new_prune_candidates(zeros_df: pd.DataFrame) -> list:
'''
Function creates a list of prune candidates from a dataframe of features with a high frequency of 0 values
'''
return list(zeros_df.T.columns)
def intersection_of_prune_candidates(pruneCandidates: list, newPruneCandidates: list) -> list:
'''
Function will return a list of features that are in both pruneCandidates and newPruneCandidates
'''
return list(set(pruneCandidates).intersection(newPruneCandidates))
def test_infs(data_summary: dict) -> bool:
'''
Function asserts the dataset has no inf values.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
inf_df = vals[vals['Value'] == 'Inf'].T
assert inf_df[inf_df[0] != 0].shape[0] == 2, 'Dataset has inf values'
return True
def test_nans(data_summary: dict) -> bool:
'''
Function asserts the dataset has no NaN values
'''
vals: pd.DataFrame = data_summary['Feature_stats']
nan_df = vals[vals['Value'] == 'NaN'].T
assert nan_df[nan_df[1] != 0].shape[0] == 2, 'Dataset has NaN values'
return True
def test_pruned(data_summary: dict, prune: list) -> bool:
'''
Function asserts the dataset has none of the columns present in the prune list
'''
pruned: bool = True
for col in prune:
if col in data_summary['Dataset'].columns:
pruned = False
assert pruned, 'Dataset has columns present in prune list'
return pruned
def test_pruned_size(data_summary_original: dict, data_summary_pruned: dict, prune: list) -> bool:
'''
Function asserts the dataset has none of the columns present in the prune list
'''
original_size: int = data_summary_original['Dataset'].shape[1]
pruned_size: int = data_summary_pruned['Dataset'].shape[1]
prune_list_size: int = len(prune)
assert original_size - prune_list_size == pruned_size, 'Dataset has columns present in prune list'
return True
# -
def run_deep_nn_experiment(df: pd.DataFrame, name: str, target_label: str, shape: tuple) -> tuple:
'''
Run binary classification on a given dataframe, saving the model as {name}.model
returns the 7-tuple with the following indicies:
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
# First we split the features into the dependent variable and
# continous and categorical features
dep_var: str = target_label
assert len(shape) == 2, 'Shape must be a tuple of length 2'
categorical_features: list = []
# categorical_features: list = ['Application Type']
print(df.shape)
if 'Protocol' in df.columns:
categorical_features.append("Protocol")
continuous_features = list(set(df) - set(categorical_features) - set([dep_var]))
# Next, we set up the feature engineering pipeline, namely filling missing values
# encoding categorical features, and normalizing the continuous features
# all within a pipeline to prevent the normalization from leaking details
# about the test sets through the normalized mapping of the training sets
procs = [FillMissing, Categorify, Normalize]
splits = RandomSplitter(valid_pct=0.2, seed=seed)(range_of(df))
# The dataframe is loaded into a fastai datastructure now that
# the feature engineering pipeline has been set up
to = TabularPandas(
df , y_names=dep_var ,
splits=splits , cat_names=categorical_features ,
procs=procs , cont_names=continuous_features ,
)
# The dataframe is then converted into a fastai dataset
dls = to.dataloaders(bs=64)
# extract the name from the path
p = pathlib.Path(name)
name: str = str(p.parts[-1])
# Next, we set up, train, and save the deep neural network
model = tabular_learner(dls, layers=[100, 60], metrics=accuracy, cbs=ShowGraphCallback)
model.fit_one_cycle(10)
model.save(f'{name}.model')
model._description = f'fastai_{name}_model'
# We print the results of the training
loss, acc = model.validate()
print('loss {}: accuracy: {:.2f}%'.format(loss, acc*100))
# A confusion matrix is created to help evaluate the results
interp = ClassificationInterpretation.from_learner(model)
interp.plot_confusion_matrix()
# We extract the training and test datasets from the dataframe
X_train = to.train.xs.reset_index(drop=True)
X_test = to.valid.xs.reset_index(drop=True)
y_train = to.train.ys.values.ravel()
y_test = to.valid.ys.values.ravel()
# We wrap our model to make it look like a scikitlearn model
# for visualization using yellowbrick
wrapped_model = SklearnWrapper(model)
wrapped_model._description = f'wrapped_{name}_model'
# we add a target_type_ attribute to our model so yellowbrick knows how to make the visualizations
classes = list(model.dls.vocab)
if len(classes) == 2:
wrapped_model.target_type_ = 'binary'
elif len(classes) > 2:
wrapped_model.target_type_ = 'multiclass'
else:
print('Must be more than one class to perform classification')
raise ValueError('Wrong number of classes')
wrapped_model._target_labels = dep_var
# Now that the classifier has been created and trained, we pass out our training values
# so that yellowbrick can use them to create various visualizations
viz_data: tuple = (name, wrapped_model, classes, X_train, y_train, X_test, y_test)
return viz_data
# +
def visualize_confusion_matrix(viz_data: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a confusion matrix
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ConfusionMatrix(viz_data[1], classes=viz_data[2], title=viz_data[0])
visualizer.score(viz_data[5], viz_data[6])
visualizer.show()
def visualize_roc(viz_data: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a
Receiver Operating Characteristic (ROC) Curve
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ROCAUC(viz_data[1], classes=viz_data[2], title=viz_data[0])
visualizer.score(viz_data[5], viz_data[6])
visualizer.poof()
def visualize_pr_curve(viz_data: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a
Precision-Recall Curve
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.PrecisionRecallCurve(viz_data[1], title=viz_data[0])
visualizer.score(viz_data[5], viz_data[6])
visualizer.poof()
def visualize_report(viz_data: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a report
detailing the Precision, Recall, f1, and Support scores for all
classification outcomes
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.classifier.ClassificationReport(viz_data[1], classes=viz_data[2], title=viz_data[0], support=True)
visualizer.score(viz_data[5], viz_data[6])
visualizer.poof()
def visualize_class_balance(viz_data: tuple) -> None:
'''
Takes a 7-tuple from the run_experiments function and creates a histogram
detailing the balance between classification outcomes
viz_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
visualizer = yb.target.ClassBalance(labels=viz_data[0])
visualizer.fit(viz_data[4], viz_data[6])
visualizer.show()
def confusion_matrix_from_dataset(model_data: tuple, df: pd.DataFrame) -> None:
'''
Takes a 7-tuple from the run_experiments function and uses the model to classify
the data passed in as the dataframe. Produces a confusion matrix
model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test)
'''
dl = model_data[1].model.dls.test_dl(df, bs=64)
preds, v, dec_preds = model_data[1].model.get_preds(dl=dl, with_decoded=True)
visualizer = yb.classifier.ConfusionMatrix(model_data[1], classes=model_data[2], title=model_data[0])
visualizer.score(dl.xs, dl.y)
visualizer.show()
acc = accuracy_score(dl.y, dec_preds)
print(f'Accuracy: {acc}')
# -
print(f'We will be cleaning {len(file_set)} files:')
pretty(file_set)
# +
dataset_1 : dict = examine_dataset(1)
fake_dataset_1: dict = examine_dataset(4)
traffic_dataset_1: dict = package_data_for_inspection_with_label(
prune_dataset(dataset_1, ['Application Type']),
'Traffic_Dataset_1_Tor_VPN_Non_Tor_NonVPN'
)
traffic_dataset_2: dict = package_data_for_inspection_with_label(
rename_values_in_column(traffic_dataset_1, [('Traffic Type', {'Non-Tor': 'Regular', 'NonVPN': 'Regular'})]),
'Traffic_Dataset_2_Tor_VPN_Regular'
)
# -
traffic_dataset_2['Results'] = run_deep_nn_experiment(
traffic_dataset_2['Dataset'],
traffic_dataset_2['File'],
'Traffic Type',
(100, 80)
)
fake_dataset_1['Results'] = run_deep_nn_experiment(
fake_dataset_1['Dataset'],
fake_dataset_1['File'],
'Traffic Type',
(100, 80)
)
confusion_matrix_from_dataset(traffic_dataset_2['Results'], fake_dataset_1['Dataset'])
confusion_matrix_from_dataset(fake_dataset_1['Results'], traffic_dataset_2['Dataset'])
print(f'Last Execution: {datetime.datetime.now()}')
assert False, 'Nothing after this point is included in the study'
| Data/basic_vae_tests.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
from bigbang.archive import Archive
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# One interesting question for open source communities is whether they are *growing*. Often the founding members of a community would like to see new participants join and become active in the community. This is important for community longevity; ultimatley new members are required to take leadership roles if a project is to sustain itself over time.
#
# The data available for community participation is very granular, as it can include the exact traces of the messages sent by participants over a long history. One way of summarizing this information to get a sense of overall community growth is a *cohort visualization*.
#
# In this notebook, we will produce a visualization of changing participation over time.
url = "6lo"
arx = Archive(url,archive_dir="../archives")
arx.data[:1]
# Archive objects have a method that reports for each user how many emails they sent each day.
act = arx.get_activity()
# This plot will show when each sender sent their first post. A slow ascent means a period where many people joined.
# +
fig = plt.figure(figsize=(12.5, 7.5))
#act.idxmax().order().T.plot()
(act > 0).idxmax().order().plot()
fig.axes[0].yaxis_date()
# -
# This is the same data, but plotted as a histogram. It's easier to see the trends here.
# +
fig = plt.figure(figsize=(12.5, 7.5))
(act > 0).idxmax().order().hist()
fig.axes[0].xaxis_date()
# -
# While this is interesting, what if we are interested in how much different "cohorts" of participants stick around and continue to participate in the community over time?
#
# What we want to do is divide the participants into N cohorts based on the percentile of when they joined the mailing list. I.e, the first 1/N people to participate in the mailing list are the first cohort. The second 1/N people are in the second cohort. And so on.
#
# Then we can combine the activities of each cohort and do a stackplot of how each cohort has participated over time.
n = 5
# +
from bigbang import plot
# A series, indexed by users, of the day of their first post
# This series is ordered by time
first_post = (act > 0).idxmax().order()
# Splitting the previous series into five equal parts,
# each representing a chronological quintile of list members
cohorts = np.array_split(first_post,n)
cohorts = [list(c.keys()) for c in cohorts]
plot.stack(act,partition=cohorts,smooth=10)
# -
# This gives us a sense of when new members are taking the lead in the community. But what if the old members are just changing their email addresses? To test that case, we should clean our data with entity resolution techniques.
cohorts[1].index.values
| examples/experimental_notebooks/Cohort Visualization.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Table of Conetents
# - [Example Starts Here](#example_starts_here)
# - [init_db()](#init_db)
# - [insert_hist_data(), query_hist_data()](#insert_query_hist_data)
# - [download_insert_hist_data()](#download_insert_hist_data)
# - [get_hist_data()](#get_hist_data)
# Prepare environment
import os, sys
sys.path.insert(0, os.path.abspath('..'))
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from io import StringIO
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
# +
gs1h_csv = StringIO("""
Symbol,DataType,BarSize,TickerTime,opening,high,low,closing,volume,barcount,average
GS,TRADES,1h,2017-09-05 12:00:00+00:00,224.5,224.5,223.98,223.98,23,18,224.302
GS,TRADES,1h,2017-09-05 13:00:00+00:00,224.25,224.25,220.01,220.39,6431,3782,221.423
GS,TRADES,1h,2017-09-05 14:00:00+00:00,220.39,220.7,217.3,218.12,11332,5881,218.82
GS,TRADES,1h,2017-09-05 15:00:00+00:00,218.09,219.64,218.07,219.45,6457,3843,218.795
GS,TRADES,1h,2017-09-05 16:00:00+00:00,219.45,219.46,218.11,218.67,4940,3550,218.633
GS,TRADES,1h,2017-09-05 17:00:00+00:00,218.72,219.19,218.13,218.73,3228,2527,218.657
GS,TRADES,1h,2017-09-05 18:00:00+00:00,218.72,218.86,217.62,217.67,4939,3219,218.285
GS,TRADES,1h,2017-09-05 19:00:00+00:00,217.68,218.3,217.46,217.85,8173,5594,217.747
GS,TRADES,1h,2017-09-05 20:00:00+00:00,217.79,218.85,217.78,217.92,2445,10,217.781
GS,TRADES,1h,2017-09-05 21:00:00+00:00,218.0,218.11,217.91,218.11,8,5,218.022
GS,TRADES,1h,2017-09-05 22:00:00+00:00,218.11,218.17,217.95,217.95,15,11,218.12
GS,TRADES,1h,2017-09-05 23:00:00+00:00,218.15,218.15,217.93,217.93,2,2,218.04
GS,TRADES,1h,2017-09-06 12:00:00+00:00,218.97,219.29,218.97,219.2,28,11,219.159
GS,TRADES,1h,2017-09-06 13:00:00+00:00,219.1,220.78,218.67,219.58,4729,2596,219.796
GS,TRADES,1h,2017-09-06 14:00:00+00:00,219.61,221.02,219.54,220.01,4451,2722,220.49
GS,TRADES,1h,2017-09-06 15:00:00+00:00,219.98,220.2,217.73,218.2,4222,2500,219.02
GS,TRADES,1h,2017-09-06 16:00:00+00:00,218.2,219.83,217.61,219.8,2680,1809,218.335
GS,TRADES,1h,2017-09-06 17:00:00+00:00,219.77,220.5,219.41,219.57,2470,1492,219.954
GS,TRADES,1h,2017-09-06 18:00:00+00:00,219.61,219.8,218.9,219.33,2127,1447,219.428
GS,TRADES,1h,2017-09-06 19:00:00+00:00,219.33,219.7,218.85,219.05,5587,3451,219.363
GS,TRADES,1h,2017-09-06 20:00:00+00:00,218.83,219.09,218.83,218.99,3634,6,218.83
GS,TRADES,1h,2017-09-06 21:00:00+00:00,218.98,218.98,218.98,218.98,2,1,218.98
GS,TRADES,1h,2017-09-06 22:00:00+00:00,218.7,218.7,218.7,218.7,1,1,218.7
GS,TRADES,1h,2017-09-06 23:00:00+00:00,218.69,218.7,218.69,218.7,8,2,218.696
GS,TRADES,1h,2017-09-07 11:00:00+00:00,219.0,219.0,219.0,219.0,1,1,219.0
GS,TRADES,1h,2017-09-07 12:00:00+00:00,219.21,219.4,218.5,218.5,31,16,219.015
GS,TRADES,1h,2017-09-07 13:00:00+00:00,218.57,218.83,216.07,216.31,3338,1726,217.503
GS,TRADES,1h,2017-09-07 14:00:00+00:00,216.35,216.35,214.64,215.77,7048,4299,215.392
GS,TRADES,1h,2017-09-07 15:00:00+00:00,215.74,216.41,214.96,215.28,4571,3190,215.666
GS,TRADES,1h,2017-09-07 16:00:00+00:00,215.24,216.28,215.06,216.07,2191,1541,215.518
GS,TRADES,1h,2017-09-07 17:00:00+00:00,216.04,216.41,215.26,215.6,2058,1495,215.708
GS,TRADES,1h,2017-09-07 18:00:00+00:00,215.58,215.74,215.25,215.37,2206,1509,215.428
GS,TRADES,1h,2017-09-07 19:00:00+00:00,215.4,215.94,214.95,215.83,6582,4149,215.313
GS,TRADES,1h,2017-09-07 20:00:00+00:00,215.84,216.88,215.8,216.02,1869,9,215.846
GS,TRADES,1h,2017-09-07 21:00:00+00:00,215.98,215.98,215.9,215.9,9,6,215.927
GS,TRADES,1h,2017-09-07 22:00:00+00:00,215.9,215.99,215.9,215.99,14,3,215.909
GS,TRADES,1h,2017-09-07 23:00:00+00:00,216.09,216.09,216.09,216.09,1,1,216.09
GS,TRADES,1h,2017-09-08 11:00:00+00:00,215.44,215.44,215.44,215.44,1,1,215.44
GS,TRADES,1h,2017-09-08 12:00:00+00:00,214.9,215.5,214.8,215.5,22,8,215.05
GS,TRADES,1h,2017-09-08 13:00:00+00:00,215.5,218.76,215.1,218.67,5788,3250,217.577
GS,TRADES,1h,2017-09-08 14:00:00+00:00,218.68,219.28,217.78,218.04,4696,3283,218.707
GS,TRADES,1h,2017-09-08 15:00:00+00:00,218.06,218.39,216.82,216.89,2574,1880,217.345
GS,TRADES,1h,2017-09-08 16:00:00+00:00,216.92,217.3,216.67,217.14,2049,1433,217.015
GS,TRADES,1h,2017-09-08 17:00:00+00:00,217.12,217.17,216.15,216.76,2254,1565,216.591
GS,TRADES,1h,2017-09-08 18:00:00+00:00,216.76,217.35,216.61,217.01,1921,1373,217.117
GS,TRADES,1h,2017-09-08 19:00:00+00:00,217.01,217.34,216.69,217.24,3980,2789,217.075
GS,TRADES,1h,2017-09-08 20:00:00+00:00,217.21,217.21,216.71,216.71,2222,6,217.209
GS,TRADES,1h,2017-09-08 21:00:00+00:00,217.0,217.0,217.0,217.0,2,1,217.0
GS,TRADES,1h,2017-09-08 22:00:00+00:00,216.46,216.8,216.46,216.8,3,2,216.698
GS,TRADES,1h,2017-09-08 23:00:00+00:00,216.8,216.8,216.8,216.8,0,0,216.8
""")
gs1h = pd.read_csv(gs1h_csv)
# -
# <a id='example_starts_here'></a>
#
# ## Example starts here
# ------
import pytz
import asyncio
import aiomysql.sa as aiosa
from sqlalchemy import create_engine, MetaData
from ibstract import IB
from ibstract import MarketDataBlock
from ibstract import HistDataReq
from ibstract import init_db, insert_hist_data, query_hist_data
from ibstract import download_insert_hist_data
from ibstract import get_hist_data
from ibstract.utils import dtest
# <a id='init_db'></a>
# ### `init_db()` : Initialize MySQL database by creating one table for each security type.
db_info = {
'host': '127.0.0.1',
'user': 'root',
'password': '<PASSWORD>',
'db': 'ibstract_test',
}
init_db(db_info)
engine = create_engine(
"mysql+pymysql://{}:{}@{}/{}".format(
db_info['user'], db_info['password'], db_info['host'], db_info['db']),
echo=False)
meta = MetaData()
meta.reflect(bind=engine)
print("Tables in Ibstract MySQL database:")
list(meta.tables.keys())
print("Columns in Stock table:")
meta.tables['Stock'].columns.values()
# <a id='insert_query_hist_data'></a>
# ### Coroutines `insert_hist_data()`, `query_hist_data()` : Insert / Read MarketDataBlock() to/from MySQL database
# The MarketDataBlock() to be inserted.
blk_gs1h = MarketDataBlock(gs1h)
blk_gs1h.tz_convert('US/Eastern')
blk_gs1h.df.head()
# +
async def run(loop, blk):
engine = await aiosa.create_engine(
user=db_info['user'], db=db_info['db'],
host=db_info['host'], password=db_info['password'],
loop=loop, echo=False)
await insert_hist_data(engine, 'Stock', blk)
data = await query_hist_data(engine, 'Stock', 'GS', 'TRADES', '1h',
dtest(2017, 9, 6, 10), dtest(2017, 9, 6, 14),)
engine.close()
await engine.wait_closed()
return data
loop = asyncio.get_event_loop()
blk_readback = loop.run_until_complete(run(loop, blk_gs1h))
blk_readback.df
# -
# <a id='download_insert_hist_data'></a>
# ### Coroutine `download_insert_hist_data()` : Download historical data and insert part of them to MySQL database
# +
# Clear Stock table
engine.execute(meta.tables['Stock'].delete())
# A user coroutine to download historical data and insert to MySQL database
async def run(loop, req, broker, insert_limit):
engine = await aiosa.create_engine(
user=db_info['user'], db=db_info['db'],
host=db_info['host'], password=db_info['password'],
loop=loop, echo=False)
blk_download = await download_insert_hist_data(
req, broker, engine, insert_limit)
blk_readback = await query_hist_data(
engine, req.SecType, req.Symbol, req.DataType, req.BarSize,
start=dtest(2017, 8, 1), end=dtest(2017, 10, 1))
engine.close()
await engine.wait_closed()
return blk_download, blk_readback
# Arguments
req = HistDataReq('Stock', 'GS', '1d', '5d', dtest(2017, 9, 7))
broker = IB('127.0.0.1', 4002)
insert_limit = (dtest(2017, 8, 31), dtest(2017, 9, 5)) # Only insert partial data between (SQL inclusive) 8/31 and 9/5
# Run loop
loop = asyncio.get_event_loop()
blk_download, blk_readback = loop.run_until_complete(
run(loop, req, broker, insert_limit))
blk_download.df
blk_readback.df
# -
# <a id='get_hist_data'></a>
# ### Coroutine `get_hist_data()` : Try to query data from local MySQL database. If any part is not found, download and insert back to MySQL all missing parts concurrently and asynchronously.
#
#
# #### `get_hist_data()` executes in these steps:
# 1. Try to query historical data from local MySQL for the input user request.
# 2. Determine missing data parts and corresponding start-end date/time gaps. Create multiple HistDataReq() requests for these gaps.
# 3. Concurrently download these requests from broker API.
# 4. Concurrently combine downloaded data pieces with the data from local MySQL data block.
# 5. Return the combined data per the input user request.
# +
# Use data above
blk_gs_3days = blk_readback
# Clear Stock table
engine.execute(meta.tables['Stock'].delete())
# Populate database with some data
async def populate_db(blk_db):
engine = await aiosa.create_engine(
user=db_info['user'], db=db_info['db'],
host=db_info['host'], password=<PASSWORD>['password'],
loop=loop, echo=False)
await insert_hist_data(engine, 'Stock', blk_db)
data_exist_in_db = await query_hist_data(engine, 'Stock', 'GS', 'TRADES', '1d',
dtest(2017,1,1),dtest(2017,12,31))
engine.close()
await engine.wait_closed()
return data_exist_in_db
# Insert and query local MySQL database
loop = asyncio.get_event_loop()
blk_db = loop.run_until_complete(populate_db(blk_gs_3days))
blk_db.df
# +
# A user coroutine to get wider range of historical data than those existing in MySQL.
# Data existing in MySQL will not be downloaded, but combined with downloaded data.
async def run(req, broker, loop):
blk_ret = await get_hist_data(req, broker, mysql={**db_info, 'loop': loop})
return blk_ret
# Request daily data of 8 days, from 8/29 - 9/8.
# Data from 8/31 - 9/5 exist in local database and will not be downloaded.
req = HistDataReq('Stock', 'GS', '1d', '8d', dtest(2017, 9, 9))
broker = IB('127.0.0.1', 4002)
loop = asyncio.get_event_loop()
blk_ret = loop.run_until_complete(run(req, broker, loop))
blk_ret.df
| examples/example_histdata.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Q1. 데이터를 클래스와 객체로 나타내세요.
# 타율을 계산하는 함수를 추가
# 객체를 만들어서 각 선수의 타율(안타/타석)을 출력해주세요.
# 타율은 소수 3째자리까지 출력 (round)
# - a1_player - 476타석, 176안타
# - a2_player - 8975타, 6503안타
class Player:
def __init__(self, bb, hit):
self.bb = bb
self.hit = hit
def avg(self):
return round(self.hit/self.bb, 3)
a1_player = Player(476, 305)
a2_player = Player(8975, 6503)
a1_player.avg(), a2_player.avg()
# ---------------
#
# Q2. 학생의 국어, 영어, 수학 점수를 입력받아서 총점과 평균을 구하는 클래스를 만드세요.
# - 학생 한명이 하나의 객체
# - 두가지 방법
# - 생성자 함수에서 국어, 영어, 수학를 받도록 코드 작성
# - 생성자 함수에서 과목의 갯수 제한 없이 데이터 받도록 코드 작성
# 방법 1
class Student:
def __init__(self, korean, english, math):
self.korean = korean
self.english = english
self.math = math
def total(self):
return self.korean + self.english + self.math
def avg(self):
return round(self.total() / 3, 2)
s1 = Student(98, 87, 78)
s1.total(), s1.avg()
# 방법 2
class Student:
def __init__(self, **kwargs):
self.datas = kwargs
def total(self):
return sum(self.datas.values())
def avg(self):
return round(self.total()/len(self.datas), 2)
s2 = Student(korean=54, english=87, math=77,science=87)
s2.total(), s2.avg()
# -------------
#
# Q3. 상속을 이용해서 아이폰 버전 1 ~ 3까지의 클래스를 작성해주세요.
# - 기능들은 print(기능이름)로 출력이 되도록 함수내용을 작성
# - iPhone_1 : calling
# - iPhone_2 : calling, send_msg
# - iPhone_3 : calling, send_msg, internet
# +
class Iphone1:
def calling(self):
print("calling")
class Iphone2(Iphone1):
def send_msg(self):
print("send_msg")
class Iphone3(Iphone2):
def internet(self):
print("internet")
# -
iphone1 = Iphone1()
iphone2 = Iphone2()
iphone3 = Iphone3()
def show_func(obj):
return [var for var in dir(obj) if var[:2] != "__"]
show_func(iphone1), show_func(iphone2), show_func(iphone3)
# -----------
#
# Q4. Starcraft Unit
# - Wizard, Warrior
# - wizard 공격력 10~50, 체력 100
# - warrior 공격력 20~30, 체력 120
# - 공격 기능과 상태 확인 기능
# +
import random
class Unit:
def attack(self, obj):
attack_pow = random.randint(self.min_attack_pow, self.max_attack_pow)
obj.health -= attack_pow
obj.health = 0 if obj.health < 0 else obj.health
print("{} 공격력 {}로 공격!".format(self.cls, attack_pow))
print("{} 남은 체력:{}".format(obj.cls, obj.health))
return obj.health
def disp(self):
print("클래스:{}, 체력:{}, 최소공격력:{}, 최대공격력:{}".format(self.cls, self.health, self.min_attack_pow, self.max_attack_pow))
class Wizard(Unit):
def __init__(self):
self.cls = "Wizard"
self.health = 100
self.min_attack_pow = 10
self.max_attack_pow = 50
class Warrior(Unit):
def __init__(self):
self.cls = "Warrior"
self.health = 120
self.min_attack_pow = 20
self.max_attack_pow = 30
# +
team1 = [Wizard(), Wizard(), Wizard(),]
team2 = [Warrior(), Warrior(), Warrior(), Warrior(),]
def fight(team1, team2):
turn = 0
while team1 and team2:
turn += 1
print("\n턴:{}".format(turn))
print("남은 유닛: 팀1:{}, 팀2:{}".format(len(team1), len(team2)))
print("team1 턴")
health = team1[0].attack(team2[0])
if health == 0 :
del team2[0]
continue
print("team2 턴")
health = team2[0].attack(team1[0])
if health == 0 :
del team1[0]
continue
result = "team1 승리" if len(team1) > len(team2) else "team2 승리"
print("\n결과:{}".format(result))
print("남은 유닛: 팀1:{}, 팀2:{}".format(len(team1), len(team2)))
# -
fight(team1, team2)
| quiz/quiz_02_class.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + init_cell=true slideshow={"slide_type": "skip"}
from jupyter_plotly_dash import JupyterDash
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# + init_cell=true slideshow={"slide_type": "skip"}
from IPython.display import HTML
import random
# #!jupyter nbextension enable init_cell/main
def hide_toggle(for_next=False):
this_cell = """$('div.cell.code_cell.rendered.selected')"""
next_cell = this_cell + '.next()'
toggle_text = 'Toggle show/hide' # text shown on toggle link
target_cell = this_cell # target cell to control with toggle
js_hide_current = '' # bit of JS to permanently hide code in current cell (only when toggling next cell)
if for_next:
target_cell = next_cell
toggle_text += ' next cell'
js_hide_current = this_cell + '.find("div.input").hide();'
js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))
html = """
<script>
function {f_name}() {{
{cell_selector}.find('div.input').toggle();
}}
{js_hide_current}
</script>
<a href="javascript:{f_name}()">{toggle_text}</a>
""".format(
f_name=js_f_name,
cell_selector=target_cell,
js_hide_current=js_hide_current,
toggle_text=toggle_text
)
return HTML(html)
# + [markdown] slideshow={"slide_type": "slide"}
# # Dash app in a presentation
# + init_cell=true slideshow={"slide_type": "skip"} tags=["hide_input"]
app = JupyterDash('SimpleExample')
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
hide_toggle(for_next=True)
# + init_cell=true slideshow={"slide_type": "slide"}
app
| dash_rise.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Processing handwritten equation with OpenCV
import numpy as np
import tensorflow as tf
import cv2 as cv
import matplotlib.pyplot as plt
from datetime import datetime
image = cv.imread('sevenplusthree.png')
image_working_copy = image.copy()
plt.imshow(image)
imgray = cv.cvtColor(image_working_copy, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 100, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
plt.imshow(thresh, cmap = 'gray')
# +
image_with_contours = cv.drawContours(image_working_copy, contours, -1, (0,255,0), 3)
plt.imshow(image_with_contours)
# -
def find_contours(path):
"""
Finds all contours in a given picture.
Args:
path (str): path to image
Returns:
contours: Detected contours. Each contour is stored as a vector of points.
hierarchy: Optional output vector, containing information about the image topology.
"""
img = cv.imread(path)
imgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 100, 255, 0)
return cv.findContours(
thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
contours, hierarchy = find_contours('sevenplusthree.png')
# create list of tuples
boundingRects = [cv.boundingRect(contour) for contour in contours]
# sort list of tuples by first element (which is x coordinate), that way we get bounding boxes in right order
boundingRects.sort()
# +
#check
boundingRects = boundingRects[1:]
boundingRects
# -
boundingRects[1]
(x, y, w, h) = (189, 75, 106, 100)
rect_img = cv.rectangle(image_working_copy, (x-10, y-10), (x+w+10, y+h+10), (255, 0, 0), 3)
plt.imshow(rect_img)
def overlapping_axes(coord1, delta1, coord2, delta2):
"""Checks wether 2 bounding boxes overlap over given axes
Args:
coord1 (int): start coordinate of axes for first bounding box
delta1 (int): size of first bounding box along axes
coord2 (int): coordinate of start axes for second bounding box
delta2 (int): size of second bounding box along axes
Returns:
bool: true if they overlap else false
"""
if coord1 <= coord2 + delta2 and coord1 >= coord2:
return True
if coord1 + delta1 <= coord2 + delta2 and coord1 + delta1 >= coord2:
return True
if coord2 <= coord1 + delta1 and coord2 >= coord1:
return True
if coord2 + delta2 <= coord1 + delta1 and coord2 + delta2 >= coord1:
return True
return False
def remove_overlapping_bounding_boxes(boundingRects):
"""Finds all contours and chooses ones that best contour given characters.
Args:
boundingRects (list): list of bounding boxes to check and remove if overlapping
Returns:
list: list of bounding boxes for filtered contours
"""
# If 2 bounding boxes are overlapping, take the bigger one
for i in range(len(boundingRects)):
if boundingRects[i] is None:
continue
for j in range(i + 1, len(boundingRects)):
if boundingRects[j] is None:
continue
x1, y1, width1, height1 = boundingRects[i]
x2, y2, width2, height2 = boundingRects[j]
if overlapping_axes(x1, width1, x2, width2) and overlapping_axes(y1, height1, y2, height2):
if width1 * height1 > width2 * height2:
boundingRects[j] = None
else:
boundingRects[i] = None
break
return [bounding for bounding in boundingRects if bounding is not None]
def crop_bounding_box(image, bounding_boxes):
"""Crops images given their bounding boxes
Args:
image (np.ndarray): np.ndarray representation of the image
bounding_boxes (list): bounding box to be used for cropping
Returns:
np.ndarray: np.ndarray representation of the cropped image
"""
cropped_images = list()
for i in range(0, len(bounding_boxes)):
x, y, w, h = bounding_boxes[i]
cropped_image = image[(y-10):(y+h+10), (x-10):(x+w+10)]
cropped_images.append(cropped_image)
return cropped_images
cropped_imgs = crop_bounding_box(image, boundingRects)
plt.imshow(cropped_imgs[2])
# +
# define a function that will resize images to predetermined standard size, which is 150x150 in our case
def resize_images(images_list, pixels_height = 150, pixels_width = 150):
"""This function resizes all images in the given input list to desired
pixels height and pixels width.
Args:
images_list (list): List of images in .
pixels_height (int): Desired height of the resized image in pixels.
pixels_width (int): Desired width of the resized image in pixels.
Returns:
resized_imgs (list): List of resized images.
"""
resized_imgs = []
for image in images_list:
try:
resized_image = cv.resize(image, (pixels_height, pixels_width))
resized_imgs.append(resized_image)
except:
break
return resized_imgs
# -
resized_images = resize_images(cropped_imgs)
def plot_imgs(imgs_list):
"""This function plots images from a list on a grid.
Args:
imgs_list (list): List of images.
"""
imgs_no = len(imgs_list)
img_count = 0
fig, axes = plt.subplots(nrows = 1, ncols = imgs_no, figsize = (10,10))
for i in range(imgs_no):
if img_count <= imgs_no:
axes[i].imshow(imgs_list[img_count])
img_count+=1
# +
resized_images_array = np.array(resized_images)
# check for expected output
resized_images_array.shape
# -
plt.imshow(resized_images[2])
def save_array(numpy_array):
"""This function saves numpy array to a .npy file.
Args:
numpy_array (ndarray): Array to save in the form of .npy file.
"""
np.save(r'output\output_array_{}.npy'.format(datetime.now().strftime("%d_%m_%Y_%H%M%S")), numpy_array)
save_array(resized_images_array)
# +
"""define a pipeline function that takes all necessary steps to proceess handwritten equation picture
and prepares it for model prediction"""
def equation_image_preprocess_pipeline(image_path):
print('Processing started!')
image = cv.imread(image_path)
# find all conours in a given picture
print('Extracting contours from the image!...')
contours, hierarchy = find_contours(image_path)
print('Contours extracted!...')
# create list of bounding boxes (list of tuples)
print('Creating bounding boxes around contours!...')
boundingBoxes = [cv.boundingRect(contour) for contour in contours]
# sort list of bounding boxes by first element of tuples (which is x coordinate)
boundingBoxes.sort()
# drop first element (bounding box that frames whole image)
boundingBoxes = boundingBoxes[1:]
# remove overlapping bounding boxes
boundingBoxes_filtered = remove_overlapping_bounding_boxes(boundingBoxes)
print('Bounding boxes created!...')
# crop images given their bounding boxes
print('Cropping images!...')
cropped_imgs = crop_bounding_box(image, boundingBoxes_filtered)
# resize images to right size for prediction
resized_imgs = resize_images(cropped_imgs)
print('Images resized to right format!...')
# plot resized images
print('Plotting images!...')
plot_imgs(resized_imgs)
# create an numpy array of resized images
resized_imgs_array = np.array(resized_imgs)
# save numpy array to a .npy file
save_array(resized_imgs_array)
print('Array of images saved to output! Processing done!')
# -
# test images paths
img_path_1 = '2+2.jpg'
img_path_2 = '3+8.jpeg'
img_path_3 = '7+3.png'
img_path_4 = '15+100.JPG'
img_path_5 = '87+95.jpg'
img_path_6 = '189+82.jpg'
img_path_7 = '2+35.jpg'
img_path_8 = '24-23.jpg'
equation_image_preprocess_pipeline(img_path_8)
| model/Handwritten equation processing/Processing handwritten equation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Command line interface
# ====================
#
# xclim provides the `xclim` command line executable to perform basic indicator
# computation easily without having to start up a full python environment. However, not
# all indicators listed in [Climate Indicators](../indicators.rst) are available through this tool.
#
# Its use is simple. Type the following to see the usage message:
# !xclim --help
# To list all available indicators, use the "indices" subcommand:
# !xclim indices
# For more information about a specific indicator, you can either use the `info` subcommand or directly access the `--help` message of the indicator. The former gives more information about the metadata while the latter only prints the usage. Note that the module name (`atmos`, `land` or `seaIce`) is mandatory.
# !xclim info liquidprcptot
# In the usage message, `VAR_NAME` indicates that the passed argument must match a variable in the input dataset.
# +
import xarray as xr
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import warnings
warnings.filterwarnings('ignore', 'implicitly registered datetime converter')
# %matplotlib inline
xr.set_options(display_style='html')
time = pd.date_range('2000-01-01', periods=366)
tasmin = xr.DataArray(-5 * np.cos(2 * np.pi * time.dayofyear / 365) + 273.15, dims=("time"),
coords={'time': time}, attrs={'units':'K'})
tasmax = xr.DataArray(-5 * np.cos(2 * np.pi * time.dayofyear / 365) + 283.15, dims=("time"),
coords={'time': time}, attrs={'units':'K'})
pr = xr.DataArray(np.clip(10 * np.sin(18 * np.pi * time.dayofyear / 365), 0, None), dims=("time"),
coords={'time': time}, attrs={'units':'mm/d'})
ds = xr.Dataset({'tasmin': tasmin, 'tasmax': tasmax, 'pr': pr})
ds.to_netcdf('example_data.nc')
# -
# Computing indicators
# -------------------------------
#
# So let's say we have the following toy dataset:
import xarray as xr
ds = xr.open_dataset('example_data.nc')
ds
import matplotlib.pyplot as plt
fig, (axT, axpr) = plt.subplots(1, 2, figsize=(10, 5))
ds.tasmin.plot(label='tasmin', ax=axT)
ds.tasmax.plot(label='tasmax', ax=axT)
ds.pr.plot(ax=axpr)
axT.legend()
# To compute an indicator, say the monthly solid precipitation accumulation, we simply call:
# !xclim -i example_data.nc -o out1.nc solidprcptot --pr pr --tas tasmin --freq MS
# In this example, we decided to use `tasmin` for the `tas` variable. We didn't need to provide the `--pr` parameter as our data has the same name.
#
# Finally, more than one indicators can be computed to the output dataset by simply chaining the calls:
# !xclim -i example_data.nc -o out2.nc liquidprcptot --tas tasmin --freq MS tropical_nights --thresh "2 degC" --freq MS
# Let's see the outputs:
# +
ds1 = xr.open_dataset('out1.nc')
ds2 = xr.open_dataset('out2.nc', decode_timedelta=False)
fig, (axPr, axTn) = plt.subplots(1, 2, figsize=(10, 5))
ds1.solidprcptot.plot(ax=axPr, label=ds1.solidprcptot.long_name)
ds2.liquidprcptot.plot(ax=axPr, label=ds2.liquidprcptot.long_name)
ds2.tropical_nights.plot(ax=axTn, marker='o')
axPr.legend()
# -
ds1.close()
ds2.close()
| docs/notebooks/cli.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: PythonData
# language: python
# name: pythondata
# ---
#import required dependencies here:
import pandas as pd
import datetime
from sqlalchemy import create_engine
# ## Extract from CSV files
#read csv for games
#read csv 1
df1 = pd.read_csv("./Resources/game_origin.csv")
df1.head()
#read csv for games
#read csv 2
df2 = pd.read_csv("./Resources/team.csv")
df2.head()
# ## Transform
#renaming columns
df1 = df1.rename(columns={"Teamid":"TEAM_ID_HOME"})
df1.head()
#delete unneeded columns
df2.drop(df2.columns[[6]],axis=1, inplace=True)
df2.head
# ## Load
CREATE TABLE team (
id VARCHAR NOT NULL,
full_name VARCHAR NOT NULL,
abbreviation VARCHAR NOT NULL,
nickname VARCHAR NOT NULL,
city VARCHAR NOT NULL,
state VARCHAR NOT NULL,
year_founded VARCHAR NOT NULL,
PRIMARY KEY (id)
);
#SQL login info
protocol = 'postgres'
url = 'localhost'
port - '5432'
db = 'my_nba_data_class_db'
connection_string = f"{protocol}://{username}:{password}@{url}:{port}/{db}"
engine = create_engine(connection_string)
# Load my pandas dataframe for table 1
new_df.to_sql(name="game", con=engine, if_exists='append', index=False)
# Load my pandas dataframe for table 2
new_df.to_sql(name="team", con=engine, if_exists='append', index=False)
# Confirm data has been added to the table
pd.read_sql_query("SELECT * FROM game", con=engine).head()
# Confirm data has been added to the table
pd.read_sql_query("SELECT * FROM team", con=engine).head()
| .ipynb_checkpoints/ETL NBA Final Project-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### 필요 모듈 및 데이터 로드
# +
import sys
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
# -
dacon_data_path = os.path.join("./data/dacon_data")
sys.path.insert(0, dacon_data_path)
case = pd.read_csv("./Case.csv")
p_info = pd.read_csv("./PatientInfo.csv")
p_route = pd.read_csv("./PatientRoute.csv")
pol = pd.read_csv("./Policy.csv")
reg = pd.read_csv("./Region.csv")
st = pd.read_csv("./SearchTrend.csv")
sf = pd.read_csv("./SeoulFloating.csv")
ta = pd.read_csv("./TimeAge.csv")
time = pd.read_csv("./Time.csv")
tg = pd.read_csv("./TimeGender.csv")
tp = pd.read_csv("./TimeProvince.csv")
wt = pd.read_csv("./Weather.csv")
# # utils
def uniform_pdf(x):
""" Uniform Distribution(균등 분포) 확률 밀도 함수 """
return 1 if 0 <= x < 1 else 0
def uniform_cdf(x):
""" 균등 분포 누적 분포 함수 """
if x < 0:
return 0
elif 0 <= x < 1:
return x
else:
return 1
def normal_pdf(x, mu=0.0, sigma=1.0):
"""평균이 mu이고, 표준편차가 sigma인 정규 분포(Normal Distribution)
확률 밀도 함수
"""
return math.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (SQRT_TWO_PI * sigma)
def normal_cdf(x, mu=0.0, sigma=1.0):
"""평균이 mu이고, 표준편차가 sigma인
정규 분포(Normal Distribution)의 누적 분포 함수(Cumulative Distribution Function)
math.erf() 함수(error function)를 이용해서 구현"""
return (1 + math.erf((x - mu) / (math.sqrt(2) * sigma))) / 2
def inverse_normal_cdf(p, mu=0.0, sigma=1.0, tolerance=0.00001):
"""누적 확률 p를 알고 있을 때 정규 분포 확률 변수 x = ?"""
# 표준 정규 분포가 아니라면 표준 정규 분포로 변환
if mu != 0.0 or sigma != 1.0:
return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance)
low_z = -10.0 # 하한(lower bound)
high_z = 10.0 # 상한(upper bound)
while high_z - low_z > tolerance:
mid_z = (low_z + high_z) / 2.0 # 중간 값
mid_p = normal_cdf(mid_z) # 중간 값에서의 누적 확률
if mid_p < p:
low_z = mid_z
else:
high_z = mid_z
return mid_z
# ### data EDA
data_list = [case, p_info, p_route, pol, reg, st, sf, ta, time, tg, tp, wt]
data_str_list = ['case', 'p_info', 'p_route', 'pol', 'reg', 'st', 'sf', 'ta', 'time', 'tg', 'tp', 'wt']
# +
def data_shape_print(d_list, d_str_list):
col_list = []
for d_idx in range(len(d_list)):
print(str(d_idx+1),'_',d_str_list[d_idx], ': ', d_list[d_idx].shape)
print('columns : ', list(d_list[d_idx].columns))
print()
for c_idx in list(d_list[d_idx].columns):
col_list.append(c_idx)
return col_list
col_list = data_shape_print(data_list, data_str_list)
# +
from collections import Counter
col_d = dict(sorted(dict(Counter(col_list)).items(), key=lambda item: item[1]))
col_d
# -
# ### 사용할 데이터 추출
# - 그룹화 할 수 있는 데이터(mapper?)
# + date
# + location(city, province)
# 확진자 중 기저질환 보유 여부
_per = float(list(p_info.disease.value_counts())[0]/len(p_info))
print("percentge : %s%%"%round(_per*100,2))
# util
def group_cals_func(df, group_col, target_col, agg):
grouped = df.groupby(group_col)
if agg == 'mean':
return grouped[target_col].mean().sort_values(ascending=False)
elif agg == 'sum':
return grouped[target_col].sum().sort_values(ascending=False)
# 감염 케이스 별 확진자 수
group_cals_func(case, 'infection_case', 'confirmed', 'mean')
province_code_mapper = dict(zip(wt.code, wt.province))
province_code_mapper
# ### 감염 케이스 중 집단 감염일 확률?
_per = len(case[case['group'] == True])/len(case)*100
print("percentage : %s%%"%round(_per,3))
# ### contact number 따른 확률변수?
# - 데이터를 수집한다.
#
# - 수집한 데이터가 어떤 확률변수의 표본 데이터라고 가정
#
# - 데이터를 사용하여 해당 확률변수의 확률분포함수의 모양을 결정
#
# - 결정된 확률변수로부터 다음에 생성될 데이터나 데이터 특성을 예측
import scipy.stats as stats
import sympy
_p_info = p_info[['sex','age','province','infection_case','contact_number','symptom_onset_date','confirmed_date','released_date','deceased_date']]
_p_info
case.infection_case
p_info
p_info.infection_case.value_counts()
# 연령대 별 감염 수
age_infect_cnt_dict = dict(zip(p_info.age.value_counts().index, p_info.age.value_counts().values))
age_infect_cnt_dict
# +
# 연령대별 감염률
age_infect_rate_dict = {}
for k,v in age_infect_cnt_dict.items():
age_infect_rate_dict[k] = v/sum([v for k,v in age_infect_cnt_dict.items()])
age_infect_rate_dict
# -
age_infect_cnt_df = pd.DataFrame(list(age_infect_cnt_dict.items()), columns=['age', 'cnt'])
age_infect_cnt_df.plot.hist(bins=14)
age_infect_rate_df = pd.DataFrame(list(age_infect_rate_dict.items()), columns=['age', 'rate'])
age_infect_rate_df.plot.hist(bins=14)
sns.distplot(age_infect_rate_df['rate'])
sns.distplot(p_info['contact_number'])
p_info['age_rate'] = p_info['age'].map(age_infect_rate_dict)
p_info
# 연령대에 따른 확률분포 도식화?
sns.distplot(p_info['age_rate'])
# 유동 인구수
sns.distplot(sf['fp_num'])
import seaborn as sns
print(sp.stats.describe(x))
print(x.describe())
# ## 기댓값
#
# - 확률밀도함수나 확률분포함수는 확률변수의 전체적인 성격을 설명하는데, 때로 우리는 몇 개의 수치로 확률분포의 성질을 요약하고자 하기도 함
# - 이러한 성질을 요약하는 수치들 중 하나로 변수의 expectation을 생각해보자
#
age_infect_rate_dict
len(age_infect_rate_dict)
# +
# 미성년 (0s or 10s)
# 청장년 (20s ~ 50s)
# 노년 (60s ~ 100s)
# +
# 10명을 임의로 선정했을 때 미성년일 확률?
a = list(age_infect_rate_dict.keys())
# +
# 임의로 두 명을 뽑았을 때 나올 수 있는 모든 가정의 수
# p = itertools.permutations(a, 2) # 순열
b = itertools.combinations(a,2) # 조합
len(list(itertools.combinations(a,2)))
# -
age_infect_rate_dict
# 두 명을 뽑았을때 미성년이 나오는 모든 경우의 수
len(d) + len(a)
# debug 용 function
def permutations_with_replacement(data, n=2):
_list = [data]*n
return list(itertools.product(*_list))
num_of_cases = permutations_with_replacement(a,2)
num_of_cases
len(num_of_cases)
# +
# 미성년일 확률
prob_of_minor = age_infect_rate_dict['0s']+age_infect_rate_dict['10s']
print('Probability of minor : ', prob_of_minor)
# 성년일 확률
prob_of_adult = 1-(prob_of_minor)
print('Probability of adult : ', prob_of_adult)
# -
# #### 관심있는 변수 -> 두 명을 추출했을 때, 추출한 인원 중 한 명 이상이 미성년일 확률
#
# - P(X=0) = 0.003849706716929806
# + 임의의 두 명이 모두 미성년인 경우
#
#
# - P(X=1) = 0.00002964048361274893
# + 임의의 두 명 중 한 명만 미성년인 경우
#
#
# - P(X=2) = 0.9923154068079466
# + 임의의 두 명이 모두 성인인 경우
# +
# P(X=2)
x_0 = prob_of_minor**2
print(x_0)
# P(X=1)
x_1 = 2*(x_0**2)
print(x_1)
# P(X=1)
x_2 = (1-x_0)**2
print(x_2)
# +
# x(추출한 인원 중 한 명 이상이 미성년)의 기대값
# E(X) = x_2*0 + x_1*1 + x_1*1 + x_0*2
e = x_2*0 + x_1*1 + x_1*1 + x_0*2
e
# 이거 맞나??
# -
# x(추출한 인원 중 한 명 이상이 성년)의 기대값
# E(X) = x_2*0 + x_1*1 + x_1*1 + x_0*2
e2 = x_2*2 + x_1*1 + x_1*1 + x_0*0
e2
# probabilily mass function
rand_var_dict = {'x_0': x_0, 'x_1':x_1,'x_2':x_2}
rand_var_dict
_k = [k for k,v in rand_var_dict.items()]
_v = [v for k,v in rand_var_dict.items()]
plt.bar(_k, _v)
plt.ylabel("Probability")
plt.xlabel("Random Variable")
plt.show()
plt.close()
| 4_code/Choi/covid_data_analysis_test.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Free time series data at provider pages
#
# <span style='color:red;background-color:yellow;font-weight:bold'>^^^ move all data files of all notebooks to 'data', update all data download instructions and all code accordingly</span>
#
# <span style='color:red;background-color:yellow;font-weight:bold'>^^^ missing module: statsmodels</span>
#
# <span style='color:red;background-color:yellow;font-weight:bold'>^^^ add two tasks at the end</span>
#
# <span style='color:red;background-color:yellow;font-weight:bold'>^^^ math clarify diff of AC and PAC</span>
#
#
# ### List of selected data sets
#
# <span style='color:red;background-color:yellow;font-weight:bold'>^^^ explain which data files need to be downloaded</span>
#
# | Source | Name, Link to page | Type | Further information |
# | :--- | :--| :--- | :-- |
# | [Yahoo Finance](https://finance.yahoo.com) | [Walmart stock price](https://finance.yahoo.com/quote/WMT/history) | Equity | Retail, Big capitalization |
# | | [Amazon](https://finance.yahoo.com/quote/AMZN/history) | | IT, Big cap |
# | | [Tesla](https://finance.yahoo.com/quote/TSLA/history) | | New technology |
# | | [BJ's Restaurants](https://finance.yahoo.com/quote/BJRI/history) | | Catering industry, Small cap |
# | | [Bitcoin](https://finance.yahoo.com/quote/BTC-USD/history) | Crypto | Meant for payments |
# | | [Ethereum](https://finance.yahoo.com/quote/ETH-USD/history) | | More infrastructural |
# | [FRED](https://fred.stlouisfed.org) | Employment: [Not seasonally adjusted](https://fred.stlouisfed.org/series/PAYNSA)<br/>and [Seasonally adjusted](https://fred.stlouisfed.org/series/PAYEMS) | Macroeconomy | Total non-farm employees |
# | | [S&P500 stock market index](https://fred.stlouisfed.org/series/SP500) | Equity index | Large cap stocks |
# | | [USD 2Y swap rate ICE](https://fred.stlouisfed.org/series/ICERATES1100USD2Y) | Rate | [ICE methodology](https://www.theice.com/publicdocs/ICE_Swap_Rate_Full_Calculation_Methodology.pdf) |
# | | [Ounce of gold in USD](https://fred.stlouisfed.org/series/GOLDAMGBD228NLBM) | Commodity | Gold: bullion |
# | | [Moody's AAA 10Y credit spread](https://fred.stlouisfed.org/series/AAA10Y) | Credit | Spread to 10Y T-bond |
# | | [YEN / USD exchange rate](https://fred.stlouisfed.org/series/DEXJPUS) | FX | FX: Foreign Exchange |
# | | [Wilshire US Real Estate Securities Price Index](https://www.wilshire.com/indexes/wilshire-real-estate-family/wilshire-us-resi) | Real estate index | [Wilshire's description](https://www.wilshire.com/indexes/wilshire-real-estate-family/wilshire-us-resi) |
# | [ECB](https://sdw.ecb.europa.eu) | [USD / EUR exchange rate](https://sdw.ecb.europa.eu/quickview.do?SERIES_KEY=120.EXR.D.USD.EUR.SP00.A) | FX | ECB reference rate |
# | [Portfolio.hu](https://www.portfolio.hu/adatletoltes) | OTP | Equity | Banking, Regional |
# | | Richter | | Pharma |
# | | BUX | Equity Index | Budapest Stock Exch |
# | | EUR / HUF | FX | Hu Natl Bank |
#
# ### Task: Getting to know the data sets
# 1. Based on the descriptions at the provider pages, explain what each data set means.
#
# 2. Select two data sets and compare their changes at time points when something happened in the world.
#
# ## Investigate the data locally
#
# 1. For Yahoo and FRED data sets, explain the meaning of each column.
# 2. For each Yahoo data set calculate the median / maximum ratio of the daily Volume shown in the last column. Which data set has the lowest ratio ?
#
# + code_folding=[]
# open/close code
import warnings
warnings.filterwarnings('ignore')
# modules, variables
import pandas as pd
import os
data_dir = 'data'
file_ext = 'csv'
df = {} # data frames by data set code
# Time series from: Yahoo Finance, Federal Reserve Economic Data, European Central Bank, Portfolio.hu
yahooCodes = ['WMT','AMZN','TSLA','BJRI','BTC-USD','ETH-USD']
fred_codes = ['PAYEMS','PAYNSA','AAA10Y','DEXJPUS','GOLDPMGBD228NLBM','ICERATES1100USD1Y','SP500','WILLRESIPR']
ecb_codes = ['EXR.D.USD.EUR.SP00.A']
pf_codes = ['BUX','OTP','RICHTER']
all_codes = yahooCodes + fred_codes + ecb_codes + pf_codes
# Investigate each data frame
for code in all_codes:
df[code] = pd.read_csv(os.path.join(data_dir, code + '.' + file_ext))
# print(os.linesep+"> "+code)
# print(df[code].head())
# print(df[code].tail())
# print(df[code].describe())
# -
# ## Plot value. Plot Daily and Monthly log return.
#
# 1. Noting that the vertical scale is logarithmic, which stocks have had long periods of exponential growth ?
# 2. In which year did WMT (Walmart) have bigger changes relative to itself: 1975 or 2005 ?
# + code_folding=[]
# open/close code
# modules, variables
import matplotlib.pyplot as plt
import datetime
import numpy as np
def last_date_in_each_month(businessDays):
'''Get last date in each month of a time series'''
dateRange = []
tempYear = None
dictYears = businessDays.groupby(businessDays.year)
for yr in dictYears.keys():
tempYear = pd.DatetimeIndex(dictYears[yr]).groupby(pd.DatetimeIndex(dictYears[yr]).month)
for m in tempYear.keys():
dateRange.append(max(tempYear[m]))
return dateRange
# set dataframe index to datetime
for code in yahooCodes:
df[code].index = pd.to_datetime( df[code]['Date'] )
# create dataframe of monthly returns
dfm = dict() # dict to save monthly close data by data set key
for code in yahooCodes:
all_dates = df[code].index
month_last_dates = last_date_in_each_month(all_dates)
dfm[code] = pd.DataFrame(df[code], index=month_last_dates)
# daily and monthly log return
for code in yahooCodes:
df[code]['LogReturn'] = np.log(df[code]['Close']) - np.log(df[code]['Close'].shift())
dfm[code]['LogReturn'] = np.log(dfm[code]['Close']) - np.log(dfm[code]['Close'].shift())
# parameters for drawing
xlims=[datetime.date(1971,12,31),datetime.date(2020,6,30)] # horizontal axis limits
ylims=[-.45,.45]
removeOutlierBelowMinusOne = True # whether we should remove the log daily return outlier
yahooColors = ['black','blue','#a0a0ff','salmon','limegreen','darkgreen']
fontsize=12
marker='.'
# plot daily values
plt.subplot(311)
for code,color in zip(yahooCodes,yahooColors):
plt.plot(df[code]['Close'], c=color, marker=marker, label=code, lw=0)
plt.legend(bbox_to_anchor=(0.01, .98), loc=2, borderaxespad=0., fontsize=fontsize)
plt.yscale('log')
plt.xlabel('Time [year]',fontsize=fontsize)
plt.ylabel('Value of 1 Unit on log scale',fontsize=fontsize)
plt.xlim(xlims)
# plot logarithmic daily returns
plt.subplot(312)
for code,color in zip(yahooCodes,yahooColors):
s = df[code]['LogReturn']
if removeOutlierBelowMinusOne:
s = s[s>-1]
plt.plot(s, c=color, marker='.', ms=1, label=code, lw=0)
plt.yscale('linear')
plt.xlabel('Time [year]', fontsize=fontsize)
plt.ylabel('Business Day Log Return', fontsize=fontsize)
plt.xlim(xlims)
#plt.ylim(ylims)
# plot logarithmic monthly returns
plt.subplot(313)
normalization_factor = 1.0 # / np.sqrt(number_of_business_days_per_month)
number_of_business_days_per_month = 21
for code,color in zip(yahooCodes,yahooColors):
s = dfm[code]['LogReturn']
plt.plot(s * normalization_factor, c=color, marker='.', ms=2, label=code, lw=0)
plt.yscale('linear')
plt.xlabel('Time [year]', fontsize=fontsize)
#plt.ylabel('Log Monthly Return / ' + r'$\sqrt{' + str(number_of_business_days_per_month) + r'}$', fontsize=fontsize)
plt.ylabel('Log Monthly Return', fontsize=fontsize)
plt.xlim(xlims)
#plt.ylim(ylims)
fig = plt.gcf()
fig.set_size_inches([16, 15])
plt.show()
# -
# ## Log return distribution vs Normal
# 1. On which time scale is BTC closer to normal: daily log returns or monthly log returns ?
# 2. Can you find any data errors, for example, cutoff around zero ?
# + code_folding=[0]
# open/close code
# selected data set for plotting
selectedCode = 'BTC-USD'
# import modules
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from scipy.special import erf
# from scipy.stats import norm # only for norm.ppf
import pandas as pd
# select color for the data set
code2num = { yahooCodes[num]:num for num in np.arange(len(yahooColors)) }
selectedColor = yahooColors[code2num[selectedCode]]
fontsize=12
# helper functions
def cdf(series):
'''Calculate CDF (cumulated density function)'''
series_dropna = series.dropna()
series_dropna_sorted = np.sort(series_dropna)
n = series_dropna.size
values = np.arange(1, n+1) / n
return(series_dropna_sorted, values)
def func_normal_cdf(x, mu, sigma):
'''CDF of normal distribution with parameters mu,sigma'''
return 0.5 * ( 1.0 + erf((x-mu)/(sigma*np.sqrt(2.0))) )
# plot DAILY and MONTHLY
for which_period in (["DAILY", "MONTHLY"]):
dfsel = dict()
if which_period == "DAILY":
for key in df:
dfsel[key] = df[key].copy()
else:
for key in dfm:
dfsel[key] = dfm[key].copy()
# Left: one selected time series as an example
cdfx, cdfy = cdf(dfsel[selectedCode]['LogReturn']) # CDF of daily log returns
popt, pcov = curve_fit(func_normal_cdf, cdfx, cdfy) # fit normal's CDF to observed CDF
cdfy_fit = func_normal_cdf(cdfx, *popt) # CDF fit points
plt.subplot(121)
plt.xlabel(which_period + " log return", fontsize=fontsize)
plt.ylabel("Cumulated density function (CDF)", fontsize=fontsize)
plt.title(selectedCode + " : Observed CDF and Normal Fit CDF", fontsize=fontsize)
plt.plot(cdfx, cdfy, c=selectedColor, marker='o', label=selectedCode, markersize=1, lw=1)
plt.plot(cdfx, cdfy_fit, c='k', ls=':', label='Normal fit',lw=1)
plt.legend(bbox_to_anchor=(.02, .93), loc=2, borderaxespad=0., fontsize=fontsize)
plt.axhline(0, c='k', ls=':', lw=.3)
plt.axhline(1, c='k', ls=':', lw=.3)
plt.axvline(0, c='k', ls=':', lw=.3)
# Right panel: Plot only selected or Plot all
plt.subplot(122)
for code,color in zip(yahooCodes,yahooColors):
#if True:
if code == selectedCode: # plot the CDF-CDF only for the selected data set, use True to plot for all
cdfx, cdfy = cdf(dfsel[code]['LogReturn']) # CDF of daily log returns
popt, pcov = curve_fit(func_normal_cdf, cdfx, cdfy) # fit normal's CDF to observed CDF
cdfy_fit = func_normal_cdf(cdfx, *popt) # CDF fit points
plt.plot(cdfy_fit,cdfy,c=color, marker='.', label=code, markersize=1, lw=1)
plt.title("Slope > 1 means : observed PDF > normal PDF", fontsize=fontsize)
plt.xlabel("Normal fit CDF", fontsize=fontsize)
plt.ylabel("Observed " + which_period + " log returns CDF", fontsize=fontsize)
plt.plot([0,1],[0,1],"k:",lw=1,label="Slope=1")
plt.legend(bbox_to_anchor=(0.02, .98), loc=2, borderaxespad=0., fontsize=fontsize)
fig = plt.gcf()
fig.set_size_inches([14, 4])
plt.show()
# -
# ## Log return and Abs value of log return
#
# 1. The number beside each symbol shows 1-step autocorrelation, for example, WMT (0.055). Which ticker's log return has negative autocorrelation ?
# 2. When we switch from log return to the abs value of log return, how does the autocorrelation change ?
# + code_folding=[]
# open/close code
import matplotlib.pyplot as plt
ylims=[-.45,.45]
abs_ylims=[-.02,.45]
fontsize=12
marker='o'
markersize=2
# daily log return
plt.subplot(211)
for code,color in zip(yahooCodes,yahooColors):
s = df[code]['LogReturn']
autocorr = '%.3f' % s.autocorr()
plt.plot(s, c=color, marker=marker, ms=markersize, label = code + " (" + str(autocorr) + ")", lw=0)
plt.legend(bbox_to_anchor=(1.01, .98), loc=2, borderaxespad=0., fontsize=fontsize)
plt.yscale('linear')
plt.xlabel('Time [year]', fontsize=fontsize)
plt.ylabel('Business Day Log Return', fontsize=fontsize)
plt.xlim(xlims)
plt.ylim(ylims)
# absolute value of log return
plt.subplot(212)
for code,color in zip(yahooCodes,yahooColors):
s = np.absolute(df[code]['LogReturn'])
autocorr = '%.3f' % s.autocorr()
plt.plot(s, c=color, marker=marker, ms=markersize, label = code + " (" + str(autocorr) + ")", lw=0)
plt.legend(bbox_to_anchor=(1.01, .98), loc=2, borderaxespad=0., fontsize=fontsize)
plt.yscale('linear')
plt.xlabel('Time [year]', fontsize=fontsize)
plt.ylabel('Absolute value of Log Return', fontsize=fontsize)
plt.xlim(xlims)
plt.ylim(abs_ylims)
fig = plt.gcf()
fig.set_size_inches([12, 10])
plt.show()
# -
# ## Autocorr of log return and abs log return
#
# These plots show autocorrelation vs time difference.
#
# 1. Which daily log return has significantly nonzero autocorrelation ?
# 2. Which abs daily log return has the highest and lowest autocorrelation after long time ?
#
# + code_folding=[0]
# open/close code
# main parameters
autocorr_len = 126 # check autocorrelation up to this number of business days
xmargin_of_plot = 3
autocorr_shifts = np.arange( 1 , autocorr_len + 1 )
# imports and other parameters
import matplotlib.pyplot as plt
fontsize =14
marker = 'o'
markersize = 4
xlims = ( 1 - xmargin_of_plot, autocorr_len + xmargin_of_plot)
ylims = ( -.2, .35 )
axhline_width = 0.5
# daily log return
plt.subplot(121)
for code,color in zip(yahooCodes,yahooColors):
s = df[code]['LogReturn']
autocorr = [ float( '%.3f' % s.autocorr(shift) ) for shift in autocorr_shifts ]
plt.plot(autocorr_shifts, autocorr, c=color, marker=marker, ms=markersize, label=code, lw=0)
plt.legend(bbox_to_anchor=(.05, .98), loc=2, borderaxespad=0., fontsize=fontsize)
plt.title("Autocorrelation of daily log return", fontsize=fontsize)
plt.yscale('linear')
plt.xlabel('Shift [business days]', fontsize=fontsize)
plt.ylabel('Autocorrelation with selected shift', fontsize=fontsize)
plt.axhline(0, c='k', ls=':', lw=axhline_width)
plt.axvline(0, c='k', ls=':', lw=axhline_width)
plt.xlim(xlims)
plt.ylim(ylims)
# daily log return
plt.subplot(122)
for code,color in zip(yahooCodes,yahooColors):
s = np.absolute(df[code]['LogReturn'])
autocorr = [ float( '%.3f' % s.autocorr(shift) ) for shift in autocorr_shifts ]
plt.plot(autocorr_shifts, autocorr, c=color, marker=marker, ms=markersize, lw=0)
plt.title("Autocorr. of the abs. value of the daily log return", fontsize=fontsize)
plt.yscale('linear')
plt.xlabel('Shift [business days]', fontsize=fontsize)
plt.axhline(0, c='k', ls=':', lw=axhline_width)
plt.axvline(0, c='k', ls=':', lw=axhline_width)
plt.xlim(xlims)
plt.ylim(ylims)
fig = plt.gcf()
fig.set_size_inches([16, 8])
plt.show()
# -
# ## Volume vs log Return
#
# 1. What do you conclude from daily log return vs traded volume plotted for each day ?
# 2. What do you conclude when points are binned by log return ?
# + code_folding=[0]
# open/close code
# the portfolio.hu time series contain trading volume
# we are assuming here that the data sets are already imported
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pf_colors = ['red','limegreen','blue']
markersize=2
(xmin, xmax) = ( -0.55, 0.25 )
xlims = (xmin, xmax)
xbins = np.linspace(xmin, xmax, 100)
axvline_width = 0.5
marker='o'
# set index to datetime, set closing value, log return, and traded volume
for code in pf_codes:
df[code].index = pd.to_datetime( df[code]['Dátum'] )
df[code]['Close'] = df[code]['Záró ár']
df[code]['LogReturn'] = np.log(df[code]['Close']) - np.log(df[code]['Close'].shift())
df[code]['Volume'] = df[code]['Forgalom (mFt)']
# plot daily values
plt.subplot(121)
for code,color in zip(pf_codes, pf_colors):
if True: # plot all data sets
#if 'RICHTER' == code: # plot selected data set
plt.plot(df[code]['LogReturn'], df[code]['Volume'] / 1e+9,
c=color, marker=marker, label=code, lw=0, markersize=markersize)
plt.xlim(xlims)
plt.title("Daily traded volume vs log return")
plt.legend(bbox_to_anchor=(.02, .02), loc=3, borderaxespad=0., fontsize=fontsize)
plt.yscale('log')
plt.xlabel('Daily log return', fontsize=fontsize)
plt.ylabel('Traded volume (billion HUF)', fontsize=fontsize)
plt.yticks([0.01,0.1,1,10,100],['0.01','0.1','1','10','100'])
plt.axvline(0, c='k', ls=':', lw=axvline_width)
plt.subplot(122)
for code,color in zip(pf_codes, pf_colors):
if True: # plot all data sets
#if 'RICHTER' == code: # plot selected data set
groups = df[code].groupby(pd.cut(df[code]['LogReturn'], xbins))
plot_centers = ( xbins[:-1] + xbins[1:] ) / 2
plot_values = groups['Volume'].mean() / 1e+9
plt.plot(plot_centers, plot_values,
c=color, marker=marker, label=code, lw=0, markersize=3*markersize)
plt.xlim(xlims)
plt.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0., fontsize=fontsize)
plt.title("Traded volume is averaged in bins of log return")
plt.yscale('log')
plt.xlabel('Daily log return', fontsize=fontsize)
plt.ylabel('Traded volume (billion HUF)', fontsize=fontsize)
plt.yticks([3,10,30],['3','10','30'])
plt.axvline(0, c='k', ls=':', lw=axvline_width)
fig = plt.gcf()
fig.set_size_inches([13, 5])
plt.show()
# -
# ## Volume vs Volatility of daily close
#
# 1. Based on the below scatter plot what do you conclude for the relationship between daily log(volume) and log(volatility) ?
# 2. Based on the roughly even distribution of the daily points in the plot what is your chance of having a high volume day ?
# + code_folding=[0]
# open/close code
# imports, parameters
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pf_colors = ['red','green','blue']
markersize = 2
def calculate_monthly_volatility_and_average_traded_volume(data):
'''For each month calculate the volatility of the daily close and the average daily traded volume.'''
monthly_data = pd.DataFrame(columns=['volatility','average_volume'])
dates = data.index
yearly_dates = dates.groupby(dates.year)
for year in yearly_dates.keys():
monthly_dates = pd.DatetimeIndex(yearly_dates[year]).groupby(pd.DatetimeIndex(yearly_dates[year]).month)
for month in monthly_dates.keys():
date_all = monthly_dates[month]
date_first = min( date_all )
close_daily_all = [ data.loc[date]['Close'] for date in date_all ]
volume_daily_all = [ data.loc[date]['Volume'] for date in date_all ]
volatility = np.std( close_daily_all )
volume_daily_average = np.average( volume_daily_all )
monthly_data.loc[date_first] = [volatility, volume_daily_average]
return monthly_data
# volume vs volatility
monthly_data = dict()
for code, color in zip(pf_codes, pf_colors):
if True: # all data sets
#if 'RICHTER' == code: # only selected data set
monthly_data[code] = calculate_monthly_volatility_and_average_traded_volume( df[code] )
plt.plot(monthly_data[code]['volatility'], monthly_data[code]['average_volume'] / 1e+9,
c=color, marker=marker, label=code, lw=0, markersize=markersize)
plt.legend(bbox_to_anchor=(.98, .02), loc=4, borderaxespad=0., fontsize=fontsize)
plt.title("Monthly data: Average daily volume vs Volatility of daily close")
plt.xscale('log')
plt.yscale('log')
plt.xlabel('Volatility of daily close in a month (HUF)', fontsize=fontsize)
plt.ylabel('Average daily volume (billion HUF)', fontsize=fontsize)
plt.xticks([30,100,300,1000],['30','100','300','1000'])
plt.yticks([1,3,10,30],['1','3','10','30'])
fig = plt.gcf()
fig.set_size_inches([8, 6])
plt.show()
# -
# ## Skewness of log returns distribution
#
# 1. What does the sum of the highest and the lowest value tell about a distribution ?
# 2. Does the negative skew of SP500 mean that stock prices respond faster to negative news than to positive news ?
#
# | Name | Symbol and Calculation |
# |:-----|:------------|
# | Random variable | $X$ |
# | Mean | $\mu = E\left[ \,X \,\right]$ |
# | Variance | ${\displaystyle \sigma^{\,2} = E\left[ \, \left( \, X - \mu \, \right)^{\,2} \, \right] }$ |
# | Volatility = Std.dev. | $\sigma$ |
# | Skewness | ${\displaystyle E\left[\,\left(\frac{X-\mu}{\sigma}\,\right)^{\,3} \, \right]}$|
# + code_folding=[0]
# open/close code
import numpy as np
import pandas as pd
from scipy import stats
import datetime
# select data sets to be analyzed, set their display names, set colors for plotting them
fred_selected_codes = {'AAA10Y':'AAA10Y', 'GOLDPMGBD228NLBM':'GOLD', 'DEXJPUS':'JPYUSD',
'ICERATES1100USD1Y': 'US1YSW', 'SP500':'SP500', 'WILLRESIPR':'WILLSH'}
fred_colors = ['black','blue','green','black','red','red']
fred_markers = ['o','^','v','x','o','x']
fred_fill = ['none','none','none','none','none','none']
axhline_width = 0.5
markersize = 6
markeredgewidth = 1
display_len = 32 # display this number of points
linthreshy = 0.002 # threshold for the simlog y scaling
# read fred data sets again without the . lines, calculate log return
for code in fred_selected_codes:
df[code] = pd.read_csv(data_dir + os.sep + code + "." + file_ext, na_values='.')
df[code]['LogReturn'] = np.log(df[code][code]) - np.log(df[code][code]).shift()
# write skewness and plot differences
print("Skew\tLabel\tLong Code of Data")
for code, color, marker, fill in zip(fred_selected_codes, fred_colors, fred_markers, fred_fill):
if True: # plot all data
#if code.startswith('AA'): # plot selected
log_returns = df[code]['LogReturn']
log_returns_num = log_returns[ (log_returns>-1e+6) & (log_returns<1e+6) ] # select numbers
sorted_log_returns = pd.Series.sort_values( log_returns_num ).tolist() # sort into ascending order
sum_reversed = np.add( sorted_log_returns, sorted_log_returns[::-1] ) # add list to itself reversed
sum_reversed = sum_reversed[:display_len:] # keep only the requested number of items from the start
display_name = fred_selected_codes[code]
print("%+.2f\t%s\t%s" % (stats.skew(sorted_log_returns), display_name, code))
is_first = False
plt.plot(1 + np.arange(len(sum_reversed)) , sum_reversed,
c=color, marker=marker, label=display_name, lw=0, fillstyle=fill,
markersize=markersize, markeredgewidth=markeredgewidth)
plt.title('Sum of $n^{th}$ lowest and $n^{th}$ highest daily log returns', fontsize=fontsize)
plt.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0., fontsize=fontsize)
plt.xscale('log')
plt.yscale('symlog', linthreshy=linthreshy)
plt.xlabel('Index of sorted daily log returns ($n$)', fontsize=fontsize)
plt.xticks([1,3,10,30],['1','3','10','30'])
plt.yticks([-0.01,-0.001,0,0.001,0.01,0.1],['$-\,0.01$','$-\,0.001$','','0.001','0.01','0.1'])
plt.axhline(0, c='k', ls='--', lw=axhline_width)
fig = plt.gcf()
fig.set_size_inches([7, 5])
plt.show()
# -
# ## Autocorrelation vs Partial autocorrelation
#
# This section is optional material.
#
# The PAC at lag $\,k\,$ is the correlation between $\,X(t)\,$ and $\,X(t-k)\,$ after removing the effects of $\,X(t-1)\,$, ... , $\,X(t-k+1)\,$.
#
# One of the algorithms calculates ordinary least squares (OLS) with regressand $\,X(t)\,$ and the lagged values as regressors.
# + code_folding=[0]
# open/close code
import pandas as pd
from statsmodels.tsa import stattools
nlags = 10 # number of earlier values used for the PACF
pf_markers = ['o','x','^']
markersize = 6
fill = 'none'
axline_width = 0.5
xticks = [1,2,4,6,8,10]
# calculate ACF and PACF, plot ACF
plt.subplot(121)
data_pacf = dict()
for code, color, marker in zip(pf_codes, pf_colors, pf_markers):
log_returns = pd.Series( data = np.log(df[code]['Záró ár']) - np.log(df[code]['Záró ár'].shift()) )
log_returns.dropna(inplace=True)
data_acf = stattools.acf(log_returns, nlags=nlags)
data_pacf[code] = stattools.pacf(log_returns, nlags=nlags)
plt.plot( np.arange(1,nlags+1), data_acf[1:], c=color, marker=marker,
label=code, lw=0, fillstyle=fill, markersize=markersize )
plt.xlabel('$k\,$ (lag)', fontsize=fontsize)
plt.title('Autocorrelation at lag $k$', fontsize=fontsize)
plt.xticks(xticks)
plt.axhline(0, c='k', ls=':', lw=axline_width)
plt.axvline(1, c='k', ls=':', lw=axline_width)
# plot PACF
plt.subplot(122)
for code, color, marker in zip(pf_codes, pf_colors, pf_markers):
plt.plot( np.arange(1,nlags+1), data_pacf[code][1:], c=color, marker=marker,
label=code, lw=0, fillstyle=fill, markersize=markersize )
plt.legend(bbox_to_anchor=(1.03, 1), loc=2, borderaxespad=0., fontsize=fontsize)
plt.xlabel('$k\,$ (lag)', fontsize=fontsize)
plt.title('Partial autocorrelation at lag $k$', fontsize=fontsize)
plt.xticks(xticks)
plt.axhline(0, c='k', ls=':', lw=axline_width)
plt.axvline(1, c='k', ls=':', lw=axline_width)
fig = plt.gcf()
fig.set_size_inches([10, 6])
plt.show()
# -
# Question: For each year separately, calculate the mean of the daily log return of WMT.
#
#
# Help: 1. List the years (use one of the columns of the data frame), 2. Use a for loop over the years, 3. For each year calculate the mean daily log return, 4. Print formatted output.
#
# !ls | grep WMT
| .ipynb_checkpoints/05 Observed distributions-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Ch12 Figure6
# +
# "What about a shoe makes it a hit?” He or she works with the data analysts to come up with some interesting questions: Is it the color of the shoe? Is it some new technology? Was the shoe featured in a magazine and benefited from a network effect?
shoe_sku = np.arange(500)
color = ['red', 'blue', 'white', 'black', 'green', 'orange']
marketing_channel = ['digital news platform', 'blog', 'youtube', 'magazine']
tech = ['gps', 'step-tracker', 'extra-light-material']
data = []
for i in shoe_sku:
sales = rd.random() * 10000
d = [i, sales]
for j in [color, marketing_channel, tech]:
how_many = rd.randint(0, len(j))
ary = [0 for x in range(len(j))]
ary[:how_many] = [1 for j in range(how_many)]
rd.shuffle(ary)
d.extend(ary)
data.append(d)
df = pd.DataFrame(data, columns=['sku', 'sales', 'red', 'blue', 'white', 'black', 'green', 'orange', 'digital news platform', 'blog', 'youtube', 'magazine', 'gps', 'step-tracker', 'extra-light-material'])
# df.to_csv('csv_output/ch12_fig6.csv', index=False)
df = pd.read_csv('csv_output/ch12_fig6.csv')
df.head()
# +
df = pd.read_csv('csv_output/ch12_fig6.csv')
# %matplotlib inline
sns.set_style("whitegrid")
f, ax = plt.subplots(1, figsize=(8,6))
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit (df.iloc[:,2:], df.iloc[:,1])
ax.barh(width=reg.coef_[::-1], bottom=[x for x in range(1,14)]);
ax.barh(width=0, bottom=0, lw=0)
ax.set_yticks(np.arange(1,14)+.5);
ax.set_yticklabels(['', 'red', 'blue', 'white', 'black', 'green', 'orange', 'digital news platform', 'blog', 'youtube', 'magazine', 'gps', 'step-tracker', 'extra-light-material'][::-1]);
ax.set_title('regression coefficient by variables');
f.savefig('svg_output/ch12_fig6.svg', format='svg')
# -
# Using sales value as y variable and colors, marketing channels and technologies as x dummy variables, we can see the top selling products are most likely to have black but not white, orange also helps. It can be intepreted in this way- holding everything else to be the same, if it's advertised on digital news platform, it's likely to help its sales by 200 dollars versus blog will decrese close to 200 dollars.
| ch12_fig6.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Q#
# language: qsharp
# name: iqsharp
# ---
# ## Oracle Definition ##
# This implements the oracle $D |z\rangle |k\rangle = |z \oplus x_k \rangle |k\rangle$ used in the Grover
# search algorithm.
# +
operation ApplyDatabaseOracle(
markedElement : Int,
markedQubit: Qubit,
databaseRegister: Qubit[]
) : Unit is Adj + Ctl {
(ControlledOnInt(markedElement, X))(databaseRegister, markedQubit);
}
# -
ControlledOnInt?
# ## State Preparation ##
# This implements an oracle $DU$ that prepares the start state
# $DU |0\rangle|0\rangle = 1 / \sqrt{N} |1\rangle|\text{marked}\rangle + \sqrt{N - 1} / \sqrt{N} |0\rangle|\text{unmarked}\rangle$ where $N = 2^n$.
# +
open Microsoft.Quantum.Arrays;
operation PrepareDatabaseRegister(
markedElement : Int,
idxMarkedQubit: Int,
startQubits: Qubit[]
) : Unit is Adj + Ctl {
let flagQubit = startQubits[idxMarkedQubit];
let databaseRegister = Exclude([idxMarkedQubit], startQubits);
// Apply 𝑈.
ApplyToEachCA(H, databaseRegister);
// Apply 𝐷.
ApplyDatabaseOracle(markedElement, flagQubit, databaseRegister);
}
# -
# Here, we wrap our state preparation in a *user-defined type* to indicate that it is a state preparation oracle.
# +
open Microsoft.Quantum.Oracles;
function GroverStatePrepOracle(markedElement : Int) : StateOracle {
return StateOracle(PrepareDatabaseRegister(markedElement, _, _));
}
# -
# ## Grover's Algorithm ##
# +
open Microsoft.Quantum.AmplitudeAmplification;
function GroverSearch(
markedElement: Int,
nIterations: Int,
idxMarkedQubit: Int
) : (Qubit[] => Unit is Adj + Ctl) {
return AmpAmpByOracle(nIterations, GroverStatePrepOracle(markedElement), idxMarkedQubit);
}
# +
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Convert;
operation ApplyQuantumSearch() : (Result, Int) {
let nIterations = 6;
let nDatabaseQubits = 6;
let markedElement = 3;
using ((markedQubit, databaseRegister) = (Qubit(), Qubit[nDatabaseQubits])) {
// Implement the quantum search algorithm.
(GroverSearch(markedElement, nIterations, 0))([markedQubit] + databaseRegister);
// Measure the marked qubit. On success, this should be One.
let resultSuccess = MResetZ(markedQubit);
// Measure the state of the database register post-selected on
// the state of the marked qubit.
let resultElement = ForEach(MResetZ, databaseRegister);
let numberElement = ResultArrayAsInt(resultElement);
// Returns the measurement results of the algorithm.
return (resultSuccess, numberElement);
}
}
# -
%simulate ApplyQuantumSearch
# ## Epilogue ##
%version
| samples/algorithms/database-search/Database Search.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# import packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import featuretools as ft
import lightgbm as lgb
# %matplotlib inline
import seaborn as sns
RSEED = 50
# -
# # Load Data
# Load sample training data
df_train_transac = pd.read_csv('./data/train_transaction.csv')
df_train_identity = pd.read_csv('./data/train_identity.csv')
df_train = pd.merge(df_train_transac,df_train_identity,on='TransactionID',how='left')
# Load sample training data
df_test_transac = pd.read_csv('./data/test_transaction.csv')
df_test_identity = pd.read_csv('./data/test_identity.csv')
df_test = pd.merge(df_test_transac,df_test_identity,on='TransactionID',how='left')
# combine train and test
df_total = df_train.append(df_test,sort=False)
df_total.shape
# # Feature Engineer
# clean Pemail
df_total['P_emaildomain'] = df_total['P_emaildomain'].str.split('.',expand=True)[0]
# clean R_emaildomain
df_total['R_emaildomain'] = df_total['R_emaildomain'].str.split('.',expand=True)[0]
df_total['id_30'] = df_total['id_30'].str.split(' ',expand=True)[0]
def clean_id31(df):
df['id_31'] = df['id_31'].str.replace("([0-9\.])", "")
df['id_31'][df['id_31'].str.contains('chrome', regex=False)==True] = 'chrome'
df['id_31'][df['id_31'].str.contains('Samsung', regex=False)==True] = 'Samsung'
df['id_31'][df['id_31'].str.contains('samsung', regex=False)==True] = 'Samsung'
df['id_31'][df['id_31'].str.contains('firefox', regex=False)==True] = 'firefox'
df['id_31'][df['id_31'].str.contains('safari', regex=False)==True] = 'safari'
df['id_31'][df['id_31'].str.contains('opera', regex=False)==True] = 'opera'
df['id_31'] = df['id_31'].str.replace(" ", "")
return df
df_total = clean_id31(df_total)
def label_encoder(df, categorical_columns=None):
"""Encode categorical values as integers (0,1,2,3...) with pandas.factorize. """
# if categorical_colunms are not given than treat object as categorical features
if not categorical_columns:
categorical_columns = [col for col in df.columns if df[col].dtype == 'object']
for col in categorical_columns:
df[col], uniques = pd.factorize(df[col])
return df, categorical_columns
# +
'''
to_encode = ['ProductCD', 'card4', 'card6', 'P_emaildomain', 'R_emaildomain',
'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'id_12', 'id_15',
'id_16', 'id_23', 'id_27', 'id_28', 'id_29', 'id_30', 'id_31', 'id_33',
'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType', 'DeviceInfo']
'''
df_total,colname = label_encoder(df_total, categorical_columns=None)
# -
# # Train Model
# ## Train Test Split
features_train = df_total[df_total['isFraud'].notnull()]
features_test = df_total[df_total['isFraud'].isnull()]
print(features_train.shape)
print(features_test.shape)
# ## Prepare Train Set
labels_train = features_train['isFraud']
features_train = features_train.drop(columns = ['isFraud', 'TransactionID'])
categorical = ['ProductCD', 'card1', 'card2', 'card3', 'card4', 'card5','card6',
'addr1','addr2','P_emaildomain','R_emaildomain','M1','M2','M3',
'M4','M5','M6','M7','M8','M9','DeviceType','DeviceInfo']
ids = [ 'id_%s'%(i) for i in range(12,39)]
categorical = categorical + ids
# Create a lgb training set
train_set = lgb.Dataset(features_train, label = labels_train.values,
categorical_feature=categorical)
# ## Cross Validate
# Find default hyperparameters
model = lgb.LGBMClassifier()
params = model.get_params()
cv_results = lgb.cv(params, train_set, num_boost_round = 10000, metrics = 'auc',
early_stopping_rounds = 100, seed = RSEED, nfold = 5)
print('Cross Validation ROC AUC: {:.5f} with std: {:.5f}.'.format(cv_results['auc-mean'][-1],
cv_results['auc-stdv'][-1]))
model = lgb.LGBMClassifier(n_estimators = len(cv_results['auc-mean']), random_state=RSEED)
model.fit(features_train, labels_train.values)
# ## Feature Importance
fi = pd.DataFrame({'feature': features_train.columns,
'importance': model.feature_importances_})
fi = fi.sort_values('importance', ascending = False)
fi[fi.importance > 0]
# ## Predict
id_test = features_test['TransactionID']
features_test = features_test.drop(columns = ['isFraud', 'TransactionID'])
# Make predictions on the testing data
preds = model.predict_proba(features_test)[:, 1]
submission = pd.DataFrame({'TransactionID': id_test,
'isFraud': preds})
submission.to_csv('./data/sub_baseline.csv', index = False)
| Baseline.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_python3
# language: python
# name: conda_python3
# ---
# + [markdown] colab_type="text" id="NjHnSAbHrInP"
# # swapゲート
# swapゲートは2つの量子ビットの値を入れ替えるゲートです。CXゲートを使って簡単に実装できるのでやってみましょう。まずはインストールです。
# + colab={} colab_type="code" id="qQgzV_yUnZP5"
# !pip install blueqat
# + [markdown] colab_type="text" id="PKhFYi-drld1"
# ## 回路の作成
# 2つの回路を入れ替えるには、CXゲートを3つ使うことで実装できます。下記はまず0番目の量子ビットを1にしてみてから、2つの回路を入れ替えます。
#
# すなわち以下のような図になります。
#
# <img src="./img/006/006_0.png" width="35%">
#
# まずは入れ替える前を見てみましょう。
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="O674HiVxjc7P" outputId="b69d00ae-0b42-4841-dc15-8dd7dbff5af1"
from blueqat import Circuit
Circuit(2).x[0].m[:].run(shots=1)
# + [markdown] colab_type="text" id="KpoGH9wMoGN3"
# この場合には0番目の量子ビットが1となりました。早速入れ替えてみます。
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="0Rjl5jjxoMHl" outputId="97dc90fe-e071-482a-ba8e-202966d1364e"
Circuit().x[0].cx[0,1].cx[1,0].cx[0,1].m[:].run(shots=1)
# -
# また、blueqatでは、swapゲートは下記のように簡単に書くこともできます。
Circuit().x[0].swap[0,1].m[:].run(shots=1)
# + [markdown] colab_type="text" id="Pj4TW4zHDG7d"
# swapゲートはCXゲートを交互に三回使うことで実現できます。CXゲートは真ん中だけ上下逆にします。上記の回路では0番目の量子ビットに1を設定した後にswapゲートを適用して交換して01と入れ替えに成功しています。
#
# swapゲートの行列表現と各ビットでの対応は以下のようになります。
#
# <img src="./img/006/006_1.png" width="50%">
#
# swapゲートは度々出てくるテクニックなので覚えておいた方がいいでしょう。以上です。
#
# -
| tutorial-ja/010_swap_ja.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="I-OVHaX9enRv"
# # NumPy, Pandas 복습
# + [markdown] colab_type="text" id="RjCo3jrpfJ0l"
# ### NumPy 실습 문제
#
#
# 문제 1.
#
# 길이가 10인 0-벡터(모든 요소가 0인)를 만드세요.
#
#
# + colab={} colab_type="code" id="7HJCoRUo0-Kj"
# + [markdown] colab_type="text" id="jBqZrWqqiFk_"
# 문제 2.
#
# 길이가 10이며 다섯번째 원소만 1이고 나머지 원소는 모두 0인 벡터를 만드세요.
#
#
# + colab={} colab_type="code" id="Na01fyVf0-jS"
# + [markdown] colab_type="text" id="BoYSsYGhiIef"
# 문제 3.
#
# 10 부터 49까지의 값을 가지는 벡터를 만드세요.
#
#
# + colab={} colab_type="code" id="tUb4Oroe0_FK"
# + [markdown] colab_type="text" id="xlZ0xpKMiNGN"
# 문제 4.
#
# 위 벡터의 순서를 바꾸세요.
#
#
# + colab={} colab_type="code" id="QlB6jHE10_nI"
# + [markdown] colab_type="text" id="zxiD5ItZiPta"
# 문제 5.
#
# 0부터 8까지의 값을 가지는 3x3 행렬을 만드세요.
#
#
# + colab={} colab_type="code" id="M9i-9Tzz0_-M"
# + [markdown] colab_type="text" id="0RSXeMRviR75"
# 문제 6.
#
# 벡터 [1,2,0,0,4,0] 에서 원소의 값이 0이 아닌 원소만 선택한 벡터를 만드세요.
#
#
# + colab={} colab_type="code" id="ZLh_tgKr1Aef"
# + [markdown] colab_type="text" id="FpjT4iZUiUkG"
# 문제 7.
#
# 3x3 단위 행렬(identity matrix, 주대각선의 원소가 모두 1이며 나머지 원소는 모두 0인)을 만드세요
#
#
# + colab={} colab_type="code" id="b1r57MrO1A9l"
# + [markdown] colab_type="text" id="TbnT-pA4iWkl"
# 문제 8.
#
# 난수 원소를 가지는 3x3 행렬을 만드세요
#
#
# + colab={} colab_type="code" id="jQoqkFko1Bat"
# + [markdown] colab_type="text" id="F0mr3gNHiYkY"
# 문제 9.
#
# 위에서 만든 난수 행렬에서 최대값/최소값 원소를 찾으세요.
#
#
# + colab={} colab_type="code" id="x4WNmwW81B4F"
# + [markdown] colab_type="text" id="tbaqoKpniawg"
# 문제 10.
#
# 위에서 만든 난수 행렬에서 행 평균, 열 평균을 계산하세요.
# + colab={} colab_type="code" id="LlCDgQoU1Clm"
# + [markdown] colab_type="text" id="y0fFRV3_1Ddi"
# # Pandas 실습문제
#
# 다음의 코드를 실행하여 샘플 데이터를 생성하시오.
#
# seaborn 패키지에 있는 타이타닉 데이터를 사용하여 실습한다. 필요한 데이터를 로드한다.
# + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" executionInfo={"elapsed": 842, "status": "ok", "timestamp": 1592127138765, "user": {"displayName": "\uc774\uc120\ud654", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGEcSuxiespWUAaMC6eXljdm2fXmv29ZXuZ14n=s64", "userId": "08084686575025891086"}, "user_tz": -540} id="a0n_T0I11Kd_" outputId="cc3e248d-ee77-4a25-cf17-7f7323ff5101"
import pandas as pd
titanic = pd.read_csv("../data/titanic.csv")
titanic.head()
# + [markdown] colab_type="text" id="Gdn78u7c2sb_"
# 문제 1.
#
# 타이타닉호 승객중 성별(sex) 인원수, 나이별(age) 인원수, 선실별(class) 인원수, 사망/생존(alive) 인원수를 구하라. (힌트. value_counts 메소드)
# + colab={} colab_type="code" id="iSTAR-c33YcM"
# + [markdown] colab_type="text" id="HT6WffB45jrc"
# 문제 2.
#
# 성별(sex) 및 선실(class)에 의한 생존율을 피봇 데이터 형태로 만들어 표시하시오.(힌트. pivot_table)
# + colab={} colab_type="code" id="Mh2eWUA6TgZX"
# + [markdown] colab_type="text" id="G169SxRZTgwv"
# 문제 3.
#
# 'age' 컬럼의 null 값을 'age'의 median 값으로 대체하시오.(fillna 사용)
# + colab={} colab_type="code" id="iIkhbfSwV17P"
# + [markdown] colab_type="text" id="eCxEZJxhZnDF"
# 문제 4.
#
# 가장 고액의 운임(fare)를 지불한 승객에 대한 정보를 출력하시오.
# + colab={} colab_type="code" id="7JiOjTG8aTyj"
# + [markdown] colab_type="text" id="YjuDkHXnaT83"
# 문제 5.
#
# 승객의 나이('age')의 평균을 구하시오.
# + colab={} colab_type="code" id="74jE-pkaa-Pv"
# + [markdown] colab_type="text" id="ltsYSMtHa-Xa"
# 문제 6.
#
# 'embark_town' 이 'Queenstown' 이면서 생존한 남성 승객에 대한 정보를 출력하시오.
# + colab={} colab_type="code" id="QCO_s4RBdovs"
| 01Review/NumpyPandas.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## The Middle
# Suppose that Yulin, another Data 8 student, is tasked with writing code to find the middle of three distinct numbers named `a`, `b`, and `c`. (By “middle” we mean the value that is neither the maximum nor the minimum.) For example, given the values 4, 2, and 7, the code should give back 4.
#
# Yulin has a moment of inspired thought and rapidly types the following into her Jupyter notebook:
a + b + c - max(a, b, c) + min(a, b, c)
# Is her code correct? Why or why not? If not, make a *simple* change to the cell above to fix it.
#
# *Hint:* Running the cell will produce an error because we haven't defined `a`, `b`, and `c`, but you're free to make any changes you want to test your ideas. (Please have just 1 line in the cell above in the notebook you submit, though.)
| hw02/05_maxmin.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="XKWG6kWvtFal" colab_type="text"
# # PROYECTO MACHINE LEARNING
# ## CSI QT 2019/20
# + [markdown] id="kDP9R7H0tFam" colab_type="text"
# Para la realización de este proyecto, se escoge el modelo de **Yacht Hydrodynamics (regresión)** y se genera un modelo predictivo que minimiza el error de generalización.
# + [markdown] id="sGys7DMvtFan" colab_type="text"
# Se ha prodedido a la obtención de los datos a partir del siguiente enlace:
# http://archive.ics.uci.edu/ml/datasets/yacht+hydrodynamics
#
# Según el **Dr <NAME>** la contextualización del *dataset* es el siguiente:
#
# *La predicción de la resistencia residual de los yates de vela en la etapa de diseño inicial es de gran valor para evaluar el rendimiento del barco y para estimar la potencia propulsora requerida. Las entradas esenciales incluyen las dimensiones básicas del casco y la velocidad del barco.*
#
# *El conjunto de datos de Delft comprende 308 experimentos a gran escala, que se realizaron en el Laboratorio de Hidromecánica de Barcos de Delft para ese propósito.*
#
# *Estos experimentos incluyen 22 formas diferentes de casco, derivadas de una forma parental estrechamente relacionada con el "Standfast 43" diseñado por Frans Maas.*
# + [markdown] id="QX4NgYsWtFao" colab_type="text"
# Según el enuncidado, el modelo tiene que predecir la variable en la última columna a partir de las 6 variables numéricas anteriores.
#
#
# Las variables se refieren a los coeficientes de geometría del casco y al número de Froude:
#
# 1. Posición longitudinal del centro de flotabilidad, adimensional.
# 2. Coeficiente prismático, adimensional.
# 3. Relación longitud-desplazamiento, adimensional.
# 4. Relación viga-tiro, adimensional.
# 5. Relación longitud-viga, adimensional.
# 6. Número de Froude, adimensional.
#
# La variable que se quiere predecir es la resistencia residual por unidad de peso de desplazamiento:
#
# 7. Resistencia residual por unidad de peso de desplazamiento, adimensional.
# + [markdown] id="mgHnZmL9tFap" colab_type="text"
# ## Importación del *dataset*
# + id="j5Gs8VJItFaq" colab_type="code" colab={}
import pandas as pd
yacht_dataset = pd.read_csv('yacht_hydrodynamics.data', sep=" ")
# + [markdown] id="XA_-NzgftFat" colab_type="text"
# Se puede observar la estructura que tiene el *dataset*: los parámetros son los descritos anteriormente, donde la última variable (*Res_residual*) es la que se desea realizar el modelo para que se aproxime más a los valores reales del *dataset*.
# + id="h9lA97MstFat" colab_type="code" outputId="78e8c9e2-8e7b-49ed-90db-0a5bb1becdc6" colab={"base_uri": "https://localhost:8080/", "height": 402}
yacht_dataset
# + [markdown] id="IEay8f9x5iZ1" colab_type="text"
# ## Inspección del *dataset*
# + [markdown] id="TpXcYVlvtFaw" colab_type="text"
# Mostramos los gráficos por pantalla para tener una referencia visual sobre cómo son de dispares los datos en el set que tenemos
# + id="z_omsVeetFaw" colab_type="code" outputId="f573890b-8f7d-493a-ba2a-2db932c17b59" colab={"base_uri": "https://localhost:8080/", "height": 545}
# %matplotlib inline
import matplotlib.pyplot as plt
centro_flotab = yacht_dataset.Pos_long_centro_flotab
coef_prism = yacht_dataset.Coef_prism
long_despl = yacht_dataset.Long_Despl
viga_tiro = yacht_dataset.Viga_tiro
long_viga = yacht_dataset.Long_viga
num_froude = yacht_dataset.Num_Froude
res_residual = yacht_dataset.Res_residual
# Dataset subplots of each feature
centro_flotab_plot = plt.subplot(3, 2, 1)
centro_flotab_plot.title.set_text('Pos. long. centro de flotab.')
plt.plot(centro_flotab)
coef_prism_plot = plt.subplot(3, 2, 2)
coef_prism_plot.title.set_text('Coeficiente prismático')
plt.plot(coef_prism)
long_despl_plot = plt.subplot(3, 2, 3)
long_despl_plot.title.set_text('Relación longitud-desplazamiento')
plt.plot(long_despl)
viga_tiro_plot = plt.subplot(3, 2, 4)
viga_tiro_plot.title.set_text('Relación viga-tiro')
plt.plot(viga_tiro)
long_viga_plot = plt.subplot(3, 2, 5)
long_viga_plot.title.set_text('Relación longitud-viga')
plt.plot(long_viga)
num_froude_plot = plt.subplot(3, 2, 6)
num_froude_plot.title.set_text('Número de Froude')
plt.plot(num_froude)
plt.tight_layout()
plt.show()
# Se muestra la variable la cual que se quiere aproximar el modelo
res_residual_plot = plt.plot(res_residual)
# + [markdown] id="LB2PMY_XpU2D" colab_type="text"
# Mostramos un gráfico que aglutina todas las variables de entrada del dataset.
# + id="bWXTeF2JpTbB" colab_type="code" outputId="fda017ba-0cd2-4f28-8c80-71c19695c2fa" colab={"base_uri": "https://localhost:8080/", "height": 310}
# Make a dataframe with input data
df_yacht = pd.DataFrame({'num_data': range(0,308),
'centre_flotab': centro_flotab,
'coef_prism': coef_prism,
'long_despl': long_despl,
'manega_calat': viga_tiro,
'long_manega': long_viga,
'num_froude': num_froude})
# Style of the plot
plt.style.use('seaborn-darkgrid')
# Create palette color
palette = plt.get_cmap('Set1')
# Plot multiple plots in one
num=0
for column in df_yacht.drop('num_data', axis=1):
num+=1
plt.plot(df_yacht['num_data'], df_yacht[column], marker='', color=palette(num), linewidth=2, alpha=0.9, label=column)
# Legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# Titles
plt.title("Variables de entrada", loc='center', fontsize=15, fontweight=0, color='orange')
plt.xlabel("Nombre d'experiments")
plt.ylabel("Variables de Entrada")
# + [markdown] id="r9Qo03ujY2_B" colab_type="text"
# Vemos cómo están los datos distribuídos estadísticamente
# + id="31pWQ5evtFay" colab_type="code" outputId="b70fa5a1-201e-4472-95c6-26584194e0ce" colab={"base_uri": "https://localhost:8080/", "height": 284}
yacht_dataset.describe()
# + [markdown] id="LmcG75y45vZ2" colab_type="text"
# ## Preprocesamiento de los datos
# + [markdown] id="ugCtDP8wEweo" colab_type="text"
# Preprocesamos los datos normalizándolos
# + id="mHQLVQlYtFa0" colab_type="code" outputId="15e0c9dc-1fe3-485a-e806-3b1e55d0657c" colab={"base_uri": "https://localhost:8080/", "height": 435}
import numpy as np
# MinMaxScaler it is not used since it rescales the data worse than MaxAbsScaler
# from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import MaxAbsScaler
# Selected the scaler to rescale data
scaler = MaxAbsScaler()
# Make a copy of the data in order not to change original one
yacht_dataset_scaled = yacht_dataset.copy()
# Rescale the data using the scaler selected above
yacht_data_scaled = scaler.fit_transform(yacht_dataset)
yacht_dataset_scaled.loc[:,:] = yacht_data_scaled
scaler_params = scaler.get_params()
# Getting the function that relates original and resized data of each feature (used later for rescaling)
# Create array containing all the data
extract_scaling_function = np.ones((1,yacht_dataset_scaled.shape[1]))
print(extract_scaling_function)
# Fill the array with resized ratio of each feature
extract_scaling_function = scaler.inverse_transform(extract_scaling_function)
print(extract_scaling_function)
display(yacht_dataset_scaled)
# + id="XksoXUqMDAQC" colab_type="code" outputId="c860a018-b74a-4ddb-c9fe-d50b147d41a0" colab={"base_uri": "https://localhost:8080/", "height": 310}
# Make dataframe with input data
df_yacht_scaled = pd.DataFrame({'num_data': range(0,308),
'centre_flotab': yacht_data_scaled[:,0],
'coef_prism': yacht_data_scaled[:,1],
'long_despl': yacht_data_scaled[:,2],
'manega_calat': yacht_data_scaled[:,3],
'long_manega': yacht_data_scaled[:,4],
'num_froude': yacht_data_scaled[:,5]})
# Style
plt.style.use('seaborn-darkgrid')
# Make palette color
palette = plt.get_cmap('Set1')
# Display multiple plots in one
num=0
for column in df_yacht_scaled.drop('num_data', axis=1):
num+=1
plt.plot(df_yacht_scaled['num_data'], df_yacht_scaled[column], marker='', color=palette(num), linewidth=2, alpha=0.9, label=column)
# Legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# Titles
plt.title("Variables d'entrada Reescalades", loc='center', fontsize=15, fontweight=0, color='orange')
plt.xlabel("Nombre d'experiments")
plt.ylabel("Variables de Entrada Reescalades")
# + [markdown] id="2g0dkZ9V57Vn" colab_type="text"
# ## Separación train/test de los datos
# + id="4ZfqxsV3tFa2" colab_type="code" colab={}
from sklearn.model_selection import train_test_split
# Store in a vector output data of the dataset
y = yacht_dataset_scaled['Res_residual'].values.reshape(-1,1)
# Create a new dataset with scaled variables in order not to damage original one
X_df = yacht_dataset_scaled.copy()
# Delete from scaled dataset output values = Store input values
X_df.drop(['Res_residual'], axis=1, inplace=True)
X = X_df.values
# Split data into train and test (20% of data) and suffle it
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2,
random_state=42,
shuffle=True)
# Create a dictionary with all important values of the dataset
dataset = {'X_train': X_train, 'X_test' : X_test,
'y_train': y_train, 'y_test' : y_test,
'scaler' : scaler,
'scaler_function' : extract_scaling_function}
# + [markdown] id="hC0Qk-IQ6CDW" colab_type="text"
# ## Entrenamiento del modelo
# + [markdown] id="1P0j9aAFb8oZ" colab_type="text"
# Definimos la función del para el training del modelo
# + id="HftDfhseHXCa" colab_type="code" colab={}
from sklearn.model_selection import GridSearchCV
import time
def trainYachtModelGridSearchCV(X_train, x_test,
y_train, y_test,
estimator,
parameters,
cv_size):
# Start training
start_time = time.time()
# Combine all permutation of parameters
grid_obj = GridSearchCV(estimator = estimator,
param_grid = parameters,
n_jobs = -1,
cv = cv_size,
verbose = 1)
# Train model
grid_trained = grid_obj.fit(X_train, y_train)
training_time = time.time() - start_time
# Get the score of the GridSearchCV()
score_gridsearchcv = grid_trained.score(X_test, y_test)
# Get the best parameters that GridSearchCV() found
best_parameters_gridsearchcv = grid_trained.best_params_
# Get the best estimator from GridSearchCV()
best_estimator_gridsearchcv = grid_trained.best_estimator_
# Predict all new test values using the best estimator obtained
predictions_test = best_estimator_gridsearchcv.predict(X_test)
return {'Regression type' : estimator.__class__.__name__,
'Training time' : training_time,
'Score GRCV' : score_gridsearchcv,
'Best parameters estimator GRCV' : best_parameters_gridsearchcv,
'Best estimator GRCV' : best_estimator_gridsearchcv,
'Output Predictions' : predictions_test}
# + [markdown] id="c_sIhVRcXMmX" colab_type="text"
# Ejecutamos el training del modelo
# + id="tsN_rFKgXLyR" colab_type="code" colab={}
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
# Choose which estimator we want to train our data
linear_regression = LinearRegression()
ridge_regression = Ridge()
lasso_regression = Lasso()
decision_tree_regression = DecisionTreeRegressor(random_state = 42)
random_forest_regression = RandomForestRegressor(random_state = 42)
adaboost_regression = AdaBoostRegressor()
regression_type = {"linear_regression" : linear_regression,
"ridge_regression" : ridge_regression,
"lasso_regression" : lasso_regression,
"decision_tree_regression" : decision_tree_regression,
"random_forest_regression" : random_forest_regression,
"adaboost_regression" : adaboost_regression}
# Their parameters
grid_parameters_linear_regression = {'fit_intercept':('True', 'False'), 'normalize':('True', 'False'), 'copy_X':('True', 'False')}
grid_parameters_ridge_regression = {'alpha': [25,10,4,2,1.0,0.8,0.5,0.3,0.2,0.1,0.05,0.02,0.01]}
grid_parameters_lasso_regression = {'alpha': [1, 2, 3, 5, 7, 10, 20, -5, -3]}
grid_parameters_decision_tree_regression = {'max_depth' : [None, 3,5,7,9,10,11]}
grid_parameters_random_forest_regression = {
'bootstrap': [True],
'max_depth': [5, 10, 20],
'max_features': [2, 3],
'min_samples_leaf': [3, 4, 5],
'min_samples_split': [8, 10, 12],
'n_estimators': [10, 20, 30]
}
grid_parameters_adaboost_regression = {
'n_estimators': [50, 100],
'learning_rate' : [0.01,0.05,0.1,0.3,1],
'loss' : ['linear', 'square', 'exponential']
}
parameter_type = {"grid_parameters_linear_regression" : grid_parameters_linear_regression,
"grid_parameters_ridge_regression" : grid_parameters_ridge_regression,
"grid_parameters_lasso_regression" : grid_parameters_lasso_regression,
"grid_parameters_decision_tree_regression" : grid_parameters_decision_tree_regression,
"grid_parameters_random_forest_regression" : grid_parameters_random_forest_regression,
"grid_parameters_adaboost_regression" : grid_parameters_adaboost_regression}
# Size of samples of Cross Validation
kfold_cv_size = 10
# Run model training -> Example to train one model, below they are trained all at once
# trainedModel = trainYachtModelGridSearchCV(dataset['X_train'], dataset['X_test'],
# dataset['y_train'], dataset['y_test'],
# decision_tree_regression,
# grid_parameters_decision_tree_regression,
# kfold_cv_size)
# Output status values of trained model
# print(
# "Regression type: {}".format(trainedModel['Regression type']),
# "Training time: {}".format(trainedModel['Training time']),
# "Score GRCV: {}".format(trainedModel['Score GRCV']),
# "Best parameters estimator GRCV: {}".format(trainedModel['Best parameters estimator GRCV']),
# "Best estimator GRCV: {}".format(trainedModel['Best estimator GRCV']),
# sep = "\n"
# )
# + [markdown] id="ZdUIqKdydVrq" colab_type="text"
# Definimos la obtención de métricas del entrenamiento
# + id="THQw06fpRA3a" colab_type="code" colab={}
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
def getMetricsFromTrainedModel(original_output_data,
predicted_output_data,
data_scaling_function):
# Get metrics from scaled [-1, 1] data
r2 = r2_score(y_true = original_output_data,
y_pred = predicted_output_data)
mse = mean_squared_error(y_true = original_output_data,
y_pred = predicted_output_data)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_true = original_output_data,
y_pred = predicted_output_data)
medae = median_absolute_error(y_true = original_output_data,
y_pred = predicted_output_data)
# Rescale predicted data
predictions_true_scale = predicted_output_data * data_scaling_function[:,-1]
# Rescale output test data
y_test_true_scale = original_output_data * data_scaling_function[:,-1]
# Get metrics from true scaled data (original)
r2_true_scale = r2_score(y_true = y_test_true_scale,
y_pred = predictions_true_scale)
mse_true_scale = mean_squared_error(y_true = y_test_true_scale,
y_pred = predictions_true_scale)
rmse_true_scale = np.sqrt(mse_true_scale)
mae_true_scale = mean_absolute_error(y_true = y_test_true_scale,
y_pred = predictions_true_scale)
medae_true_scale = median_absolute_error(y_true = y_test_true_scale,
y_pred = predictions_true_scale)
return {'R2' : r2,
'R2 True scale' : r2_true_scale,
'MSE' : mse,
'MSE True scale' : mse_true_scale,
'RMSE' : rmse,
'RMSE True scale' : rmse_true_scale,
'MAE' : mae,
'MAE True scale' : mae_true_scale,
'MEDAE' : medae,
'MEDAE True scale' : medae_true_scale,
"Predictions True scale": predictions_true_scale,
"Output Test True scale" : y_test_true_scale}
# + [markdown] id="zfdq-4G6dbhy" colab_type="text"
# Ejecutamos las métricas del modelo
# + id="OxhFGDvGdeQU" colab_type="code" outputId="1b82d856-7c44-42f0-8865-2bc7ab75d71b" colab={"base_uri": "https://localhost:8080/", "height": 187}
# Run statiscitcs of the model -> Example to get the metrics, below they are obtained all at once
# Run statistics of trained model
# metricsTrainedModel = getMetricsFromTrainedModel(dataset['y_test'],
# trainedModel['Output Predictions'],
# dataset['scaler_function'])
# # Output their values
# print(
# "R2: {}".format(metricsTrainedModel['R2']),
# "R2 True scale: {}".format(metricsTrainedModel['R2 True scale']),
# "MSE: {}".format(metricsTrainedModel['MSE']),
# "MSE True scale: {}".format(metricsTrainedModel['MSE True scale']),
# "RMSE: {}".format(metricsTrainedModel['RMSE']),
# "RMSE True scale: {}".format(metricsTrainedModel['RMSE True scale']),
# "MAE: {}".format(metricsTrainedModel['MAE']),
# "MAE True scale: {}".format(metricsTrainedModel['MAE True scale']),
# "MEDAE: {}".format(metricsTrainedModel['MEDAE']),
# "MEDAE True scale: {}".format(metricsTrainedModel['MEDAE True scale']),
# sep = "\n"
# )
# + id="ph4DnrNl_GRb" colab_type="code" outputId="6779f45f-81c5-47d9-e487-ae2538ffb613" colab={"base_uri": "https://localhost:8080/", "height": 591}
# Define function for running all regression types
def runAllRegressionTypes(regression_types, parameters_types):
# Create dataframe for the final table
df_metrics_regression_table = pd.DataFrame(columns = ["Tipus de Regressió",
"Temps d'entrenament [s]",
"Puntuació GRCV",
"Millor param. GRCV",
"R2",
"MSE",
"RMSE",
"MAE",
"MEDAE",
"R2 Reescalat",
"MSE Reescalat",
"RMSE Reescalat",
"MAE Reescalat",
"MEDAE Reescalat"])
# Create dataframe for output predicted values
df_output_predicted_table = pd.DataFrame(columns = ["Tipus de Regressió",
"Valor predit",
"Valor predit reescalat",
"Valor test reescalat"])
# Execute all regression types
i = 0
for (key1, value1), (key2, value2) in zip(regression_types.items(), parameters_types.items()):
i += 1
trainedModelMethod = trainYachtModelGridSearchCV(dataset['X_train'], dataset['X_test'],
dataset['y_train'], dataset['y_test'],
value1,
value2,
kfold_cv_size)
metricsTrainedMethod = getMetricsFromTrainedModel(dataset['y_test'],
trainedModelMethod['Output Predictions'],
dataset['scaler_function'])
df_output_predicted_table.loc[i] = [trainedModelMethod['Regression type'],
trainedModelMethod['Output Predictions'],
metricsTrainedMethod['Predictions True scale'],
metricsTrainedMethod['Output Test True scale']]
df_metrics_regression_table.loc[i] = [trainedModelMethod['Regression type'],
trainedModelMethod['Training time'],
trainedModelMethod['Score GRCV'],
trainedModelMethod['Best parameters estimator GRCV'],
metricsTrainedMethod['R2'],
metricsTrainedMethod['MSE'],
metricsTrainedMethod['RMSE'],
metricsTrainedMethod['MAE'],
metricsTrainedMethod['MEDAE'],
metricsTrainedMethod['R2 True scale'],
metricsTrainedMethod['MSE True scale'],
metricsTrainedMethod['RMSE True scale'],
metricsTrainedMethod['MAE True scale'],
metricsTrainedMethod['MEDAE True scale']]
return df_metrics_regression_table, df_output_predicted_table
# Run all regression types
allRegressionTypes = runAllRegressionTypes(regression_type, parameter_type)
# + [markdown] id="RLYFA8wv6HHu" colab_type="text"
# ## Resultados
# + [markdown] id="xRI3uAeI_HnQ" colab_type="text"
# Tabla que resume las métricas de todos los algoritmos de entrenamiento utilizados, para **GridSearchCV**
# + id="j5X1uo-V0Abz" colab_type="code" outputId="3eec3b61-1488-45aa-e2d9-d63c5c116c31" colab={"base_uri": "https://localhost:8080/", "height": 430}
# Show metrics table
allRegressionTypes[0]
# + id="j-1PtvhJImJe" colab_type="code" outputId="1dbb8e4a-fc31-4c37-bf03-9b273abd05f1" colab={"base_uri": "https://localhost:8080/", "height": 326}
# Show output trained values
allRegressionTypes[1]
# + [markdown] id="0zlQRsHNqBMB" colab_type="text"
# Gráficas que muestran la salida de los modelos y cómo se ajustan los datos reales
# + id="oXopnllFtFa6" colab_type="code" outputId="58ea37f2-2abf-4808-bf0b-dd93ee6ab56d" colab={"base_uri": "https://localhost:8080/", "height": 1000}
# %matplotlib inline
for i in range(1,7):
x = np.linspace(0, 1, 100)
plt.plot(allRegressionTypes[1]['Valor predit'][i], dataset['y_test'], linestyle='none', marker='o')
plt.plot(x, x, '--')
plt.title(allRegressionTypes[1]['Tipus de Regressió'][i])
plt.xlabel('Valor predit')
plt.ylabel('Valor real')
plt.show()
for i in range(1,7):
x = np.linspace(-5, 50, 100)
plt.plot(allRegressionTypes[1]['Valor predit reescalat'][i], allRegressionTypes[1]['Valor test reescalat'][i], linestyle='none', marker='o')
plt.plot(x, x, '--')
plt.title(allRegressionTypes[1]['Tipus de Regressió'][i])
plt.xlabel('Valor predit reescalat')
plt.ylabel('Valor real reescalat')
plt.show()
| Bloc 3 - Machine Learning/Proyecto_ML_CSI.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda root]
# language: python
# name: conda-root-py
# ---
# # Playlist no youtube
#
# https://www.youtube.com/playlist?list=PLvu-cXEstYRPZXyug9IqTJq4JtdBxXgeS
listaNomes = ['python', 'c++','java','fortran']
vogais = ['a','e','i', 'o', 'u']
nv = 0
for nomes in listaNomes:
for letra in nomes:
if letra in vogais:
nv += 1
print('Numeros de vogais em {} é : {}'.format(nomes,nv))
nv = 0
novosNomes = [nomes for nomes in listaNomes]
| 10-nested-loops/nested loops.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={} colab_type="code" id="P0Pffkxc5Mp8"
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import datetime as dt
from datetime import timedelta
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from statsmodels.tsa.api import Holt
# + colab={"base_uri": "https://localhost:8080/", "height": 355} colab_type="code" id="_B0aAhNh6VKk" outputId="d05e3fc9-fa06-46cd-caa6-906d94ad4d52"
covid = pd.read_csv("covid_19_india.csv")
covid.head(10)
# + colab={"base_uri": "https://localhost:8080/", "height": 347} colab_type="code" id="cHHaAVo98ksl" outputId="7ecc92e1-469e-4ee5-8772-29a2d90af68f"
print("Size/Shape of the dataset",covid.shape)
print("Checking for null values",covid.isnull().sum())
print("Checking Data-type",covid.dtypes)
# + colab={} colab_type="code" id="_rnPaCMq9j14"
#Dropping the column
covid.drop(["Sno"],1,inplace=True)
# + colab={"base_uri": "https://localhost:8080/", "height": 156} colab_type="code" id="4ugvWmzo-CKH" outputId="2645e7e6-7595-489d-ab9e-5f7c00ddeebf"
covid.isnull().sum()
# + colab={} colab_type="code" id="zqTvvoU9-Ouf"
covid["Date"] = pd.to_datetime(covid["Date"])
covid["Date"]
# + colab={} colab_type="code" id="HMwOFbap-uVw"
#Grouping differnent types of cases as per the date
datewise = covid.groupby(["Date"]).agg({"Confirmed":"sum","Cured":"sum","Deaths":"sum"})
datewise
# + colab={"base_uri": "https://localhost:8080/", "height": 121} colab_type="code" id="sD_c8lcj_1FY" outputId="68d53054-02bf-425e-f89b-5f56070f016b"
print("Basic Information")
print("Total number of Confirmed cases around the Country",datewise["Confirmed"].iloc[-1])
print("Total number of Recovered cases around the Country",datewise["Cured"].iloc[-1])
print("Total number of Death cases around the Country",datewise["Deaths"].iloc[-1])
print("Total number of Active cases around the Country",(datewise["Confirmed"].iloc[-1]-datewise["Cured"].iloc[-1]-datewise["Deaths"].iloc[-1]))
print("Total number of Closed cases around the Country",(datewise["Cured"].iloc[-1]+datewise["Deaths"].iloc[-1]))
# + colab={"base_uri": "https://localhost:8080/", "height": 467} colab_type="code" id="ozKjnxdaA5lN" outputId="f5e3a590-05ab-4408-a8c2-e869491a8ff7"
plt.figure(figsize=(15,5))
sns.barplot(x=datewise.index.date,y=datewise["Confirmed"]-datewise["Cured"]-datewise["Deaths"])
plt.title("Distributions plot for Active Cases")
plt.xticks(rotation=90)
# + colab={"base_uri": "https://localhost:8080/", "height": 469} colab_type="code" id="jDBqNIyaB4mG" outputId="d7759769-3489-4874-8d39-0b9799de2cbe"
plt.figure(figsize=(15,5))
sns.barplot(x=datewise.index.date,y=datewise["Cured"]+datewise["Deaths"])
plt.title("Distribution plot for Closed Cases")
plt.xticks(rotation=90)
# + colab={"base_uri": "https://localhost:8080/", "height": 367} colab_type="code" id="WOH0PDBOCQO_" outputId="e7b9fa99-7323-4b48-8fbf-664a4d3dbcdb"
datewise["WeekofYear"] = datewise.index.weekofyear
week_num = []
weekwise_confirmed = []
weekwise_recovered = []
weekwise_deaths = []
w = 1
for i in list(datewise["WeekofYear"].unique()):
weekwise_confirmed.append(datewise[datewise["WeekofYear"]==i]["Confirmed"].iloc[-1])
weekwise_recovered.append(datewise[datewise["WeekofYear"]==i]["Cured"].iloc[-1])
weekwise_deaths.append(datewise[datewise["WeekofYear"]==i]["Deaths"].iloc[-1])
week_num.append(w)
w=w+1
plt.figure(figsize=(8,5))
plt.plot(week_num,weekwise_confirmed,'b',linewidth=3)
plt.plot(week_num,weekwise_recovered,'g',linewidth =3)
plt.plot(week_num,weekwise_deaths,'r',linewidth = 3)
plt.legend(['Confirmed','Recovered','Deaths'])
plt.xlabel("WeekNumber")
plt.ylabel("Number of cases")
plt.title("Weekly Progress of different types of cases")
# + colab={"base_uri": "https://localhost:8080/", "height": 295} colab_type="code" id="eOU60zEKETQV" outputId="6fa3e61f-ce97-44f5-9538-252588cd10e9"
fig,(ax1,ax2) = plt.subplots(1,2,figsize=(50,15))
sns.barplot(x= week_num,y=pd.Series(weekwise_confirmed).diff().fillna(0),ax=ax1)
sns.barplot(x= week_num,y=pd.Series(weekwise_deaths).diff().fillna(0),ax=ax2)
ax1.set_xlabel("Week Number")
ax2.set_xlabel("Week Number")
ax1.set_ylabel("Numberof Confirmed cases")
ax2.set_ylabel("Numberof Death cases")
ax1.set_title("Weekly increase in number of Confirmed cases")
ax2.set_title("Weekly increase in number of Death Cases")
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 446} colab_type="code" id="2xofznbZFp-X" outputId="d30c5b35-a770-4235-9e0a-202897b572c6"
from pandas.plotting import register_matplotlib_converters
print("Average increase in number of Confirmed cases everyday:",np.round(datewise["Confirmed"].diff().fillna(0).mean()))
print("Average increase in number of Recovered cases everyday:",np.round(datewise["Cured"].diff().fillna(0).mean()))
print("Average increase in number of Death cases everyday:",np.round(datewise["Deaths"].diff().fillna(0).mean()))
plt.figure(figsize=(15,6))
plt.plot(datewise["Confirmed"].diff().fillna(0),label="Daily increase in confirmed cases",linewidth=3)
plt.plot(datewise["Cured"].diff().fillna(0),label="Daily increase in recovered cases",linewidth=3)
plt.plot(datewise["Deaths"].diff().fillna(0),label="Daily increase in death cases",linewidth=3)
plt.xlabel("Timestamp")
plt.ylabel("Daily increase")
plt.title("Daily increase")
plt.legend()
plt.xticks(rotation=90)
plt.show()
# + colab={} colab_type="code" id="iZ3OXFn0HBKl"
#State wise analysis
#Calculating State wise Mortality rate
countrywise= covid[covid["Date"]==covid["Date"].max()].groupby(["State/UnionTerritory"]).agg({"Confirmed":"sum","Cured":"sum","Deaths":"sum"}).sort_values(["Confirmed"],ascending=False)
countrywise["Mortality"]=(countrywise["Deaths"]/countrywise["Cured"])*100
print("State wise Mortality:",countrywise["Mortality"])
countrywise["Recovered"]=(countrywise["Cured"]/countrywise["Confirmed"])*100
print("State wise Recovered:",countrywise["Recovered"])
# + colab={"base_uri": "https://localhost:8080/", "height": 351} colab_type="code" id="ksTfgDoNIIFQ" outputId="bd2d4281-0c6f-4c2e-cb71-5801e50a85bc"
fig,(ax1,ax2)=plt.subplots(1,2,figsize=(30,15))
top_15confirmed = countrywise.sort_values(["Confirmed"],ascending=False).head(15)
top_15deaths = countrywise.sort_values(["Deaths"],ascending=False).head(15)
sns.barplot(x=top_15confirmed["Confirmed"],y=top_15confirmed.index,ax=ax1)
ax1.set_title("Top 15 states as per number of confirmed cases")
sns.barplot(x=top_15deaths["Deaths"],y=top_15deaths.index,ax=ax2)
ax1.set_title("Top 15 states as per number of cases")
# + colab={"base_uri": "https://localhost:8080/", "height": 121} colab_type="code" id="zrVntjFaKCN7" outputId="f1b64dd4-2893-4a70-8e0e-934aaf340d95"
#Data Anlaysis for Maharashtra
print("Data Anlaysis for Maharashtra\n")
india_data = covid[covid["State/UnionTerritory"]=="Maharashtra"]
datewise_india = india_data.groupby(["Date"]).agg({"Confirmed":"sum","Cured":"sum","Deaths":"sum"})
print(datewise_india.iloc[-1])
print("Total Active Cases",datewise_india["Confirmed"].iloc[-1]-datewise_india["Cured"].iloc[-1]-datewise_india["Deaths"].iloc[-1])
print("Total Closed Cases",datewise_india["Cured"].iloc[-1]+datewise_india["Deaths"].iloc[-1])
# + colab={"base_uri": "https://localhost:8080/", "height": 367} colab_type="code" id="24HqY4g_Lj7M" outputId="cffdb2be-d8e3-4f24-d0a5-8f2d4e8e2b4f"
datewise_india["WeekofYear"] = datewise_india.index.weekofyear
week_num_india = []
india_weekwise_confirmed = []
india_weekwise_recovered = []
india_weekwise_deaths = []
w = 1
for i in list(datewise_india["WeekofYear"].unique()):
india_weekwise_confirmed.append(datewise_india[datewise_india["WeekofYear"]==i]["Confirmed"].iloc[-1])
india_weekwise_recovered.append(datewise_india[datewise_india["WeekofYear"]==i]["Cured"].iloc[-1])
india_weekwise_deaths.append(datewise_india[datewise_india["WeekofYear"]==i]["Deaths"].iloc[-1])
week_num_india.append(w)
w=w+1
plt.figure(figsize=(8,5))
plt.plot(week_num_india,india_weekwise_confirmed,linewidth=3)
plt.plot(week_num_india,india_weekwise_recovered,linewidth =3)
plt.plot(week_num_india,india_weekwise_deaths,linewidth = 3)
plt.xlabel("WeekNumber")
plt.ylabel("Number of cases")
plt.title("Weekly Progress of different types of cases in India")
# + colab={} colab_type="code" id="YvJTmn_IQQW-"
datewise["Days Since"]=datewise.index-datewise.index[0]
datewise["Days Since"] = datewise["Days Since"].dt.days
print(datewise["Days Since"])
train_ml = datewise.iloc[:int(datewise.shape[0]*0.95)]
valid_ml = datewise.iloc[:int(datewise.shape[0]*0.95):]
model_scores=[]
# + colab={"base_uri": "https://localhost:8080/", "height": 107} colab_type="code" id="eqEkxiSTSFYM" outputId="d9735999-6df0-4848-9779-5dbc768b6bc5"
lin_reg = LinearRegression(normalize=True)
svm = SVR(C=1,degree=5,kernel='poly',epsilon=0.001)
lin_reg.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Confirmed"]).reshape(-1,1))
svm.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Confirmed"]).reshape(-1,1))
# + colab={} colab_type="code" id="-vdSWf-vSs-i"
prediction_valid_lin_reg = lin_reg.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
prediction_valid_svm = svm.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
# + colab={"base_uri": "https://localhost:8080/", "height": 202} colab_type="code" id="H5Ru-3q_THpI" outputId="e1d7d9d3-4043-46c7-c752-c384f49dd415"
new_date = []
new_prediction_lr=[]
new_prediction_svm=[]
for i in range(1,11):
new_date.append(datewise.index[-1]+timedelta(days=i))
new_prediction_lr.append(lin_reg.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0][0])
new_prediction_svm.append(svm.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0])
pd.set_option("display.float_format",lambda x: '%.f' % x)
model_predictions=pd.DataFrame(zip(new_date,new_prediction_lr,new_prediction_svm),columns = ["Dates","LR","SVR"])
model_predictions.head(10)
# + colab={} colab_type="code" id="X6Pt_-i5UZU_"
model_train=datewise.iloc[:int(datewise.shape[0]*0.85)]
valid=datewise.iloc[int(datewise.shape[0]*0.85):]
# + colab={} colab_type="code" id="qd34fQ4IVzLR"
holt=Holt(np.asarray(model_train["Confirmed"]).astype('double')).fit(smoothing_level=1.4,smoothing_slope=0.2)
y_pred = valid.copy()
y_pred["Holt"]=holt.forecast(len(valid))
# + colab={"base_uri": "https://localhost:8080/", "height": 202} colab_type="code" id="ddhHqG1wWUXW" outputId="6d0440c7-33f8-4b3f-f3f5-a8e1c1dfd02a"
holt_new_date=[]
holt_new_prediction=[]
for i in range(1,11):
holt_new_date.append(datewise.index[-1]+timedelta(days=i))
holt_new_prediction.append(holt.forecast((len(valid)+i))[-1])
model_predictions["Holts Linear Model Prediction"]=holt_new_prediction
print("Confirmed Cases")
model_predictions.head(10)
# -
lin_reg = LinearRegression(normalize=True)
svm = SVR(C=1,degree=5,kernel='poly',epsilon=0.001)
lin_reg.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Cured"]).reshape(-1,1))
svm.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Cured"]).reshape(-1,1))
prediction_valid_lin_reg = lin_reg.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
prediction_valid_svm = svm.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
new_date = []
new_prediction_lr=[]
new_prediction_svm=[]
for i in range(1,11):
new_date.append(datewise.index[-1]+timedelta(days=i))
new_prediction_lr.append(lin_reg.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0][0])
new_prediction_svm.append(svm.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0])
pd.set_option("display.float_format",lambda x: '%.f' % x)
model_predictions=pd.DataFrame(zip(new_date,new_prediction_lr,new_prediction_svm),columns = ["Dates","LR","SVR"])
model_predictions.head(10)
model_train=datewise.iloc[:int(datewise.shape[0]*0.85)]
valid=datewise.iloc[int(datewise.shape[0]*0.85):]
holt=Holt(np.asarray(model_train["Cured"]).astype('double')).fit(smoothing_level=1.4,smoothing_slope=0.2)
y_pred = valid.copy()
y_pred["Holt"]=holt.forecast(len(valid))
# +
holt_new_date=[]
holt_new_prediction=[]
for i in range(1,11):
holt_new_date.append(datewise.index[-1]+timedelta(days=i))
holt_new_prediction.append(holt.forecast((len(valid)+i))[-1])
model_predictions["Holts Linear Model Prediction"]=holt_new_prediction
print("Cured Cases")
model_predictions.head(10)
# -
lin_reg = LinearRegression(normalize=True)
svm = SVR(C=1,degree=5,kernel='poly',epsilon=0.001)
lin_reg.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Deaths"]).reshape(-1,1))
svm.fit(np.array(train_ml["Days Since"]).reshape(-1,1),np.array(train_ml["Deaths"]).reshape(-1,1))
prediction_valid_lin_reg = lin_reg.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
prediction_valid_svm = svm.predict(np.array(valid_ml["Days Since"]).reshape(-1,1))
new_date = []
new_prediction_lr=[]
new_prediction_svm=[]
for i in range(1,11):
new_date.append(datewise.index[-1]+timedelta(days=i))
new_prediction_lr.append(lin_reg.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0][0])
new_prediction_svm.append(svm.predict(np.array(datewise["Days Since"].max()+i).reshape(-1,1))[0])
pd.set_option("display.float_format",lambda x: '%.f' % x)
model_predictions=pd.DataFrame(zip(new_date,new_prediction_lr,new_prediction_svm),columns = ["Dates","LR","SVR"])
model_predictions.head(10)
model_train=datewise.iloc[:int(datewise.shape[0]*0.85)]
valid=datewise.iloc[int(datewise.shape[0]*0.85):]
holt=Holt(np.asarray(model_train["Deaths"]).astype('double')).fit(smoothing_level=1.4,smoothing_slope=0.2)
y_pred = valid.copy()
y_pred["Holt"]=holt.forecast(len(valid))
# +
holt_new_date=[]
holt_new_prediction=[]
for i in range(1,11):
holt_new_date.append(datewise.index[-1]+timedelta(days=i))
holt_new_prediction.append(holt.forecast((len(valid)+i))[-1])
model_predictions["Holts Linear Model Prediction"]=holt_new_prediction
print("Death Cases")
model_predictions.head(10)
| covid.ipynb |
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .fs
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: .NET (F#)
// language: F#
// name: .net-fsharp
// ---
// <img src="http://fsharp.org/img/logo/fsharp512.png" style="align:center" />
//
//
// ## Functional verifiable tensor fabric for scientific computing built with F# and TensorFlow 2
| notebooks/TFWorld.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
import syft as sy
import pandas as pd
canada = pd.read_csv("../../../trade_demo/datasets/ca - feb 2021.csv")
canada.head()
canada[canada["Partner"] == "Egypt"] and canada[canada["
import numpy as np
data1 = np.zeros((10, 10))
data2 = np.eye(10, 10)
data1
ishan = sy.core.adp.entity.Entity(name="Ishan")
tensor1 = sy.Tensor(data1).tag("test_tensor")
tensor2 = sy.Tensor(data2).tag("test_tensor")
from syft.core.tensor.logical_and import logical_and
logical_and(tensor1, tensor2)
from numpy import logical_and as np_and
np_and(tensor1.child, tensor2.child)
| notebooks/Experimental/Ishan/ADP Demo/Debugging/Debug AND Debug.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/harshatejas/cats_vs_dogs_instance_segmentation/blob/main/Train.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + colab={"base_uri": "https://localhost:8080/"} id="umV37zrMXoLO" outputId="c3775ad4-6818-4852-b7c1-d3b492c84579"
# !git clone https://github.com/harshatejas/cats_vs_dogs_instance_segmentation.git
# + colab={"base_uri": "https://localhost:8080/"} id="gPaWm2UkX1yR" outputId="33207147-e039-4733-8882-5d75b10a640b"
# %cd /content/cats_vs_dogs_instance_segmentation
# + [markdown] id="zyJFALVNYC5J"
# # Download the dataset
# from Oxford-IIIT Pet Dataset website - https://www.robots.ox.ac.uk/~vgg/data/pets/
#
#
#
#
# + colab={"base_uri": "https://localhost:8080/"} id="ZcAw7JaiX7ys" outputId="b0c6c6d4-9d74-423c-efab-8afccd6b6c97"
# !wget https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz
# !wget https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz
# + colab={"base_uri": "https://localhost:8080/"} id="YzMDnGMJYhty" outputId="c0ac9efd-61eb-469d-eb45-73fa0684ea6b"
# Extract the files in the current folder
# !tar -xvf images.tar.gz
# !tar -xvf annotations.tar.gz
# + id="wQ9pgwgSYqGd"
# Imports
import os
from PIL import Image
import numpy as np
import shutil
import xml.etree.ElementTree as ET
import torch
import torch.utils.data as data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
import sys
# Add dependencies to sys path, to be able to import from dependencies folder
sys.path.append('dependencies')
# Dependencies folder contains helpder functions to simplify training and evaluation from TorchVision repo
from engine import train_one_epoch, evaluate
import utils
import transforms as T
# + id="r0bv5GGzZDKP"
# Hyperparameters
test_set_length = 500 # Test set (number of images)
train_batch_size = 2 # Train batch size
test_batch_size = 1 # Test batch size
num_classes = 3 # Number of classes
# Number of classes - background + cat + dog
learning_rate = 0.005 # Learning rate
num_epochs = 10 # Number of epochs
output_dir = "saved_model" # Output directory to save the model
# + id="87CHNXIEZFMn"
class OxfordPetDataset(data.Dataset):
""" The dataset contains images, masks and annotations
The dataset also includes the breed of cats and dogs """
def __init__(self, root, transforms = None):
self.root = root
self.transforms = transforms
self.imgs = list(sorted(os.listdir(os.path.join(root, "Images"))))
self.masks = list(sorted(os.listdir(os.path.join(root, "Masks"))))
self.xmls = list(sorted(os.listdir(os.path.join(root, "Xmls"))))
def __getitem__(self, idx):
img_path = os.path.join(self.root, "Images", self.imgs[idx])
mask_path = os.path.join(self.root, "Masks", self.masks[idx])
xml = ET.parse(os.path.join(self.root, "Xmls", self.xmls[idx]))
# Extract class(label) name from xml file
annotation = xml.getroot()
class_name = annotation[5][0].text
# Assign label id, 1 - cat and 2 - dog
if class_name == 'cat':
label_id = 1
elif class_name == 'dog':
label_id = 2
# Read image
img = Image.open(img_path).convert("RGB")
# Read mask and convert to numpy array
mask = Image.open(mask_path)
mask = np.array(mask)
# Instances are encoded as different colors
obj_ids = np.unique(mask)
# First id is background, so remove it
obj_ids = obj_ids[1:]
# Creating binary masks
masks = mask == obj_ids[:, None, None]
# Get bounding box coordinates for each mask
boxes = []
pos = np.where(masks[1])
xmin = np.min(pos[1])
xmax = np.max(pos[1])
ymin = np.min(pos[0])
ymax = np.max(pos[0])
boxes.append([xmin, ymin, xmax, ymax])
# Convert bounding box coordinates into torch tensor
boxes = torch.as_tensor(boxes, dtype = torch.float32)
# Convert label into torch tensor
labels = torch.tensor((label_id,), dtype = torch.int64)
# Convert boolean to 1's and 0's
masks = masks.astype('uint8')
# The array contains two masks, first one is the mask without boundary around the object
# The second array is the boundary around the object
# Add both the arrays
masks = masks[0] + masks[1]
# Converting all the 1's into 0's and 0's into 1's
# This is done in order to swap the mask covering the object to the mask covering the area other than object
indices_one = masks == 1
indices_zero = masks == 0
masks[indices_zero] = 1
masks[indices_one] = 0
# Add batch_size (1) to the mask shape
masks = np.reshape(masks, (1, masks.shape[0], masks.shape[1]))
# Convert mask into torch tensor
masks = torch.as_tensor(masks, dtype = torch.uint8)
image_id = torch.tensor([idx])
# Area of the bouding box
area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
iscrowd = torch.tensor((label_id,), dtype = torch.int64)
target = {}
target["boxes"] = boxes
target["labels"] = labels
target["masks"] = masks
target["image_id"] = image_id
target["area"] = area
target["iscrowd"] = iscrowd
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
# + id="MkxvxDT9a-ms"
# Helper functions
def get_model(num_classes):
# Load instance segmentation model pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained = True)
# Get the number of input features
in_features = model.roi_heads.box_predictor.cls_score.in_features
# Replace the pre-trained head with a new head
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# Get the number of input features for mask classification
in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
hidden_layer = 256
# Replace the mask predictor with new one
model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes)
return model
def get_transforms(train):
transforms = []
# Convert numpy image to PyTorch Tensor
transforms.append(T.ToTensor())
if train:
# Data augmentation
transforms.append(T.RandomHorizontalFlip(0.5))
return T.Compose(transforms)
# + colab={"base_uri": "https://localhost:8080/"} id="R60qFFPUZc97" outputId="0da225e8-c161-4ec4-a696-0ae9ed973736"
# Spliting the data into train and validation based on availability of annotations
os.mkdir("OxfordDataset")
os.mkdir("OxfordDataset/Images")
os.mkdir("OxfordDataset/Masks")
os.mkdir("OxfordDataset/Xmls")
os.mkdir("OxfordDataset/Images_val")
os.mkdir("OxfordDataset/Masks_val")
xml_list = list(sorted(os.listdir('annotations/xmls')))
for i in xml_list:
source = os.path.join("annotations/xmls/", i)
dest = "OxfordDataset/Xmls/"
shutil.move(source, dest)
images_list = []
masks_list = []
for xml_string in xml_list:
image_string = xml_string.replace(".xml",".jpg")
mask_string = xml_string.replace(".xml",".png")
images_list.append(image_string)
masks_list.append(mask_string)
for i in masks_list:
source = os.path.join("annotations/trimaps/", i)
dest = "OxfordDataset/Masks/"
shutil.move(source, dest)
print("Done creating train masks folder")
for i in images_list:
source = os.path.join("images", i)
dest = "OxfordDataset/Images/"
shutil.move(source, dest)
print("Done creating train images folder")
val_masks_list = list(sorted(os.listdir("annotations/trimaps/")))
val_images_list = list(sorted(os.listdir("images")))
for i in val_masks_list:
source = os.path.join("annotations/trimaps/", i)
dest = "OxfordDataset/Masks_val/"
shutil.move(source, dest)
print("Done creating validation masks folder")
for i in val_images_list:
source = os.path.join("images", i)
dest = "OxfordDataset/Images_val/"
shutil.move(source, dest)
print("Done creating validation images folder")
# + id="B86SLFZHZuxK"
# Remove corrupted images
os.remove("OxfordDataset/Images/Egyptian_Mau_129.jpg")
os.remove("OxfordDataset/Masks/Egyptian_Mau_129.png")
os.remove("OxfordDataset/Xmls/Egyptian_Mau_129.xml")
os.remove("OxfordDataset/Images/Egyptian_Mau_162.jpg")
os.remove("OxfordDataset/Masks/Egyptian_Mau_162.png")
os.remove("OxfordDataset/Xmls/Egyptian_Mau_162.xml")
os.remove("OxfordDataset/Images/Egyptian_Mau_165.jpg")
os.remove("OxfordDataset/Masks/Egyptian_Mau_165.png")
os.remove("OxfordDataset/Xmls/Egyptian_Mau_165.xml")
os.remove("OxfordDataset/Images/Egyptian_Mau_196.jpg")
os.remove("OxfordDataset/Masks/Egyptian_Mau_196.png")
os.remove("OxfordDataset/Xmls/Egyptian_Mau_196.xml")
os.remove("OxfordDataset/Images/leonberger_18.jpg")
os.remove("OxfordDataset/Masks/leonberger_18.png")
os.remove("OxfordDataset/Xmls/leonberger_18.xml")
os.remove("OxfordDataset/Images/miniature_pinscher_14.jpg")
os.remove("OxfordDataset/Masks/miniature_pinscher_14.png")
os.remove("OxfordDataset/Xmls/miniature_pinscher_14.xml")
os.remove("OxfordDataset/Images/saint_bernard_108.jpg")
os.remove("OxfordDataset/Masks/saint_bernard_108.png")
os.remove("OxfordDataset/Xmls/saint_bernard_108.xml")
# + colab={"base_uri": "https://localhost:8080/"} id="rbxzo-z0Z_Q5" outputId="544c0473-5542-4ab0-ff68-d081eb571457"
# Set up the device
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# Define train and test dataset
dataset = OxfordPetDataset('OxfordDataset', get_transforms(train = True))
dataset_test = OxfordPetDataset('OxfordDataset', get_transforms(train = False))
# Split the dataset into train and test
torch.manual_seed(1)
indices = torch.randperm(len(dataset)).tolist()
dataset = torch.utils.data.Subset(dataset, indices[:-test_set_length])
dataset_test = torch.utils.data.Subset(dataset_test, indices[-test_set_length:])
# Define train and test dataloaders
data_loader = torch.utils.data.DataLoader(dataset, batch_size = train_batch_size,
shuffle = True, num_workers = 2, collate_fn = utils.collate_fn)
data_loader_test = torch.utils.data.DataLoader(dataset_test, batch_size = test_batch_size,
shuffle = False, num_workers = 2, collate_fn = utils.collate_fn)
print(f"We have: {len(indices)} images in the dataset, {len(dataset)} are training images and {len(dataset_test)} are test images")
# + colab={"base_uri": "https://localhost:8080/", "height": 103, "referenced_widgets": ["f27b8041f1f44a228707d6a82cae19f2", "4f72aef600754622beae9fd4a1e3948a", "aa51873141394b47ab8501ec2909f35c", "44ff51e93aae4895b274c2e27e03c438", "125c18a979a24bf0a17dfabfec2676f6", "<KEY>", "2f49898f35b447a7b30d41794d0301c4", "39e5de348c8d45bd8acb9b65630f54ee"]} id="mnmApIAYaD7h" outputId="4e8681ff-f458-42ff-e7a8-5b6b6bc87701"
# Get the model using helper function
model = get_model(num_classes)
model.to(device)
# Construct the optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr = learning_rate, momentum = 0.9, weight_decay = 0.0005)
# Learning rate scheduler decreases the learning rate by 10x every 3 epochs
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size = 3, gamma = 0.1)
# + colab={"base_uri": "https://localhost:8080/"} id="PdKIF2M1aO83" outputId="77ff73ca-6032-42af-fa4d-1472cc2c31b7"
for epoch in range(num_epochs):
train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
lr_scheduler.step()
# Evaluate on the test datase
evaluate(model, data_loader_test, device = device)
# + id="e21Gl-WsaYnZ"
if not os.path.exists(output_dir):
os.mkdir(output_dir)
# Save the model state
torch.save(model.state_dict(), output_dir + "/model")
# + colab={"base_uri": "https://localhost:8080/", "height": 17} id="XysbqoC2aapk" outputId="8348008e-0341-49bb-c643-0b8cb0fb803b"
from google.colab import files
files.download(output_dir + "/model")
| Train.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Quick study to investigate oscillations in reported infections in Germany. Here is the plot of the data in question:
# +
import coronavirus
import numpy as np
import matplotlib.pyplot as plt
# %config InlineBackend.figure_formats = ['svg']
coronavirus.display_binder_link("2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb")
# +
# get data
cases, deaths, country_label = coronavirus.get_country_data("Germany")
# plot daily changes
fig, ax = plt.subplots(figsize=(8, 4))
coronavirus.plot_daily_change(ax, cases, 'C1')
# -
# The working assumption is that during the weekend fewer numbers are captured or reported. The analysis below seems to confirm this.
#
# We compute a discrete Fourier transform of the data, and expect a peak at a frequency corresponding to a period of 7 days.
# ## Data selection
#
# We start with data from 1st March as numbers before were small. It is convenient to take a number of days that can be divided by seven (for alignment of the freuency axis in Fourier space, so we choose 63 days from 1st of March):
# +
data = cases['2020-03-01':'2020-05-03']
# compute daily change
diff = data.diff().dropna()
# plot data points (corresponding to bars in figure above:)
fig, ax = plt.subplots()
ax.plot(diff.index, diff, '-C1',
label='daily new cases Germany')
fig.autofmt_xdate() # avoid x-labels overlap
# How many data points (=days) have we got?
diff.size
# -
diff2 = diff.resample("24h").asfreq() # ensure we have one data point every day
diff2.size
# ## Compute the frequency spectrum
fig, ax = plt.subplots()
# compute power density spectrum
change_F = abs(np.fft.fft(diff2))**2
# determine appropriate frequencies
n = change_F.size
freq = np.fft.fftfreq(n, d=1)
# We skip values at indices 0, 1 and 2: these are large because we have a finite
# sequence and not substracted the mean from the data set
# We also only plot the the first n/2 frequencies as for high n, we get negative
# frequencies with the same data content as the positive ones.
ax.plot(freq[3:n//2], change_F[3:n//2], 'o-C3')
ax.set_xlabel('frequency [cycles per day]');
# A signal with oscillations on a weekly basis would correspond to a frequency of 1/7 as frequency is measured in `per day`. We thus expect the peak above to be at 1/7 $\approx 0.1428$.
#
# We can show this more easily by changing the frequency scale from cycles per day to cycles per week:
#
fig, ax = plt.subplots()
ax.plot(freq[3:n//2] * 7, change_F[3:n//2], 'o-C3')
ax.set_xlabel('frequency [cycles per week]');
# In other words: there as a strong component of the data with a frequency corresponding to one week.
#
#
# This is the end of the notebook.
# # Fourier transform basics
#
# A little playground to explore properties of discrete Fourier transforms.
# +
time = np.linspace(0, 4, 1000)
signal_frequency = 3 # choose this freely
signal = np.sin(time * 2 * np.pi * signal_frequency)
fourier = np.abs(np.fft.fft(signal))
# compute frequencies in fourier spectrum
n = signal.size
timestep = time[1] - time[0]
freqs = np.fft.fftfreq(n, d=timestep)
# -
fig, ax = plt.subplots()
ax.plot(time, signal, 'oC9', label=f'signal, frequency={signal_frequency}')
ax.set_xlabel('time')
ax.legend()
fig, ax = plt.subplots()
ax.plot(freqs[0:n//2][:20], fourier[0:n//2][0:20], 'o-C8', label="Fourier transform")
ax.legend()
ax.set_xlabel('frequency');
coronavirus.display_binder_link("2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb")
| ipynb/2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:nes-lter-ims-dev]
# language: python
# name: conda-env-nes-lter-ims-dev-py
# ---
# ## NES-LTER: Comparison between CTD and sampled chlorophyll concentration estimates
#
# This notebook combines chlorophyll concentration estimates derived from a CTD-mounted fluorometer with corresponding estaimates derived from lab processing of samples. This enables confirming that the estimates match, which aids in the decision of when to take samples.
# First, read chlorophyll and CTD data from GitHub
# +
import pandas as pd
BASE_URL = 'https://nes-lter-data.whoi.edu/api/'
chl = pd.read_csv(BASE_URL + 'chl/en608.csv')
btl = pd.read_csv(BASE_URL + 'ctd/en608/bottles.csv')
# -
btl.head(5)
# Samples are replicated, so the chlorophyll concentration needs to be averaged across those replicates. This uses a function called `average_replicates`
def average_replicates(chl, replicates=['a','b'], var='chl'):
rows = []
# group by cruise, cast, niskin, and filter mesh size
for ccnf, sdf in chl.groupby(['cruise','cast','niskin','filter_size']):
# remove all rows except the replicates we want
sdf_reps = sdf[sdf['replicate'].isin(replicates)]
# average the variable
var_average = sdf_reps[var].mean()
# construct the output row
row = ccnf + (var_average,)
rows.append(row)
return pd.DataFrame(rows, columns=['cruise','cast','niskin','filter_size',var])
# +
chl_avg = average_replicates(chl)
# now only include WSW
chl_avg = chl_avg[chl_avg['filter_size'] == '>0']
chl_avg.head()
# -
# Now the two datasets need to be collated so that they align on cruise, cast, and niskin bottle number.
# The column containing CTD-derived data is called `fleco_afl` and the one containing the sample-derived data is called `chl`.
# +
# merge sample and CTD data per-niskin
merged = btl.merge(chl_avg, on=['cruise','cast','niskin'])
# display a few rows to make sure we're doing it right
merged[['cruise','cast','niskin','chl','fleco_afl','par']].head()
# +
# %matplotlib inline
# now plot CTD against sampled data
ax = merged.plot.scatter(
x='chl',
y='fleco_afl',
c='par',
s=50,
cmap='viridis',
edgecolor='black',
title='CHL concentration: CTD vs. sampled',
grid=True,
figsize=(10,8),
sharex=False
)
ax.set_xlabel('sampled')
ax.set_ylabel('CTD');
| notebooks/compare_ctd_chl_api.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Moving, rotating, mirroring
# There are several actions we can take to move and rotate PHIDL objects. These actions include movement, rotation, and reflection. There are several types of PHIDL objects (`Device`, `DeviceReference`, `Port`, `Polygon`, `CellArray`, `Label`, and `Group`) but they all can be moved and manipulated in the same ways.
#
# ## Basic movement and rotation
#
# We'll start by creating a blank Device and some shapes. We'll add the shapes to the Device as references
# +
import phidl.geometry as pg
from phidl import quickplot as qp
from phidl import Device
# Start with a blank Device
D = Device()
# Create some more shape Devices
T = pg.text('hello', size = 10, layer = 1)
E = pg.ellipse(radii = (10,5))
R = pg.rectangle(size = (10,3), layer = 2)
# Add the shapes to D as references
text = D << T
ellipse = D << E
rect1 = D << R
rect2 = D << R
qp(D) # quickplot it!
# -
# Now let's practice moving and rotating the objects:
# +
text.move([10,4]) # Translate by dx = 10, dy = 4
ellipse.move(origin = [1,1], destination = [2,2.5]) # Translate by dx = 1, dy = 1.5
rect1.move([1,1], [5,5], axis = 'y') # Translate by dx = 0, dy = 4 (motion only along y-axis)
rect2.movey(4) # Same as specifying axis='y' in the move() command
rect2.movex(4) # Same as specifying axis='x'' in the move() command
ellipse.movex(30,40) # Moves "from" x=30 "to" x=40 (i.e. translates by dx = 10)
rect1.rotate(45) # Rotate the first waveguide by 45 degrees around (0,0)
rect2.rotate(-30, center = [1,1]) # Rotate the second waveguide by -30 degrees around (1,1)
text.mirror(p1 = [1,1], p2 = [1,3]) # Reflects across the line formed by p1 and p2
qp(D) # quickplot it!
# -
# ## Working with properties
#
# Each Device and DeviceReference object has several properties which can be used to learn information about the object (for instance where it's center coordinate is). Several of these properties can actually be used to move the geometry by assigning them new values.
#
# Available properties are:
#
# - `xmin` / `xmax`: minimum and maximum x-values of all points within the object
# - `ymin` / `ymax`: minimum and maximum y-values of all points within the object
# - `x`: centerpoint between minimum and maximum x-values of all points within the object
# - `y`: centerpoint between minimum and maximum y-values of all points within the object
# - `bbox`: bounding box (see note below) in format ((xmin,ymin),(xmax,ymax))
# - `center`: center of bounding box
print('bounding box:')
print(text.bbox) # Will print the bounding box of text in terms of [(xmin, ymin), (xmax, ymax)]
print('xsize and ysize:')
print(text.xsize) # Will print the width of text in the x dimension
print(text.ysize) # Will print the height of text in the y dimension
print('center:')
print(text.center) # Gives you the center coordinate of its bounding box
print('xmax')
print(ellipse.xmax) # Gives you the rightmost (+x) edge of the ellipse bounding box
# Let's use these properties to manipulate our shapes to arrange them a little better
# +
# First let's center the ellipse
ellipse.center = [0,0] # Move the ellipse such that the bounding box center is at (0,0)
# Next, let's move the text to the left edge of the ellipse
text.y = ellipse.y # Move the text so that its y-center is equal to the y-center of the ellipse
text.xmax = ellipse.xmin # Moves the ellipse so its xmax == the ellipse's xmin
# Align the right edge of the rectangles with the x=0 axis
rect1.xmax = 0
rect2.xmax = 0
# Move the rectangles above and below the ellipse
rect1.ymin = ellipse.ymax + 5
rect2.ymax = ellipse.ymin - 5
qp(D)
# -
# In addition to working with the properties of the references inside the Device, we can also manipulate the whole Device if we want. Let's try mirroring the whole Device `D`:
# +
print(D.xmax) # Prints out '10.0'
D.mirror((0,1)) # Mirror across line made by (0,0) and (0,1)
qp(D)
# -
# ### A note about bounding boxes
#
# When we talk about bounding boxes, we mean it in the sense of the smallest enclosing box which contains all points of the geometry. So the bounding box for the device D looks like this:
# +
# The phidl.geometry library has a handy bounding-box function
# which takes a bounding box and creates a rectangle shape for it
device_bbox = D.bbox
D << pg.bbox(device_bbox, layer = 3)
qp(D)
# -
# When we query the properties of D, they will be calculated with respect to this bounding-rectangle. For instance:
# +
print('Center of Device D:')
print(D.center)
print('X-max of Device D:')
print(D.xmax)
# -
# ## Chaining commands
#
# Many of the movement/manipulation functions return the object they manipulate. We can use this to chain multiple commands in a single line.
#
# For instance these two expressions:
# ```
# rect1.rotate(angle = 37)
# rect1.move([10,20])
# ```
# ...are equivalent to this single-line expression
# ```
# rect1.rotate(angle = 37).move([10,20])
# ```
| docs/tutorials/movement.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # RANSAC
#
# It is well known that least squares parameter estimation is not resistent, i.e. sensitive to outliers. Even one outlier may break least squares estimation, which means a possibly infinitely large parameter bias.
#
# This problem is effectively solved by **RANSAC (RANdom Sample And Consensus)** introduced By <NAME> Bolles in 1981. They solved a problem with a large percent of outliers in the input data. Even 50% of outliers may be tolerated by RANSAC.
#
# Therefore RANSAC is a resistent iterative parameter estimation procedure that uses a subset of data consistent with a model. At each iteration step the procedure works as follows:
#
# 1. Select a random minimal sample from data and check conformity
# 2. Estimate model and check its validity
# 3. Classify data as conformal or outlier based on deviations from the model - data are conformal if deviations are below threshold
# 4. Keep model if the number of conformal data is maximum.
#
# Iteration ends upon reaching a specified maximum number or upon a specific criterion. Model parameters are then estimated using the best model.
# ## RANSAC ellipse fitting
#
# RANSAC is illustrated with a simple problem.
#
# Generate conformal data that approximately fit on an ellipse:
import numpy as np
t = np.linspace(0, 2 * np.pi, 50)
a = 10
b = 5
xc = 20
yc = 30
theta = np.pi/6
x = xc + a*np.cos(theta)*np.cos(t) - b*np.sin(theta)*np.sin(t)
y = yc + a*np.sin(theta)*np.cos(t) + b*np.cos(theta)*np.sin(t)
data = np.column_stack([x, y])
# for reproducibility:
np.random.seed(seed=1234)
data += np.random.normal(size=data.shape)
# Add some outliers:
# +
data[0] = (100, 100)
data[1] = (110, 120)
data[2] = (120, 130)
data[3] = (140, 130)
# %matplotlib inline
import matplotlib.pyplot as plt
plt.plot(data[:,0],data[:,1],'r.')
plt.show()
# -
# ### Use total least squares estimation
#
# The image processing library [Scikit-image](http://scikit-image.org) will be used for estimation. It contains implementation of both least squares and RANSAC estimation that can be used for our problem. We import only a few functions in `sm.py`
import sm
model = sm.EllipseModel()
model.estimate(data)
# ellipse parameters:
# xc, yc, a, b, theta
np.set_printoptions(suppress=True)
model.params
# As we see these parameters are completely wrong. Original semi-axes of the ellipse were 10 and 5, the centre was at $O(20,30)$.
# ### RANSAC estimation
# at least 5 points are needed for ellipse fitting
n_min = 5
# maximum distance of conform points
t_max = 3.0
ransac_model, inliers = sm.ransac(data, sm.EllipseModel, n_min, t_max, max_trials=50)
print(ransac_model.params)
original_params = np.array([xc,yc,a,b,theta])
print(original_params - ransac_model.params)
# Conformal data were found and stored in array 'inliers' as logical 'True' elements:
inliers
# We see that the first four data are outliers that were added by us.
# ### Plot best fitting ellipse to conformal data
t = np.linspace(0, 2 * np.pi, 100)
p = ransac_model.params
xe = p[0] + p[2]*np.cos(p[4])*np.cos(t) - p[3]*np.sin(p[4])*np.sin(t)
ye = p[1] + p[2]*np.sin(p[4])*np.cos(t) + p[3]*np.cos(p[4])*np.sin(t)
plt.clf()
plt.plot(data[inliers,0],data[inliers,1],'r.')
plt.plot(xe,ye,'b-')
plt.plot(p[0],p[1],'bo')
plt.axis('equal')
plt.show()
# Next we first determine position and radius of a reference sphere using laser scanner data.([SphRANSAC](https://nbviewer.jupyter.org/github/gyulat/Korszeru_matek/blob/master/SphRANSAC_en.ipynb)). Then we solve a more complicated geometrical problem: determine parameters of a best fitting right circular cylinder using a point cloud with outliers ([CylRANSAC](https://nbviewer.jupyter.org/github/gyulat/Korszeru_matek/blob/master/CylRANSAC_en.ipynb)).
| RANSAC.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as plt
from scipy import integrate
import sympy
import mpmath
sympy.init_printing()
a, b, X = sympy.symbols("a, b, X")
f = sympy.Function("f")
x = b, (a+b)/ 5, b
w = [sympy.symbols("w_%i" %i) for i in range (len(x))]
q_rule = sum([w[i] * f(x[i]) for i in range(len(x))])
q_rule
| beta_01/08_integration/Untitled-Copy1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# !pip3 install tqdm requests dill
# +
import requests
from tqdm import tqdm
import os
def download_from_url(url, dst):
file_size = int(requests.head(url).headers["Content-Length"])
if os.path.exists(dst):
first_byte = os.path.getsize(dst)
else:
first_byte = 0
if first_byte >= file_size:
return file_size
header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}
pbar = tqdm(
total=file_size, initial=first_byte,
unit='B', unit_scale=True, desc=url.split('/')[-1])
req = requests.get(url, headers=header, stream=True)
with(open(dst, 'ab')) as f:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
pbar.update(1024)
pbar.close()
return file_size
def load_mnist(path, kind='train'):
import os
import gzip
import numpy as np
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
'%s-labels-idx3-ubyte.gz'
% kind)
images_path = os.path.join(path,
'%s-images-idx3-ubyte.gz'
% kind)
with gzip.open(labels_path, 'rb') as lbpath:
labels = np.frombuffer(lbpath.read(), dtype=np.uint8,
offset=8)
with gzip.open(images_path, 'rb') as imgpath:
images = np.frombuffer(imgpath.read(), dtype=np.uint8,
offset=16).reshape(len(labels), 784)
return images, labels
# +
download_from_url('http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz',
'fashion/train-images-idx3-ubyte.gz')
download_from_url('http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz',
'fashion/train-labels-idx3-ubyte.gz')
download_from_url('http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz',
'fashion/t10k-images-idx3-ubyte.gz')
download_from_url('http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz',
'fashion/t10k-labels-idx3-ubyte.gz')
# -
X_train, y_train = load_mnist('fashion', kind='train')
X_test, y_test = load_mnist('fashion', kind='t10k')
from pyspark.ml.linalg import Vectors
df_train = map(lambda i: (int(y_train[i]), Vectors.dense(X_train[i])), range(len(X_train)))
df_test = map(lambda i: (int(y_test[i]), Vectors.dense(X_test[i])), range(len(X_test)))
from pyspark.sql import SparkSession
sparkSession = SparkSession.builder \
.appName("examples") \
.master('local[4]').config('spark.driver.memory', '8g') \
.getOrCreate()
df_train = sparkSession.createDataFrame(df_train,schema=["labels", "features"])
df_test = sparkSession.createDataFrame(df_test,schema=["labels", "features"])
# +
import tensorflow.contrib.slim as slim
import tensorflow as tf
import inception_v1
def inception():
x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
y = tf.placeholder(tf.int32, shape=[None, 1], name='y')
y = tf.reshape(y, [-1])
x = tf.reshape(x, shape=[-1, 28, 28, 1])
x = tf.image.grayscale_to_rgb(x)
x = tf.image.resize_images(x, (224, 224))
with slim.arg_scope(inception_v1.inception_v1_arg_scope()):
logits, endpoints = inception_v1.inception_v1(
x, num_classes = 10, is_training = True)
z = tf.argmax(logits, 1, name='out')
loss = tf.losses.sparse_softmax_cross_entropy(y,logits)
return loss
# +
from sparkflow.graph_utils import build_graph
from sparkflow.tensorflow_async import SparkAsyncDL
from pyspark.ml.pipeline import Pipeline
from sparkflow.graph_utils import build_adam_config
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
mg = build_graph(inception)
adam_config = build_adam_config(learning_rate=0.001, beta1=0.9, beta2=0.999)
# -
spark_model = SparkAsyncDL(
inputCol='features',
tensorflowGraph=mg,
tfInput='x:0',
tfLabel='y:0',
tfOutput='out:0',
tfOptimizer='adam',
miniBatchSize=16,
miniStochasticIters=1,
shufflePerIter=True,
iters=10,
predictionCol='predicted',
labelCol='labels',
partitions=3,
verbose=1,
optimizerOptions=adam_config
)
fitted_model = spark_model.fit(df_train)
# ### This is probably took a very long time
#
# 
| notebooks/10.fashion-mnist-inceptionv1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Simple Classifier / Logistic Regression
# After having worked with the Dataloading part last week, we want to start this week to take a more detailed look into how the training process looks like. So far, our tools are limited and we must restrict ourselves to a simplified model. But nevertheless, this gives us the opportunity to look at the different parts of the training process in more detail and builds up a good base when we turn to more complicated model architectures in the next exercises.
#
# This notebook will demonstrate a simple logistic regression model predicting whether a house is ```low-priced``` or ```expensive```. The data that we will use here is the HousingPrice dataset. Feeding some features in our classifier, the output should then be a score that determines in which category the considered house is.
#
# 
# Before we start, let us first import some libraries and code that we will need along the way.
# +
from exercise_code.data.csv_dataset import CSVDataset
from exercise_code.data.csv_dataset import FeatureSelectorAndNormalizationTransform
from exercise_code.data.dataloader import DataLoader
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
pd.options.mode.chained_assignment = None # default='warn'
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2
# -
# ## 0.Dataloading and Data Preprocessing
# Before we start preprocessing our data, let us first download the dataset and use the ```CSVDataset``` class to access the downloaded dataset.
# +
i2dl_exercises_path = os.path.dirname(os.path.abspath(os.getcwd()))
root_path = os.path.join(i2dl_exercises_path, "datasets", 'housing')
housing_file_path = os.path.join(root_path, "housing_train.csv")
download_url = 'https://cdn3.vision.in.tum.de/~dl4cv/housing_train.zip'
# Always make sure this line was run at least once before trying to
# access the data manually, as the data is downloaded in the
# constructor of CSVDataset.
target_column = 'SalePrice'
train_dataset = CSVDataset(target_column=target_column, root=root_path, download_url=download_url, mode="train")
# -
# You should now be able to see the dataset in ```i2dl_exercises/datasets/housing``` in your file browser, which should contain a csv file containing all the data.
#
# It is always a good idea to get an overview of how our dataset looks like. By executing the following cell you can see some data samples. For each house, our dataset provides 81 features.
train_dataset.df.head()
# There are 80 features of our models. But not all the features are correlated with our target 'SalePrice'. So we need to perform a feature selection.
train_dataset.df.corr()[target_column].sort_values(ascending=False)[:3]
# Since our classifier is a very simple version we restrict our model to only one of the given features. In our case, let us select the feature ```GrLivArea``` and use this one to predict the target column , which will be the feature ```SalePrice```. This setting has the advantage that we can easiliy visualize our data in a 2 dimensional setting. Of course, a greater choice of features would make our model more powerful and accurate. But as we said, we want to keep it simple here and focus on the training process. The required data for training our model will then reduce to:
# selected feature and target
train_dataset.df[['GrLivArea',target_column]]
# Using a scatter plot, we can visualize the relationship between ‘GrLivArea’ and 'SalePrice'.
plt.scatter(train_dataset.df[['GrLivArea']], train_dataset.df[[target_column]])
plt.xlabel("GrLivArea")
plt.ylabel("SalePrice")
# The features are at very different scales and variances. Therfore, we normalize the features ranges with the minimum and maximum value of each numeric column. For filling in missing numeric values (if any), we need the mean value. These values should be pre-computed on the training set and used for all dataset splits.
#
# The ```FeatureSelectorAndNormalizationTransform``` class defined in ```exercise_code/data/csv_dataset.py``` is implementing this transformation. Make sure you have a look at the code of this file to understand the next cells.
# +
df = train_dataset.df
# Select only 2 features to keep plus the target column.
selected_columns = ['GrLivArea', target_column]
mn, mx, mean = df.min(), df.max(), df.mean()
column_stats = {}
for column in selected_columns:
crt_col_stats = {'min' : mn[column],
'max' : mx[column],
'mean': mean[column]}
column_stats[column] = crt_col_stats
transform = FeatureSelectorAndNormalizationTransform(column_stats, target_column)
def rescale(data, key = "SalePrice", column_stats = column_stats):
""" Rescales input series y"""
mx = column_stats[key]["max"]
mn = column_stats[key]["min"]
return data * (mx - mn) + mn
# -
# After having computed the ```min```, ```max``` and ```mean``` value, we load the data splits and perform the transformation on our data using the ```CSVDataset``` class. To check whether the partitions are correct, we print for each one of them the number of samples. Remember to not touch the test set until you are done with the training of your model.
# +
# Always make sure this line was run at least once before trying to
# access the data manually, as the data is downloaded in the
# constructor of CSVDataset.
train_dataset = CSVDataset(mode="train", target_column=target_column, root=root_path, download_url=download_url, transform=transform)
val_dataset = CSVDataset(mode="val", target_column=target_column, root=root_path, download_url=download_url, transform=transform)
test_dataset = CSVDataset(mode="test", target_column=target_column, root=root_path, download_url=download_url, transform=transform)
print("Number of training samples:", len(train_dataset))
print("Number of validation samples:", len(val_dataset))
print("Number of test samples:", len(test_dataset))
# -
# Let us load the respective data splits ('train', 'val, and 'test') into one matrix of shape $N \times D$ where $N$ represents the number of samples and $D$ the number of features (in our case we only have one feature). Similarly, we load the target data in one matrix.
# +
# load training data into a matrix of shape (N, D), same for targets resulting in the shape (N, 1)
X_train = [train_dataset[i]['features'] for i in range((len(train_dataset)))]
X_train = np.stack(X_train, axis=0)
y_train = [train_dataset[i]['target'] for i in range((len(train_dataset)))]
y_train = np.stack(y_train, axis=0)
print("train data shape:", X_train.shape)
print("train targets shape:", y_train.shape)
# load validation data
X_val = [val_dataset[i]['features'] for i in range((len(val_dataset)))]
X_val = np.stack(X_val, axis=0)
y_val = [val_dataset[i]['target'] for i in range((len(val_dataset)))]
y_val = np.stack(y_val, axis=0)
print("val data shape:", X_val.shape)
print("val targets shape:", y_val.shape)
# load train data
X_test = [test_dataset[i]['features'] for i in range((len(test_dataset)))]
X_test = np.stack(X_test, axis=0)
y_test = [test_dataset[i]['target'] for i in range((len(test_dataset)))]
y_test = np.stack(y_test, axis=0)
print("test data shape:", X_test.shape)
print("test targets shape:", y_test.shape)
# 0 encodes small prices, 1 encodes large prices.
# -
# In the following, we model our binary classification problem. We divide our target in the categories ```low-priced``` and ```expensive``` by labeling the 30% of the houses that are sold with the lowest price with ```0``` and, accordingly, the 30% of the houses with the highest price with ```1```. All other houses will be deleted from our data. We will use the method ```binarize()```. For more information, take a look at the file ```networks/utils.py```.
# +
from exercise_code.networks.utils import binarize
y_all = np.concatenate([y_train, y_val, y_test])
thirty_percentile = np.percentile(y_all, 30)
seventy_percentile = np.percentile(y_all, 70)
# Prepare the labels for classification.
X_train, y_train = binarize(X_train, y_train, thirty_percentile, seventy_percentile )
X_val, y_val = binarize(X_val, y_val, thirty_percentile, seventy_percentile)
X_test, y_test = binarize(X_test, y_test, thirty_percentile, seventy_percentile)
print("train data shape:", X_train.shape)
print("train targets shape:", y_train.shape)
print("val data shape:", X_val.shape)
print("val targets shape:", y_val.shape)
print("test data shape:", X_test.shape)
print("test targets shape:", y_test.shape)
# -
# Obviously, we reduced our data and the remaining houses in our dataset are now either labeled with ```1``` and hence categorized as ```expensive```, or they are labeled with ```0``` and hence categorized as ```low-priced```.
#
# The data is now ready and can be used to train our classifier model.
# ## 1. Set up a classfier model
# Let $\mathbf{X} \in \mathbb{R}^{N\times (D+1)}$ be our data with $N$ samples and $D$ feature dimensions. With our classifier model, we want to predict binary labels $\mathbf{\hat{y}} \in \mathbb{R}^{N\times 1}$. Our classifier model should be of the form
#
# $$ \mathbf{\hat{y}} = \sigma \left( \mathbf{X} \cdot \mathbf{w} \right), $$
#
# $ $ where $\mathbf{w}\in \mathbb{R}^{(D+1) \times 1}$ is the weight matrix of our model.
#
# The **sigmoid function** $\sigma: \mathbb{R} \to [0, 1]$, defined by
#
# $$ \sigma(t) = \frac{1}{1+e^{-t}}, $$
#
# is used to squash the outputs of the linear layer into the interval $[0, 1]$. Remember that the sigmoid function is a real-valued function. When applying it on a vector, the sigmoid is operating componentwise.
#
# The output of the sigmoid function can be seen as the probability that our sample is indicating a house that can be categorized as ```expensive```. As the probability gets closer to 1, our model is more confident that the input sample is in the class ```expensive```.
# <img src="https://miro.medium.com/max/2400/1*RqXFpiNGwdiKBWyLJc_E7g.png" width="800">
# Take a look at the implementation of the ```Classifier``` class in `exercise_code/networks/classifier.py`. To create a `Classifier` object, you need to define the number of features that our classifier models takes as input.
#
# Furthermore, the class provides a method `initialize_weights()` that can be used to randomly initialize the weights of our model.
# ## 2. Loss: Binary Cross Entropy
# For a binary classification like our task, we use a loss function called Binary Cross Entropy (BCE).
#
# $$BCE(y,\hat{y}) =- y \cdot log(\hat y ) - (1- y) \cdot log(1-\hat y) $$
#
# where $y\in\mathbb{R}$ is the ground truth and $\hat y\in\mathbb{R}$ is the predicted probability of the house being expensive.
#
# BCE can be understood as two separate cost functions: One for ground truth $y=0$ and one for $y=1$.
#
# $$BCE(y=0,\hat{y}) = - log(1-\hat y)$$
# $$BCE(y=1,\hat{y}) = - log(\hat y )$$
#
# Since the BCE functioon is a non-convex function, there is no closed-form solution for the optimal weights vector. In order to find the optimal parameters for our model, we need to use numeric methods such as Gradient Descent. But let us have a look at that later.
#
# +
from exercise_code.networks.loss import BCE
bce_loss = BCE()
# -
# Now it is time for your first task:
# ### Task 1: Implement the BCE loss function
# In `exercise_code/networks/loss.py` complete the implementation of the BCE loss function. You need to write the forward and backward pass of BCE as `forward()` and `backward()` function. The backward pass of the loss is needed to later optimize your weights of the model.
# ### Forward and Backward Check
#
# Once you have finished the implementation of the BCE loss class, you can run the following code to check whether your forward result and backward gradient are correct. You should expect your relative error to be lower than 1e-8.
#
# Here we will use a numeric gradient check to debug the backward pass:
#
# $$ \frac {df(x)}{dx} = \frac{f(x+h) - f(x-h)}{2h} $$
#
# where $h$ is a very small number, in practice approximately 1e-5.
from exercise_code.tests.loss_tests import *
print (BCETest(bce_loss)())
# ## 3. Backpropagation
# The backpropagation algorithm allows the information from the loss flowing backward through the network in order to compute the gradient of the loss function $L$ w.r.t the weights $w$ of the model.
#
# The key idea of backpropagation is decomposing the derivatives by applying the chain rule to the loss function.
#
# $$ \frac{\partial L(w)}{\partial w} = \frac{\partial L(w)}{\partial \hat y} \cdot \frac{\partial \hat y}{\partial w}$$
#
# It means that we need to compute the gradient of the loss function $L$ w.r.t to predictions $\hat y$ and the gradient of predictions $\hat y$ w.r.t weights $w$ separately.
#
# You have already completed the `forward()` and `backward()` pass of the loss function, which can be used to compute the derivative $\frac{\partial L(w)}{\partial \hat y}$. In order to compute the second term $\frac{\partial \hat y}{\partial w}$, we need to implement a similar `forward()` and `backward()` method in our `Classifier` class.
#
# **Forward-pass**
#
# Our classifier is given by
#
# $$ \mathbf{\hat{y}} = \sigma \left( \mathbf{X} \cdot w \right) $$
#
# Hence the forward pass consists of two parts: The multiplication of our data matrix $X \in \mathbb{R}^{N \times D+1}$ with the weight matrix of our model $w \in \mathbb{R}^{D+1}$ and the sigmoid function $\sigma: \mathbb{R} \rightarrow [0,1]$ that is operating componentwise on the vector $ X \cdot w$.
#
# **Backward-propagation**
#
# The backward-pass is definitely the more complicated part here and consists of computing $\frac{\partial \hat y}{\partial w}$. Again, we can decompose this derivative into two parts: Let $s = X \cdot w$ and hence we can decompose the term:
#
# $$\frac{\partial \hat y}{\partial w} = \frac{\partial \sigma(s)}{\partial w} = \frac{\partial \sigma(s)}{\partial s} \cdot \frac{\partial s}{\partial w}$$
#
#
# **Hint:** From the mathematical point of view, the backward pass is not very difficult, but taking track of the dimensions in higher dimensional settings can make it complicated. Make sure you understand the operations here. If you find it difficult, maybe it helps to understand the forward and backward pass if the input is only one sample consisting of $D+1$ features. Then our data matrix has dimension $X \in \mathbb{R}^{1 \times D+1}$. After you understood this situation, you can go back to the setting where our data matrix has dimension $X \in \mathbb{R}^{N \times D+1}$ and consists of $N$ samples each having $D+1$ features.
# ### Task 2: Implement the forward- and backward-pass in the Classifier model
# Implement the `forward()` and `backward()` pass in the `Classifier` class in `exercise_code/networks/classifier.py`. Don't forget to also implement the sigmoid function.
# <font color='red'> TESTING TEAM: Insert a test to check whether the implementation of the forward() and backward() methods are correct.</font>
# ## 4. Optimizer and Gradient Descent
# Previously, we have successfully dealt with the loss function, which is a method of measuring how well our model fits the given data. The idea of the training process is to adjust iteratively the weights of our model in order to minimize the loss function.
#
# And this is where the optimizer comes in. In each training step, the optimizer updates the weights of the model w.r.t. the output of the loss function, thereby linking the loss function and model parameters together. The goal is to obtain a model which is accurately predicting the class for a sample.
#
# In other words, the loss function is a guide to the terrain and can tell the optimizer when to move in the right or wrong direction.
#
# Any discussion about optimizers needs to begin with the most popular one, and it’s called Gradient Descent. This algorithm is used across all types of Machine Learning (and other math problems) to optimize. It’s fast, robust, and flexible. Here’s how it works:
#
#
# 0. Initialize the weights with random values.
# 1. Calculate loss with the current weights and the loss function.
# 2. Calculate the gradient of the loss function w.r.t. the weights
# 3. Update weights with the corresponding gradient
# 4. Iteratively perform Step 1 to 3 until converges
#
# The name of the optimizer already hints to the required concept: We use gradients which are very useful for minimizing a function. The gradient of the loss function w.r.t to the weights $w$ of our model tells us how to change our weights $w$ in order to minimize our loss function.
#
# The weights are updated each step as follows:
# $$ w^{(n+1)} = w^{(n)} - \alpha \cdot \frac {dL}{dw}, $$
# $ $ where $ \frac {dL}{dw}$ is the gradient of your loss function w.r.t. the weights $w$, $\alpha$ is the learning rate which is a predefined positive scalar determining the size of the step.
# ### Task 3: Implement a Naive Optimizer using Gradient Descent
#
# In our model, we will use gradient descent to update the weights. Take a look at the `Optimizer` class in the file `networks/optimizer.py`. Your task is now to implement the gradient descent step in the `step()` method.
# <font color='red'> TESTING TEAM: Insert a test to check whether the implementation of step() method is correct. </font>
# ## 5. Training
# We have now implemented all necessary parts of our training process, namely:
# - **Classifier Model:** We set up a simple classifier model and you implemented the corresponding ```forward()``` and ```backward()``` methods.
# - **Loss function:** We chose the Binary Cross Entropy Loss for our model to measure the distance between the prediction of our model and the ground-truth labels. You implemented a forward and backward pass for the loss function.
# - **Optimizer**:We use the Gradient Descent method to update the weights of our model. Here, you implemented the ```step()``` function which performs the update of the weights.
#
# Before we start our training and put all the parts together, let us shortly talk about the weight initialization. In ```networks/classifier.py``` you can check the ```Classifier``` class. It contains a method called ```initialize_weights()``` that randomly initializes the weights of our classifier model. Later in the lecture, we will learn about more efficient methods to initialize the weights. But for now, a random initialization as it happens in the ```initialize_weights()``` method is sufficient.
#
# Let's start with our classifier model and look at it's performance before any training happened.
# +
from exercise_code.networks.classifier import Classifier
#initialization
model = Classifier(num_features=1)
model.initialize_weights()
y_out, _ = model(X_train)
# plot the prediction
plt.scatter(X_train, y_train)
plt.plot(X_train, y_out, color='r')
# -
# As you can see the predictions of our model are really bad when we randomly initialize the weights (which is of course not surprising). Let's see how the performance improves when we start our training, which means that we update our weights applying the gradient descent method. The following cell combines the forward- and backward passes with the gradient update step and performs a training step for our classifier:
#
# Note that the ```Classifier``` class is derived from the more general ```Network``` class. It is worth having a look at the basis class ```Network``` in the file ```exercise_code/networks/base_networks.py```. We will make use of the ```__call__()``` method, which computes the forward and backward pass of your classifier. In a similar manner, we use the ```__call__()``` function for our Loss function.
#
# The following cell performs a training with 800 training steps:
# +
from exercise_code.networks.optimizer import *
from exercise_code.networks.classifier import *
# Hyperparameter Setting, we will specify the loss function we use, and implement the optimizer we finished in the last step.
num_features = 1
# initialization
model = Classifier(num_features=num_features)
model.initialize_weights()
loss_func = BCE()
learning_rate = 5e-1
loss_history = []
opt = Optimizer(model,learning_rate)
steps = 800
# Full batch Gradient Descent
for i in range(steps):
# Enable your model to store the gradient.
model.train()
# Compute the output and gradients w.r.t weights of your model for the input dataset.
model_forward, model_backward = model(X_train)
# Compute the loss and gradients w.r.t output of the model.
loss, loss_grad = loss_func(model_forward, y_train)
# Use back prop method to get the gradients of loss w.r.t the weights.
grad = loss_grad * model_backward
# Compute the average gradient over your batch
grad = np.mean(grad, 0, keepdims = True)
# After obtaining the gradients of loss with respect to the weights, we can use optimizer to
# do gradient descent step.
opt.step(grad.T)
# Average over the loss of the entire dataset and store it.
average_loss = np.mean(loss)
loss_history.append(average_loss)
if i%100 == 0:
print("Epoch ",i,"--- Average Loss: ", average_loss)
# -
# We can see that our average loss is decreasing as we expected it. Let us visualize the average loss and the prediction after our short training:
# +
# Plot the loss history to see how it goes after several steps of gradient descent.
plt.plot(loss_history, label = 'Train Loss')
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title('Training Loss history')
plt.legend()
plt.show()
# forward pass
y_out, _ = model(X_train)
# plot the prediction
plt.scatter(X_train, y_train, label = 'Ground Truth')
inds = X_train.argsort(0).flatten()
plt.plot(X_train[inds], y_out[inds], color='r', label = 'Prediction')
plt.legend()
plt.show()
# -
# This looks pretty good already and our model gets better in explaining the underlying relationship of data.
# ## 6. Solver
# Now we want to put everything we have learned so far together in an organized and concise way, that provides easy access to train a network/model in your own script/code. The purpose of a solver is to mainly to provide an abstraction for all the gritty details behind training your parameters, such as logging your progress, optimizing your model, and handling your data.
#
# This part of the exercise will require you to complete the missing code in the ```Solver``` class and to train your model end to end. Therefore, have a look at the code in the file ```exercise_code/solver.py```.
#
# ### Task 4: Implement the Solver
#
# Open the file `exercise_code/solver.py` and have a look at the ```Solver``` class. The ```_step()``` function is representing one single training step. So when using the Gradient Descent method, it represents one single update step using the Gradient Descent method. Your task is now to finalize this ```_step()``` function.
#
# Note here that our Solver takes as input our classifier model, the training and validation data and our loss function. Furthermore, we need to choose a learning rate. The ```_step()``` function is now a combination of the methods that you have been seen so far in this notebook. You will need to use the ```forward()``` and ```backward()``` method of your model and your loss function as well as the ```step()``` function of your optimizer.
#
#
# ***Hint:*** The implementation of the ```_step()``` function is very similar to the implementation of a training step as we observed above.
# <font color='red'> TESTING TEAM: Insert a test to check whether the implementation of step() method is correct. </font>
# +
from exercise_code.solver import Solver
from exercise_code.networks.utils import test_accuracy
from exercise_code.networks.classifier import Classifier
# Select the number of features, you want your task to train on.
# Feel free to play with the sizes.
num_features = 1
# initialize model and weights
model = Classifier(num_features=num_features)
model.initialize_weights()
y_out, _ = model(X_test)
accuracy = test_accuracy(y_out, y_test)
print("Accuracy BEFORE training {:.1f}%".format(accuracy*100))
if np.shape(X_val)[1]==1:
plt.scatter(X_val, y_val, label = "Ground Truth")
inds = X_test.flatten().argsort(0)
plt.plot(X_test[inds], y_out[inds], color='r', label = "Prediction")
plt.legend()
plt.show()
data = {'X_train': X_train, 'y_train': y_train,
'X_val': X_val, 'y_val': y_val}
#We use the BCE loss
loss = BCE()
# Please use these hyperparmeter as we also use them later in the evaluation
learning_rate = 1e-1
epochs = 25000
# Setup for the actual solver that's going to do the job of training
# the model on the given data. set 'verbose=True' to see real time
# progress of the training.
solver = Solver(model,
data,
loss,
learning_rate,
verbose=True,
print_every = 1000)
# Train the model, and look at the results.
solver.train(epochs)
# -
# During the training process losses in each epoch are stored in the lists solver.train_loss_history and solver.val_loss_history. We can use them to plot the training result easily.
# +
plt.plot(solver.val_loss_history, label = "Validation Loss")
plt.plot(solver.train_loss_history, label = "Train Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.show()
# Test final performance
y_out, _ = model(X_test)
accuracy = test_accuracy(y_out, y_test)
print("Accuracy AFTER training {:.1f}%".format(accuracy*100))
if np.shape(X_test)[1]==1:
plt.scatter(X_test, y_test, label = "Ground Truth")
inds = X_test.argsort(0).flatten()
plt.plot(X_test[inds], y_out[inds], color='r', label = "Prediction")
plt.legend()
plt.show()
# -
# ### - Save your BCELoss, Classifier and Solver for Submission
#
# Your model should be trained now and able to predict whether a house is expensive or not. Hooooooray! The model will be saved as a pickle file to `models/logistic_regression.p`.
# +
from exercise_code.tests import save_pickle
save_pickle(
data_dict={
"BCE_class": BCE,
"Classifier_class": Classifier,
"Solver_class": Solver
},
file_name="logistic_regression.p"
)
| exercise_04/.ipynb_checkpoints/Ex4_new_approach-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/agemagician/CodeTrans/blob/main/prediction/multitask/fine-tuning/function%20documentation%20generation/java/base_model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="c9eStCoLX0pZ"
# **<h3>Predict the documentation for java code using codeTrans mulititask finetuning model</h3>**
# <h4>You can make free prediction online through this
# <a href="https://huggingface.co/SEBIS/code_trans_t5_base_code_documentation_generation_java_multitask_finetune">Link</a></h4> (When using the prediction online, you need to parse and tokenize the code first.)
# + [markdown] id="6YPrvwDIHdBe"
# **1. Load necessry libraries including huggingface transformers**
# + colab={"base_uri": "https://localhost:8080/"} id="6FAVWAN1UOJ4" outputId="8b0333c3-78ae-466b-f893-cb02e32cf161"
# !pip install -q transformers sentencepiece
# + id="53TAO7mmUOyI"
from transformers import AutoTokenizer, AutoModelWithLMHead, SummarizationPipeline
# + [markdown] id="xq9v-guFWXHy"
# **2. Load the token classification pipeline and load it into the GPU if avilabile**
# + colab={"base_uri": "https://localhost:8080/", "height": 316, "referenced_widgets": ["2e675188165f4ae99c9fbf3e611101fe", "ce044711cc00409292ed987630f8e157", "e26c965dc4e24ecaa3f47bb51c7e8059", "<KEY>", "3a253f277fa84768afac75cd9c05572a", "<KEY>", "3558a4017fe5417283cadcf98ad5685f", "68d8aa0b0d014a4ca0df49cc8bb8eb77", "57a7461d0b0c474bb3ceba7b9e7df6b7", "b7d8266b68a2434ea4418e6624f8b0d9", "f4f847e3ece0486da06ec4095deafc7c", "<KEY>", "f5eddbf7ff9b4c3ab137c3a8a6295dd4", "2e13dae8fb5d47f5a7c0de13eba65288", "f7dd95bee6a4436b98ac220e186785a3", "2548a1a71006465ca19172db0d40f534", "d1fcb6f7fc584b6e81dae1763e852dcc", "36914b4bbc1a489696c696e509be1a4b", "307a6b55b1dc44e985dca447583f65ed", "34f3af595a64495b97e4696ab2e9871e", "<KEY>", "<KEY>", "ddb5579d207a4d0ba3ccec9317466f35", "<KEY>", "35a09fad42ce4dfea3372230b702898f", "d42e90b0560c46f689f516fee2bce340", "<KEY>", "c8701bf4ed9f444faf0b6e526d86e3b6", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "560f9ebe7862444bb5854a47baf5126f", "aa3bc065e00941ccb894413ece99011e", "ee78c8c691584adc8649e23aba188f32", "b9ecfd32503d4358ab2fd2ee0ac7e533", "463f0b2ea84c45c0910129d91bce05a8", "<KEY>", "<KEY>", "<KEY>"]} id="5ybX8hZ3UcK2" outputId="0d55ddca-fc8c-422d-9361-66201202d5c5"
pipeline = SummarizationPipeline(
model=AutoModelWithLMHead.from_pretrained("SEBIS/code_trans_t5_base_code_documentation_generation_java_multitask_finetune"),
tokenizer=AutoTokenizer.from_pretrained("SEBIS/code_trans_t5_base_code_documentation_generation_java_multitask_finetune", skip_special_tokens=True),
device=0
)
# + [markdown] id="hkynwKIcEvHh"
# **3 Give the code for summarization, parse and tokenize it**
# + id="nld-UUmII-2e"
code = """public static <T, U> Function<T, U> castFunction(Class<U> target) {\n return new CastToClass<T, U>(target);\n }""" #@param {type:"raw"}
# + id="cJLeTZ0JtsB5" colab={"base_uri": "https://localhost:8080/"} outputId="861bf4e9-7489-45bb-d13a-c4f25a67e4f1"
# !pip install tree_sitter
# !git clone https://github.com/tree-sitter/tree-sitter-java
# + id="hqACvTcjtwYK"
from tree_sitter import Language, Parser
Language.build_library(
'build/my-languages.so',
['tree-sitter-java']
)
JAVA_LANGUAGE = Language('build/my-languages.so', 'java')
parser = Parser()
parser.set_language(JAVA_LANGUAGE)
# + id="LLCv2Yb8t_PP"
def my_traverse(node, code_list):
lines = code.split('\n')
if node.child_count == 0:
line_start = node.start_point[0]
line_end = node.end_point[0]
char_start = node.start_point[1]
char_end = node.end_point[1]
if line_start != line_end:
code_list.append(' '.join([lines[line_start][char_start:]] + lines[line_start+1:line_end] + [lines[line_end][:char_end]]))
else:
code_list.append(lines[line_start][char_start:char_end])
else:
for n in node.children:
my_traverse(n, code_list)
return ' '.join(code_list)
# + id="BhF9MWu1uCIS" colab={"base_uri": "https://localhost:8080/"} outputId="204e6776-acc0-4355-bcb8-68a645d69285"
tree = parser.parse(bytes(code, "utf8"))
code_list=[]
tokenized_code = my_traverse(tree.root_node, code_list)
print("Output after tokenization: " + tokenized_code)
# + [markdown] id="sVBz9jHNW1PI"
# **4. Make Prediction**
# + colab={"base_uri": "https://localhost:8080/"} id="KAItQ9U9UwqW" outputId="359bb728-1dcd-4c52-d26e-b8f24169e57c"
pipeline([tokenized_code])
| prediction/multitask/fine-tuning/function documentation generation/java/base_model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] colab_type="text" id="h3Nuf-G4xJ0u"
# ##### Copyright 2019 The TensorFlow Authors.
# + cellView="form" colab={} colab_type="code" id="zZ81_4tLxSvd"
#@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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# + [markdown] colab_type="text" id="wNBP_f0QUTfO"
# # Getting started with [TensorBoard.dev](https://tensorboard.dev)
# + [markdown] colab_type="text" id="DLXZ3t1PWdOp"
# [TensorBoard.dev](https://tensorboard.dev) provides a managed [TensorBoard](https://tensorflow.org/tensorboard) experience that lets you upload and share your ML experiment results with everyone.
#
# This notebook trains a simple model and shows how to upload the logs to TensorBoard.dev.
# + [markdown] colab_type="text" id="yjBn-ptXTppA"
# ### Setup and imports
# + colab={} colab_type="code" id="5C8BOea_rF49"
try:
# # %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
# !pip install -U tensorboard >piplog 2>&1
# + colab={} colab_type="code" id="L3ns52Luracm"
import tensorflow as tf
import datetime
# + [markdown] colab_type="text" id="GqUABmUTT1Cl"
# ### Train a simple model and create TensorBoard logs
# + colab={} colab_type="code" id="LZExSr2Qrc5S"
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# + colab={} colab_type="code" id="dsVjm5CrUtXm"
model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
log_dir="logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tensorboard_callback])
# + [markdown] colab_type="text" id="TgF35qdzIC3T"
# ### Upload to TensorBoard.dev
#
# Uploading the TensorBoard logs will give a link that can be shared with anyone. Note that uploaded TensorBoards are public. Do not upload sensitive data.
#
# The uploader will keep running until it is stopped, in order to read new data from the directory during ongoing training.
# + colab={} colab_type="code" id="n2PvxhOkW7vn"
# !tensorboard dev upload --logdir ./logs \
# --name "Simple experiment with MNIST" \
# --description "Training results from https://colab.sandbox.google.com/github/tensorflow/tensorboard/blob/master/docs/tbdev_getting_started.ipynb"
# + [markdown] colab_type="text" id="5QH5k4AUNE27"
# Note that each experiment you upload has a unique experiment ID. Even if you start a new upload with the same directory, you will get a new experiment ID. It is possible to look at the list of experiments you have uploaded using the `list` command.
# + colab={} colab_type="code" id="C2Pj3RQCNQvP"
# !tensorboard dev list
# + [markdown] colab_type="text" id="JcZOGmjQNWk_"
# To remove an experiment you have uploaded, you may use the `delete` command and specifiy the appropriate experiment_id.
# + colab={} colab_type="code" id="VSkJTT9rNWJq"
# You must replace YOUR_EXPERIMENT_ID with the value output from the previous
# tensorboard `list` command or `upload` command. For example
# `tensorboard dev delete --experiment_id pQpJNh00RG2Lf1zOe9BrQA`
# ## !tensorboard dev delete --experiment_id YOUR_EXPERIMENT_ID_HERE
| docs/tbdev_getting_started.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from scipy.stats import norm
from tqdm import trange
# plotting params
# %matplotlib inline
plt.rcParams['font.size'] = 10
plt.rcParams['axes.labelsize'] = 10
plt.rcParams['axes.titlesize'] = 10
plt.rcParams['xtick.labelsize'] = 8
plt.rcParams['ytick.labelsize'] = 8
plt.rcParams['legend.fontsize'] = 10
plt.rcParams['figure.titlesize'] = 12
# plt.rcParams['figure.figsize'] = (15.0, 8.0)
sns.set_style("white")
# path params
plot_dir = './'
# -
# ## Question Prompt
#
# Given the following current equation
#
# $$I(\Delta L, \Delta V_{TH}) = \frac{50}{0.1 + \Delta L} (0.6 - \Delta V_{TH})^2$$
#
# * $\Delta L \sim \ N(0, 0.01^2)$
# * $\Delta V_{TH} \sim \ N(0, 0.03^2)$
#
# We would like to calculate $P(I > 275)$ using direct Monte-Carlo and Importance Sampling.
# ## Direct Monte-Carlo Estimation
#
# In MC estimation, we approximate an integral by the sample mean of a function of simulated random variables. In more mathematical terms,
#
# $$\int p(x)\ f(x)\ dx = \mathbb{E}_{p(x)} \big[\ f(x) \big] \approx \frac{1}{N} \sum_{n=1}^{N}f(x_n)$$
#
# where $x_n \sim \ p(x)$.
#
# A useful application of MC is probability estimation. In fact, we can cast a probability as an expectation using the indicator function. In our case, given that $A = \{I \ | \ I > 275\}$, we define $f(x)$ as
#
# $$f(x) = I_{A}(x)= \begin{cases}
# 1 & I \geq 275 \\
# 0 & I < 275
# \end{cases}$$
#
# Replacing in our equation above, we get
#
# $$\int p(x) \ f(x) \ dx = \int I(x)\ p(x) \ d(x) = \int_{x \in A} p(x)\ d(x) \approx \frac{1}{N} \sum_{n=1}^{N}I_{A}(x_n)$$
def monte_carlo_proba(num_simulations, num_samples, verbose=True, plot=False):
if verbose:
print("===========================================")
print("{} Monte Carlo Simulations of size {}".format(num_simulations, num_samples))
print("===========================================\n")
num_samples = int(num_samples)
num_simulations = int(num_simulations)
probas = []
for i in range(num_simulations):
mu_1, sigma_1 = 0, 0.01
mu_2, sigma_2 = 0, 0.03
length = np.random.normal(mu_1, sigma_1, num_samples)
voltage = np.random.normal(mu_2, sigma_2, num_samples)
num = 50 * np.square((0.6 - voltage))
denum = 0.1 + length
I = num / denum
true_condition = np.where(I >= 275)
false_condition = np.where(I < 275)
num_true = true_condition[0].shape[0]
proba = num_true / num_samples
probas.append(proba)
if plot:
if i == (num_simulations - 1):
plt.scatter(length[true_condition], voltage[true_condition], color='r')
plt.scatter(length[false_condition], voltage[false_condition], color='b')
plt.xlabel(r'$\Delta L$ [$\mu$m]')
plt.ylabel(r'$\Delta V_{TH}$ [V]')
plt.title("Monte Carlo Estimation of P(I > 275)")
plt.grid(True)
plt.savefig(plot_dir + 'monte_carlo_{}.pdf'.format(num_samples), format='pdf', dpi=300)
plt.show()
mean_proba = np.mean(probas)
std_proba = np.std(probas)
if verbose:
print("Probability Mean: {:0.5f}".format(mean_proba))
print("Probability Std: {:0.5f}".format(std_proba))
return probas
probas = monte_carlo_proba(10, 10000, plot=False)
def MC_histogram(num_samples, plot=True):
num_samples = int(num_samples)
mu_1, sigma_1 = 0, 0.01
mu_2, sigma_2 = 0, 0.03
length = np.random.normal(mu_1, sigma_1, num_samples)
voltage = np.random.normal(mu_2, sigma_2, num_samples)
num = 50 * np.square((0.6 - voltage))
denum = 0.1 + length
I = num / denum
if plot:
n, bins, patches = plt.hist(I, 50, density=1, facecolor='green', alpha=0.75)
plt.ylabel('Number of Samples')
plt.xlabel(r'$I_{DS}$ [$\mu$A]')
plt.title("Monte Carlo Estimation of P(I > 275)")
plt.grid(True)
plt.savefig(plot_dir + 'mc_histogram_{}.pdf'.format(num_samples), format='pdf', dpi=300)
plt.show()
MC_histogram(1e6)
# +
num_samples = [1e3, 1e4, 1e5, 1e6]
num_repetitions = 25
total_probas = []
for i, num_sample in enumerate(num_samples):
print("Iter {}/{}".format(i+1, len(num_samples)))
probas = monte_carlo_proba(num_repetitions, num_sample, verbose=False)
total_probas.append(probas)
# +
# plt.figure(figsize=(8, 10))
y_axis_monte = np.asarray(total_probas)
x_axis_monte = np.asarray(num_samples)
for x, y in zip(x_axis_monte, y_axis_monte):
plt.scatter([x] * len(y), y, s=0.5)
plt.xscale('log')
plt.title("Direct Monte-Carlo Estimation")
plt.ylabel("Probability Estimate")
plt.xlabel('Number of Samples')
plt.grid(True)
plt.savefig(plot_dir + 'monte_carlo_convergence_speed.jpg', format='jpg', dpi=300)
plt.show()
# -
# ## Importance Sampling
# With importance sampling, we try to reduce the variance of our Monte-Carlo integral estimation by choosing a better distribution from which to simulate our random variables. It involves multiplying the integrand by 1 (usually dressed up in a “tricky fashion”) to yield an expectation of a quantity that varies less than the original integrand over the region of integration. Concretely,
#
# $$\mathbb{E}_{p(x)} \big[\ f(x) \big] = \int f(x)\ p(x)\ dx = \int f(x)\ p(x)\ \frac{q(x)}{q(x)}\ dx = \int \frac{p(x)}{q(x)}\cdot f(x)\ q(x)\ dx = \mathbb{E}_{q(x)} \big[\ f(x)\cdot \frac{p(x)}{q(x)} \big]$$
#
# Thus, the MC estimation of the expectation becomes:
#
# $$\mathbb{E}_{q(x)} \big[\ f(x)\cdot \frac{p(x)}{q(x)} \big] \approx \frac{1}{N} \sum_{n=1}^{N} w_n \cdot f(x_n)$$
#
# where $w_n = \dfrac{p(x_n)}{q(x_n)}$
# In our current example above, we can alter the mean and/or standard deviation of $\Delta L$ and $\Delta V_{TH}$ in the hopes that more of our sampling points will fall in the failure region (red area). For example, let us define 2 new distributions with altered $\sigma^2$.
#
# * $\Delta \hat{L} \sim \ N(0, 0.02^2)$
# * $\Delta \hat{V}_{TH} \sim \ N(0, 0.06^2)$
def importance_sampling(num_simulations, num_samples, verbose=True, plot=False):
if verbose:
print("===================================================")
print("{} Importance Sampling Simulations of size {}".format(num_simulations, num_samples))
print("===================================================\n")
num_simulations = int(num_simulations)
num_samples = int(num_samples)
probas = []
for i in range(num_simulations):
mu_1, sigma_1 = 0, 0.01
mu_2, sigma_2 = 0, 0.03
mu_1_n, sigma_1_n = 0, 0.02
mu_2_n, sigma_2_n = 0, 0.06
# setup pdfs
old_pdf_1 = norm(mu_1, sigma_1)
new_pdf_1 = norm(mu_1_n, sigma_1_n)
old_pdf_2 = norm(mu_2, sigma_2)
new_pdf_2 = norm(mu_2_n, sigma_2_n)
length = np.random.normal(mu_1_n, sigma_1_n, num_samples)
voltage = np.random.normal(mu_2_n, sigma_2_n, num_samples)
# calculate current
num = 50 * np.square((0.6 - voltage))
denum = 0.1 + length
I = num / denum
# calculate f
true_condition = np.where(I >= 275)
# calculate weight
num = old_pdf_1.pdf(length) * old_pdf_2.pdf(voltage)
denum = new_pdf_1.pdf(length) * new_pdf_2.pdf(voltage)
weights = num / denum
# select weights for nonzero f
weights = weights[true_condition]
# compute unbiased proba
proba = np.sum(weights) / num_samples
probas.append(proba)
false_condition = np.where(I < 275)
if plot:
if i == num_simulations -1:
plt.scatter(length[true_condition], voltage[true_condition], color='r')
plt.scatter(length[false_condition], voltage[false_condition], color='b')
plt.xlabel(r'$\Delta L$ [$\mu$m]')
plt.ylabel(r'$\Delta V_{TH}$ [V]')
plt.title("Monte Carlo Estimation of P(I > 275)")
plt.grid(True)
plt.savefig(plot_dir + 'imp_sampling_{}.pdf'.format(num_samples), format='pdf', dpi=300)
plt.show()
mean_proba = np.mean(probas)
std_proba = np.std(probas)
if verbose:
print("Probability Mean: {}".format(mean_proba))
print("Probability Std: {}".format(std_proba))
return probas
probas = importance_sampling(10, 10000, plot=False)
def IS_histogram(num_samples, plot=True):
num_samples = int(num_samples)
mu_1_n, sigma_1_n = 0, 0.02
mu_2_n, sigma_2_n = 0, 0.06
length = np.random.normal(mu_1_n, sigma_1_n, num_samples)
voltage = np.random.normal(mu_2_n, sigma_2_n, num_samples)
# calculate biased current
num = 50 * np.square((0.6 - voltage))
denum = 0.1 + length
I = num / denum
if plot:
n, bins, patches = plt.hist(I, 50, density=1, facecolor='green', alpha=0.75)
plt.ylabel('Number of Samples')
plt.xlabel(r'$I_{DS}$ [$\mu$A]')
plt.title("Importance Sampling of P(I > 275)")
plt.grid(True)
plt.savefig(plot_dir + 'is_histogram_{}.pdf'.format(num_samples), format='pdf', dpi=300)
plt.show()
IS_histogram(1e5)
# +
num_samples = [1e3, 1e4, 1e5, 1e6]
num_repetitions = 25
total_probas = []
for i, num_sample in enumerate(num_samples):
print("Iter {}/{}".format(i+1, len(num_samples)))
probas = importance_sampling(num_repetitions, num_sample, verbose=False)
total_probas.append(probas)
# +
# plt.figure(figsize=(8, 10))
y_axis_imp = np.asarray(total_probas)
x_axis_imp = np.asarray(num_samples)
for x, y in zip(x_axis_imp, y_axis_imp):
plt.scatter([x] * len(y), y, s=0.5)
plt.xscale('log')
plt.title("Importance Sampling")
plt.ylabel("Probability Estimate")
plt.xlabel('Number of Samples')
plt.grid(True)
plt.savefig(plot_dir + 'imp_sampling_convergence_speed.jpg', format='jpg', dpi=300)
plt.show()
# -
# ## Side by Side
# +
fig, ax = plt.subplots(1, 1)
# monte carlo
for x, y in zip(x_axis_imp, y_axis_monte):
ax.scatter([x] * len(y), y, s=0.5, c='r', alpha=0.3)
# importance sampling
for x, y in zip(x_axis_imp, y_axis_imp):
ax.scatter([x] * len(y), y, s=0.5, c='b', alpha=0.3)
blue = mlines.Line2D([], [], color='blue', marker='_', linestyle='None', markersize=10, label='importance sampling')
red = mlines.Line2D([], [], color='red', marker='_', linestyle='None', markersize=10, label='monte carlo')
plt.xscale('log')
plt.grid(True)
plt.legend(handles=[blue, red], loc='lower right')
plt.savefig('/Users/kevin/Desktop/plot.jpg', format='jpg', dpi=300, bbox_inches='tight')
plt.tight_layout()
plt.show()
# -
# ## References
#
# * http://ib.berkeley.edu/labs/slatkin/eriq/classes/guest_lect/mc_lecture_notes.pdf
| pr-lr/Monte Carlo and Importance Sampling.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Problem #6
# Description of the problem
# ### Solution #1
# There are several formulas to find the sum of an arithmetic series. Some of them are described below.
# $$\displaystyle S_n = \frac{(u_1 + u_n) \cdot n}{2}$$
# Some other variations of the formula can be found by isolating the number of terms on the formula of the generic term into the sum:
# $$u_n = u_1 + (n-1) \cdot d \quad \Rightarrow \quad d \cdot (u_n - u_1) = n - 1 \quad \therefore \quad n = \frac{u_n - u_1}{d} + 1$$
Therefore we have a new formula for the sum of an arithmetic sequence that does not require knowing the number of terms:
# $$S_n = \frac{(u_1 + u_n) \cdot n}{2} = \frac{(u_1 + u_n) \cdot \left( \frac{u_n - u_1}{d} + 1 \right)}{2} = \frac{\left( \frac{u_n^2 - u_1^2}{d} \right) + u_1 + u_n}{2}$$
#
# $$\therefore \quad S_n = \frac{u_n^2 - u_1^2 + d \cdot (u_1 + u_n)}{2d}$$
# Sharing a Python code on a jupyter notebook:
| _posts/.ipynb_checkpoints/X-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
df_order = pd.read_csv('orders.csv',dtype='str')
df_bank = pd.read_csv('bank_accounts.csv',dtype='str')
df_device = pd.read_csv('devices.csv',dtype='str')
df_card = pd.read_csv('credit_cards.csv',dtype='str')
df_device.head(10)
df_order.head(10)
df_new = pd.merge(df_order,df_device,how='outer',left_on='buyer_userid',right_on='userid')
df_new = df_new.rename(columns={'device': 'buyer_device'})
df_new.head(10)
df_new = pd.merge(df_new,df_device,how='outer',left_on='seller_userid',right_on='userid')
df_new = df_new.rename(columns={'device': 'seller_device'})
df_new.head(10)
del df_new['userid_x']
del df_new['userid_y']
df_new.head(10)
df_fraud = df_new.loc[df_new['buyer_device']==df_new['seller_device']]
df_fraud.head(10)
df_order_fraud = df_order.copy()
df_order_fraud['is_fraud'] = 0
df_order_fraud = df_order_fraud.set_index('orderid')
df_order_fraud.head(10)
df_order_fraud.loc[df_fraud.orderid,'is_fraud'] = 1
df_order_fraud.head(10)
df_order_fraud = df_order_fraud.reset_index()
df_order_fraud.head(10)
df_order_fraud.is_fraud.sum()
df_order_fraud.loc[df_order_fraud.is_fraud==1]
df_bank.head(10)
# +
df_new = pd.merge(df_order,df_bank,how='outer',left_on='buyer_userid',right_on='userid')
df_new = df_new.rename(columns={'bank_account': 'buyer_bank'})
df_new = pd.merge(df_new,df_bank,how='outer',left_on='seller_userid',right_on='userid')
df_new = df_new.rename(columns={'bank_account': 'seller_bank'})
del df_new['userid_x']
del df_new['userid_y']
df_new.head(10)
# +
df_fraud = df_new.loc[df_new['buyer_bank']==df_new['seller_bank']]
df_order_fraud = df_order_fraud.set_index('orderid')
df_order_fraud.loc[df_fraud.orderid,'is_fraud'] = 1
df_order_fraud = df_order_fraud.reset_index()
df_order_fraud.is_fraud.sum()
# -
df_card.head(10)
# +
df_new = pd.merge(df_order,df_card,how='outer',left_on='buyer_userid',right_on='userid')
df_new = df_new.rename(columns={'credit_card': 'buyer_card'})
df_new = pd.merge(df_new,df_card,how='outer',left_on='seller_userid',right_on='userid')
df_new = df_new.rename(columns={'credit_card': 'seller_card'})
del df_new['userid_x']
del df_new['userid_y']
df_fraud = df_new.loc[df_new['buyer_card']==df_new['seller_card']]
df_order_fraud = df_order_fraud.set_index('orderid')
df_order_fraud.loc[df_fraud.orderid,'is_fraud'] = 1
df_order_fraud = df_order_fraud.reset_index()
df_order_fraud.is_fraud.sum()
# -
df_order_fraud.to_csv('output2_extended.csv',index=False,columns=['orderid','is_fraud'])
| shopee2019/round2/Round 2 - extended (with pd.merge).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Overview
#
#
#
# - **목적** : 데이터프레임의 `artist` 컬럼 속, 뮤지션 SNS계정의 팔로워/구독자 수를 크롤링.
#
#
# - **크롤링 대상 웹페이지** : http://www.chartmetric.io
#
#
# - **크롤링 대상 sns** : Twitter, Instagram, Facebook, Spotify, Soundcloud, Youtube
#
# <img src="screenshot2.png", width="800">
# ### 1번 째 접근 : Selenium
# - pickle을 이용하여 계정 로그인
# - Selenium을 이용하여 search창에 아티스트 이름을 입력
# - 아티스트 페이지 이동
# - SNS 팔로워에 해당하는 css element text 스크래핑
#
# **문제점**
# - 페이지 로드 시간이 들쭉날쭉해서인지, 종종 element를 찾지 못 하는 에러가 발생합니다.
# - `time.sleep`을 적용해면 시간이 매우 오래 걸리고, 이 또한 element를 찾지 못 하는 에러가 발생합니다.
# +
import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pickle
import time
# -
debut_df = pd.read_csv("debut_album_1118.csv")
debut_df.shape[0]
def get_followers(dataframe):
# Search 창에 입력 할 뮤지션 이름 리스트 생성
ls = list(dataframe['artist'])
# 스크래핑한 데이터를 입력 할 데이터프레임 생성
sns_df = pd.DataFrame(columns=['artist', 'twitter', 'instagram', 'facebook', 'spotify', 'soundcloud', 'youtube'])
# 로그인 페이지 이동
driver = webdriver.Chrome()
driver.get('https://chartmetric.io/login')
time.sleep(3)
# pickle 파일 로드
pickle_pw = pickle.load(open("chartmetric_pw.pickle", "rb"))
# 아이디, PW 입력 후 로그인
driver.find_element_by_css_selector( "body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(4) > div > input" ).send_keys( "<EMAIL>" )
driver.find_element_by_css_selector( "body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(5) > div > input" ).send_keys( pickle_pw )
driver.find_element_by_css_selector("body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(7) > div > button").click()
time.sleep(7)
for artist in ls:
# Search 창으로 이동
driver.get('https://chartmetric.io/search')
time.sleep(10)
# 아티스트 이름 입력
driver.find_element_by_css_selector( "body > div:nth-child(1) > div:nth-child(2) > div > div > form > input" ).send_keys(artist)
driver.find_element_by_css_selector("body > div:nth-child(1) > div:nth-child(2) > div > div > form > input").send_keys(Keys.ENTER)
time.sleep(10)
# 아티스트 페이지로 이동
keyword = driver.find_element_by_css_selector("#artist > ul > li > div.media-body > div.media-heading > a").text
driver.find_element_by_link_text(keyword).click()
time.sleep(10)
# element 가져오기
social = driver.find_element_by_id("socialStats")
time.sleep(5)
twitter = social.find_element_by_id("twitterfollowers-total-fans").text
instagram = social.find_element_by_id("instagram-total-fans").text
facebook = social.find_element_by_id("facebooklikes-total-fans").text
spotify = social.find_element_by_id("spotify-total-fans").text
soundcloud = social.find_element_by_id("soundcloud-total-fans").text
youtube = social.find_element_by_id("youtubesubscribers-total-fans").text
# 데이터 입력
data = {
"artist": artist,
"twitter":twitter,
"instagram":instagram,
"facebook":facebook,
"spotify":spotify,
"soundcloud":soundcloud,
"youtube":youtube,
}
sns_df.loc[len(sns_df)] = data
time.sleep(2)
driver.close()
return sns_df
df_1 = get_followers(debut_df)
print(df_1.shape)
df_1.head()
# * * * *
# ### 2번 째 접근 : requests, bs4
#
# - 위의 selenium을 통해 고유한 artist번호를 알아낸 후
# - 해당 api를 통해 scraping
#
# **문제점**
# - user agent만 헤더로 입력 했을 시, "No authorization token was found"이라는 에러가 뜹니다.
# - user agent와 authorization을 헤더로 입력 했을 시, 400 에러가 뜹니다.
#
# <img src="screenshot1.png", width="800">
import requests
from bs4 import BeautifulSoup
# +
# ex) 뮤지션 이름 " eminem "
artist = 'eminem'
# 로그인 페이지 이동
driver = webdriver.Chrome()
driver.get('https://chartmetric.io/login')
time.sleep(3)
# pickle 파일 로드
pickle_pw = pickle.load(open("chartmetric_pw.pickle", "rb"))
# 아이디, PW 입력 후 로그인
driver.find_element_by_css_selector( "body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(4) > div > input" ).send_keys( "<EMAIL>" )
driver.find_element_by_css_selector( "body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(5) > div > input" ).send_keys( pickle_pw )
driver.find_element_by_css_selector("body > div > div:nth-child(2) > div.container.ng-scope > div > div > div > div > form > div:nth-child(7) > div > button").click()
time.sleep(10)
# Search 창으로 이동
driver.get('https://chartmetric.io/search')
time.sleep(10)
# 아티스트 이름 입력
driver.find_element_by_css_selector( "body > div:nth-child(1) > div:nth-child(2) > div > div > form > input" ).send_keys(artist)
driver.find_element_by_css_selector("body > div:nth-child(1) > div:nth-child(2) > div > div > form > input").send_keys(Keys.ENTER)
time.sleep(5)
# 아티스트 고유번호 체크
artist_num = driver.find_element_by_css_selector("#artist > ul > li:nth-child(1) > div.media-body > div.media-heading > a").get_attribute("href")[33:]
artist_num
# -
# 각 아티스트 페이지의 api 주소
link = 'https://api.chartmetric.io/SNS/socialStat/cm_artist/' + str(artist_num) + '/twitter?fromDaysAgo=9999&valueColumn=followers'
link
# +
# authrization
headers = {
"autorization token" : "<KEY>",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
}
# -
response = requests.get(link, headers=headers)
dom = BeautifulSoup(response.content, "html.parser")
dom
# #### 각 계정 별 api
#
# - twitter : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/twitter?fromDaysAgo=9999&valueColumn=followers
# - instagram : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/instagram?fromDaysAgo=9999
# - facebook : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/facebook?fromDaysAgo=9999&valueColumn=likes
# - spotify : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/spotify?fromDaysAgo=9999&valueColumn=popularity
# - soundcloud : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/soundcloud?fromDaysAgo=9999
# - youtube : https://api.chartmetric.io/SNS/socialStat/cm_artist/200408/youtube?fromDaysAgo=9999&valueColumn=subscribers
| archive/troubleshooting_qna/scraping-sns-followers.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
from multiprocessing import Pool
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from skimage import color, exposure, io, img_as_ubyte
from skimage.transform import resize
from sklearn import preprocessing
from sklearn.externals import joblib
# -
shape = 256
scaler_filename = "../models/images_StandardScaler.save"
out_dir = "../input/preprocessed/"
def process_image(image_dir):
image = io.imread(image_dir)
save_dir = out_dir + "/".join(image_dir.split("/")[-3:])
image = resize(image, (shape, shape), mode='reflect', anti_aliasing=True)
image = color.rgb2gray(image)
image = exposure.equalize_hist(image)
image = img_as_ubyte(image)
# print("preprocessed: "+ image_dir)
# print("saved in: "+ out_dir)
io.imsave(save_dir,image)
return image
# +
processes = 4
scaler = preprocessing.MinMaxScaler(feature_range=(-1,1))
# scaler = preprocessing.StandardScaler()
split_n = 100
test_normal_dir = "../input/test/NORMAL"
test_pneumonia_dir = "../input/test/PNEUMONIA"
train_normal_dir = "../input/train/NORMAL"
train_pneumonia_dir = "../input/train/PNEUMONIA"
val_normal_dir = "../input/val/NORMAL"
val_pneumonia_dir = "../input/val/PNEUMONIA"
full_url = np.vectorize(lambda url,prev_url: prev_url+"/"+url)
test_normal_data = pd.DataFrame(full_url(np.array(os.listdir(test_normal_dir)),test_normal_dir), columns=["image_dir"])
test_pneumonia_data = pd.DataFrame(full_url(np.array(os.listdir(test_pneumonia_dir)),test_pneumonia_dir), columns=["image_dir"])
train_normal_data = pd.DataFrame(full_url(np.array(os.listdir(train_normal_dir)),train_normal_dir), columns=["image_dir"])
train_pneumonia_data = pd.DataFrame(full_url(np.array(os.listdir(train_pneumonia_dir)),train_pneumonia_dir), columns=["image_dir"])
val_normal_data = pd.DataFrame(full_url(np.array(os.listdir(val_normal_dir)),val_normal_dir), columns=["image_dir"])
val_pneumonia_data = pd.DataFrame(full_url(np.array(os.listdir(val_pneumonia_dir)),val_pneumonia_dir), columns=["image_dir"])
test_data = test_normal_data.append(test_pneumonia_data)
train_data = train_normal_data.append(train_pneumonia_data)
val_data = val_normal_data.append(val_pneumonia_data)
os.makedirs(out_dir, exist_ok=True)
os.makedirs(out_dir + "test", exist_ok=True)
os.makedirs(out_dir + "train", exist_ok=True)
os.makedirs(out_dir + "val", exist_ok=True)
os.makedirs(out_dir + "test/NORMAL", exist_ok=True)
os.makedirs(out_dir + "test/PNEUMONIA", exist_ok=True)
os.makedirs(out_dir + "train/NORMAL", exist_ok=True)
os.makedirs(out_dir + "train/PNEUMONIA", exist_ok=True)
os.makedirs(out_dir + "val/NORMAL", exist_ok=True)
os.makedirs(out_dir + "val/PNEUMONIA", exist_ok=True)
os.makedirs("../models/", exist_ok=True)
pool = Pool(processes=processes) # Num of CPUs
i = 0
for sub_dir_list in np.array_split(train_data["image_dir"].values, split_n):
# crop, resize, rgb to grey and hist equalization.
train_images = np.array(pool.map(process_image, sub_dir_list, chunksize = 8))
# standarization or normalization
train_images = np.reshape(train_images,(len(train_images),-1))
scaler.partial_fit(train_images)
print("{}%".format(i))
i += 1
i = 0
for sub_dir_list in np.array_split(test_data["image_dir"].values, split_n):
# crop, resize, rgb to grey and hist equalization.
test_images = np.array(pool.map(process_image, sub_dir_list, chunksize = 8))
# standarization or normalization
test_images = np.reshape(test_images,(len(test_images),-1))
scaler.partial_fit(test_images)
print("{}%".format(i))
i += 1
i = 0
for sub_dir_list in np.array_split(val_data["image_dir"].values, 10):
# crop, resize, rgb to grey and hist equalization.
val_images = np.array(pool.map(process_image, sub_dir_list, chunksize = 8))
# standarization or normalization
val_images = np.reshape(val_images,(len(val_images),-1))
scaler.partial_fit(val_images)
print("{}%".format(i))
i += 1
joblib.dump(scaler, scaler_filename)
pool.close()
pool.terminate()
| data-preprocesing/dataPreprocessing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# %pylab inline
# # Modelling using MEANS
# This tutorial describes a way biological systems could be modelled using `MEANS` package.
# In this example we will consider a simplified version of tumor-supressor protein *p53* system.
# This system models three proteins: *p53*, *Mdm2 precursor* and *Mdm2* and their interactions.
#
# A short schematic of this system is provided below:
from IPython.display import SVG
SVG('images/p53.svg')
# Typically the system is described by the following set of equations:
# $$
# \begin{aligned}
# \text{p53 production} && \emptyset\rightarrow p53 \\
# \text{Mdm2 independent p53 degradation} && p53 \rightarrow \emptyset \\
# \text{Mdm2 dependent p53 degradation} && Mdm2 + p53 \rightarrow Mdm2 \\
# \text{p53 dependent Mdm2 production} && p53 + Mdm2_{precursor} \rightarrow p53 + Mdm2 \\
# \text{Mdm2 synthesis from precursor} && Mdm2_{precursor} \rightarrow Mdm2 \\
# \text{Mdm2 degradation} && Mdm2 \rightarrow \emptyset \\
# \end{aligned}
# $$
# In this tutorial we alias the protein $p53$, $Mdm2_{precursor}$ and $Mdm2$ names with $y_0$, $y_1$ and $y_2$, respectively.
# We do this purely for notational convenience, to keep the equations light, and is not strictly necessary, as the actual names of proteins can be used in the models directly.
# In python, this can be done by building a list of ``sympy`` symbols with our species names:
import sympy
species = sympy.symbols(['y_0', 'y_1', 'y_2'])
print species
# From the reactions above, we can directly derive the <a href="http://en.wikipedia.org/wiki/Stoichiometry#Stoichiometry_matrix">stoichiometry matrix</a>:
#
# $$
# S = \left( \begin{array}{cccccc}
# +1 & -1 & -1 & 0 & 0 & 0\\
# 0 & 0 & 0 & +1 & -1 & 0\\
# 0 & 0 & 0 & 0 & +1 & -1 \end{array} \right)
# $$
#
# We can use ``numpy`` ``array`` to encode this matrix in python, for example:
import numpy as np
stoichiometry_matrix = np.array([[1, -1, -1, 0, 0, 0],
[0, 0, 0, 1, -1, 0],
[0, 0, 0, 0, 1, -1]])
print stoichiometry_matrix
# In addition to the stoichiometry matrix, which only gives the net production of species in each reaction, the propensities need to be defined for each reactions. Importantly, **stochastic** propensities (as opposed to deterministic rates) must be provided.
# Using this notation, the propensities of the $p53$ model are:
#
# $$
# \begin{aligned}
# a_0 &= c_0 \\
# a_1 &= c_1 y_0\\
# a_2 &= \frac{c_2 y_2 y_0}{(y_0+c_6)}\\
# a_3 &= c_3 y_0\\
# a_4 &= c_4 y_1\\
# a_5 &= c_5 y_2\\
# \end{aligned}
# $$
#
# where:
#
# * $c_0$ is the *p53* production rate,
# * $c_1$ is the *Mdm2*-independent *p53* degradation rate,
# * $c_2$ is the saturation *p53* degradation rate
# * $c_3$ is the *p53*-dependent *Mdm2* production rate,
# * $c_4$ is the *Mdm2* maturation rate,
# * $c_5$ is the *Mdm2* degradation rate.
# * $c_6$ is the threshold for degradation by *Mdm2*.
#
# In Python, we need to explicitly write down the constant parameters of the model using `sympy` package:
parameters = sympy.symbols(['c_0', 'c_1', 'c_2', 'c_3', 'c_4', 'c_5', 'c_6'])
print parameters
# We can now describe the actual propensities as python objects.
# To do this, we drop the left-hand-side of equations ($a_0$, ..., $a_5$) and create a python list (or, alternatively, a ``sympy.Matrix``) of the right-hand-sides:
propensities=['c_0',
'c_1*y_0',
'c_2*y_2*y_0/(y_0+c_6)',
'c_3*y_0',
'c_4*y_1',
'c_5*y_2']
print propensities
# Note that we just used a list of strings as our propensities above.
# In most cases `MEANS` would be able to convert the string representation into an object of the right kind, so one does not need to explicitly worry about that.
#
# The propensities were the final objects we need to describe in order to be able to create a `MEANS` model object.
# But before we do so, we need to the `MEANS` package first:
import means
# The ``means.Model`` constructor takes the list of species, the list of parameters, the propensities and the stoichiometry matrix in that order.
my_model = means.Model(species, parameters, propensities, stoichiometry_matrix)
# The model created should be the same as described earlier:
my_model
# In addition to the $\LaTeX$ rendering, which is the default in the IPython environment,
# pythonic representation of model can be displayed using ``print``.
print my_model
# The attributes for each of the elements in the model can be accessed directly, but are read-only:
print my_model.species
print my_model.parameters
print my_model.stoichiometry_matrix
print my_model.propensities
# ## Example Models in Means
# `MEANS` already package provides a few sample models:
#
# * `MODEL_DIMERISATION`,
# * `MODEL_MICHAELIS_MENTEN`,
# * `MODEL_P53`
# * `MODEL_HES1`,
# * `MODEL_LOTKA_VOLTERRA`.
#
# These models can be accesseed from `examples` submodule. Let's use `MODEL_LOTKA_VOLTERRA` as an example.
from means.examples.sample_models import MODEL_LOTKA_VOLTERRA
print MODEL_LOTKA_VOLTERRA
# As noted above, the names of the species may not necessarily be mathematical symbols: $y_0$, $y_1$.
# In the Lotka-Volterra model, for instance, we use shortenings of the actual names of the species (*Predator* and *Prey*).
# ### Reading Models From Files
# ``MEANS`` models can be saved to file and read from it with the help of ``means.io`` package.
# This package provides methods ``to_file`` and ``from_file`` that can read arbitrary python objects from files,
# as long as they were serialised in YAML format.
# Similarly, `Model` class itself has a ``to_file()`` and ``from_file()`` methods designed to help you with these tasks.
#
# We took great care of making `Model` objects cleanly serialisable with YAML into human-readable fashion.
#
# Please find a demonstration below:
# Let's save `my_model` to file:
my_model.to_file('my_model.model')
# Let's print the contents of this newly-created file:
with open('my_model.model') as f:
print f.read()
# One can se how easy to read this serialisation form is.
#
# This form is also machine-readable, and we can indeed read the model object back from this file easily:
my_model_new = means.Model.from_file('my_model.model')
my_model_new
# Which is the same model we used previously.
#
# Let's delete this file we used to illustrate this:
import os
os.unlink('my_model.model')
# #### SBML Support (**requires SBML library installed on your machine**)
# More complicated biological models can be parsed from SBML files.
#
# [Biomodels repository](http://www.ebi.ac.uk/biomodels-main/) hosts a large number of published biological models.
#
#
# Consider the Tutorial 1a. SBML Parsing Example for more information on how to download SBML models using MEANS.
# # Modelling Stochastic Dynamics
# Creating models is nice and fun, however, what we are really interested in is the ability to study them.
# ## Moment Expansion Approximation
# In their [2013 paper](http://scitation.aip.org/content/aip/journal/jcp/138/17/10.1063/1.4802475),
# Ale *et al.* describe a Moment Expansion Approximation method for studying the moments of stochastic distributions.
#
# This method, shortened as MEA, approximate the solution for chemical master equation by a system of ODEs.
# The algorithm performs a set of moment expansions and returns as a set of ODEs,
# each one representing the time derivative of all approximated moments (mixed and non-mixed).
#
# Without going into much mathematical detail, the moment expansions are essentially infinite.
# In order to make the problem computable, the approximation needs to be stop at some higher order moment, or in other words, needs to be closed at that moment.
#
# Typically, the moments higher than the maximum specified moment are assumed to be equal to a constant scalar value (most often 0).
# We call this type of moment closure ``scalar`` in our package. This is where the "approximation" in Moment Expansion Approximation occurs.
#
# Besides the standard assumption of ``scalar`` value for higher order moments,
# we could replace them with the expressions derived from specific probability distributions.
# Currently our package supports ``normal``, ``log-normal`` and ``gamma`` distributions to close the higher order moments.
# The MEA moment closure is implemented by the ``MomentExpansionApproximation`` class in the ``means.approximation.mea`` package, this class can be used explicitly to generate the set of ODEs from a given model.
# Before we show how to use it, let's set up our workspace:
# +
import means
import means.examples
# Use dimerisation example model for this, due to the relative simplicity of it
model = means.examples.MODEL_DIMERISATION
# -
model
# To use this class, first instantiate it with appropriate model and max_order parameters:
mea = means.MomentExpansionApproximation(model, max_order=3)
# Here we specify the system that we want to perform Moment Expansion Approximation
# for moments up to order three for the model defined above.
# Note that default closure method is always the scalar closure (*i.e.* assuming higher order values to be zero).
#
# After defining the approximation, we need to perform it. This is done by calling the ``.run()`` method of this class instance, and it returns an ``ODEProblem`` object, which is essentially a collection of ordinary differential equations.
ode_problem = mea.run()
# If you are viewing this in an interactive environment, such as IPython notebook,
# you can view the ode_problem results formatted in $\LaTeX$ notation by just outputting it from a cell:
ode_problem
# The list of the terms used is given above the equations along with their descriptions.
# We use the convention for the first set of ODEs to explicitly model the species concentrations (first-order moments), and then each subsequent ODE is modelling higher order moments.
# Symbolic notation for moments matches the $M_\mathbf{n}$ notation used in the paper and describes the moment orders in the sub-index.
# ``ODEProblem`` objects offer a convenient way of retrieving the description of a symbol programmatically via the ``descriptor_for_symbol(symbol)`` method, i.e.:
ode_problem.descriptor_for_symbol('y_0')
# We also provide a convenience method for performing this approximation, ``means.mea_approximation``.
# This method takes exactly the same set of parameters as the ``MomentExpansionApproximation``, creates an instance of it, issues the ``run()`` method and returns the resulting ODE problem back:
# Returns same set of ODEs as above
ode_problem = means.mea_approximation(model, max_order=3)
# In order to use the probability distributions described above as closure methods, supply additional ``closure`` argument to the function, for instance, closure using ``log-normal`` distribution can be performed as follows:
ode_problem_log_normal = means.mea_approximation(model, max_order=3,
closure='log-normal')
ode_problem_log_normal
# A keen eyed reader might notice that the ODEs generated using the different closure methods are very different from each other.
# Each of the probabilistic distribution closures exist in both multivariate and univariate forms.
# By default, these distributions are assumed to be multivariate. In case, univariate distributions are desired, the parameter ``multivariate=False`` can be passed to the closure function.
# Essentially this parameter would set all the covariances to zero.
# For single species models, such as this one, this parameter makes no difference.
# Gamma closure distribution is a bit different from the others as it has three forms: type 0, 1 and 2.
# Type zero is equivalent to univariate gamma, while type 1 and 2 are two different forms of multivariate Gamma distribution.
# Please consult the documentation and accompanying papers for explanation on these differences.
# ## Linear Noise Approximation
# Linear Noise Approximation (or LNA, for short) is an alternative method to generate the system of ODEs approximating the stochastic dynamics.
# It calculates the deterministic macroscopic rate and linear Fokker-Planck equations for the fluctuations around the steady state.
#
# It evaluates the deterministic rate and noise based only on mean, variance and covariance.
# Therefore, the number of resulting ODEs is equivalent to the number of ODEs obtained from MEA closed at second-order moments.
#
# We provide a ``LinearNoiseApproximation`` class that works similarly to the ``MomentExpansionApproximation`` class described earlier, as well as a convenience method ``lna_approximation`` that is equivalent to the ``mea_approximation`` used a couple of times in this tutorial already.
#
# As opposed to MEA described earlier, LNA is parameterless and only needs the model as input:
ode_problem_lna = means.lna_approximation(model)
# The resulting set of ODEs returned is structurally equivalent to the one returned by MEA expansion, and can be viewed in the same fashion:
ode_problem_lna
# The major difference is that MEA returns ``VarianceTerm`` objects instead of second-order moments,
# that match the notation used for variance, with indices specifying the position in the covariance matrix.
# Besides this difference, the ``ODEProblem`` objects generated from MEA and LNA are interchangeable, and the subsequent steps described in following tutorials are able to support both of them.
# In the next tutorial we use these ``ODEProblem`` objects to simulate the behaviour of the systems.
| tutorial/1. Modelling Using MEANS.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
# #!/usr/bin/python
# -*- coding: latin-1 -*-
"""
This notebook adds the WLE per contributor category to all the files in the
WLE_CATEGORY category. It does not include the {{see also}} templates.
"""
import os, sys, inspect
current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
folder_parts = current_folder.split(os.sep)
pywikibot_folder = os.sep.join(folder_parts[0:-1])
if current_folder not in sys.path:
sys.path.insert(0, current_folder)
if pywikibot_folder not in sys.path:
sys.path.insert(0, pywikibot_folder)
import pywikibot as pb
from pywikibot import pagegenerators, textlib
from StringIO import StringIO
import mwparserfromhell as mwh
import pandas as pd
# +
WLE_CATEGORY = u"Category:Images from Wiki Loves Earth 2017 in Spain"
commons_site = pb.Site("commons", "commons")
# +
# Retrieving list of images
cat_wle = pb.Category(commons_site, WLE_CATEGORY)
gen_wle = pagegenerators.CategorizedPageGenerator(cat_wle)
images_wle = [page.title(withNamespace=True) for page in gen_wle if page.isImage()]
# -
for index, image in enumerate(images_wle):
page = pb.Page(commons_site, image)
if (index != 0) and (index % 50 == 0) :
pb.output ('Retrieving --> %d image descriptions downloaded' %(index))
author = page.oldest_revision["user"]
text = page.text
cats = [cat.title() for cat in textlib.getCategoryLinks(text)]
author_category = u'Category:Images from Wiki Loves Earth 2017 in Spain by {0}'.format(author)
author_category_string = u'\n[[{0}]]'.format(author_category)
if author_category in cats:
continue
page.text = text + author_category_string
page.save("WLE Spain 2017: user category management")
| WLE author category enhancer.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Compute the $z_{vdw}$ distance
import numpy as np
import matplotlib.pyplot as plt
kt = 4e-21
A = 0.62 * kt
a = 1.5e-6
B = 4 * kt
ld = 100e-9
def F_elec(z):
return B/ld * np.exp(z / ld)
def F_vdw(z):
return - (A*a) / (6 * z**2)
def minimizer(z):
z = z*1e-9
return np.abs(F_elec(z) + F_vdw(z)) / F_vdw(z)
z = np.linspace(1e-12, 1e-6, 100000)
plt.semilogx(z, F_tot(z))
minimize(F_tot, x0 = 2e-9, method="Nelder-Mead")
| 02_body/chapter3/images/zvdw/.ipynb_checkpoints/zvdw-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: PySpark 2.4 (Python 3.7)
# language: python
# name: pyspark3
# ---
# # NYC Taxi Trips Example
#
# This data is freely available. You can find some interesting background information at https://chriswhong.com/open-data/foil_nyc_taxi/ . We will use this data to perform some analytical tasks. The whole wotkshop is split up into multiple sections, which represents the typical data processing flow in a data centric project. We will follow the (simplified) steps when using a data lake.
#
# 1. Build "Structured Zone" containing all sources
# 2. Build "Refined Zone" that contains pre-processed data
# 3. Analyze the data before working on the next steps to find an appropriate approach
# 4. Build "Integrated Zone" that contains integrated data
# 5. Use Machine Learning for business questions
# ## Requirements
#
# The workshop will require the following Python packages:
#
# * PySpark (tested with Spark 2.4)
# * Matplotlib
# * Pandas
# * GeoPandas
# * Cartopy
# * Contextily
# # Part 1 - Build Structured Zone
#
# The first part is about building the structured zone. It will contain a copy of the raw data stored in Hive tables and thereby easily accessible for downstream processing.
taxi_basedir = "s3://dimajix-training/data/nyc-taxi-trips/"
weather_basedir = "s3://dimajix-training/data/weather/"
holidays_basedir = "s3://dimajix-training/data/bank-holidays/"
dwh_basedir = "/user/hadoop/nyc-dwh"
structured_basedir = dwh_basedir + "/structured"
# # 0 Create Spark Session
#
# Before we begin, we create a Spark session if none was provided in the notebook.
# +
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
if not 'spark' in locals():
spark = SparkSession.builder \
.master("local[*]") \
.config("spark.driver.memory","64G") \
.getOrCreate()
spark
# -
# # 1 Taxi Data
#
# This data is freely available. You can find some interesting background information at https://chriswhong.com/open-data/foil_nyc_taxi/ . In the first step we read in the raw data. The data is split into two different entities: Basic trip information and payment information. We will store the data in a more efficient representation (Parquet) to form the structured zone.
# ## 1.1 Trip Information
#
# We start with reading in the trip information. It contains the following columns
# * **medallion** - This is some sort of a license for a taxi company. A single medallion is attached to a single cab and may be used by multiple drivers.
# * **hack_license** - This is the drivers license
# * **vendor_id**
# * **rate_code** The final rate code in effect at the end of the trip.
# * 1=Standard rate
# * 2=JFK
# * 3=Newark
# * 4=Nassau or Westchester
# * 5=Negotiated fare
# * 6=Group ride
# * **store_and_fwd_flag** This flag indicates whether the trip record was held in vehicle memory before sending to the vendor, aka “store and forward,” because the vehicle did not have a connection to the server
# * **pickup_datetime** This is the time when a passenger was picked up
# * **dropoff_datetime** This is the time when the passenger was dropped off again
# * **passenger_count** Number of passengers of this trip
# * **trip_time_in_secs**
# * **trip_distance**
# * **pickup_longitude**
# * **pickup_latitude**
# * **dropoff_longitude**
# * **dropoff_latitude**
#
# The primary key uniquely identifying each trip is given by the columns `medallion`, `hack_license`, `vendor_id` and `pickip_datetime`.
# +
from pyspark.sql.types import *
trip_schema = StructType([
StructField('medallion', StringType()),
StructField('hack_license', StringType()),
StructField('vendor_id', StringType()),
StructField('rate_code', StringType()),
StructField('store_and_fwd_flag', StringType()),
StructField('pickup_datetime', TimestampType()),
StructField('dropoff_datetime', TimestampType()),
StructField('passenger_count', IntegerType()),
StructField('trip_time_in_secs', IntegerType()),
StructField('trip_distance', DoubleType()),
StructField('pickup_longitude', DoubleType()),
StructField('pickup_latitude', DoubleType()),
StructField('dropoff_longitude', DoubleType()),
StructField('dropoff_latitude', DoubleType()),
])
trip_data = # YOUR CODE HERE
# -
# Inspect the first 10 rows by converting them to a Pandas DataFrame.
# +
# YOUR CODE HERE
# -
# ### Inspect Schema
#
# Just to be sure, let us inspect the schema. It should match exactly the specified one.
# +
# YOUR CODE HERE
# -
# ### Write into Structured Zone
#
# Now we store data as parquet files.
# +
# YOUR CODE HERE
# -
# ## 1.2 Fare information
#
# Now we read in the second table containing the trips fare information.
#
# * **medallion** - This is some sort of a license for a taxi company
# * **hack_license** - This is the drivers license
# * **vendor_id**
# * **pickup_datetime** This is the time when a passenger was picked up
# * **payment_type** A numeric code signifying how the passenger paid for the trip.
# * CRD = Credit card
# * CDH = Cash
# * ??? = No charge
# * ??? = Dispute
# * ??? = Unknown
# * ??? = Voided trip
# * **fare_amount** The time-and-distance fare calculated by the meter
# * **surcharge**
# * **mta_tax** $0.50 MTA tax that is automatically triggered based on the metered rate in use
# * **tip_amount** Tip amount –This field is automatically populated for credit card tips. Cash tips are not included
# * **tolls_amount** Total amount of all tolls paid in trip
# * **total_amount** The total amount charged to passengers. Does not include cash tips.
# +
fare_schema = StructType([
StructField('medallion', StringType()),
StructField('hack_license', StringType()),
StructField('vendor_id', StringType()),
StructField('pickup_datetime', TimestampType()),
StructField('payment_type', StringType()),
StructField('fare_amount', DoubleType()),
StructField('surcharge', DoubleType()),
StructField('mta_tax', DoubleType()),
StructField('tip_amount', DoubleType()),
StructField('tolls_amount', DoubleType()),
StructField('total_amount', DoubleType())
])
trip_fare = spark.read \
.option("header", True) \
.option("ignoreLeadingWhiteSpace", True) \
.schema(fare_schema) \
.csv(taxi_basedir + "/fare/")
# -
trip_fare.limit(10).toPandas()
# ### Inspect Schema
#
# Let us inspect the schema of the data, which should match exactly the schema that we originally specified
trip_fare.printSchema()
# ### Store into Structured Zone
#
# Finally store the data into the structured zone as Parquet files into the sub directory `taxi-fare`
trip_fare.write.parquet(structured_basedir + "/taxi-fare")
# # 2. Weather Data
#
# In order to improve our analysis, we will relate the taxi trips with weather information. We use the NOAA ISD weather data (https://www.ncdc.noaa.gov/isd), which contains measurements from many stations around the world, some of them dating back to 1901. You can download all data from ftp://ftp.ncdc.noaa.gov/pub/data/noaa . We will only use a small subset of the data which is good enough for our purposes.
# ## 2.1 Station Master Data
#
# The weather data is split up into two different data sets: the measurements themselves and meta data about the stations. The later contains valuable information like the geo location of the weather station. This will be useful when trying to find the weather station nearest to all taxi trips.
#
# Among other data the columns provide specifically the following informations
# * **USAF** & **WBAN** - weather station id
# * **CTRY** - the country of the weather station
# * **STATE** - the state of the weather station
# * **LAT** & **LONG** - latitude and longitude of the weather station (geo coordinates)
# * **BEGIN** & **END** - date range when this weather station was active
# +
weather_stations = # YOUR CODE HERE
weather_stations.limit(10).toPandas()
# -
# ### Store data into Structured Zone
#
# In the next step we want to store the data as Parquet files (which are much more efficient and very well supported by most batch frameworks in the Hadoop and Spark universe). In order to do so, we first need to rename some columns, which contain unsupported characters:
# * "STATION NAME" => "STATION_NAME"
# * "ELEV(M)" => "ELEVATION"
#
# After the columns have been renamed, the data frame is written into the structured zone into the sub directory `weather-stations` using the `DataFrame.write.parquet` function.
weather_stations \
.withColumnRenamed("STATION NAME", "STATION_NAME") \
.withColumnRenamed("ELEV(M)", "ELEVATION") \
.write.parquet(structured_basedir + "/weather-stations")
# ### Read in data agin
#
# Using the `spark.read.parquet` function we read in the data back into Spark and display some records.
weather_stations = # YOUR CODE HERE
weather_stations.limit(10).toPandas()
# ## 2.2 Weather Measurements
#
# Now we will work with the second and more interesting part of the NOAA weather data set: The measurements. These are stored in different subdirectories per year. For us, the year 2013 is good enough, since the taxi trips are all from 2013.
#
# The data format is a proprietary ASCII encoding, so we use the `spark.read.text` method to read each line as one record.
raw_weather = # YOUR CODE HERE
raw_weather.limit(10).toPandas()
# ### Extract precipitation
#
# Now we extract the precipitation from the measurements. This is not trivial, since that information is stored in a variable part. We assume that the record contains precipitation data when it contains the substring `AA1` at position 109. This denotes the type of the subsection in the data record followed by the number of hours of this measurement and the precipitation depth.
#
# We use some PySpark string functions to extract the data.
raw_weather.select(
f.substring(raw_weather["value"],106,999),
f.instr(raw_weather["value"],"AA1").alias("s"),
f.when(f.instr(raw_weather["value"],"AA1") == 109,f.substring(raw_weather["value"], 109+3, 8)).alias("AAD")
)\
.withColumn("precipitation_hours", f.substring(f.col("AAD"), 1, 2).cast("INT")) \
.withColumn("precipitation_depth", f.substring(f.col("AAD"), 3, 4).cast("FLOAT")) \
.filter(f.col("precipitation_depth") > 0) \
.limit(10).toPandas()
# ### Extract all relevant measurements
#
# The precipitation was the hardest part. Other measurements like wind speed and air temperature are stored at fixed positions together with some quality flags denoting if a measurement is valid. In the following statement, we extract all relevant measurements. Specifically we extract the following information
# * **USAF** & **WBAN** - weather station identifier
# * **ts** - timestamp of measurement
# * **wind_direction** - wind direction (in degrees)
# * **wind_direction_qual** - quality flag of the wind direction
# * **wind_speed** - wind speed
# * **wind_speed_qual** - quality flag indicating the validity of the wind speed
# * **air_temperature** - air temperature in degree Celsius
# * **air_temperature_qual** - quality flag for air temperature
# * **precipitation_hours**
# * **precipitation_depth**
# +
weather = raw_weather.select(
f.substring(raw_weather["value"],5,6).alias("usaf"),
f.substring(raw_weather["value"],11,5).alias("wban"),
f.to_timestamp(f.substring(raw_weather["value"],16,12), "yyyyMMddHHmm").alias("ts"),
f.substring(raw_weather["value"],42,5).alias("report_type"),
f.substring(raw_weather["value"],61,3).alias("wind_direction"),
f.substring(raw_weather["value"],64,1).alias("wind_direction_qual"),
f.substring(raw_weather["value"],65,1).alias("wind_observation"),
(f.substring(raw_weather["value"],66,4).cast("float") / 10.0).alias("wind_speed"),
f.substring(raw_weather["value"],70,1).alias("wind_speed_qual"),
(f.substring(raw_weather["value"],88,5).cast("float") / 10.0).alias("air_temperature"),
f.substring(raw_weather["value"],93,1).alias("air_temperature_qual"),
f.when(f.instr(raw_weather["value"],"AA1") == 109,f.substring(raw_weather["value"], 109+3, 8)).alias("AAD")
) \
.withColumn("precipitation_hours", f.substring(f.col("AAD"), 1, 2).cast("INT")) \
.withColumn("precipitation_depth", f.substring(f.col("AAD"), 3, 4).cast("FLOAT")) \
.withColumn("date", f.to_date(f.col("ts"))) \
.drop("AAD")
weather.limit(10).toPandas()
# -
# ### Store into Structured Zone
#
# After successful extraction, we write the result again into the structured zone into the subdirectory `weather/2013`.
weather.write.parquet(structured_basedir + "/weather/2013")
# ### Read in from Structured Zone
#
# Again we read back the data from the Parquet files.
weather = spark.read.parquet(structured_basedir + "/weather/2013")
weather.limit(10).toPandas()
# # 3. Holidays
#
# Another important data source is additional date information, specifically if a certain date is a bank holiday. While other information like week days can be directly computed from a date, for bank holidays an additional source is required.
#
# We follow again the same approach of reading in the raw data and storing it into the structured zone as Parquet files.
# +
holidays_schema = StructType([
StructField('id', IntegerType()),
StructField('date', DateType()),
StructField('description', StringType()),
StructField('bank_holiday', BooleanType())
])
holidays = # YOUR CODE HERE
holidays.limit(10).toPandas()
# -
holidays.printSchema()
# ### Store into Structured Zone
holidays.write.parquet(structured_basedir + "/holidays")
# ### Read in from Structured Zone
#
# Again let us check if writing was successful.
holidays = spark.read.parquet(structured_basedir + "/holidays")
holidays.limit(10).toPandas()
| pyspark-ml-taxis/notebooks/02 - NYC Taxi Trips - Part 1 - Preparation - Skeleton.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage import io
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KernelDensity
import skimage.segmentation as seg
import skimage.filters as filters
import skimage.draw as draw
import skimage.color as color
with open('1581508801.rectified.jpg','rb') as f:
im = io.imread(f)
plt.imshow(im)
# -
im_slic = seg.slic(im,n_segments=100,start_label=1,compactness=.1,enforce_connectivity=True)
im_felz = seg.felzenszwalb(im, scale=1000, sigma=0.8, min_size=20, multichannel=True)
im_quick = seg.quickshift(im, ratio=1.0, kernel_size=5, max_dist=10, return_tree=False, sigma=0, convert2lab=True, random_seed=42)
gradient = filters.sobel(color.rgb2gray(im))
im_watershed=segments_watershed = seg.watershed(gradient, markers=250, compactness=0.001)
# +
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4, figsize=(12, 3),
sharex=True, sharey=True)
for aa in (ax1, ax2, ax3, ax4):
aa.set_axis_off()
ax1.imshow(color.label2rgb(im_slic, im, kind='avg',bg_label=0))
ax1.set_title('Kmeans {}'.format(np.max(im_slic)))
ax2.imshow(color.label2rgb(im_felz, im, kind='avg',bg_label=0))
ax2.set_title('Felzenswalb {}'.format(np.max(im_felz)))
ax3.imshow(color.label2rgb(im_quick, im, kind='avg',bg_label=0))
ax3.set_title('Quick {}'.format(np.max(im_quick)))
ax4.imshow(color.label2rgb(im_watershed, im, kind='avg',bg_label=0))
ax4.set_title('Watershed {}'.format(np.max(im_watershed)))
plt.tight_layout()
plt.show()
# +
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
# similar to MATLAB ksdensity example x = [randn(30,1); 5+randn(30,1)];
Vecvalues=np.concatenate((np.random.normal(0,1,30), np.random.normal(5,1,30)))[:,None]
Vecpoints=np.linspace(-8,12,100)[:,None]
kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(Vecvalues)
logkde = kde.score_samples(Vecpoints)
plt.plot(Vecpoints,np.exp(logkde))
plt.show()
# -
i = 500
pr = (im[i,:,0]-im[i,:,2]).reshape(-1,1)
kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(pr)
logkde = kde.score_samples(pr)
plt.plot(pr,np.exp(logkde),'o')
plt.show()
print(np.shape(im[300,:,1].reshape(-1,1)))
| test_segmentation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## 使用PCA去噪
# ### 回忆我们之前的例子
import numpy as np
import matplotlib.pyplot as plt
X = np.empty((100, 2))
X[:,0] = np.random.uniform(0., 100., size=100)
X[:,1] = 0.75 * X[:,0] + 3. + np.random.normal(0, 5, size=100)
plt.scatter(X[:,0], X[:,1])
plt.show()
# +
from sklearn.decomposition import PCA
pca = PCA(n_components=1)
pca.fit(X)
X_reduction = pca.transform(X)
X_restore = pca.inverse_transform(X_reduction)
# -
plt.scatter(X_restore[:,0], X_restore[:,1])
plt.show()
# 降维的过程可以理解成是去噪。
# ### 手写识别的例子
# +
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target
# -
noisy_digits = X + np.random.normal(0, 4, size=X.shape)
example_digits = noisy_digits[y==0,:][:10]
for num in range(1,10):
example_digits = np.vstack([example_digits, noisy_digits[y==num,:][:10]])
example_digits.shape
# +
def plot_digits(data):
fig, axes = plt.subplots(10, 10, figsize=(10, 10),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(data[i].reshape(8, 8),
cmap='binary', interpolation='nearest',
clim=(0, 16))
plt.show()
plot_digits(example_digits)
# -
pca = PCA(0.5).fit(noisy_digits)
pca.n_components_
components = pca.transform(example_digits)
filtered_digits = pca.inverse_transform(components)
plot_digits(filtered_digits)
| 07-PCA-and-Gradient-Ascent/08-PCA-for-Noise-Reduction/08-PCA-for-Noise-Reduction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
#
# # Parametric Curve
#
#
# This example demonstrates plotting a parametric curve in 3D.
#
# +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
# Prepare arrays x, y, z
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
| matplotlib/gallery_jupyter/mplot3d/lines3d.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# + code_folding=[0]
# Initial imports and notebook setup, click arrow to show
import sys
import os
from HARK.ConsumptionSaving.ConsIndShockModel import *
import HARK.ConsumptionSaving.ConsumerParameters as Params
from HARK.utilities import plotFuncsDer, plotFuncs
from time import clock
mystr = lambda number : "{:.4f}".format(number)
import matplotlib.pyplot as plt
# -
# ## What Happens To the Consumption Function When A Liquidity Constraint is Tightened?
#
# (This example builds on the ConsIndShockModel notebook; digest that before proceeding)
#
# The $\texttt{KinkedRconsumerType}$ class solves the problem of a consumer for whom the interest rate on borrowing is higher than the rate that the consumer will receive on any positive saving they do. The default calibration is meant to capture a case where the borrowing occurs at an interest rate typical of credit cards.
#
# (Fuller discussion of the issues here can be found in [A Theory of the Consumption Function, With or Without Liquidity Constraints](http://econ.jhu.edu/people/ccarroll/ATheoryv3JEP.pdf))
# +
# Create an instance of the type of consumer we are interested in
KinkyExample = KinkedRconsumerType(**Params.init_kinked_R)
# Make the example infinite horizon (not a life cycle model)
KinkyExample.cycles = 0
# The consumer cannot borrow more than 0.4 times their permanent income
KinkyExample.BoroCnstArt = -0.4
# Solve the consumer's problem
KinkyExample.solve()
# Plot the results
plt.ylabel('Consumption c')
plt.xlabel('Market Resources m')
plotFuncs([KinkyExample.solution[0].cFunc],KinkyExample.solution[0].mNrmMin,5)
# -
# 'Market Resources' $M$ is the total amount of money (assets plus current income) available to the consumer when the consumption decision is made. Lower case $m = M/P$ is the ratio of $M$ to permanent income. Likewise, $c = C/P$ is the ratio of consumption to permanent income.
#
# The line segment near $m=1$ captures the interval over which the consumer spends all of their market resources, because it's not worth it to borrow at the high credit card interest rate, but also not worth it to save at the low bank account interest rate.
#
# The bottommost point on the consumption function is at $m=-0.4$, where consumption is zero. This consumer would like to borrow to finance spending out of future income, but is already at the maximum borrowing limit.
#
# The consumption function has a linear portion with a slope of 45 degrees along which the marginal propensity to consume out of extra market resources is 1. But eventually resources get high enough that the consumer is willing to spend less than the maximum possible amount; this concave part of the consumption function terminates at the point where the consumer's desired borrowing reaches zero: The bottommost point on the line segment discussed above.
# ### Solution With A Tighter Constraint
#
# We are now interested in the solution to the problem when the constraint is tighter; concretely, the maximum amount of borrowing allowed is now 0.2, rather than 0.4.
#
# +
# Make a copy of the example consumer
KinkyExampleTighten = deepcopy(KinkyExample)
# Now change the location of the borrowing constraint -- the consumer cannot borrow more than 0.2
KinkyExampleTighten.BoroCnstArt = -0.2
# Solve the modified problem
KinkyExampleTighten.solve()
# Compare the two functions
plotFuncs([KinkyExample.solution[0].cFunc,KinkyExampleTighten.solution[0].cFunc],KinkyExampleTighten.solution[0].mNrmMin,5)
# -
# ### Discussion
#
# The interesting question that this analysis does not address is how to handle the transition from a looser to a tighter constraint.
#
# The toolkit can simulate a population of households behaving according to the first rule. But it is not obvious how to treat consumers whose debt, say, was 0.3 before the constraint was tightened. A simple, but implausible, approach is to assume that such consumer must immediately cut their consumption by enough to reduce their debt to the new more stringent maximum. A reasonable solution might be to say that the new tighter constraint applies only to new borrowers; different papers in the literature take different approaches to this transition question.
| notebooks/.ipynb_checkpoints/ChangeLiqConstr-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: shenoy_lab_nwb
# language: python
# name: shenoy_lab_nwb
# ---
# ## Analysis scripts:
# This script shows how to retrieve relavant data from an nwb file (both stored locally and streaming from DANDI).
# 1. Functions to retrive the cloud storage path for an nwb file stored in DANDI.
# + jupyter={"outputs_hidden": true} tags=[]
import pynwb
from pynwb import NWBHDF5IO
from nwbwidgets import nwb2widget
import requests
from dandi.dandiapi import DandiAPIClient
dandiset_id = "000121"
filepath = "sub-Reggie/sub-Reggie_ses-20170118T094022_behavior+ecephys.nwb"
with DandiAPIClient() as client:
asset = client.get_dandiset(dandiset_id, 'draft').get_asset_by_path(filepath)
s3_path = asset.get_content_url(follow_redirects=1, strip_query=True)
# -
# 2. Open the nwb file:
# + tags=[]
# use the "Read Only S3" (ros3) driver to stream data directly from DANDI (or any other S3 location)
io = NWBHDF5IO(s3_path, mode='r', load_namespaces=True, driver='ros3')
# io = NWBHDF5IO(local_path, mode='r', load_namespaces=True) # if using a local file instead
nwb = io.read()
# + tags=[]
print(nwb.processing['ecephys'].data_interfaces.keys())
# -
# ## Visualization:
# 1. Position
# +
from nwbwidgets.behavior import route_spatial_series
from bisect import bisect
import plotly.graph_objects as go
import matplotlib.pyplot as plt
# retrieve all the spatial series ((x,y) position timeseries) stored in the nwb file:
spatial_series_dict = nwb.processing['behavior'].data_interfaces['Position'].spatial_series
names = list(spatial_series_dict)
print(f'available behavior variables: {names}')
selected_name = names[0]
# get x,y data for a specific dataset:
spatial_series = spatial_series_dict[selected_name]
spatial_series_data = spatial_series.data
if spatial_series.timestamps is not None:
spatial_series_timestamps = spatial_series.timestamps
else:
spatial_series_timestamps = spatial_series.starting_time + np.arange(spatial_series.shape[0])/spatial_series.rate
#plot x,y trace for a specific trial no:
trial_nos = [12, 15, 6]
for trial_no in trial_nos:
start_idx = bisect(spatial_series_timestamps, nwb.trials['start_time'][trial_no])
end_idx = bisect(spatial_series_timestamps, nwb.trials['stop_time'][trial_no])
# plot the x,y position:
plt.plot(spatial_series_data[start_idx:end_idx,0], spatial_series_data[start_idx:end_idx,1], label = f'trial {trial_no}')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title(f'x,y position for {selected_name}')
plt.show()
# -
#using nwbwidgets to plot:
wid = route_spatial_series(spatial_series)
wid
# 2. Electrophysiology time series:
# +
from nwbwidgets.ecephys import ElectricalSeriesWidget
import numpy as np
import matplotlib.pyplot as plt
from bisect import bisect
# LFP data stored:
if 'ecephys' in nwb.processing:
eseries_name = list(nwb.processing['ecephys'].data_interfaces)[0]
ephys_trace_dict = nwb.processing['ecephys'].data_interfaces[eseries_name].electrical_series
# get data for a specific probe:
names = list(ephys_trace_dict)
print(f'available behavior variables: {names}')
selected_name = names[0]
ephys_trace_container = ephys_trace_dict[selected_name]
else:
# raw 30k Hz data:
eseries_name = "raw"
ephys_trace_container = nwb.acquisition['ElectricalSeries_raw']
ephys_data = ephys_trace_container.data
if ephys_trace_container.timestamps is not None:
ephys_timestamps = ephys_trace_container.timestamps
else:
ephys_timestamps = ephys_trace_container.starting_time + np.arange(ephys_data.shape[0])/ephys_trace_container.rate
#plot trace for a specific trial no:
trial_nos = np.arange(10,12)
electrode_no = np.arange(ephys_data.shape[1])[10]
for trial_no in trial_nos:
start_idx = bisect(ephys_timestamps, nwb.trials['start_time'][trial_no])
end_idx = bisect(ephys_timestamps, nwb.trials['stop_time'][trial_no])
# plot trace:
plt.plot(ephys_timestamps[start_idx:end_idx], ephys_data[start_idx:end_idx, electrode_no], label = f'trial {trial_no}')
plt.xlabel('sec')
plt.ylabel('uV')
plt.legend()
plt.title(f'{eseries_name} trace for array {selected_name}')
plt.show()
# -
ElectricalSeriesWidget(ephys_trace_container)
# 3. Getting trials metadata:
# +
trials = nwb.trials
column_names = trials.colnames
print(column_names)
# can also convert to dataframe:
trials_df = trials.to_dataframe()
# retrieve specific column data:
stop_time=trials['stop_time'] # in seconds with respect to the session start time
start_time=trials['start_time']
print(start_time.description)
# for array like elements:
barrier_points=trials['barrier_points']
print(barrier_points[0].shape)
print(f'sample barrier point:{barrier_points[0]}')
print(barrier_points.target.description)
# -
# 4. Retrieve units/clusters metadata and raster:
# +
units = nwb.units
print(units.colnames, len(units))
# get spike timestamps for a specific unit
unit_no = 10
spike_times = units['spike_times'][unit_no]
spike_times.shape
# -
from nwbwidgets.misc import PSTHWidget, RasterWidget
PSTHWidget(nwb.units)
| nwb_usage/analysis_script.ipynb |
(* --- *)
(* jupyter: *)
(* jupytext: *)
(* text_representation: *)
(* extension: .ml *)
(* format_name: light *)
(* format_version: '1.5' *)
(* jupytext_version: 1.14.4 *)
(* kernelspec: *)
(* display_name: OCaml 4.11.1 *)
(* language: OCaml *)
(* name: ocaml-jupyter *)
(* --- *)
#use "topfind"
#require "owl-jupyter"
open Owl_jupyter
open Owl;;
(* +
let f x = Maths.sin x /. x in
let h = Plot.create "plot_001.png" in
Plot.set_title h "Function: f(x) = sine x / x";
Plot.set_xlabel h "x-axis";
Plot.set_ylabel h "y-axis";
Plot.set_font_size h 8.;
Plot.set_pen_size h 3.;
Plot.plot_fun ~h f 1. 15.;
Plot.output h
(* +
open Algodiff.D
let f x = Maths.(x ** (F 2.) - (F 2.))
let _ =
let x = ref 1. in
for _ = 0 to 6 do
let g = diff f (F !x) |> unpack_elt in
let v = f (F !x) |> unpack_elt in
x := !x -. v /. g;
Printf.printf "%.15f\n" !x
done
(* -
let f x = x *. x -. 2.;;
Owl_maths_root.brent f 0. 2.;;
(* +
open Algodiff.D
let f x = Maths.(
(F 1.) / ((x - F 0.3) ** (F 2.) + F 0.01) +
(F 1.) / ((x - F 0.9) ** (F 2.) + F 0.04) - F 6.)
let g = diff f
let f' x = f (F x) |> unpack_flt
let g' x = g (F x) |> unpack_flt
(* -
let _ =
let h = Plot.create ~m:1 ~n:2 "plot_hump.png" in
Plot.set_pen_size h 1.5;
Plot.subplot h 0 0;
Plot.plot_fun ~h f' 0. 2.;
Plot.set_ylabel h "f(x)";
Plot.subplot h 0 1;
Plot.plot_fun ~h g' 0. 2.;
Plot.set_ylabel h "f'(x)";
Plot.output h
| 0_OCaml/OCaml_Scientific_Computing_1st_Edition/Untitled.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Recommender Systems 2020/21
#
#
# ## Practice 4 - Building an ItemKNN Recommender From Scratch
#
# This practice session is created to provide a guide to students of how to crete a recommender system from scratch, going from the data loading, processing, model creation, evaluation, hyperparameter tuning and a sample submission to the competition.
#
# Outline:
# - Data Loading with Pandas (MovieLens 10M, link: http://files.grouplens.org/datasets/movielens/ml-10m.zip)
# - Data Preprocessing
# - Dataset splitting in Train, Validation and Testing
# - Similarity Measures
# - Collaborative Item KNN
# - Evaluation Metrics
# - Evaluation Procedure
# - Hyperparameter Tuning
# - Submission to competition
# +
__author__ = '<NAME>'
__credits__ = ['<NAME>']
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Dev'
import os
from typing import Tuple, Callable, Dict, Optional, List
import numpy as np
import pandas as pd
import scipy.sparse as sp
from sklearn.model_selection import train_test_split
# -
# ## Dataset Loading with pandas
#
# The Movielens 10M dataset is a collection of ratings given by users to items. They are stored in a columnar `.dat` file using `::` as separators for each attribute, and every row follows this structure: `<user_id>::<item_id>::<rating>::<timestamp>`.
#
# The function `read_csv` from pandas provides a wonderful and fast interface to load tabular data like this. For better results and performance we provide the separator `::`, the column names `["user_id", "item_id", "ratings", "timestamp"]`, and the types of each attribute in the `dtype` parameter.
# ## Data Preprocessing
#
# This section wors with the previously-loaded ratings dataset and extracts the number of users, number of items, and min/max user/item identifiers. Exploring and understanding the data is an essential step prior fitting any recommender/algorithm.
#
# In this specific case, we discover that item identifiers go between 1 and 65133, however, there are only 10677 different items (meaning that ~5/6 of the items identifiers are not present in the dataset). To ease further calculations, we create new contiguous user/item identifiers, we then assign each user/item only one of these new identifiers. To keep track of these new mappings, we add them into the original dataframe using the `pd.merge` function.
# ## Dataset Splitting into Train, Validation, and Test
#
# This is the last part before creating the recommender. However, this step is super *important*, as it is the base for the training, parameters optimization, and evaluation of the recommender(s).
#
# In here we read the ratings (which we loaded and preprocessed before) and create the `train`, `validation`, and `test` User-Rating Matrices (URM). It's important that these are disjoint to avoid information leakage from the train into the validation/test set, in our case, we are safe to use the `train_test_split` function from `scikit-learn` as the dataset only contains *one* datapoint for every `(user,item)` pair. On another topic, we first create the `test` set and then we create the `validation` by splitting again the `train` set.
#
#
# `train_test_split` takes an array (or several arrays) and divides it into `train` and `test` according to a given size (in our case `testing_percentage` and `validation_percentage`, which need to be a float between 0 and 1).
#
# After we have our different splits, we create the *sparse URMs* by using the `csr_matrix` function from `scipy`.
# ## Cosine Similarity
#
# We can implement different versions of a cosine similarity. Some of these are faster and others are slower.
#
# The most simple version is just to loop item by item and calculate the similarity of item pairs.
# $$ W_{i,j}
# = cos(v_i, v_j)
# = \frac{v_i \cdot v_j}{|| v_i || ||v_j ||}
# = \frac{\Sigma_{u \in U}{URM_{u,i} \cdot URM_{u,j}}}{\sqrt{\Sigma_{u \in U}{URM_{u,i}^2}} \cdot \sqrt{\Sigma_{u \in U}{URM_{u,j}^2}} + shrink} $$
#
# Another (faster) version of the similarity is by operating on vector products
# $$ W_{i,I}
# = cos(v_i, URM_{I})
# = \frac{v_i \cdot URM_{I}}{|| v_i || IW_{I} + shrink} $$
#
# and where
#
# $$ IW_{i} = \sqrt{{\Sigma_{u \in U}{URM_{u,i}^2}}}$$
# Lastly, a faster but more memory-intensive version of the similarity is by operating on matrix products
# $$ W
# = \frac{URM^{t} \cdot URM}{IW^{t} IW + shrink} $$
# ## Collaborative Filtering ItemKNN Recommender
#
# This step creates a `CFItemKNN` class that represents a Collaborative Filtering ItemKNN Recommender. As we have mentioned in previous practice sessions, our recommenders have two main functions: `fit` and `recommend`.
#
# The first receives the similarity function and the dataset with which it will create the similarities, the result of this function is to save the similarities (`weights`) into the class instance.
#
# The second function takes a user id, the train URM, the recommendation lenght and a boolean value to remove already-seen items from users. It returns a recommendation list for the user.
# ## Evaluation Metrics
#
# In this practice session we will be using the same evaluation metrics defined in the Practice session 2, i.e., precision, recall and mean average precision (MAP).
# +
def recall(recommendations: np.array, relevant_items: np.array) -> float:
is_relevant = np.in1d(recommendations, relevant_items, assume_unique=True)
recall_score = np.sum(is_relevant) / relevant_items.shape[0]
return recall_score
def precision(recommendations: np.array, relevant_items: np.array) -> float:
is_relevant = np.in1d(recommendations, relevant_items, assume_unique=True)
precision_score = np.sum(is_relevant) / recommendations.shape[0]
return precision_score
def mean_average_precision(recommendations: np.array, relevant_items: np.array) -> float:
is_relevant = np.in1d(recommendations, relevant_items, assume_unique=True)
precision_at_k = is_relevant * np.cumsum(is_relevant, dtype=np.float32) / (1 + np.arange(is_relevant.shape[0]))
map_score = np.sum(precision_at_k) / np.min([relevant_items.shape[0], is_relevant.shape[0]])
return map_score
# -
# ## Evaluation Procedure
#
# The evaluation procedure returns the averaged accuracy scores (in terms of precision, recall and MAP) for all users (that have at least 1 rating in the test set). It also calculates the number of evaluated and skipped users. It receives a recommender instance, and the train and test URMs.
# ## Hyperparameter Tuning
#
# This step is fundamental to get the best performance of an algorithm, specifically, because we will train different configurations of the parameters for the `CFItemKNN` recommender and select the best performing one.
#
# In order for this step to be meaningful (and to avoid overfitting on the test set), we perform it using the `validation` URM as test set.
#
# This step is the longest one to run in the entire pipeline when building a recommender.
# ## Submission to competition
#
# This step serves as a similar step that you will perform when preparing a submission to the competition. Specially after you have chosen and trained your recommender.
#
# For this step the best suggestion is to select the most-performing configuration obtained in the hyperparameter tuning step and to train the recommender using both the `train` and `validation` set. Remember that in the competition you *do not* have access to the test set.
#
# We simulated the users to generate recommendations by randomly selecting 100 users from the original identifiers. Do consider that in the competition you are most likely to be provided with the list of users to generate recommendations.
#
# Another consideration is that, due to easier and faster calculations, we replaced the user/item identifiers with new ones in the preprocessing step. For the competition, you are required to generate recommendations using the dataset's original identifiers. Due to this, this step also reverts back the newer identifiers with the ones originally found in the dataset.
#
# Last, this step creates a function that writes the recommendations for each user in the same file in a tabular format following this format:
# ```csv
# <user_id>,<item_id_1> <item_id_2> <item_id_3> <item_id_4> <item_id_5> <item_id_6> <item_id_7> <item_id_8> <item_id_9> <item_id_10>
# ```
#
# Always verify the competitions' submission file model as it might vary from the one we presented here.
# ## Exercises
# In this lecture we saw the most simple version of Cosine Similarity, where it just includes a shrink factor. There are different optimizations that we can do to it.
#
# - Implement TopK Neighbors
# - When calculating the cosine similarity we used `urm.T.dot(urm)` to calculate the enumerator. However, depending of the dataset and the number of items, this matrix could not fit in memory. Implemenent a `block` version, faster than our `vector` version but that does not use `urm.T.dot(urm)` beforehand.
# - Implement Adjusted Cosine [Formula link](http://www10.org/cdrom/papers/519/node14.html)
# - Implement Dice Similarity [Wikipedia Link](https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient)
# - Implement an implicit CF ItemKNN.
# - Implement a CF UserKNN model
| Practice 4 - Empty - Building an ItemKNN from scratch.ipynb |