text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
<div class="alert alert-block alert-warning">
<b>Warning:</b> Before running below cells please make sure you have API key and XYZ access token.
Please see <a href="https://github.com/heremaps/here-map-widget-for-jupyter/blob/master/examples/README.md">README.md</a> for more info on API key and XYZ access token.
</div>
```
import os
os.environ["LS_API_KEY"] = "MY-API-KEY" # replace your API key here.
os.environ["XYZ_TOKEN"] = "MY-XYZ-TOKEN" # replace your XYZ access token here.
# Create a normal map view
from here_map_widget import TileLayer, XYZ
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [44.20022717941052, -72.75660780639646]
m
m.center = [19.0760, 72.8777]
m.zoom = 3
m.center
# Add XYZ Space data on Map
style_flagged = {
"layers.xyz.points.Places": {
"filter": {"properties.GPSFLG": "Flagged for coordinate check"},
"draw": {
"points": {
"color": "blue",
"text": {
"priority": 0,
"font": {
"size": "12px",
"fill": "red",
"stroke": {"color": "white", "width": "0.5px"},
},
},
}
},
}
}
xyz_token = os.environ["XYZ_TOKEN"]
provider = XYZ(space_id="m2pcsiNi", token=xyz_token, show_bubble=True)
space = TileLayer(provider=provider, style=style_flagged)
m.add_layer(space)
# Set center and zoom for Map
from here_map_widget import Marker
from here_map_widget import TileLayer, XYZ
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [19.0760, 72.8777]
m.zoom = 6
m
# Add marker
mumbai_marker = Marker(lat=19.0760, lng=72.8777, evt_type="tap", draggable=True)
m.add_object(mumbai_marker)
pune_marker = Marker(lat=18.5204, lng=73.8567)
m.add_object(pune_marker)
# Remove a Marker
m.remove_object(mumbai_marker)
# Add LineString as Polyline
from here_map_widget import LineString, Polyline
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [51.1657, 10.4515]
style = {"lineWidth": 15}
l = [53.3477, -6.2597, 0, 51.5008, -0.1224, 0, 48.8567, 2.3508, 0, 52.5166, 13.3833, 0]
ls = LineString(points=l)
pl = Polyline(object=ls, style=style)
m.add_object(pl)
m
ls.push_point(lat=53.3477, lng=-6.2597)
m
# Add MultiLineString as Polyline
from here_map_widget import Map
from here_map_widget import LineString, MultiLineString, Polyline
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [51.1657, 10.4515]
style = {"lineWidth": 15}
l = [53.3477, -6.2597, 0, 51.5008, -0.1224, 0, 48.8567, 2.3508, 0, 52.5166, 13.3833, 0]
l_1 = [-53.3477, 6.2597, 0, -51.5008, 0.1224, 0, 48.8567, 2.3508, 0, 52.5166, 13.3833, 0]
ls = LineString(points=l)
ls_1 = LineString(points=l_1)
ml = MultiLineString(lines=[ls])
pl = Polyline(object=ml, style=style)
m.add_object(pl)
m
ml.push_line(ls_1)
m
ml.remove_line(ls_1)
m
# Add Polygon on Map
from here_map_widget import Map
from here_map_widget import LineString, Polygon
import os
center = [51.1657, 10.4515]
m = Map(api_key=os.environ["LS_API_KEY"], center=center)
style = {"fillColor": "#FFFFCC", "strokeColor": "#829", "lineWidth": 8}
l = [52, 13, 100, 48, 2, 100, 48, 16, 100, 52, 13, 100]
ls = LineString(points=l)
pg = Polygon(object=ls, style=style)
m.add_object(pg)
m
# Add GeoJSON from URL
from here_map_widget import Map
from here_map_widget import GeoJSON
import os
m = Map(api_key=os.environ["LS_API_KEY"])
geojson = GeoJSON(
url="https://gist.githubusercontent.com/peaksnail/5d4f07ca00ed7c653663d7874e0ab8e7/raw/64c2a975482efd9c42e54f6f6869f091055053cd/countries.geo.json",
disable_legacy_mode=True,
style={"fillColor": "rgba(245, 176, 65, 0.5)", "strokeColor": "black"},
show_bubble=True,
)
m.add_layer(geojson)
m
# Add geojson from Local File
from here_map_widget import Map
from here_map_widget import GeoJSON
import json
import os
m = Map(api_key=os.environ["LS_API_KEY"])
with open("countries.json", "r") as f:
data = json.load(f)
def call_back(feature):
return {"fillColor": "rgba(245, 176, 65, 0.7)", "strokeColor": "black", "lineWidth": 1}
hover_style = {"fillColor": "rgba(245, 176, 65, 0.2)", "strokeColor": "red", "lineWidth": 5}
geojson = GeoJSON(
data=data, style_callback=call_back, hover_style=hover_style, disable_legacy_mode=True
)
m.add_layer(geojson)
m
# Add WKT Point on Map
from here_map_widget import WKT, Marker
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [19.0760, 72.8777]
m.zoom = 9
wkt = WKT(data="POINT (72.8777 19.0760)")
mumbai_marker = Marker(object=wkt)
m.add_object(mumbai_marker)
m
# Add WKT LineString on Map
from here_map_widget import WKT, Polyline
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [6.1256, 1.2254]
m.zoom = 6
style = {"lineWidth": 15}
wkt = WKT(data="LINESTRING(4 6,7 10)")
line = Polyline(object=wkt, style=style)
m.add_object(line)
m
# Add WKT MultiLineString on Map
from here_map_widget import WKT, Polyline
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [40.4168, 3.7038]
m.zoom = 6
style = {"lineWidth": 15}
wkt = WKT(
data="MULTILINESTRING( (-2 41.5, -1 50, 0 60 ),(-1.541 40.141, -2.5 40.661, -1.8 41.541, -0.7 42.151) )"
)
line = Polyline(object=wkt, style=style)
m.add_object(line)
m
# Add WKT Polygon on Map
from here_map_widget import WKT, Polygon
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [52.5200, 13.4050]
m.zoom = 3
style = {"lineWidth": 15}
wkt = WKT(
data="POLYGON((23.972060 54.377196, 22.697646 49.763346, 14.567764 51.872928, 13.600967 55.637141))"
)
polygon = Polygon(object=wkt)
m.add_object(polygon)
m
# HeatMap Example
import numpy as np
data = (np.random.normal(size=(100, 3)) * np.array([[1, 1, 1]]) + np.array([[48, 5, 1]])).tolist()
data_list = []
for d in data:
data_list.append({"lat": d[0], "lng": d[1], "value": d[2]})
data_list
from here_map_widget import TileLayer, HeatMap
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"], center=[48.1575, 12.7134], zoom=12)
provider = HeatMap(interpolate=True, opacity=0.6, assume_values=True)
provider.add_data(data_list)
heatmap = TileLayer(provider=provider)
m.add_layer(heatmap)
m
provider.clear()
# Add millions of points data
from here_map_widget import TileLayer, XYZ
from here_map_widget import Map
import os
m = Map(api_key=os.environ["LS_API_KEY"])
m.center = [44.20022717941052, -72.75660780639646]
provider = XYZ(space_id="ZManj2D5", token=xyz_token)
space = TileLayer(provider=provider)
m.add_layer(space)
m
```
| github_jupyter |
# OpenCV Overlay: Filter2D and Dilate
<img src="attachment:image.png" width="200" align="right">
This notebook takes the design from notebook [1\_\_Intro_to_OpenCV_on_Jupyter_notebooks.ipynb](http://192.168.3.1:9090/notebooks/computer_vision/1__Intro_to_OpenCV_on_Jupyter_notebooks.ipynb) and shows the power of FPGA acceleration through the use of PYNQ overlays. If you are unfamiliar with the OpenCV function filter2D and dilate, please go through [1\_\_Intro_to_OpenCV_on_Jupyter_notebooks.ipynb](http://192.168.3.1:9090/notebooks/computer_vision/1__Intro_to_OpenCV_on_Jupyter_notebooks.ipynb) first. This example consists of a 2D filter and a dilate function and does the following.
1. Program overlay
2. Sets up USB camera
3. Run software only filter2D
4. Run SW filter2D + dilate and measure performance
5. Run SW filter2D + dilate and measure performance
6. Plot performance
7. Setup widgets
8. Run HW filter2D + dilate on input frames from USB camera in real-time
## Program overlay
Here we program the overlay on the FPGA, load the associated overlay library and load the PYNQ xlnk memory manager library. This process takes a few seconds to do. Overlays are generally composed of an FPGA bitstream and a shared library to access the accelerators via function calls. We use the pynq.Bitstream class to load the overlay and rename the associated shared library to xv2. It is also important to set the xlnk allocator library to point the same shared library so allocated memory maps are consistent. The pynq.Xlnk class contains hooks to the SDx memory allocation functions which is important when allocating certain kinds of memory for our accelerators (e.g. continguous non-cacheable buffers)
```
import cv2 #NOTE: This needs to be loaded first
# Load filter2D + dilate overlay
from pynq import Bitstream
bs = Bitstream("/usr/local/lib/python3.6/dist-packages/pynq_cv/overlays/xv2Filter2DDilate.bit")
bs.download()
import pynq_cv.overlays.xv2Filter2DDilate as xv2
# Load xlnk memory mangager
from pynq import Xlnk
Xlnk.set_allocator_library('/usr/local/lib/python3.6/dist-packages/pynq_cv/overlays/xv2Filter2DDilate.so')
mem_manager = Xlnk()
```
## Setup and configure USB camera <img src="attachment:image.png" width="80" align="right">
We use OpenCV (cv2) for capturing frames from a USB camera and processing those image frames. Here, we start by setting up the interface to the USB camera and configuring its resolution (1080p). A successful camera setup returns a 'True'. If something is is outputted, shutdown the notebook and restart it again.
```
import cv2
camera = cv2.VideoCapture(0)
width = 1920
height = 1080
camera.set(cv2.CAP_PROP_FRAME_WIDTH,width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT,height)
```
We add another helper function which sets up an IPython-based imshow call which encodes OpenCV image data to jpeg format before displaying it within the notebook itself. Other methods of displaying image data would perform similar conversions as well.
```
import IPython
def imshow(img):
returnValue, buffer = cv2.imencode('.jpg', img)
IPython.display.display(IPython.display.Image(data=buffer.tobytes()))
```
## Read input frame from USB camera
Read input frame and convert image to gray scale with OpenCV function cvtColor.
**NOTE**: We do a few extra reads up front to flush out the frame buffers in case camera was previously used
```
# Flush webcam buffers (needed when rerunning notebook)
for _ in range(5):
ret, frame_in = camera.read()
# Read in a frame
ret, frame_in = camera.read()
if ret:
frame_in_gray = cv2.cvtColor(frame_in,cv2.COLOR_RGB2GRAY)
else:
print("Error reading frame from camera.")
```
Show input frame in notebook.
```
imshow(frame_in_gray)
```
## Run SW Filter2D
Here, we call the OpenCV 2D filter function on the input frame using kernel coefficients for a Laplacian high-pass filter (which gives a kind edge detection). Note that many of the vision processing functions used will operate on gray scale only images. The matrix returned by filter2D is an 2D array (1920x1080) of 8-bit values denoting the brightness of each pixel.
* [OpenCV Filter2D](https://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04)
```
import numpy as np
#Sobel Hor filter
kernelF = np.array([[1.0,2.0,1.0],[0.0,0.0,0.0],[-1.0,-2.0,-1.0]],np.float32)
frameF = np.ones((height,width),np.uint8)
cv2.filter2D(frame_in_gray, -1, kernelF, frameF, borderType=cv2.BORDER_CONSTANT) # software 2D filter
imshow(frameF)
```
## Run SW Filter2D + SW Dilate and measure performance
We first run our vision processing pipeline in software only mode. By doing a 2D filter followed by a dilate function, we effectively brighten all the white edge lines of our image. In addition, we will iterate our small image processing pipeline (filter2d, dilate) over a few frames and measure the performance of each function as well as the overall performance. We also enable profiling with the %%prun command.
```
%%prun -s cumulative -q -l 10 -T prunSW
import numpy as np
import time
kernelF = np.array([[1.0,2.0,1.0],[0.0,0.0,0.0],[-1.0,-2.0,-1.0]],np.float32) #Sobel Hor filter
kernelD = np.ones((3,3),np.uint8)
frameF = np.ones((height,width),np.uint8)
frameD = np.ones((height,width),np.uint8)
num_frames = 20
start = time.time()
for _ in range(num_frames):
cv2.filter2D(frame_in_gray, -1, kernelF, frameF)
cv2.dilate(frameF, kernelD, frameD, iterations=1)
time_sw_total = time.time() - start
print("Frames per second: " + str(num_frames / time_sw_total))
imshow(frameD)
```
## Process SW profile results
```
print(open('prunSW','r').read())
res = !cat prunSW | grep filter2D | awk '{{print $$2}}'
tottime_sw_filter2d = float(res[0])
res = !cat prunSW | grep dilate | awk '{{print $$2}}'
tottime_sw_dilate = float(res[0])
```
## Run HW Filter2D + HW Dilate and measure performance
Now we take advantage of the library of accelerators in our overlay and accelerate the same two OpenCV functions in hardware. From a function signature point of view, it's about as simple as replacing the OpenCV library call (cv2) with a python-extended Xilinx OpenCV function call (xv2) provided to us by the overlay. The other concept necessary for hardware acceleration is making sure we use continguous memory for our frames. This is done through the use of cma_array calls as opposed to the numpy calls. Some data copying will be necessary when moving data between numpy arrays and cma_arrays if the data.
* [xFOpenCV Filter2D](https://github.com/Xilinx/xfopencv/blob/master/include/imgproc/xf_custom_convolution.hpp) ([ug1233](https://www.xilinx.com/support/documentation/sw_manuals/xilinx2018_2/ug1233-xilinx-opencv-user-guide.pdf))
```
%%prun -s cumulative -q -l 10 -T prunHW
import numpy as np
import time
#laplacian filter, high-pass
kernelF = np.array([[1.0,2.0,1.0],[0.0,0.0,0.0],[-1.0,-2.0,-1.0]],np.float32) #Sobel Hor filter
kernelVoid = np.zeros(0)
xFin = mem_manager.cma_array((height,width),np.uint8)
xFbuf = mem_manager.cma_array((height,width),np.uint8)
xFout = mem_manager.cma_array((height,width),np.uint8)
num_frames = 20
xFin[:] = frame_in_gray[:]
start = time.time()
for _ in range(num_frames):
xv2.filter2D(xFin, -1, kernelF, xFbuf, borderType=cv2.BORDER_CONSTANT)
xv2.dilate(xFbuf, kernelVoid, xFout, borderType=cv2.BORDER_CONSTANT)
time_hw_total = time.time() - start
print("Frames per second: " + str(num_frames / time_hw_total))
frame_out = np.ones((height,width),np.uint8)
frame_out[:] = xFout[:]
imshow(frame_out)
```
## Process HW profile results
```
print(open('prunHW','r').read())
res = !cat prunHW | grep filter2D | awk '{{print $$2}}'
tottime_hw_filter2d = float(res[0])
res = !cat prunHW | grep dilate | awk '{{print $$2}}'
tottime_hw_dilate = float(res[0])
```
## Plot performance
In addition to having easy access to OpenCV functions, we can access functions from pyPlot for plotting results in graphs and charts. Here, we take the recorded time data and plot out the processing times in a bar chart along with computed FPS of each function. Pay particular attention to the actual performance of each function and note the effect when placing two functions back-to-back in this example.
```
%matplotlib inline
from matplotlib import pyplot as plt
TIME_SW = [t*1000/num_frames for (t) in (time_sw_total, tottime_sw_dilate, tottime_sw_filter2d)]
FPS_SW = [1000/t for (t) in (TIME_SW)]
TIME_HW = [t*1000/num_frames for (t) in (time_hw_total, tottime_hw_dilate, tottime_hw_filter2d)]
FPS_HW = [1000/t for (t) in (TIME_HW)]
LABELS = ['Total','Dilate','Filter2D']
f, ((ax1, ax2),(ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(15,4))
x_pos = np.arange(len(LABELS))
plt.yticks(x_pos, LABELS)
ax1.barh(x_pos, TIME_SW, height=0.6, color='g', zorder=3)
ax1.invert_yaxis()
ax1.set_xlabel("Execution Time per frame [ms]")
ax1.set_ylabel("Kernel (SW)")
ax1.grid(zorder=0)
ax2.barh(x_pos, FPS_SW, height=0.6, color='b', zorder=3)
ax2.invert_yaxis()
ax2.set_xlabel("Frames per second")
ax2.grid(zorder=0)
ax3.barh(x_pos, TIME_HW, height=0.6, color='g', zorder=3)
ax3.invert_yaxis()
ax3.set_xlabel("Execution Time per frame [ms]")
ax3.set_ylabel("Kernel (HW)")
ax3.grid(zorder=0)
ax4.barh(x_pos, FPS_HW, height=0.6, color='b', zorder=3)
ax4.invert_yaxis()
ax4.set_xlabel("Frames per second")
ax4.grid(zorder=0)
plt.show()
```
## Setup control widgets
Here, we define some kernel configurations that will be used to change the functionality of the 2D filter on the fly. A pulldown menu will appear below this cell to be used to change the filter2D kernel used subsequent cells.
```
from ipywidgets import interact, interactive, fixed, interact_manual, IntSlider, FloatSlider
import ipywidgets as widgets
kernel_g = np.array([[1.0,2.0,1.0],[0.0,0.0,0.0],[-1.0,-2.0,-1.0]],np.float32) #Sobel Hor
def setKernelAndFilter3x3(kernelName):
global kernel_g
kernel_g = {
'laplacian high-pass': np.array([[0.0, 1.0, 0],[1.0, -4, 1.0],[0, 1.0, 0.0]],np.float32),
'gaussian high-pass': np.array([[-0.0625,-0.125,-0.0625],[-0.125,0.75,-0.125],[-0.0625,-0.125,-0.0625]],np.float32),
'gaussian blur': np.array([[0.0625,0.125,0.0625],[0.125,0.25,0.125],[0.0625,0.125,0.0625]],np.float32),
'Sobel Ver': np.array([[1.0,0.0,-1.0],[2.0,0.0,-2.0],[1.0,0.0,-1.0]],np.float32),
'Sobel Hor': np.array([[1.0,2.0,1.0],[0.0,0.0,0.0],[-1.0,-2.0,-1.0]],np.float32)
}.get(kernelName, np.ones((3,3),np.float32)/9.0)
interact(setKernelAndFilter3x3, kernelName=['Sobel Hor','Sobel Ver','laplacian high-pass','gaussian high-pass','gaussian blur']);
```
## Run HW filter2D + dilate on input frames from USB camera in real-time
Now we will run the 2D filter + dilate on input frames from the USB camera and display the results in real time. We will also respond to feedback from our pulldown menu which changes the 2D filter coefficients. While this interaction does not capture the performance acceleration of the HW implementation, it does allow us to receive real-time feedback of the accelerated hardware functions.
NOTE: To allow for live interaction of the pull-down menu selection with the processing loop, the loop will be run as a separate thread for ~20 seconds. As soon as the kernel coefficient is changed, the image will instead appear under the widget cell along with the eventual reported FPS calculations. The normal feedback of when a cell is complete will therefore not function (* will disappear immediately). The indication when the loop is complete will therefore be when the FPS calculation is reported. Adjusting the loop time requires changing the num_frames variable.
```
def loop_hw2_app():
global kernel_g
kernelD = np.ones((3,3),np.uint8)
frame_out = np.ones((height,width),np.uint8)
xFin = mem_manager.cma_array((height,width),np.uint8)
xFbuf = mem_manager.cma_array((height,width),np.uint8)
xFout = mem_manager.cma_array((height,width),np.uint8)
num_frames = 60
start = time.time()
for _ in range(num_frames):
# Capture frame-by-frame
ret, frame_in = camera.read()
if (not ret):
# Release the Video Device if ret is false
camera.release()
# Message to be displayed after releasing the device
print("Released Video Resource")
break
frame_in_gray = cv2.cvtColor(frame_in,cv2.COLOR_RGB2GRAY)
xFin[:] = frame_in_gray[:]
xv2.filter2D(xFin, -1, kernel_g, xFbuf, borderType=cv2.BORDER_CONSTANT)
xv2.dilate(xFbuf, kernelVoid, xFout, borderType=cv2.BORDER_CONSTANT)
frame_out[:] = xFout[:]
imshow(frame_out)
IPython.display.clear_output(wait=True)
end = time.time()
print("Frames per second: " + str(num_frames / (end - start)))
from threading import Thread
t = Thread(target=loop_hw2_app, )
t.start()
```
## Release USB camera resource
**NOTE**: This is needed to close the camera between subsequent runs. If the camera is unable to read a frame, be sure to call camera.release() and then try opening the VideoCapture again.
```
camera.release()
```
<font color=red size=4>IMPORTANT NOTE</font>: Be sure to run the cell below, shutting down the notebook, before starting a new one. The notebook interface shows "No Kernel", the cell below will incorrectly show a running status [ * ]. You can ignore this an safely close the tab of the notebook.
```
%%javascript
Jupyter.notebook.session.delete();
```
| github_jupyter |
# Multiple Seldon Core Operators
This notebook illustrate how multiple Seldon Core Operators can share the same cluster. In particular:
* A Namespaced Operator that only manages Seldon Deployments inside its namespace. Only needs Role RBAC and Namespace labeled with `seldon.io/controller-id`
* A Clusterwide Operator that manges SeldonDeployment with a matching `seldon.io/controller-id` label.
* A Clusterwide Operator that manages Seldon Deployments not handled by the above.
## Setup Seldon Core
Use the setup notebook to [Setup Cluster](seldon_core_setup.ipynb#Setup-Cluster) with [Ambassador Ingress](seldon_core_setup.ipynb#Ambassador) and [Install Seldon Core](seldon_core_setup.ipynb#Install-Seldon-Core). Instructions [also online](./seldon_core_setup.html).
## Namespaced Seldon Core Operator
```
!kubectl create namespace seldon-ns1
!kubectl label namespace seldon-ns1 seldon.io/controller-id=seldon-ns1
!helm install seldon-namespaced ../helm-charts/seldon-core-operator \
--set singleNamespace=true \
--set image.pullPolicy=IfNotPresent \
--set usageMetrics.enabled=false \
--set crd.create=false \
--namespace seldon-ns1 \
--wait
!kubectl rollout status deployment/seldon-controller-manager -n seldon-ns1
!kubectl create -f resources/model.yaml -n seldon-ns1
!kubectl rollout status deployment/seldon-model-example-0 -n seldon-ns1
!kubectl get sdep -n seldon-ns1
NAME=!kubectl get sdep -n seldon-ns1 -o jsonpath='{.items[0].metadata.name}'
assert(NAME[0] == "seldon-model")
!kubectl config set-context $(kubectl config current-context) --namespace=seldon-ns1
!kubectl delete -f resources/model.yaml -n seldon-ns1
!helm delete seldon-namespaced
```
## Label Focused Seldon Core Operator
* We set `crd.create=false` as the CRD already exists in the cluster.
* We set `controllerId=seldon-id1`. SeldonDeployments with this label will be managed.
```
!kubectl create namespace seldon-id1
!helm install seldon-controllerid ../helm-charts/seldon-core-operator \
--set singleNamespace=false \
--set image.pullPolicy=IfNotPresent \
--set usageMetrics.enabled=false \
--set crd.create=false \
--set controllerId=seldon-id1 \
--namespace seldon-id1 \
--wait
!kubectl rollout status deployment/seldon-controller-manager -n seldon-id1
!pygmentize resources/model_controller_id.yaml
!kubectl create -f resources/model_controller_id.yaml -n default
!kubectl rollout status deployment/test-c1-example-0 -n default
!kubectl get sdep -n default
NAME=!kubectl get sdep -n default -o jsonpath='{.items[0].metadata.name}'
assert(NAME[0] == "test-c1")
!kubectl config set-context $(kubectl config current-context) --namespace=seldon-id1
!kubectl delete -f resources/model_controller_id.yaml -n default
!helm delete seldon-controllerid
```
| github_jupyter |
# ANOVOS - Association Evaluator
Following notebook shows the list of functions related to "asociation evaultion" module provided under ANOVOS package and how it can be invoked accordingly.
- [Correlation Matrix](#Correlation-Matrix)
- [Variable Clustering](#Variable-Clustering)
- [Information Value (IV)](#Information-Value-(IV))
- [Information Gain (IG)](#Information-Gain-(IG))
**Setting Spark Session**
```
from anovos.shared.spark import *
sc.setLogLevel("ERROR")
import warnings
warnings.filterwarnings('ignore')
```
**Input/Output Path**
```
inputPath = "../data/income_dataset/csv"
outputPath = "../output/income_dataset/data_analyzer"
from anovos.data_ingest.data_ingest import read_dataset
df = read_dataset(spark, file_path = inputPath, file_type = "csv",file_configs = {"header": "True",
"delimiter": "," ,
"inferSchema": "True"})
df = df.drop("dt_1", "dt_2")
df.toPandas().head(5)
```
# Correlation Matrix
- API specification of function **correlation_matrix** can be found <a href="https://docs.anovos.ai/api/data_analyzer/association_evaluator.html">here</a>
```
from anovos.data_analyzer.association_evaluator import correlation_matrix
# Example 1 - 'all' columns (excluding drop_cols) --- MUST remove high cardinality columns
odf = correlation_matrix(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 2 - selected columns
odf = correlation_matrix(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
# Example 3 - selected columns + presaved stats
from anovos.data_analyzer.stats_generator import measures_of_cardinality
from anovos.data_ingest.data_ingest import write_dataset
unique = write_dataset(measures_of_cardinality(spark, df),outputPath+"/unique","parquet", file_configs={"mode":"overwrite"})
odf = correlation_matrix(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'],
stats_unique={"file_path":outputPath+"/unique", "file_type": "parquet"})
odf.toPandas()
```
# Variable Clustering
- API specification of function **variable_clustering** can be found <a href="https://docs.anovos.ai/api/data_analyzer/association_evaluator.html">here</a>
- Valid only on smaller dataset which can fit into pandas dataframe. Sample size can controlled by sample_size argument (default value: 100,000)
```
from anovos.data_analyzer.association_evaluator import variable_clustering
# Example 1 - with mandatory arguments (rest arguments have default values)
odf = variable_clustering(spark, df)
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = variable_clustering(spark, idf = df, list_of_cols='all', drop_cols=['ifa'])
odf.toPandas()
# Example 3 - selected columns
odf = variable_clustering(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'])
odf.toPandas()
# Example 4 - only numerical columns (user warning is shown as encoding was not required due to absence of any categorical column)
odf = variable_clustering(spark, idf = df, list_of_cols= ['age','education-num','capital-gain'])
odf.toPandas()
# Example 5 - only categorical columns
odf = variable_clustering(spark, idf = df, list_of_cols= ['sex','race','workclass'])
odf.toPandas()
# Example 6 - Change in Sample Size
odf = variable_clustering(spark, idf = df, list_of_cols= 'all', sample_size=10000)
odf.toPandas()
# Example 7 - selected columns + presaved stats
from anovos.data_analyzer.stats_generator import measures_of_cardinality, measures_of_centralTendency
from anovos.data_ingest.data_ingest import write_dataset
unique = write_dataset(measures_of_cardinality(spark, df),outputPath+"/unique","parquet", file_configs={"mode":"overwrite"})
mode = write_dataset(measures_of_centralTendency(spark, df),outputPath+"/mode","parquet", file_configs={"mode":"overwrite"})
odf = variable_clustering(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'],
stats_unique={"file_path":outputPath+"/unique", "file_type": "parquet"},
stats_mode={"file_path":outputPath+"/mode", "file_type": "parquet"})
odf.toPandas()
```
# Information Value (IV)
- API specification of function **IV_calculation** can be found <a href="https://docs.anovos.ai/api/data_analyzer/association_evaluator.html">here</a>
- Supports only binary target variable
```
from anovos.data_analyzer.association_evaluator import IV_calculation
# Example 1 - with mandatory arguments (rest arguments have default values)
odf = IV_calculation(spark, df, label_col='income', event_label=">50K")
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = IV_calculation(spark, idf = df, list_of_cols='all', drop_cols=['ifa'], label_col='income', event_label=">50K")
odf.toPandas()
# Example 3 - selected columns
odf = IV_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income', event_label=">50K")
odf.toPandas()
# Example 4 - selected columns + encoding configs (bin method equal_range instead of default equal_frequency )
odf = IV_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_range',
'bin_size': 10, 'monotonicity_check': 0})
odf.toPandas()
# Example 5 - selected columns + encoding configs (bin_size 20 instead of default 10 )
odf = IV_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_frequency',
'bin_size': 20, 'monotonicity_check': 0})
odf.toPandas()
# Example 6 - selected columns + encoding configs (monotonicity check )
odf = IV_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_frequency',
'bin_size': 10, 'monotonicity_check': 1})
odf.toPandas()
```
# Information Gain (IG)
- API specification of function **IG_calculation** can be found <a href="https://docs.anovos.ai/api/data_analyzer/association_evaluator.html">here</a>
- Supports only binary target variable
```
from anovos.data_analyzer.association_evaluator import IG_calculation
# Example 1 - with mandatory arguments (rest arguments have default values)
odf = IG_calculation(spark, df, label_col='income', event_label=">50K")
odf.toPandas()
# Example 2 - 'all' columns (excluding drop_cols)
odf = IG_calculation(spark, idf = df, list_of_cols='all', drop_cols=['ifa'], label_col='income', event_label=">50K")
odf.toPandas()
# Example 3 - selected columns
odf = IG_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income', event_label=">50K")
odf.toPandas()
# Example 4 - selected columns + encoding configs (bin method equal_range instead of default equal_frequency )
odf = IG_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_range',
'bin_size': 10, 'monotonicity_check': 0})
odf.toPandas()
# Example 5 - selected columns + encoding configs (bin_size 20 instead of default 10 )
odf = IG_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_frequency',
'bin_size': 20, 'monotonicity_check': 0})
odf.toPandas()
# Example 6 - selected columns + encoding configs (monotonicity check )
odf = IG_calculation(spark, idf = df, list_of_cols= ['age','sex','race','workclass','fnlwgt'], label_col='income',
event_label=">50K", encoding_configs={'bin_method': 'equal_frequency',
'bin_size': 10, 'monotonicity_check': 1})
odf.toPandas()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/ashishpatel26/Pytorch-Learning/blob/main/Pytorch_Variable_and_Autograd.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
### Variable
* The difference between pytorch and numpy is that it provides automatic derivation, which can automatically give you the gradient of the parameters you want. This operation is provided by another basic element, Variable.

* A Variable wraps a Tensor. It supports nearly all the API’s defined by a Tensor.
* Variable also provides a backward method to perform backpropagation. For example, to backpropagate a loss function to train model parameter x, we use a variable loss to store the value computed by a loss function.
* Then, we call loss.backward which computes the gradients ∂loss∂x for all trainable parameters. PyTorch will store the gradient results back in the corresponding variable x.
* Variable in torch is to build a computational graph, but this graph is dynamic compared with a static graph in Tensorflow or Theano.So torch does not have placeholder, torch can just pass variable to the computational graph.
```
import torch
from torch.autograd import Variable
```
* Build a **tensor**
* Build a **Variable, usually for compute Gradient**
```
tensor = torch.FloatTensor([[5,2],[6, 8]])
variable = Variable(tensor, requires_grad=True)
print(tensor) # [torch.FloatTensor of size 2x2]
print(variable) # [torch.FloatTensor of size 2x2]
```
* Till now the **tensor and variable** seem the same.However, the **variable is a part of the graph**, it's a part of the **auto-gradient**.
```
t_out = torch.mean(tensor * tensor)
v_out = torch.mean(variable * variable)
print(t_out)
print(v_out)
```
* Backpropagation from v_out
```
v_out = 1 / 4 * sum(variable * variable)
```
* the gradients w.r.t the variable,
```
d(v_out)/d(variable) = 1/4*2*variable = variable/2
```
```
v_out.backward()
print(variable.grad)
```
* This is data in **variable format**.
```
print(variable) # variable with require gradient format
```
* This is data in **tensor format**.
```
print(variable.data) # Variable with tensor format on original data
```
* This is in **numpy format**
```
print(variable.data.numpy())
```
### Torch.AutoGrad
* `torch.autograd` is PyTorch’s automatic differentiation engine that powers neural network training. In this section, you will get a conceptual understanding of how autograd helps a neural network train.
### Background
Neural networks (NNs) are a collection of nested functions that are executed on some input data. These functions are defined by parameters (consisting of weights and biases), which in PyTorch are stored in tensors.
Training a NN happens in two steps:
**Forward Propagation**: In forward prop, the NN makes its best guess about the correct output. It runs the input data through each of its functions to make this guess.
**Backward Propagation**: In backprop, the NN adjusts its parameters proportionate to the error in its guess. It does this by traversing backwards from the output, collecting the derivatives of the error with respect to the parameters of the functions (gradients), and optimizing the parameters using gradient descent. For a more detailed walkthrough of backprop, check out this
```
import torch, torchvision
model = torchvision.models.resnet18(pretrained=True)
data = torch.rand(1, 3, 64, 64)
labels = torch.rand(1, 1000)
```
* Next step run the input data through model through each of its layers to make a prediction. This is the **forward pass**
```
prediction = model(data) # forward pass
```
* Now, Model's prediction and corresponding label to calculate the error.
* Next, Step is to backpropagate this error through network.
```
loss = (prediction - labels).sum()
loss.backward() # backward pass
```
* Next step is to load an optimiser and this case we are applying SGD with learning rate 0.01 and momentum of 0.9
```
optim = torch.optim.SGD(model.parameters(), lr = 1e-02, momentum=0.9)
```
* Finally, we call `.step()` to initiate gradient descent. The optimizer adjusts each parameter by its gradient stored in `.grad.`
```
optim.step() #gradient descent
```
* _At this point, you have everything you need to train your neural network. The below sections detail the workings of autograd - feel free to skip them._
| github_jupyter |
# Think Bayes: Chapter 5
This notebook presents code and exercises from Think Bayes, second edition.
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
```
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Beta
import thinkplot
```
## Odds
The following function converts from probabilities to odds.
```
def Odds(p):
return p / (1-p)
```
And this function converts from odds to probabilities.
```
def Probability(o):
return o / (o+1)
```
If 20% of bettors think my horse will win, that corresponds to odds of 1:4, or 0.25.
```
p = 0.2
Odds(p)
```
If the odds against my horse are 1:5, that corresponds to a probability of 1/6.
```
o = 1/5
Probability(o)
```
We can use the odds form of Bayes's theorem to solve the cookie problem:
```
prior_odds = 1
likelihood_ratio = 0.75 / 0.5
post_odds = prior_odds * likelihood_ratio
post_odds
```
And then we can compute the posterior probability, if desired.
```
post_prob = Probability(post_odds)
post_prob
```
If we draw another cookie and it's chocolate, we can do another update:
```
likelihood_ratio = 0.25 / 0.5
post_odds *= likelihood_ratio
post_odds
```
And convert back to probability.
```
post_prob = Probability(post_odds)
post_prob
```
## Oliver's blood
The likelihood ratio is also useful for talking about the strength of evidence without getting bogged down talking about priors.
As an example, we'll solve this problem from MacKay's {\it Information Theory, Inference, and Learning Algorithms}:
> Two people have left traces of their own blood at the scene of a crime. A suspect, Oliver, is tested and found to have type 'O' blood. The blood groups of the two traces are found to be of type 'O' (a common type in the local population, having frequency 60) and of type 'AB' (a rare type, with frequency 1). Do these data [the traces found at the scene] give evidence in favor of the proposition that Oliver was one of the people [who left blood at the scene]?
If Oliver is
one of the people who left blood at the crime scene, then he
accounts for the 'O' sample, so the probability of the data
is just the probability that a random member of the population
has type 'AB' blood, which is 1%.
If Oliver did not leave blood at the scene, then we have two
samples to account for. If we choose two random people from
the population, what is the chance of finding one with type 'O'
and one with type 'AB'? Well, there are two ways it might happen:
the first person we choose might have type 'O' and the second
'AB', or the other way around. So the total probability is
$2 (0.6) (0.01) = 1.2$%.
So the likelihood ratio is:
```
like1 = 0.01
like2 = 2 * 0.6 * 0.01
likelihood_ratio = like1 / like2
likelihood_ratio
```
Since the ratio is less than 1, it is evidence *against* the hypothesis that Oliver left blood at the scence.
But it is weak evidence. For example, if the prior odds were 1 (that is, 50% probability), the posterior odds would be 0.83, which corresponds to a probability of:
```
post_odds = 1 * like1 / like2
Probability(post_odds)
```
So this evidence doesn't "move the needle" very much.
**Exercise:** Suppose other evidence had made you 90% confident of Oliver's guilt. How much would this exculpatory evidence change your beliefs? What if you initially thought there was only a 10% chance of his guilt?
Notice that evidence with the same strength has a different effect on probability, depending on where you started.
```
# Solution goes here
# Solution goes here
```
| github_jupyter |
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in 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.
# Overview
This notebook summarizes the numbers of aptamers that appear to be enriched in positive pools for particular particule display experiments. These values are turned into venn diagrams and pie charts in Figure 2.
The inputs are csvs, where each row is an aptamer and columns indicate the sequencing counts within each particle display subexperiment.
```
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
```
# Parameters used in Manuscript
```
# Required coverage level for analysis. This is in units of number of apatamer
# particles (beads). This is used to minimize potential contamination.
# For example, a tolerated bead fraction of 0.2 means that if, based on read
# depth and number of beads, there are 100 reads expected per bead, then
# sequences with fewer than 20 reads would be excluded from analysis.
TOLERATED_BEAD_FRAC = 0.2
# Ratio cutoff between positive and negative pools to count as being real.
# The ratio is calculated normalized by read depth, so if the ratio is 0.5,
# then positive sequences are expected to have equal read depth (or more) in
# the positive pool as the negative pool. So, as a toy example, if the
# positive pool had 100 reads total and the negative pool had 200 reads total,
# then a sequence with 5 reads in the positive pool and 10 reads in the
# negative pool would have a ratio of 0.5.
POS_NEG_RATIO_CUTOFF = 0.5
# Minimum required reads (when 0 it uses only the above filters)
MIN_READ_THRESH = 0
```
# Load in data
## Load in experimental conditions for Particle Display experiments
The mlpd_params_df contains the experimental information for MLPD.
Parameters are:
* apt_collected: The number of aptamer bead particles collected during the FACs experiment of particle display.
* apt_screened: The number of aptamer bead particles screened in order to get the apt_collected beads.
* seq_input: The estimated number of unique sequences in the input sequence library during bead construction.
```
#@title Original PD Data Parameters
# Since these are small I'm going to embed in the colab.
apt_screened_list = [ 2.4*10**6, 2.4*10**6, 1.24*10**6]
apt_collected_list = [3.5 * 10**4, 8.5 * 10**4, 8 * 10**4]
seq_input = [10**5] * 3
conditions = ['round2_high_no_serum_positive',
'round2_medium_no_serum_positive',
'round2_low_no_serum_positive']
flags = ['round2_high_no_serum_flag', 'round2_medium_no_serum_flag',
'round2_low_no_serum_flag']
stringency = ['High', 'Medium', 'Low']
pd_param_df = pd.DataFrame.from_dict({'apt_screened': apt_screened_list,
'apt_collected': apt_collected_list,
'seq_input': seq_input,
'condition': conditions,
'condition_flag': flags,
'stringency': stringency})
pd_param_df
#@title MLPD Data Parameters
apt_screened_list = [ 3283890.016, 6628573.952, 5801469.696, 3508412.512]
apt_collected_list = [12204, 50353, 153845, 201255]
seq_input = [200000] * 4
conditions = ['round1_very_positive',
'round1_high_positive',
'round1_medium_positive',
'round1_low_positive']
flags = ['round1_very_flag', 'round1_high_flag', 'round1_medium_flag',
'round1_low_flag']
stringency = ['Very High', 'High', 'Medium', 'Low']
mlpd_param_df = pd.DataFrame.from_dict({'apt_screened': apt_screened_list,
'apt_collected': apt_collected_list,
'seq_input': seq_input,
'condition': conditions,
'condition_flag': flags,
'stringency': stringency})
mlpd_param_df
```
## Load CSVs
```
# PD and MLPD sequencing counts across experiments
# Upload pd_clustered_input_data_manuscript.csv and mlpd_input_data_manuscript.csv
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
# Load PD Data
with open('pd_clustered_input_data_manuscript.csv') as f:
pd_input_df = pd.read_csv(f)
# Load MLPD data
with open('mlpd_input_data_manuscript.csv') as f:
mlpd_input_df = pd.read_csv(f)
```
# Helper functions
```
def generate_cutoffs_via_PD_stats(df, col, apt_screened, apt_collected, seq_input,
tolerated_bead_frac, min_read_thresh):
"""Use the experimental parameters to determine sequences passing thresholds.
Args:
df: Pandas dataframe with experiment results. Must have columns named
after the col function parameter, containing the read count, and a
column 'sequence'.
col: The string name of the column in the experiment dataframe with the
read count.
apt_screened: The integer number of aptamers screened, from the experiment
parameters.
apt_collected: The integer number of aptamers collected, from the experiment
parameters.
seq_input: The integer number of unique sequences in the sequence library
used to construct the aptamer particles.
tolerated_bead_frac: The float tolerated bead fraction threshold. In other
words, the sequencing depth required to keep a sequence, in units of
fractions of a bead based on the average expected read depth per bead.
min_read_threshold: The integer minimum number of reads that a sequence
must have in order not to be filtered.
Returns:
Pandas series of the sequences from the dataframe that pass filter.
"""
expected_bead_coverage = apt_screened / seq_input
tolerated_bead_coverage = expected_bead_coverage * tolerated_bead_frac
bead_full_min_sequence_coverage = (1. / apt_collected) * tolerated_bead_coverage
col_sum = df[col].sum()
# Look at sequenced counts calculated observed fraction of pool and raw count.
seqs = df[((df[col]/col_sum) > bead_full_min_sequence_coverage) & # Pool frac.
(df[col] > min_read_thresh) # Raw count
].sequence
return seqs
def generate_pos_neg_normalized_ratio(df, col_prefix):
"""Adds fraction columns to the dataframe with the calculated pos/neg ratio.
Args:
df: Pandas dataframe, expected to have columns [col_prefix]_positive and
[col_prefix]_negative contain read counts for the positive and negative
selection conditions, respectively.
col_prefix: String prefix of the columns to use to calculate the ratio.
For example 'round1_very_positive'.
Returns:
The original dataframe with three new columns:
[col_prefix]_positive_frac contains the fraction of the total positive
pool that is this sequence.
[col_prefix]_negative_frac contains the fraction of the total negative
pool that is this sequence.
[col_prefix]_pos_neg_ratio: The read-depth normalized fraction of the
sequence that ended in the positive pool.
"""
col_pos = col_prefix + '_' + 'positive'
col_neg = col_prefix + '_' + 'negative'
df[col_pos + '_frac'] = df[col_pos] / df[col_pos].sum()
df[col_neg + '_frac'] = df[col_neg] / df[col_neg].sum()
df[col_prefix + '_pos_neg_ratio'] = df[col_pos + '_frac'] / (
df[col_pos + '_frac'] + df[col_neg + '_frac'])
return df
def build_seq_sets_from_df (input_param_df, input_df, tolerated_bead_frac,
pos_neg_ratio, min_read_thresh):
"""Sets flags for sequences based on whether they clear stringencies.
This function adds a column 'seq_set' to the input_param_df (one row per
stringency level of a particle display experiment) containing all the
sequences in the experiment that passed that stringency level in the
experiment.
Args:
input_param_df: Pandas dataframe with experimental parameters. Expected
to have one row per stringency level in the experiment and
columns 'apt_screened', 'apt_collected', 'seq_input', 'condition', and
'condition_flag'.
input_df: Pandas dataframe with the experimental results (counts per
sequence) for the experiment covered in the input_param_df. Expected
to have a [col_prefix]_pos_neg_ratio column for each row of the
input_param_df (i.e. each stringency level).
tolerated_bead_frac: Float representing the minimum sequence depth, in
units of expected beads, for a sequence to be used in analysis.
pos_neg_ratio: The threshold for the pos_neg_ratio column for a sequence
to be used in the analysis.
min_read_thresh: The integer minimum number of reads for a sequence to
be used in the analysis (not normalized, a straight count.)
Returns:
Nothing.
"""
for _, row in input_param_df.iterrows():
# Get parameters to calculate bead fraction.
apt_screened = row['apt_screened']
apt_collected = row['apt_collected']
seq_input = row['seq_input']
condition = row['condition']
flag = row['condition_flag']
# Get sequences above tolerated_bead_frac in positive pool.
tolerated_bead_frac_seqs = generate_cutoffs_via_PD_stats(
input_df, condition, apt_screened, apt_collected, seq_input,
tolerated_bead_frac, min_read_thresh)
# Intersect with seqs > normalized positive sequencing count ratio.
condition_pre = condition.split('_positive')[0]
ratio_col = '%s_pos_neg_ratio' % (condition_pre)
pos_frac_seqs = input_df[input_df[ratio_col] > pos_neg_ratio].sequence
seqs = set(tolerated_bead_frac_seqs) & set(pos_frac_seqs)
input_df[flag] = input_df.sequence.isin(set(seqs))
```
# Data Analysis
```
#@title Add positive_frac / (positive_frac + negative_frac) col to df
for col_prefix in ['round1_very', 'round1_high', 'round1_medium', 'round1_low']:
mlpd_input_df = generate_pos_neg_normalized_ratio(mlpd_input_df, col_prefix)
for col_prefix in ['round2_high_no_serum', 'round2_medium_no_serum', 'round2_low_no_serum']:
pd_input_df = generate_pos_neg_normalized_ratio(pd_input_df, col_prefix)
#@title Measure consistency of particle display data when increasing stringency thresholds within each experimental set (i.e PD and MLPD)
build_seq_sets_from_df(pd_param_df, pd_input_df, TOLERATED_BEAD_FRAC,
POS_NEG_RATIO_CUTOFF, MIN_READ_THRESH)
build_seq_sets_from_df(mlpd_param_df, mlpd_input_df, TOLERATED_BEAD_FRAC,
POS_NEG_RATIO_CUTOFF, MIN_READ_THRESH)
```
# Generate Figure Data
Here, we generate the raw data used to build Venn diagrams. The final figures were render in Figma.
```
#@title Figure 2B Raw Data
pd_input_df.groupby('round2_low_no_serum_flag round2_medium_no_serum_flag round2_high_no_serum_flag'.split()).count()[['sequence']]
#@title Figure 2C Raw Data
# To build venn (green), sum preceding True flags to get consistent sets
# 512 nM = 5426+3 = 5429
# 512 & 128 nM = 2360+15 = 2375
# 512 & 128 & 32nM (including 8 nM) = 276+84 = 360
# To build venn (grey) Inconsistent flags are summed (ignoring 8nM)
# 128 nM only = 185 + 1 = 186
# 128 nM & 32 nM = 12+1 = 13
# 32 nM only = 2
# 32 nM and 512 nM only = 22+1 = 23
#
# To build pie, look at all round1_very_flags = True
# Green = 84
# Grey = 15+1+3+1+1 = 21
mlpd_input_df.groupby('round1_low_flag round1_medium_flag round1_high_flag round1_very_flag'.split()).count()[['sequence']]
```
| github_jupyter |
### This demo shows an example of loading bulk single cell data processing followed by running RVAgene on the same.
```
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from collections import Counter
import scanpy
import anndata
from matplotlib.colors import rgb2hex
import os
from random import randint
import sys
import math
```
#### Load Data and compute pseudotime
```
lines=open("./esc_data/gse/GSM1599494_ES_d0_main.csv","r").readlines()
lines2 = open("./esc_data/gse/GSM1599497_ES_d2_LIFminus.csv","r").readlines()
lines4 = open("./esc_data/gse/GSM1599498_ES_d4_LIFminus.csv","r").readlines()
lines7 = open("./esc_data/gse/GSM1599499_ES_d7_LIFminus.csv","r").readlines()
print(len(lines),len(lines2),len(lines4),len(lines7))
exp = []
gene_names = []
for line in range(len(lines)):
l = lines[line].replace("\n","").split(",")
l2 = lines2[line].replace("\n","").split(",")
l4 = lines4[line].replace("\n","").split(",")
l7 = lines7[line].replace("\n","").split(",")
gene_names.append(l[0])
exp.append(np.array([float(i) for i in l[1:]]+ [float(i) for i in l2[1:]] + [float(i) for i in l4[1:]] + [float(i) for i in l7[1:]]))
exp = np.array(exp)
cols = ['r']*(len(l)-1) + ['g']*(len(l2)-1) + ['b']*(len(l4)-1) + ['c']*(len(l7)-1)
degenes = open("./esc_data/degenes_ES2.txt","r").read().split("\n")[:-1]
degene_indices = [gene_names.index(i) for i in degenes]
exp = exp[degene_indices,:]
mat = exp
print("Ordering the cells...")
argmax = np.argmax(np.sum(exp,axis=1))
argmax=451
print(argmax)
marker= degenes[index]
adata = anndata.AnnData(mat.T)
scanpy.pp.neighbors(adata,use_rep='X')
adata.uns
root_cell_index = 1
adata.uns['iroot'] = root_cell_index
print(adata.uns)
diff_vals = scanpy.tl.diffmap(adata,n_comps=10)
print(adata.obsm)
output = scanpy.tl.dpt(adata)
#order cells by pseudotimeall
pseudotime = adata.obs['dpt_pseudotime']
mat = exp
time_ordered_cells = np.argsort(pseudotime)
pseudotime = np.array([i for i in pseudotime])
time_ordered_cells = np.array([i for i in time_ordered_cells])
time_col = np.array(cols)[time_ordered_cells]
### plot some gene in time order
marker = 'Dppa5a'
index = degenes.index(marker)
geneid = index
plt.scatter(range(0,len(time_ordered_cells)), mat[geneid,:][time_ordered_cells],color=time_col)
#plt.scatter(pseudotime[time_ordered_cells], mat[geneid,:][time_ordered_cells],color=time_color)
plt.ylabel(degenes[geneid],fontsize = 12)
plt.xlabel("time_ordered_cells",fontsize = 12)
plt.savefig("drop_ES_pseudotime_" +marker+ ".png",dpi = 500)
plt.show()
plt.close()
plt.hist(exp[geneid,:],bins=50)
plt.show()
plt.close()
scanpy.pl.diffmap(adata,color=str(index))
```
### Average over windows to reduce noise
```
window_length = 40
smoothed_exp = []
for gene in tqdm(range(exp.shape[0])):
gene_smoothed_exp = []
for n in range(1,exp.shape[1]//window_length+2):
time_ordered_exp = exp[gene][time_ordered_cells]
gene_smoothed_exp.append(np.mean(time_ordered_exp[(n-1)*window_length:n*window_length]))
smoothed_exp.append(gene_smoothed_exp)
smoothed_time_ordered_exp = np.array(smoothed_exp)
print(smoothed_time_ordered_exp.shape)
row_sums = smoothed_time_ordered_exp.sum(axis=1) + 0.000000001
#mat = smoothed_time_ordered_exp/ row_sums[:, np.newaxis] ## normalize, if needed
mat = smoothed_time_ordered_exp
all_corrcoef = []
for gene in tqdm(range(len(degenes))):
all_corrcoef.append(np.corrcoef(range(mat.shape[1]), mat[gene,:])[0, 1])
plt.plot(range(0,mat.shape[1]), mat[geneid,:],linewidth=3)
plt.ylabel(degenes[geneid],fontsize = 12)
plt.xlabel("time ordered cells averaged over 40 length windows",fontsize = 12)
plt.show()
```
### Pearson correlation coefficent calculation
```
plt.bar(range(0,len(all_corrcoef)),all_corrcoef)
plt.xlabel("genes",fontsize=12)
plt.ylabel("correlation among time and expression axis",fontsize=12)
plt.show()
```
### prepare and write data for RVAgene
```
selected_genes = degenes
cols = []
corr_info = []
toplot = []
lines=[]
for gene in range(len(degenes)):
if(all_corrcoef[gene] >= 0):
label = "1," ## used for annotation, not used in training
cols.append("r")
corr_info.append(degenes[gene] + ","+label + str(all_corrcoef[gene]))
toplot.append(all_corrcoef[gene])
elif(all_corrcoef[gene] < 0 ):
label = "2," ## used for annotation, not used in training
cols.append("b")
corr_info.append(degenes[gene] + ","+label + str(all_corrcoef[gene]))
toplot.append(all_corrcoef[gene])
else:
print(all_corrcoef[gene],degenes[gene],gene)
continue
lines.append(label+",".join([str(i) for i in mat[gene,:].tolist()]))
len(lines)
dataset = "ESC"
if(not os.path.exists("./data/"+dataset)):
os.mkdir("./data/"+dataset)
rnn_input = open("./data/" + dataset + "/"+ dataset + "_TRAIN","w")
rnn_input.write("\n".join(lines))
rnn_input.close()
### put some genes in TEST file, not necessarily used
rnn_input = open("./data/"+ dataset + "/"+dataset+"_TEST","w")
rnn_input.write("\n".join(lines[1:5]))
rnn_input.close()
plot_input = open("./"+dataset+"_genes.txt","w")
plot_input.write("\n".join(selected_genes))
plot_input.close()
plot_input = open("./"+dataset+"_corr_info.txt","w")
plot_input.write("\n".join(corr_info))
plot_input.close()
```
### Define and run RVAgene
```
from rvagene.rvagene import RVAgene
from rvagene.utils import open_data
import numpy as np
import torch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from mpl_toolkits.mplot3d import Axes3D
from torch.utils.data import TensorDataset
import sys
### model params ###
hidden_size = 50
hidden_layer_depth = 1
latent_length = 2
batch_size = 12 ## should be a divisor of number of training genes to avoid dropping last batch
learning_rate = 0.003
n_epochs = 200
dropout_rate = 0.2
optimizer = 'Adam' # options: ADAM, SGD
cuda = False # options: True, False
print_every=30
clip = True # options: True, False
max_grad_norm=5
loss = 'SmoothL1Loss' # options: SmoothL1Loss, MSELoss
dataset='ESC'
log_file = 'esc_loss_log.txt' #set None or do not provide to log to stdout
X_train, _, y_train, _ = open_data('data', ratio_train=1, dataset=dataset)
num_classes = len(np.unique(y_train))
base = np.min(y_train) # Check if data is 0-based
if base != 0:
y_train -= base
train_dataset = TensorDataset(torch.from_numpy(X_train))
sequence_length = X_train.shape[1]
number_of_features = X_train.shape[2]
rvagene = RVAgene(sequence_length=sequence_length,
number_of_features = number_of_features,
hidden_size = hidden_size,
hidden_layer_depth = hidden_layer_depth,
latent_length = latent_length,
batch_size = batch_size,
learning_rate = learning_rate,
n_epochs = n_epochs,
dropout_rate = dropout_rate,
optimizer = optimizer,
cuda = cuda,
print_every=print_every,
clip=clip,
max_grad_norm=max_grad_norm,
loss = loss,
log_file = log_file)
rvagene.fit(train_dataset)
rvagene.save("demo_esc_model.pth")
%matplotlib inline
z_run = rvagene.transform(train_dataset)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cols = ['r' if i[0]==0 else 'b' if i[0] == 1 else 'g' for i in y_train[:]]
ax1.scatter(z_run[:,0],z_run[:,1], c=cols[:z_run[:,0].shape[0]])
legend = dict()
legend['upregulated'] = "r"
legend['downregulated'] = "b"
from matplotlib.patches import Patch
legend_elements = [Patch(facecolor=legend[i],
label=str(i)) for i in legend.keys() ]
ax1.legend(handles=legend_elements)
plt.show()
```
| github_jupyter |
```
import pandas as pd
import fasttext
import time
import numpy as np
import multiprocessing as mp
from multiprocessing import Pool
import csv
import fastparquet
import spacy
import glob, os
import re
from os.path import isfile
import seaborn as sns
to_save_path='/data/dharp/compounds/datasets/'
keep_string=r"(.+_(NOUN|ADV|VERB|ADJ|X|PRT|CONJ|PRON|DET|ADP|NUM|\.)|_END_)\s*"
nn='(?!(?:NOUN|PROPN)).*'
comp='(?:ADJ|NOUN|PROPN)\s(?:NOUN|PROPN)'
word='.*'
ner_cats=['CARDINAL', 'DATE', 'EVENT', 'FAC', 'GPE', 'LANGUAGE', 'LAW', 'LOC', 'MONEY', 'NORP', 'ORDINAL', 'ORG', 'PERCENT', 'PERSON', 'PRODUCT', 'QUANTITY', 'TIME', 'WORK_OF_ART']
n1=f'^{comp}\s{nn}\s{comp}$'
n2=f'^{comp}\s{nn}\s{word}\s{word}$'
n3=f'^{nn}\s{comp}\s{nn}\s{word}$'
n4=f'^{word}\s{nn}\s{comp}\s{nn}$'
n5=f'^{word}\s{word}\s{nn}\s{comp}$'
fmodel = fasttext.load_model('/data/dharp/packages/lid.176.bin')
nlp = spacy.load('en_core_web_lg')
def delist_lang(lst):
lang_lst=[]
for i,lang in enumerate(lst):
if not lang:
lang_lst.append(None)
else:
lang_lst.append(lang[0])
return lang_lst
def significance(lst):
significance_list=[]
for l in lst:
if len(l)>1:
significance_list.append(abs(l[0]-l[1])/np.mean(l[0]+l[1])>0.1)
#print(f'{conf[0]} {conf[1]} {abs(conf[0]-conf[1])/np.mean(conf[0]+conf[1])>0.1}')
else:
significance_list.append(True)
return significance_list
def sent_maker(sent_lst):
ret_sents=[]
g_pos=[]
for sent in sent_lst:
cur_words=[]
pos_sent=[]
sent=sent.replace('_END_','@@@_.')
for word_pos in sent.split(' '):
word,pos=word_pos.rsplit('_',1)
cur_words.append(word)
pos_sent.append(pos)
cur_sent=' '.join(cur_words)
cur_pos=' '.join(pos_sent)
ret_sents.append(cur_sent)
g_pos.append(cur_pos)
return ret_sents,g_pos
def ner_lemma_reducer(sent):
ner_sent=[]
lemma=[]
pos=[]
#parse=[]
is_comp=False
ner_token=[]
ner_length=[]
ner=[]
parsed_sent=nlp(sent)
for token in parsed_sent:
#parse.append(token.text)
lemma.append(token.lemma_)
pos.append(token.pos_)
if token.ent_type_=="":
to_add="NONNER"
else:
to_add=token.ent_type_
ner_token.append(to_add)
if token.dep_=="compound":
is_comp=True
#print(parse)
#parse_sent=' '.join(parse)
lemma_sent=' '.join(lemma)
pos_sent=' '.join(pos)
ner_token_sent=' '.join(ner_token)
#dep_sent=' '.join(dep)
ner_length=0
if parsed_sent.ents:
for ent in parsed_sent.ents:
#cur_ner=
#cur_ner='_'.join([str(ent.start_char), str(ent.end_char), ent.label_])
ner_length+=ent.end_char-ent.start_char
#ner.append(cur_ner)
#else:
#ner.append("")
ner_sent=' '.join(ner)
return ner_token_sent,ner_length,lemma_sent,pos_sent,is_comp
def lang_tagger(parsed_sent):
labels,confs=fmodel.predict(parsed_sent,k=-1,threshold=0.1)
lang_list=delist_lang(labels)
significance_list=significance(confs)
assert len(lang_list)==len(significance_list)
return lang_list,significance_list
def index_processor(df):
df.reset_index(inplace=True,drop=True)
ret_lst=sent_maker(df.old_index)
df['sent']=ret_lst[0]
df['g_pos']=ret_lst[1]
results=np.vectorize(ner_lemma_reducer)(df.sent.values)
results_df=pd.DataFrame(results)
results_df=results_df.transpose()
#results_df.columns=ner_token_sent,ner_length,lemma_sent,pos_sent,is_comp
results_df.columns=['ner_token_sent','ner_length','lemma_sent','pos_sent','is_comp']
results_df=results_df.loc[~results_df.ner_token_sent.str.contains("PERSON PERSON")]
index_df=pd.concat([df,results_df],axis=1,ignore_index=False)
lang_list,significance_list=lang_tagger(index_df.sent.values.tolist())
index_df['lang']=lang_list
index_df['lang_conf']=significance_list
index_df.lang=index_df.lang.str.split('_',n=4).str[-1]
index_df=index_df.loc[(index_df.lang=='en') &(index_df.lang_conf==True)]
index_df['nwords']=index_df.pos_sent.str.count(' ').add(1)
index_df=index_df.loc[index_df.nwords==5]
index_df.lemma_sent=index_df.lemma_sent.str.lower()
#index_df.pos_sent=index_df.pos_sent.str.replace('PROPN','NOUN',regex=False)
#index_df.pos_sent=index_df.pos_sent.str.replace('AUX','VERB',regex=False)
#index_df.pos_sent=index_df.pos_sent.str.replace('CCONJ','CONJ',regex=False)
#index_df.g_pos=index_df.g_pos.str.replace('.','PUNCT',regex=False)
#index_df.g_pos=index_df.g_pos.str.replace('PRT','ADP',regex=False)
if index_df.shape[0]==0:
return index_df
index_df['lemma_pos']=str_joiner(index_df)
index_df['nX']=index_df.pos_sent.str.count('X')-index_df.pos_sent.str.count('AUX')
index_df=index_df.loc[~(index_df.nX>1)]
index_df['ner_perc']=index_df.ner_length/index_df.sent.str.len()
index_df['comp_class']=0
index_df.loc[index_df.pos_sent.str.contains(n1),'comp_class']=1
index_df.loc[~(index_df.pos_sent.str.contains(n1))& index_df.pos_sent.str.contains(n2),'comp_class']=2
index_df.loc[index_df.pos_sent.str.contains(n3),'comp_class']=3
index_df.loc[index_df.pos_sent.str.contains(n4),'comp_class']=4
index_df.loc[~(index_df.pos_sent.str.contains(n1))& index_df.pos_sent.str.contains(n5),'comp_class']=5
index_df.drop(['old_index','g_pos','lang','lang_conf','nwords','nX','lemma_sent','ner_length'],axis=1,inplace=True)
index_year_df=year_count_split(index_df)
index_df=index_df.merge(index_year_df, on='lemma_pos',how='right')
index_df=index_df.groupby(['lemma_pos','pos_sent','year','comp_class'])['count'].sum().to_frame().reset_index()
return index_df
def year_count_split(df):
trial_df=pd.concat([df.lemma_pos, df.year_counts.str.split("\t", expand=True)], axis=1)
trial_df=pd.melt(trial_df, id_vars=["lemma_pos"], value_vars=list(range(len(trial_df.columns)-1))).dropna().drop("variable", axis = 1)
trial_df[['year','count']] = trial_df.value.str.split(",", n=3, expand=True)[[0,1]]
return trial_df.drop(['value'],axis=1).reset_index(drop=True)
def str_joiner(df):
#print(df)
new_df=pd.DataFrame()
try:
new_df[['l1','l2','l3','l4','l5']]=df.lemma_sent.str.split(" ",expand=True)
new_df[['p1','p2','p3','p4','p5']]=df.pos_sent.str.split(" ",expand=True)
except:
print(df)
new_df['lemma_pos']=new_df.l1+"_"+new_df.p1+" "+\
new_df.l2+"_"+new_df.p2+" "+\
new_df.l3+"_"+new_df.p3+" "+\
new_df.l4+"_"+new_df.p4+" "+\
new_df.l5+"_"+new_df.p5
return new_df['lemma_pos']
lnk='http://storage.googleapis.com/books/ngrams/books/20200217/eng/5-00835-of-19423.gz'
index_df = pd.read_csv(lnk, compression='gzip', header=None, sep="\n", quoting=csv.QUOTE_NONE)
index_df
index_df.shape[0]
index_df[['old_index','year_counts']]=index_df[0].str.split('\t',n=1,expand=True)
index_df=index_df.loc[index_df.old_index.str.match("^"+keep_string*5+"$",na=False)]
index_df.drop(0,axis=1,inplace=True)
index_df
num_partitions=round(0.95*mp.cpu_count())
cur_time=time.time()
df_split = np.array_split(index_df, num_partitions)
pool = Pool(num_partitions)
print('Started parallelization')
results=pool.map_async(index_processor,df_split)
pool.close()
pool.join()
curr_df_list=results.get()
new_index_df=pd.concat(curr_df_list,ignore_index=True)
print(f'Total time taken {round(time.time()-cur_time)} secs')
index_df.info()
pd.read_pickle('/data/dharp/compounds/datasets/googleV3/69.pkl')
```
| github_jupyter |
# SLU03 - Exercise notebook
## Start by importing these packages
```
# Just for evaluating the results.
import math
import json
import hashlib
#For extra visualization
import matplotlib.pyplot as plt
```
## Exercise 1: Conditionals and boolean algebra
## 1.1) Comparing Strings
In this exercise we have a series of strings that we want to sort from **smaller to larger**.
The answer should be a list where is **each element is a string that has lower value than the next string**:
For example: if we sort the strings "DDD", "XXX" and "AAA" by **ascending order of value** and insert them into a list the solution should be `["AAA", "DDD", "XXX"]`.
### 1.1.1) Sorting bananas
Sort the strings:
- `"banana"`
- `"ana"`
- `"ANA"`
- `"bananas"`
- `"BANANA"`
```
# Create a list with the strings above sorted in ascendant order of value.
# Assign the list to variable banana_list.
#Make sure that you type the strings exactly.
# banana_list = ...
# YOUR CODE HERE
raise NotImplementedError()
banana_hash_0 = '482673bdd029354608338c077b71e987ba5571dfe7cd87329c50df73eae34fac'
banana_hash_1 = '82379da710fc913d545b2d3ea7c6b7a48e5cc9f3c8c7f63a7927be3153325109'
banana_hash_2 = '24d4b96f58da6d4a8512313bbd02a28ebf0ca95dec6e4c86ef78ce7f01e788ac'
banana_hash_3 = 'b493d48364afe44d11c0165cf470a4164d1e2609911ef998be868d46ade3de4e'
banana_hash_4 = 'e4ba5cbd251c98e6cd1c23f126a3b81d8d8328abc95387229850952b3ef9f904'
assert isinstance(banana_list, list), "Review the data type of banana_list."
assert len(banana_list) == 5, "The number of strings is incorrect."
assert banana_hash_0 == hashlib.sha256(bytes(banana_list[0], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert banana_hash_1 == hashlib.sha256(bytes(banana_list[1], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert banana_hash_2 == hashlib.sha256(bytes(banana_list[2], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert banana_hash_3 == hashlib.sha256(bytes(banana_list[3], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert banana_hash_4 == hashlib.sha256(bytes(banana_list[4], encoding='utf8')).hexdigest(), "At least one value is incorrect."
print("Your solution is correct!")
```
---
### 1.1.2) Sorting numbers as string
Sort the strings:
- `"1"`
- `"801"`
- `"02"`
- `"1000"`
```
# Create a list with the strings above sorted in ascendent order of value.
# Assign the list to variable string_number_list.
#Make sure that you type the strings exactly.
# string_number_list = ...
# YOUR CODE HERE
raise NotImplementedError()
number_hash_0 = 'a953f09a1b6b6725b81956e9ad0b1eb49e3ad40004c04307ef8af6246a054116'
number_hash_1 = '6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b'
number_hash_2 = '40510175845988f13f6162ed8526f0b09f73384467fa855e1e79b44a56562a58'
number_hash_3 = '096012b7ebcaf56d1d63b2784d2b2bbdeae080d72ad6bd1b9f7018e62a3c37d0'
assert isinstance(string_number_list, list), "Review the data type of string_number_list."
assert len(string_number_list) == 4, "The number of strings is incorrect."
assert number_hash_0 == hashlib.sha256(bytes(string_number_list[0], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert number_hash_1 == hashlib.sha256(bytes(string_number_list[1], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert number_hash_2 == hashlib.sha256(bytes(string_number_list[2], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert number_hash_3 == hashlib.sha256(bytes(string_number_list[3], encoding='utf8')).hexdigest(), "At least one value is incorrect."
```
---
## 1.2) Order of precedence
In this exercise we have a boolean expression with a series of operators. Use the **table of precedence to identify the order in which the operations are executed**. Each operator is identified with a letter from `A` to `G`.
The solution should be a **list** where the first element is the letter of the first operation to be performed, the second element is the second operation to be performed, and so on until the last operation to be performed.
The result should resemble something like `["A", "B", "D", "G", ...]`
The string is:
```
#You don't need to execute this cell!
variable = 3 != 1+1 and (2**3 > 1 or False)
# A B C D E F G
```
The letters that identify the operations are:
- A: `=`
- B: `!=`
- C: `+`
- D: `and`
- E: `**`
- F: `>`
- G: `or`
```
# Create a list named operators_list that contains the identifiers of the operators sorted by the execution order.
# Make sure that you type the strings exactly.
# operators_list = ...
# YOUR CODE HERE
raise NotImplementedError()
operators_hash_0 = 'a9f51566bd6705f7ea6ad54bb9deb449f795582d6529a0e22207b8981233ec58'
operators_hash_1 = 'f67ab10ad4e4c53121b6a5fe4da9c10ddee905b978d3788d2723d7bfacbe28a9'
operators_hash_2 = '333e0a1e27815d0ceee55c473fe3dc93d56c63e3bee2b3b4aee8eed6d70191a3'
operators_hash_3 = '6b23c0d5f35d1b11f9b683f0b0a617355deb11277d91ae091d399c655b87940d'
operators_hash_4 = 'df7e70e5021544f4834bbee64a9e3789febc4be81470df629cad6ddb03320a5c'
operators_hash_5 = '3f39d5c348e5b79d06e842c114e6cc571583bbf44e4b0ebfda1a01ec05745d43'
operators_hash_6 = '559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd'
assert isinstance(operators_list, list), "Review the data type of operators_list."
assert len(operators_list) == 7, "The number of strings is incorrect."
assert operators_hash_0 == hashlib.sha256(bytes(operators_list[0], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_1 == hashlib.sha256(bytes(operators_list[1], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_2 == hashlib.sha256(bytes(operators_list[2], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_3 == hashlib.sha256(bytes(operators_list[3], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_4 == hashlib.sha256(bytes(operators_list[4], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_5 == hashlib.sha256(bytes(operators_list[5], encoding='utf8')).hexdigest(), "At least one value is incorrect."
assert operators_hash_6 == hashlib.sha256(bytes(operators_list[6], encoding='utf8')).hexdigest(), "At least one value is incorrect."
print("Your solution is correct!")
```
---
## 1.3) `if-elif-else` statements
In this exercise we'll review `if-elif-else` statements. Each code will have inputs and `if-elif-else` statements. The goal is to **follow the flow** of the `if-elif-else` statements and **predict the value of certain variable afect execution**.
**Don't copy and execute the code**. If you can't follow these statements you won't be able to do the next exercises.
### 1.3.1) Reckless driving
Given the code:
```python
traffic_light = "Red"
if traffic_light == "Green":
action = "Stop."
elif traffic_light == "Red":
action = "Go forward."
else:
action = "Turn right."
```
What is the value of `action`?
```
# Assign to variable action the value it would have if the code above was executed.
# action = ...
# YOUR CODE HERE
raise NotImplementedError()
action_hash = 'aa4615f672c620de79597e6715674bdff165ea4764e73e9afa931c5bbb44439d'
assert isinstance(action, str), "Variable action should be a string."
assert action_hash == hashlib.sha256(bytes(action, encoding='utf8')).hexdigest(), "The value of variable action is incorrect."
print("Your solution is correct!")
```
---
### 1.3.2) Cinema tickets
Given the code:
```python
age = 21
is_student = True
day_of_week = "Wednesday"
full_price = 10.00
if is_student and age < 18:
ticket_price = full_price / 2
elif is_student and age >= 18:
ticket_price = full_price * 3 / 4
elif day_of_week == "Monday":
ticket_price = full_price * 2 / 3
else:
ticket_price = full_price
```
What is the value of `ticket_price`?
```
# Assign to variable ticket_price the value it would have if the code above was executed.
# ticket_price = ...
# YOUR CODE HERE
raise NotImplementedError()
assert isinstance(ticket_price, float), "Review the data type of ticket_price."
assert math.isclose(ticket_price, 7.5, abs_tol=0.005), "The value of ticket_price is incorrect."
print("Your solution is correct!")
```
---
### 1.3.3) Shopping for groceries
Given the code:
```python
groceries = {"eggs": 3, "milk": 4, "tomatoes": 4, "soaps": 1, "carrots": 6}
budget = 10
if len(groceries) > 4:
if groceries["eggs"] > 6 and groceries["milk"] > 2:
budget = 12
elif groceries["tomatoes"] <= 2 or groceries["carrots"] < 3:
budget = 32
elif groceries["soaps"] < 4 or groceries["eggs"] > 6:
budget = 40
else:
budget = 18
else:
if groceries["eggs"] < 6 and groceries["milk"] <= 4:
budget = 6
elif groceries["tomatoes"] < 2 or groceries["carrots"] < 3:
budget = 4
else:
budget = 8
```
What is the value of `budget`?
```
# Assign to variable budget the value it would have if the code above was executed.
# budget = ...
# YOUR CODE HERE
raise NotImplementedError()
budget_hash = 'd59eced1ded07f84c145592f65bdf854358e009c5cd705f5215bf18697fed103'
assert isinstance(budget, int), "Review the data type of budget."
assert budget_hash == hashlib.sha256(json.dumps(budget).encode()).hexdigest(), "The value of variable budget is incorrect."
print("Your solution is correct!")
```
---
# Exercise 2: `while` and `for` loops
In this exercise you can use `while` and/or `for` loops to perform the tasks. It's up to decide which loop(s) you need.
A tip: you won't need `if-elif-else` statements here.
## 2.1) Multiplying by 2
Given base 2, what is the **smallest exponent** that gives a **value larger than 13210**?
```
#Assign the exponent value on variable multi_counter.
# multi_counter = ...
# YOUR CODE HERE
raise NotImplementedError()
multi_counter_hash = '8527a891e224136950ff32ca212b45bc93f69fbb801c3b1ebedac52775f99e61'
assert isinstance(multi_counter, int), "Review the data type of multi_counter."
assert multi_counter_hash == hashlib.sha256(json.dumps(multi_counter).encode()).hexdigest(), "The value of variable multi_counter is incorrect."
print("Your solution is correct!")
```
## 2.2) Summing all positive integers until 100
Calculate the sum of all positive integers until 100 (`1 + 2 + 3 +...+ 100`).
```
# Assign the sum of all positive integer until 100 to gauss_sum.
#gauss_sum =
# YOUR CODE HERE
raise NotImplementedError()
gauss_sum_hash = '3f95b1b8a32c2c0251dfdbc3c8a30aab6d6e680cf0ef03e8af84a65dff0c4a85'
assert isinstance(gauss_sum, int), "Review the data type of gauss_sum."
assert gauss_sum_hash == hashlib.sha256(json.dumps(gauss_sum).encode()).hexdigest(), "The value of variable gauss_sum is incorrect."
print("Your solution is correct!")
```
---
## 2.3) Popsicle in the freezer
In this exercise we'll be calculating the temperature of a popsicle in a freezer. Once the popsicle is in the freezer it starts to cooldown until it has the same temperature as the freezer. But this decrease in temperature is not linear over time. It depends on the difference of temperature between the popsicle and the freezer.
The initial temperature of the popsicle is stored in `temp_popsicle[0]`. The **next** temperature of the popsicle is given by
`temp_popsicle[1] = (temp_freezer - temp_popsicle[0]]) * dt + temp_popsicle[0]`
where:
- `temp_popsicle[1]` is the next temperature of the popsicle (after `dt` passed)
- `temp_popsicle[0]` is the current temperature of the popsicle
- `temp_freezer` is the temperature of the freezer. It is always constant.
- `dt` is the time between observations.
Your task is to use the values available and calculate the next temperature and **append it** to `temp_popsicle`. It becomes a list of size 2. The first element is the original temperature and the second element is the new calculated temperature. Then repeat the process by adding 1 on the indices of the equation so that for the second iteration `temp_popsicle[1]` becomes `temp_popsicle[2]` and `temp_popsicle[0]` becomes `temp_popsicle[1]`. Do this until you get a list with **length 80**.
The value of temperature on index `i` of `temp_popsicle` is given by:
`temp_popsicle[i] = (temp_freezer - temp_popsicle[i-1]]) * dt + temp_popsicle[i-1]`
**Important**: everytime you want to execute your solution you need to execute the **next cell before**. If you don't, the `temp_popsicle` list will keep getting larger and larger size and you won't have the right result.
The result should evolve like this:
`temp_popsicle = [20]`
becomes
`temp_popsicle = [20 17.0]`
and the equation becomes `temp_popsicle[2] = (temp_freezer - temp_popsicle[1]]) * dt + temp_popsicle[1]` resulting in:
`temp_popsicle = [20 17.0 14.3]`
Then you update the equation and calculate the next temperature and so on until you have a list of **length 80**.
```
#Parameters of the exercise. Anytime you execute the exercise, execute this first.
temp_popsicle = [20.0]
temp_freezer = -10
dt = 0.1
#Append the new temperature to temp_popsicle. Use the new temperature to calculate the next temperature and so on.
# temp_popsicle= [...]
# YOUR CODE HERE
raise NotImplementedError()
#Everytime you want to execute your code, execute the one above first!!!
popsicle_hash = '48449a14a4ff7d79bb7a1b6f3d488eba397c36ef25634c111b49baf362511afc'
assert isinstance(temp_popsicle, list), "Review the data type of temp_popsicle."
assert popsicle_hash == hashlib.sha256(json.dumps(len(temp_popsicle)).encode()).hexdigest(), "The length of temp_popsicle is incorrect. Make sure to execute the parameter cell first!"
assert math.isclose(temp_popsicle[0], 20.0, abs_tol=0.1), "The first value of temp_popsicle is incorrect."
assert math.isclose(temp_popsicle[1], 17.0, abs_tol=0.1), "The first temperature update is incorrect."
assert math.isclose(temp_popsicle[2], 14.3, abs_tol=0.1), "The second temperature update is incorrect."
assert math.isclose(temp_popsicle[-1], -9.9, abs_tol=0.4), "The final temperature is incorrect."
print("Your solution is correct!")
```
---
### Optional visualization (Not scored)
Below a simple code that creates a plot of the temperature of the popsicle over time. This is only a sneak peak of the visualizations that are possible with matplotlib.
If you are having problems with code below, you can ignored it.
```
# I encourage you to, after completing the exercises, play with this code:
# Change the colors and labels, use others lists as input, break the code.
%matplotlib inline
plt.rcParams["figure.figsize"] = (10,7)
ax=plt.gca()
x = range(len(temp_popsicle))
y = temp_popsicle
plt.plot(x,y, '-', color='tab:blue')
# General settings
plt.xlim(x[0], x[-1])
plt.ylim(-11, 20)
plt.ylabel("Temperature of popsicle (Cº)",fontsize='xx-large')
plt.xlabel('Time (min)',fontsize='xx-large')
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)
# Show graphic
plt.show()
```
---
# 3) Using conditionals and loops together
In this exercise, you'll need to use `if-elif-else` but also loops to solve the tasks.
<img src="./media/fun_begins.gif" />
## 3.1) The Collatz conjecture
From [Wikipedia](https://en.wikipedia.org/wiki/Collatz_conjecture):
> The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
We'll put the conjecture to the test. We'll start the task with an initial value of `n = 134`.
Next we'll apply an operation over `n` depending on its value:
If `n` is **even** the next value of `n` is given by `n / 2`.
If `n` is **odd** the next value of `n` is given by `3*n + 1`.
We'll repeat this process until `n` is equal to 1.
We want to know **how many operations are performed until `n` reaches 1** and assign this value to variable `collatz_operations`.
```
#Assign the number of operations required to reach 1 to variable collatz_operations.
# collatz_operations =
# YOUR CODE HERE
raise NotImplementedError()
collatz_operations_hash = '59e19706d51d39f66711c2653cd7eb1291c94d9b55eb14bda74ce4dc636d015a'
assert isinstance(collatz_operations, int), "The number of operations should be an integer."
assert collatz_operations_hash == hashlib.sha256(json.dumps(collatz_operations).encode()).hexdigest(), "The number of operations is incorrect."
print("Your solution is correct!")
```
---
## 2.2) Football championship points
In a particular football league a certain number of matches were played. A team wins if it has more goals than their opponents and the teams tie if the number of goals are equal. The team that wins the match gets 3 points. The losing team gets 0 points. In case of a tie, both teams get 1 point.
The result of the matches is stored in `matches_outcome`, where each element is the match output in terms of goals.
The goals of each team are placed after the name of the team.
For example, `("Deadly Reptiles",1,"Short Clowns",3)` means that the Deadly Reptiles scored 1 goal and the Short Clowns scored 3 goals.
Update the dictionary `club_points` with the final number of points of each team.
**Important**: everytime you want to execute your solution you need to execute the next cell before. If you don't, teams will keep getting more and more points and you won't have the right result.
```
matches_outcome = (("Deadly Reptiles",1,"Short Clowns",3),
("Breakfast Fallout",1,"Donkey Attackers",1),
("Deadly Reptiles",2,"Breakfast Fallout",0),
("Short Clowns",1,"Donkey Attackers",1),
("Short Clowns",0,"Breakfast Fallout",0),
("Donkey Attackers",4,"Deadly Reptiles",3)
)
club_points = {"Deadly Reptiles":0, "Short Clowns":0, "Breakfast Fallout":0, "Donkey Attackers":0}
#Iterate over every match and attribute the points to the respective teams.
#Everytime you want to execute this code, execute the one above first!!!
# club_points = ...
# YOUR CODE HERE
raise NotImplementedError()
#Everytime you want to execute your code, execute the one above first!!!
reptile_hash = '4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce'
clowns_hash = 'ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d'
fallout_hash = 'd4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35'
attackers_hash = 'ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d'
assert isinstance(club_points, dict), "Variable club_points should be a dictionary."
assert reptile_hash == hashlib.sha256(json.dumps(club_points["Deadly Reptiles"]).encode()).hexdigest(), "The number of points for the Deadly Reptiles is incorrect."
assert clowns_hash == hashlib.sha256(json.dumps(club_points["Short Clowns"]).encode()).hexdigest(), "The number of points for the Deadly Reptiles is incorrect."
assert fallout_hash == hashlib.sha256(json.dumps(club_points["Breakfast Fallout"]).encode()).hexdigest(), "The number of points for the Deadly Reptiles is incorrect."
assert attackers_hash == hashlib.sha256(json.dumps(club_points["Donkey Attackers"]).encode()).hexdigest(), "The number of points for the Deadly Reptiles is incorrect."
print("Your solution is correct!")
```
---
# 3) List comprehension
In this exercise we'll perform some tasks that are simpler to do with list comprehension.
## 3.1) Filter and grow
Given the list `["Lighting", 23, 1.3, "potatoes", [1, 2, 3], 4.5, 7]` we want to create a list with **only the numeric values and each value should be multiplied by 3.**
You should solve this with one line of code.
```
original_list = ["Lighting", 24, 1.21, "potatoes", [1, 2, 3], 4.5, 7]
# Create a list comprehension that iterates over original_list.
# The result should be a list assigned to processed_list.
# Execute the cell above
# processed_list = ...
# YOUR CODE HERE
raise NotImplementedError()
processed_hash = '4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a'
assert isinstance(processed_list, list), "Review the data type of temp_popsicle."
assert processed_hash == hashlib.sha256(json.dumps(len(processed_list)).encode()).hexdigest(), "The length of processed_list is incorrect."
assert math.isclose(processed_list[0], 72, abs_tol=0.1), "The some values of processed_list are incorrect."
assert math.isclose(processed_list[2], 13.5, abs_tol=0.1), "The some values of processed_list are incorrect."
print("Your solution is correct!")
```
---
## 3.2) Symmetric matrix
Create the following list of lists (matrix):
$
\begin{bmatrix}
\begin{bmatrix}0 & 1 & 2 & 3 & 4\end{bmatrix},\\
\begin{bmatrix}1 & 2 & 3 & 4 & 5\end{bmatrix},\\
\begin{bmatrix}2 & 3 & 4 & 5 & 6\end{bmatrix},\\
\begin{bmatrix}3 & 4 & 5 & 6 & 7\end{bmatrix},\\
\begin{bmatrix}4 & 5 & 6 & 7 & 8\end{bmatrix}\space\\
\end{bmatrix}
$
```
# Create the list of lists above using list comprehension.
# The result should be a list assigned to matrix_list.
# matrix_list = ...
# YOUR CODE HERE
raise NotImplementedError()
matrix_hash = 'ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d'
assert isinstance(matrix_list, list), "Review the data type of temp_popsicle."
assert matrix_hash == hashlib.sha256(json.dumps(len(matrix_list)).encode()).hexdigest(), "The length of matrix_list is incorrect."
assert matrix_hash == hashlib.sha256(json.dumps(len(matrix_list[0])).encode()).hexdigest(), "The length of the first element of matrix_list is incorrect."
assert matrix_hash == hashlib.sha256(json.dumps(matrix_list[2][3]).encode()).hexdigest(), "Some values are incorrect."
assert matrix_hash == hashlib.sha256(json.dumps(matrix_list[3][2]).encode()).hexdigest(), "Some values are incorrect."
print("Your solution is correct!")
```
---
### Extra fact:
There is a [story](http://mathandmultimedia.com/2010/09/15/sum-first-n-positive-integers/) about how [Gauss](https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss#Anecdotes) discovered a formula to calculate the sum of the first `n` positive integers. If there is a formula or a simple calculation that you can perform to avoid extensive code, why not using it instead?
| github_jupyter |
# How do I use dsco? (commands)
Here we will do an introduction to dsco commands.
To do this we will be setting up a new project called `foo`.
## Setup
```
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:85% !important; }</style>"))
```
Create a working directory:
```
!mkdir -p /tmp/dsco_overview
cd /tmp/dsco_overview/
```
## --help
We can use `--help` to see a list of the available commands and a
short description of what they do.
```
!dsco --help
```
## --init
```
!dsco init --help
```
The first thing we'll want to do is create our project.
We do this with `--init`
Normally the `--init` command prompts us for input. However this is being
done in a jupyter notebook, which does not allow for interactive
responses. To get around this we will pipe in our responses as follows:
- project_name [MyProject]: foo
- author [Discovery]:
- version [0.1]:
- year [2020]:
- project_port[8001]:
The only default we're changing is the project name. In actual usage
just run `dsco init` and answer the prompts.
```
!echo "foo\n\n\n\n\n" | dsco init
```
### PROJECT DIRECTORY
```
cd foo
!ls
```
One of the nice things about using dsco to create your project is the
consistency in project structure. Let's point out a few of the key
features.
#### README.md
A standard project README file.
#### builder
The builder directory contains everything necessary to build the project
containers including docker files and ansible playbooks.
#### definitions.py
```
cat definitions.py
```
This is a placeholder for defining a few useful project variables.
If you need access to the project root directory you can import
it from definitions.
#### docker-compose.yml
This defines the service definitions: dev, prod, and debug for use
with docker-compose. This is where they are tied to the appropriate
docker file.
#### docs
```
!tree docs
```
The docs directory is important. Dsco distinguishes between two different
types of docs: documentation and reports.
Documentation is project documentation. The how and why of your code.
Reports is meant to be a place to put your exploratory analysis.
Dsco facilitates the production of a static html representation of each of
these types of documentation. Put any .rst or notebook files in the source
directory and generate html with either `dsco documentation -g` or
`dsco reports -g`.
#### flask_config.ini
```
cat flask_config.ini
```
The container is running Flask with uwsgi. This is the configuration file.
Don't mess with it unless you know what you're doing.
#### flask_run.py
```
cat flask_run.py
```
This is the flask entry point. Again, don't mess with it unless you
know what you're doing.
#### project_name (e.g. foo)
```
!tree foo
```
This is your python package directory. It will have whatever name you
provided in the `--init` command for `[project_name]`. This is a standard
setup for creating python packages.
If you're not creating a package, don't worry about it. It's not taking
up a lot of overhead. Just create notebooks in the `docs/reports/source`
directory and leave this alone.
If you are creating a package, there are some nice features in this package
directory you should know about.
> **Opinionated perspective**
>
> In the introduction, we said we take an opinionated perspective on the
> data science development perspective. That started with the first step
> of doing EDA in jupyter notebooks.
>
> After EDA, the next level of maturity is to build some sort of dashboard.
> Dsco sets up the scaffolding for using plotly | Dash in conjunction with
> Flask to build your dashboard.
The flask app is created in `flask_main.py`. Flask routes are
configured in `routes.py`. This is where you can create
rest API routes that would return data.
The dash app is created in `dashapp1/__init__.py`.
`nginx` is configured to handle requests to `/`. Nginx also handles serving
the static content generated in `docs`. This can be found at
`/reports/` and `/documentation/`.
`flask` is configured to handle requests to `/webapp/`.
`dash` is configured to handle requests to `/webapp/dash`.
#### landing_page
The landing_page directory contains the html for the page you see
when you connect to the container at `http://<container>:<port>/`.
#### pyproject.toml, poetry.lock
These files manage our python dependencies. For more information see
http://https://python-poetry.org/.
#### tests
TODO: At the moment this is more of a place holder.
The intention is to build scaffolding around testing and wrap
that in something like `dsco test`.
## --build
Now that we have our project directory, it's time to build our
development image. We do that with `dsco build`.
```
!dsco build --help
# this produces a lot of output from ansible and takes ~8 minutes
!dsco build
```
Generally this build takes about 8 minutes (see execution time at the end).
We can see that it built if we run `dsco ls`. We should see
`foo_dev:latest` listed.
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
## --up
The next step is to create a container from the image. If the image is
already built, this is really fast, if the image has not been built,
this will first build the image, and then create the container, which
will take about 8 minutes.
```
!dsco up
```
We can use `dsco ls` to see if the container is up.
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
We can access the container at the specified link. If the container is not
running you will see this.
```
# we can use docker commands to interact with our containers as well
# this one stops the container without deleting it
!docker stop foo_dev_1
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
# start it again ...
!dsco up
```
## --go
```
!dsco go --help
```
Here we have used `dsco build` and `dsco up` to build and launch our
dev container. We also could have used `dsco go`.
`dsco go` runs `dsco up` and then launches a web browser connected
to the container. If a container is already running, the only
effect will be to open a web browser.
```
!dsco go
```
## --documentation / --reports
If we try to go to access our reports or documentation through the links
on the landing page we will be met with an error 403 message. This is
because we have not built it yet.
```
# build documentation
!dsco documentation --generate
# build reports
!dsco reports --generate
```
Now we should be able to access the starting points of our documentation and reports.
Of course, there's just some basic scaffolding in place. To create the documentation
write some content in reStructuredText files or jupyter notebooks and add these files
to `index.rst` in the `source/` directory.
As a simple example:
```
%%writefile docs/reports/source/example.rst
Example
=======
This is an example .rst file
%%writefile docs/reports/source/index.rst
.. Template documentation master file, created by
sphinx-quickstart
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to foo's documentation!
===============================
.. toctree::
:maxdepth: 2
:caption: Contents:
reports_template
example
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
!dsco reports --generate
```
The rendering isn't perfect here, but you can see a link to `Example`
under the `Welcome to foo's documentation!` section.
```
display(HTML("docs/reports/html/index.html"))
```
And another imperfect rendering of the `Example` page we created.
```
display(HTML("docs/reports/html/example.html"))
```
## --ls
```
!dsco ls --help
```
We've already been using `dsco ls` to see the containers and images that
are present on our local machine.
We can also use `dsco ls -r` to see containers we have running on remote
machines. This leverages docker's ability to run docker commands over
ssh by setting the `DOCKER_HOST` environment variable.
For this to work, you need to have keyless ssh set up to your remote host,
and then create a `$HOME/.dsco/settings.json` file that contains
the following:
```
{
"remote": [
{
"name": "my_name_for_my_machine",
"properties": {
"ip": "fully_qualified_domain_name"
},
"env": {
"DOCKER_HOST": "ssh://user@fqdn"
}
},
{
"name": "my_name_for_my_machine2",
"properties": {
"ip": "fully_qualified_domain_name"
},
"env": {
"DOCKER_HOST": "ssh://user@fqdn"
}
}
]
}
```
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
## --shell
```
!dsco shell --help
```
Use the `dsco shell` command to open a bash shell inside your container.
This is the preferred way to work with your project dependencies.
## --code
```
!dsco code --help
```
Use `dsco code` to launch a session of Microsoft's vscode IDE. After you
install the `Remote Development Extension`, you can use the
`Remote Explorer` to attach to running containers. Open up the `/srv`
directory and enjoy a "local-like" development experience.
Even more amazing is the ability to attach to containers running on
remote machines. If you have remote machines set up as described in the
`--ls` section, you can simple type `dsco code -r my_name_for_my_machine`.
When vscode opens you can use `Remote Explorer` to attach to the listed
containers, but this time you will see the containers running on the
remote machine. Super Cool!!!
You can read more about using vscode with containers
here: https://code.visualstudio.com/docs/remote/containers.
## --restart
```
!dsco restart --help
```
When you're working on creating your Dash dashboard, you will need to
restart flask to see the changes you made. `dsco restart` is an easy
way to do this. Without options it will restart both `nginx` and `flask`.
Use the flags to be more specific.
```
!dsco restart
```
## --update_port
```
!dsco update_port --help
```
When you set up your project, you were prompted for a port number. By
default, this is the port of the `dev` container. The `prod` container
is assigned `port + 1000` and the `debug` container is assigned `port - 500`.
If you're running multiple containers on the same machine, they all need
to be on different ports. To change the port you can use `dsco update_port`
If you enter `dsco update_port 8001`: you will get the default behavior
described above. If you want to override this behavior, simply add the
appropriate flag and specify the desired port.
For example:
```
dsco update_port 8001 --prod 8501
dev = 8001
prod = 8501
debug = 7501
dsco update_port --debug 7600
dev = unchanged
prod = unchanged
debug = 7600
```
Once you've changed the port you will need to run `dsco up` make the
changes take effect.
Note the port is 8001.
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
!dsco update_port 8023
```
Still 8001, we need to restart it.
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
!dsco up
```
Now we see it has updated.
```
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
Put it back.
```
!dsco update_port 8001
!dsco up
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
## --rm
```
!dsco rm --help
```
`dsco rm` will by default remove the `dev` container.
Add the appropriate flag to modify this behavior.
```
!dsco rm
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
## --rmi
```
!dsco rmi --help
```
`dsco rmi` will by default remove the `dev` image.
Add the appropriate flag to modify this behavior.
`dsco rmi` will fail is there is a container running that is based
on the image you are trying to delete.
```
!dsco up
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
!dsco rmi
```
You can force the removal of both with the `--force` flag.
```
!dsco rmi --all --force
# grep is just filtering the content. Generally just use 'dsco ls'
!dsco ls | egrep 'localhost|foo|NAME'
```
Finish by deleting our project directory.
```
cd /tmp
rm -rf /tmp/dsco_overview
ls
```
| github_jupyter |
<h1 id="display">The display package</h1>
<p>
The package `github.com/gopherdata/gophernotes` is automatically imported with the name `display`.
</p><p>
It provides several functions that convert `string`, `[]byte`, `image.Image`, `io.Reader` or `io.WriterTo` containing images, HTML, Markdown, LaTeX etc. to `display.Data`, which is shown graphically if returned at prompt. Example:
<p/>
```
display.HTML(`<h1 style="color:green;">Hello, World</h1>`)
```
<h1>Display function</h1>
<p>
Sometimes, returning `display.Data` at prompt is not handy - for example from deep inside functions or blocks, or because you want to display multiple data at once.
</p><p>
In such cases, you can call the function `Display(display.Data) error` to display the data immediately:
</p>
```
{
Display(display.Markdown("* hello from markdown"))
Display(display.Math(`e^{i\pi}+1=0`))
}
```
<h1 id="images">Images</h1>
<p>
The functions to display JPEG, PNG or SVG images and `image.Image` are:
</p>
```
import "image"
// in package "display"
func JPEG([]byte) error
func PNG([]byte) error
func SVG(string) error
func Image(image.Image) error
// Example: download and display a PNG
import (
"net/http"
"io/ioutil"
)
resp, err := http.Get("https://github.com/gopherdata/gophernotes/raw/master/files/gophernotes-logo.png")
bytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
display.PNG(bytes)
// download and display an SVG
resp, err := http.Get("http://jupyter.org/assets/nav_logo.svg")
bytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
display.SVG(string(bytes))
// download and display a JPEG
resp, err := http.Get("https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Gophercolor.jpg/320px-Gophercolor.jpg")
bytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
display.JPEG(bytes)
```
Or, if you prefer to use `image.Image`:
```
import "image"
resp, err := http.Get("https://github.com/gopherdata/gophernotes/raw/master/files/gophernotes-logo.png")
img, ext, err := image.Decode(resp.Body)
resp.Body.Close()
display.Image(img)
```
<h1 id="reference">Reference</h1>
<p>The list of available constants, types, and functions in package <code>display</code> is:</p>
```
// in package "display"
const (
MIMETypeHTML = "text/html"
MIMETypeJavaScript = "application/javascript"
MIMETypeJPEG = "image/jpeg"
MIMETypeJSON = "application/json"
MIMETypeLatex = "text/latex"
MIMETypeMarkdown = "text/markdown"
MIMETypePNG = "image/png"
MIMETypePDF = "application/pdf"
MIMETypeSVG = "image/svg+xml"
MIMETypeText = "text/plain"
)
// MIMEMap holds data that can be presented in multiple formats. The keys are MIME types
// and the values are the data formatted with respect to its MIME type.
// If a map does not contain a "text/plain" key with a string value,
// it will be set automatically.
type MIMEMap = map[string]interface{}
// Data is the exact structure sent to the front-end (Jupyter...) for displaying.
// It contains all the information needed to graphically show a value.
type Data = struct {
Data MIMEMap
Metadata MIMEMap
Transient MIMEMap
}
// the functions Any() and Auto() accept string, []byte, image.Image, io.Reader, io.WriterTo
func Any(mimeType string, data interface{}) Data // if mimeType is empty, autodetects it
func Auto(data interface{}) Data // autodetects mimeType
func HTML(html string) Data
func JSON(json map[string]interface{}) Data
func JavaScript(javascript string) Data
func JPEG(jpeg []byte) Data
func Image(img image.Image) Data
func Latex(latex string) Data
func Markdown(markdown string) Data
func Math(latex string) Data // LaTeX formula, without starting and ending '$$'
func PDF(pdf []byte) Data
func PNG(png []byte) Data
func SVG(svg string) Data
func MakeData(mimeType string, data interface{}) Data
func MakeData3(mimeType string, plaintext string, data interface{}) Data
func MIME(data, metadata MIMEMap) Data
```
<h1 id="advanced">Advanced usage</h1>
<p>gophernotes also provides the following interfaces, mainly targeted at authors of Go libraries.</p>
<p>If the only non-nil value returned at prompt has type <code>Data</code> or implements one of these interfaces, it will be automatically rendered graphically<p>
```
/**
* general interface, allows libraries to fully specify
* how their data is displayed by Jupyter.
* Supports multiple MIME formats.
*
* Note that Data defined above is an alias:
* libraries can implement Renderer without importing gophernotes
*/
type Renderer = interface {
Render() Data
}
/**
* simplified interface, allows libraries to specify
* how their data is displayed by Jupyter.
* Supports multiple MIME formats.
*
* Note that MIMEMap defined above is an alias:
* libraries can implement SimpleRenderer without importing gophernotes
*/
type SimpleRenderer = interface {
SimpleRender() MIMEMap
}
/**
* specialized interfaces, each is dedicated to a specific MIME type.
*
* They are type aliases to emphasize that method signatures
* are the only important thing, not the interface names.
* Thus libraries can implement them without importing gophernotes
*/
type HTMLer = interface {
HTML() string
}
type JavaScripter = interface {
JavaScript() string
}
type JPEGer = interface {
JPEG() []byte
}
type JSONer = interface {
JSON() map[string]interface{}
}
type Latexer = interface {
Latex() string
}
type Markdowner = interface {
Markdown() string
}
type PNGer = interface {
PNG() []byte
}
type PDFer = interface {
PDF() []byte
}
type SVGer = interface {
SVG() string
}
```
<p>If you want, interpreted code can implement the above interfaces too:<p>
```
// implement HTMLer
type H struct {
}
func (h H) HTML() string {
return `<h2 style="color:blue;">Hello again, world!</h2>`
}
H{}
// implement SimpleRenderer
type S struct {
}
func (s S) SimpleRender() display.MIMEMap {
return display.MIMEMap{
// Maxwell equations, in covariant formulation
display.MIMETypeLatex: `$\partial_\alpha F^{\alpha\beta} = \mu_0 J^\beta$`,
}
}
S{}
```
<p>Or also, if you want to fully control how your data should be rendered:</p>
```
// implement Renderer
type R struct {
}
func (r R) Render() display.Data {
return display.Data{
Data: display.MIMEMap{
// Einstein general relativity equations
display.MIMETypeLatex: `$G_{\mu\nu} = \frac{8 \pi G}{c^4} T_{\mu\nu}$`,
},
}
}
R{}
```
| github_jupyter |
```
!pip install numpy matplotlib pandas
# import module
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
```
# Create vector
A single tutorial from stanford. [CS231n python tutorial](http://cs231n.github.io/python-numpy-tutorial) [Ipython notebook](https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb)
1. [numpy tutoral](https://docs.scipy.org/doc/numpy-1.15.0/user/quickstart.html)
2. [matplotlib tutoral](https://matplotlib.org/users/pyplot_tutorial.html)
```
N, P = 300, 3
x = np.random.randn(N, P) # X from standard normal distribution
beta = np.array([1, 2, 3]) # Create beta
sigma = 1
y = x @ beta + np.random.randn(N) * sigma
y1 = x
y2 = 2 * x + 1
y3 = 3 * x + 2
plt.figure()
plt.plot(x, y1, 'ro')
plt.plot(x, y2, 'bo')
plt.show()
```
# Linear regression
$$y \sim N(X\beta, \sigma^2) $$
$$\hat{\beta} = argmin_{\beta} ||Y - X\beta||^2$$
**Questions**:
1. What are the assumptions for linear regression
2. What is the consistent estimator for $\beta$ and $\sigma^2$
**Practice**:
1. Generate a dataset $X\sim N(0, 1)$, with 300 observations, dimensions is 3.
Use `numpy.random.randn` or call `np.random.randn`. [More distributions](https://docs.scipy.org/doc/numpy-1.15.0/reference/routines.random.html)
2. Set $\beta = (1, 2, 3)$ and set $\sigma^2 = 1$
3. Generate $y \sim N(X\beta, \sigma^2)$
4. Create a function `lm`, and give the estimates $\hat{\beta}_{lm}$, $var(\hat{\beta}_{lm})$ and $\hat{\sigma}$
```
def lm(x, y):
'''
linear regression function used to solve ols
beta = (x'x)^-1 x'y
'''
return beta, sigma
beta_hat, sigma_hat = lm(x, y)
print("Linear regression result.\n\
Beta: {}\n\
Sigma: {}".format(beta_hat, sigma_hat))
```
## [Ridge regression](https://newonlinecourses.science.psu.edu/stat508/lesson/5/5.1)
**Questions**:
1. If you have too many predictors, what are the problems?
2. How do you solve it? List at least 3 methods.
3. What are the properties these methods?
**Programming**:
1. Implement a function ridge, which is used to solve ridge regression problem
$$\hat{\beta}_{ridge} = argmin_{\beta} ||Y - X\beta||^2 + \lambda ||\beta||^2$$
2. Give the estimates of $\hat{\beta}_{ridge}$ and $var(\hat{\beta}_{ridge})$
3. Consider what is the relationship between $\beta_{lm}$ and $\beta_{ridge}$
4. What if $X'X$ is an orthogonal matrix?
5. What is the equivalent Bayesian formulation?
```
def ridge(x, y, tunning):
'''your code here'''
return beta, sigma, beta_se
beta_hat, sigma_hat, beta_se = ridge(x, y, 500)
print("Linear ridge regression result.\n\n\
Beta: {}\n\
Beta SE: {}\n\
Sigma: {}".format(beta_hat, beta_se, sigma_hat))
```
| github_jupyter |
```
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
from sklearn.neighbors import NearestNeighbors
from scipy import ndarray
filename='preprocessed_majority.csv'
datapd_0=pd.read_csv(filename, index_col=0)
filename='preprocessed_minority.csv'
datapd_1=pd.read_csv(filename, index_col=0 )
print('Majority class dataframe shape:', datapd_0.shape)
print('Minority class dataframe shape:', datapd_1.shape)
n_feat=datapd_0.shape[1]
print('Imbalance Ratio:', datapd_0.shape[0]/datapd_1.shape[0])
features_0=np.asarray(datapd_0)
features_1=np.asarray(datapd_1)
s=93
features_1=np.take(features_1,np.random.RandomState(seed=s).permutation(features_1.shape[0]),axis=0,out=features_1)
features_0=np.take(features_0,np.random.RandomState(seed=s).permutation(features_0.shape[0]),axis=0,out=features_0)
a=len(features_1)//3
b=len(features_0)//3
fold_1_min=features_1[0:a]
fold_1_maj=features_0[0:b]
fold_1_tst=np.concatenate((fold_1_min,fold_1_maj))
lab_1_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
fold_2_min=features_1[a:2*a]
fold_2_maj=features_0[b:2*b]
fold_2_tst=np.concatenate((fold_2_min,fold_2_maj))
lab_2_tst=np.concatenate((np.zeros(len(fold_1_min))+1, np.zeros(len(fold_1_maj))))
fold_3_min=features_1[2*a:]
fold_3_maj=features_0[2*b:]
fold_3_tst=np.concatenate((fold_3_min,fold_3_maj))
lab_3_tst=np.concatenate((np.zeros(len(fold_3_min))+1, np.zeros(len(fold_3_maj))))
fold_1_trn=np.concatenate((fold_2_min,fold_3_min,fold_2_maj,fold_3_maj))
lab_1_trn=np.concatenate((np.zeros(a+len(fold_3_min))+1,np.zeros(b+len(fold_3_maj))))
fold_2_trn=np.concatenate((fold_1_min,fold_3_min,fold_1_maj,fold_3_maj))
lab_2_trn=np.concatenate((np.zeros(a+len(fold_3_min))+1,np.zeros(b+len(fold_3_maj))))
fold_3_trn=np.concatenate((fold_2_min,fold_1_min,fold_2_maj,fold_1_maj))
lab_3_trn=np.concatenate((np.zeros(2*a)+1,np.zeros(2*b)))
training_folds_feats=[fold_1_trn,fold_2_trn,fold_3_trn]
testing_folds_feats=[fold_1_tst,fold_2_tst,fold_3_tst]
training_folds_labels=[lab_1_trn,lab_2_trn,lab_3_trn]
testing_folds_labels=[lab_1_tst,lab_2_tst,lab_3_tst]
def lr(X_train,y_train,X_test,y_test):
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import balanced_accuracy_score
logreg = LogisticRegression(C=1e5, solver='lbfgs', multi_class='multinomial', class_weight={0: 1, 1: 1})
logreg.fit(X_train, y_train)
y_pred= logreg.predict(X_test)
con_mat=confusion_matrix(y_test,y_pred)
bal_acc=balanced_accuracy_score(y_test,y_pred)
tn, fp, fn, tp = con_mat.ravel()
print('tn, fp, fn, tp:', tn, fp, fn, tp)
f1 = f1_score(y_test, y_pred)
precision=precision_score(y_test, y_pred)
recall=recall_score(y_test, y_pred)
print('balanced accuracy_LR:', bal_acc)
print('f1 score_LR:', f1)
print('confusion matrix_LR',con_mat)
return(f1, bal_acc, precision, recall, con_mat)
def svm(X_train,y_train,X_test,y_test):
from sklearn import preprocessing
from sklearn import metrics
#from sklearn import svm
from sklearn.svm import LinearSVC
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import balanced_accuracy_score
X_train = preprocessing.scale(X_train)
X_test = preprocessing.scale(X_test)
#svm= svm.SVC(kernel='linear', decision_function_shape='ovo', class_weight={0: 1., 1: 1.},probability=True)
svm= LinearSVC(random_state=0, tol=1e-5)
svm.fit(X_train, y_train)
y_pred= svm.predict(X_test)
con_mat=confusion_matrix(y_test,y_pred)
bal_acc=balanced_accuracy_score(y_test,y_pred)
tn, fp, fn, tp = con_mat.ravel()
print('tn, fp, fn, tp:', tn, fp, fn, tp)
f1 = f1_score(y_test, y_pred)
precision=precision_score(y_test, y_pred)
recall=recall_score(y_test, y_pred)
print('balanced accuracy_SVM:', bal_acc)
print('f1 score_SVM:', f1)
print('confusion matrix_SVM',con_mat)
return( f1, bal_acc, precision, recall, con_mat)
def knn(X_train,y_train,X_test,y_test):
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import balanced_accuracy_score
knn = KNeighborsClassifier(n_neighbors=10)
knn.fit(X_train, y_train)
y_pred= knn.predict(X_test)
con_mat=confusion_matrix(y_test,y_pred)
bal_acc=balanced_accuracy_score(y_test,y_pred)
tn, fp, fn, tp = con_mat.ravel()
print('tn, fp, fn, tp:', tn, fp, fn, tp)
print('balanced accuracy_KNN:', bal_acc)
f1 = f1_score(y_test, y_pred)
precision=precision_score(y_test, y_pred)
recall=recall_score(y_test, y_pred)
print('f1 score_KNN:', f1)
print('confusion matrix_KNN',con_mat)
return(f1, bal_acc, precision, recall, con_mat)
def Neb_grps(data,near_neb):
nbrs = NearestNeighbors(n_neighbors=near_neb, algorithm='ball_tree').fit(data)
distances, indices = nbrs.kneighbors(data)
neb_class=[]
for i in (indices):
neb_class.append(i)
return(np.asarray(neb_class))
def LoRAS(data,num_samples,shadow,sigma,num_RACOS,num_afcomb):
np.random.seed(42)
data_shadow=([])
for i in range (num_samples):
c=0
while c<shadow:
data_shadow.append(data[i]+np.random.normal(0,sigma))
c=c+1
data_shadow==np.asarray(data_shadow)
data_shadow_lc=([])
for i in range(num_RACOS):
idx = np.random.randint(shadow*num_samples, size=num_afcomb)
w=np.random.randint(100, size=len(idx))
aff_w=np.asarray(w/sum(w))
data_tsl=np.array(data_shadow)[idx,:]
data_tsl_=np.dot(aff_w, data_tsl)
data_shadow_lc.append(data_tsl_)
return(np.asarray(data_shadow_lc))
def LoRAS_gen(num_samples,shadow,sigma,num_RACOS,num_afcomb):
RACOS_set=[]
for i in range (len(nb_list)):
RACOS_i= LoRAS(features_1_trn[nb_list[i]],num_samples,shadow,sigma,num_RACOS,num_afcomb)
RACOS_set.append(RACOS_i)
LoRAS_set=np.asarray(RACOS_set)
LoRAS_1=np.reshape(LoRAS_set,(len(features_1_trn)*num_RACOS,n_feat))
return(np.concatenate((LoRAS_1,features_1_trn)))
def OVS(training_data,training_labels,neb):
from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=62, k_neighbors=neb, kind='regular',ratio=1)
SMOTE_feat, SMOTE_labels = sm.fit_resample(training_data,training_labels)
smbl1 = SMOTE(random_state=62, k_neighbors=neb, kind='borderline1',ratio=1)
SMOTE_feat_bl1, SMOTE_labels_bl1 = smbl1.fit_resample(training_data,training_labels)
smbl2 = SMOTE(random_state=62, k_neighbors=neb, kind='borderline2',ratio=1)
SMOTE_feat_bl2, SMOTE_labels_bl2 = smbl2.fit_resample(training_data,training_labels)
smsvm = SMOTE(random_state=62, k_neighbors=neb, kind='svm',ratio=1)
SMOTE_feat_svm, SMOTE_labels_svm = smsvm.fit_resample(training_data,training_labels)
from imblearn.over_sampling import ADASYN
ad = ADASYN(random_state=62,n_neighbors=neb, ratio=1)
ADASYN_feat, ADASYN_labels = ad.fit_resample(training_data,training_labels)
return(SMOTE_feat, SMOTE_labels,SMOTE_feat_bl1, SMOTE_labels_bl1, SMOTE_feat_bl2, SMOTE_labels_bl2,SMOTE_feat_svm, SMOTE_labels_svm,ADASYN_feat, ADASYN_labels)
LR=[]
SVM=[]
KNN=[]
LR_SM=[]
SVM_SM=[]
KNN_SM=[]
LR_SMBL1=[]
SVM_SMBL1=[]
KNN_SMBL1=[]
LR_SMBL2=[]
SVM_SMBL2=[]
KNN_SMBL2=[]
LR_SMSVM=[]
SVM_SMSVM=[]
KNN_SMSVM=[]
LR_ADA=[]
SVM_ADA=[]
KNN_ADA=[]
i=0
while i<3:
SMOTE_feat, SMOTE_labels,SMOTE_feat_bl1, SMOTE_labels_bl1, SMOTE_feat_bl2, SMOTE_labels_bl2,SMOTE_feat_svm, SMOTE_labels_svm,ADASYN_feat, ADASYN_labels=OVS(training_folds_feats[i],training_folds_labels[i],3)
f1_lr, bal_acc_lr, precision_lr, recall_lr, mat_lr=lr(training_folds_feats[i],training_folds_labels[i],testing_folds_feats[i],testing_folds_labels[i])
LR.append([f1_lr, bal_acc_lr, precision_lr, recall_lr])
f1_svm,bal_acc_svm,precision_svm, recall_svm,mat_svm=svm(training_folds_feats[i],training_folds_labels[i],testing_folds_feats[i],testing_folds_labels[i])
SVM.append([f1_svm,bal_acc_svm,precision_svm, recall_svm])
f1_knn,bal_acc_knn,precision_knn, recall_knn,mat_knn=knn(training_folds_feats[i],training_folds_labels[i],testing_folds_feats[i],testing_folds_labels[i])
KNN.append([f1_knn,bal_acc_knn,precision_knn, recall_knn])
f1_lr_SMOTE,bal_acc_lr_SMOTE,precision_lr_SMOTE, recall_lr_SMOTE,mat_lr_SMOTE=lr(SMOTE_feat,SMOTE_labels,testing_folds_feats[i],testing_folds_labels[i])
LR_SM.append([f1_lr_SMOTE,bal_acc_lr_SMOTE,precision_lr_SMOTE, recall_lr_SMOTE])
f1_svm_SMOTE,bal_acc_svm_SMOTE,precision_svm_SMOTE, recall_svm_SMOTE,mat_svm_SMOTE=svm(SMOTE_feat,SMOTE_labels,testing_folds_feats[i],testing_folds_labels[i])
SVM_SM.append([f1_svm_SMOTE,bal_acc_svm_SMOTE,precision_svm_SMOTE, recall_svm_SMOTE])
f1_knn_SMOTE,bal_acc_knn_SMOTE,precision_knn_SMOTE, recall_knn_SMOTE,mat_knn_SMOTE=knn(SMOTE_feat,SMOTE_labels,testing_folds_feats[i],testing_folds_labels[i])
KNN_SM.append([f1_knn_SMOTE,bal_acc_knn_SMOTE,precision_knn_SMOTE, recall_knn_SMOTE])
f1_lr_SMOTE_bl1,bal_acc_lr_SMOTE_bl1,precision_lr_SMOTE_bl1, recall_lr_SMOTE_bl1,mat_lr_SMOTE_bl1=lr(SMOTE_feat_bl1,SMOTE_labels_bl1,testing_folds_feats[i],testing_folds_labels[i])
LR_SMBL1.append([f1_lr_SMOTE_bl1,bal_acc_lr_SMOTE_bl1,precision_lr_SMOTE_bl1, recall_lr_SMOTE_bl1])
f1_svm_SMOTE_bl1,bal_acc_svm_SMOTE_bl1,precision_svm_SMOTE_bl1, recall_svm_SMOTE_bl1,mat_svm_SMOTE_bl1=svm(SMOTE_feat_bl1,SMOTE_labels_bl1,testing_folds_feats[i],testing_folds_labels[i])
SVM_SMBL1.append([f1_svm_SMOTE_bl1,bal_acc_svm_SMOTE_bl1,precision_svm_SMOTE_bl1, recall_svm_SMOTE_bl1])
f1_knn_SMOTE_bl1,bal_acc_knn_SMOTE_bl1,precision_knn_SMOTE_bl1, recall_knn_SMOTE_bl1,mat_knn_SMOTE_bl1=knn(SMOTE_feat_bl1,SMOTE_labels_bl1,testing_folds_feats[i],testing_folds_labels[i])
KNN_SMBL1.append([f1_knn_SMOTE_bl1,bal_acc_knn_SMOTE_bl1,precision_knn_SMOTE_bl1, recall_knn_SMOTE_bl1])
f1_lr_SMOTE_bl2,bal_acc_lr_SMOTE_bl2,precision_lr_SMOTE_bl2, recall_lr_SMOTE_bl2,mat_lr_SMOTE_bl2=lr(SMOTE_feat_bl2,SMOTE_labels_bl2,testing_folds_feats[i],testing_folds_labels[i])
LR_SMBL2.append([f1_lr_SMOTE_bl2,bal_acc_lr_SMOTE_bl2,precision_lr_SMOTE_bl2, recall_lr_SMOTE_bl2])
f1_svm_SMOTE_bl2,bal_acc_svm_SMOTE_bl2,precision_svm_SMOTE_bl2, recall_svm_SMOTE_bl2,mat_svm_SMOTE_bl2=svm(SMOTE_feat_bl1,SMOTE_labels_bl1,testing_folds_feats[i],testing_folds_labels[i])
SVM_SMBL2.append([f1_svm_SMOTE_bl2,bal_acc_svm_SMOTE_bl2,precision_svm_SMOTE_bl2, recall_svm_SMOTE_bl2])
f1_knn_SMOTE_bl2,bal_acc_knn_SMOTE_bl2,precision_knn_SMOTE_bl2, recall_knn_SMOTE_bl2,mat_knn_SMOTE_bl2=knn(SMOTE_feat_bl2,SMOTE_labels_bl2,testing_folds_feats[i],testing_folds_labels[i])
KNN_SMBL2.append([f1_knn_SMOTE_bl2,bal_acc_knn_SMOTE_bl2,precision_knn_SMOTE_bl2, recall_knn_SMOTE_bl2])
f1_lr_SMOTE_svm,bal_acc_lr_SMOTE_svm,precision_lr_SMOTE_svm, recall_lr_SMOTE_svm,mat_lr_SMOTE_svm=lr(SMOTE_feat_svm,SMOTE_labels_svm,testing_folds_feats[i],testing_folds_labels[i])
LR_SMSVM.append([f1_lr_SMOTE_svm,bal_acc_lr_SMOTE_svm,precision_lr_SMOTE_svm, recall_lr_SMOTE_svm])
f1_svm_SMOTE_svm,bal_acc_svm_SMOTE_svm,precision_svm_SMOTE_svm, recall_svm_SMOTE_svm,mat_svm_SMOTE_svm=svm(SMOTE_feat_svm,SMOTE_labels_svm,testing_folds_feats[i],testing_folds_labels[i])
SVM_SMSVM.append([f1_svm_SMOTE_svm,bal_acc_svm_SMOTE_svm,precision_svm_SMOTE_svm, recall_svm_SMOTE_svm])
f1_knn_SMOTE_svm,bal_acc_knn_SMOTE_svm,precision_knn_SMOTE_svm, recall_knn_SMOTE_svm,mat_knn_SMOTE_svm=knn(SMOTE_feat_svm,SMOTE_labels_svm,testing_folds_feats[i],testing_folds_labels[i])
KNN_SMSVM.append([f1_knn_SMOTE_svm,bal_acc_knn_SMOTE_svm,precision_knn_SMOTE_svm, recall_knn_SMOTE_svm])
f1_lr_ADASYN,bal_acc_lr_ADASYN,precision_lr_ADASYN, recall_lr_ADASYN,mat_lr_ADASYN=lr(ADASYN_feat,ADASYN_labels,testing_folds_feats[i],testing_folds_labels[i])
LR_ADA.append([f1_lr_ADASYN,bal_acc_lr_ADASYN,precision_lr_ADASYN, recall_lr_ADASYN])
f1_svm_ADASYN,bal_acc_svm_ADASYN,precision_svm_ADASYN, recall_svm_ADASYN,mat_svm_ADASYN=svm(ADASYN_feat,ADASYN_labels,testing_folds_feats[i],testing_folds_labels[i])
SVM_ADA.append([f1_svm_ADASYN,bal_acc_svm_ADASYN,precision_svm_ADASYN, recall_svm_ADASYN])
f1_knn_ADASYN,bal_acc_knn_ADASYN,precision_knn_ADASYN, recall_knn_ADASYN,mat_knn_ADASYN=knn(ADASYN_feat,ADASYN_labels,testing_folds_feats[i],testing_folds_labels[i])
KNN_ADA.append([f1_knn_ADASYN,bal_acc_knn_ADASYN,precision_knn_ADASYN, recall_knn_ADASYN])
i=i+1
LR_LoRAS=[]
SVM_LoRAS=[]
KNN_LoRAS=[]
for i in range(3):
features = training_folds_feats[i]
labels= training_folds_labels[i]
label_1=np.where(labels == 1)[0]
label_1=list(label_1)
features_1_trn=features[label_1]
label_0=np.where(labels == 0)[0]
label_0=list(label_0)
features_0_trn=features[label_0]
num_samples=3
shadow=100
sigma=.005
num_RACOS=(len(features_0_trn)-len(features_1_trn))//len(features_1_trn)
num_afcomb=50
nb_list=Neb_grps(features_1_trn, num_samples)
LoRAS_1=LoRAS_gen(num_samples,shadow,sigma,num_RACOS,num_afcomb)
LoRAS_train=np.concatenate((LoRAS_1,features_0_trn))
LoRAS_labels=np.concatenate((np.zeros(len(LoRAS_1))+1, np.zeros(len(features_0_trn))))
f1_lr_LoRAS,bal_acc_lr_LoRAS,precision_lr_LoRAS, recall_lr_LoRAS,mat_lr_LoRAS=lr(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
LR_LoRAS.append([f1_lr_LoRAS,bal_acc_lr_LoRAS,precision_lr_LoRAS, recall_lr_LoRAS])
f1_svm_LoRAS,bal_acc_svm_LoRAS,precision_svm_LoRAS, recall_svm_LoRAS,mat_svm_LoRAS=svm(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
SVM_LoRAS.append([f1_svm_LoRAS,bal_acc_svm_LoRAS,precision_svm_LoRAS, recall_svm_LoRAS])
f1_knn_LoRAS,bal_acc_knn_LoRAS,precision_knn_LoRAS, recall_knn_LoRAS,mat_knn_LoRAS=knn(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
KNN_LoRAS.append([f1_knn_LoRAS,bal_acc_knn_LoRAS,precision_knn_LoRAS, recall_knn_LoRAS])
LR_tLoRAS=[]
SVM_tLoRAS=[]
KNN_tLoRAS=[]
from sklearn.manifold import TSNE
for i in range(3):
features = training_folds_feats[i]
labels= training_folds_labels[i]
label_1=np.where(labels == 1)[0]
label_1=list(label_1)
features_1_trn=features[label_1]
label_0=np.where(labels == 0)[0]
label_0=list(label_0)
features_0_trn=features[label_0]
data_embedded_min = TSNE().fit_transform(features_1_trn)
result_min= pd.DataFrame(data = data_embedded_min, columns = ['t-SNE0', 't-SNE1'])
min_t=np.asmatrix(result_min)
min_t=min_t[0:len(features_1_trn)]
min_t=min_t[:, [0,1]]
num_samples=3
shadow=100
sigma=.005
num_RACOS=(len(features_0_trn)-len(features_1_trn))//len(features_1_trn)
num_afcomb=50
nb_list=Neb_grps(min_t, num_samples)
LoRAS_1=LoRAS_gen(num_samples,shadow,sigma,num_RACOS,num_afcomb)
LoRAS_train=np.concatenate((LoRAS_1,features_0_trn))
LoRAS_labels=np.concatenate((np.zeros(len(LoRAS_1))+1, np.zeros(len(features_0_trn))))
f1_lr_LoRAS,bal_acc_lr_LoRAS,precision_lr_LoRAS, recall_lr_LoRAS,mat_lr_LoRAS=lr(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
LR_tLoRAS.append([f1_lr_LoRAS,bal_acc_lr_LoRAS,precision_lr_LoRAS, recall_lr_LoRAS])
f1_svm_LoRAS,bal_acc_svm_LoRAS,precision_svm_LoRAS, recall_svm_LoRAS,mat_svm_LoRAS=svm(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
SVM_tLoRAS.append([f1_svm_LoRAS,bal_acc_svm_LoRAS,precision_svm_LoRAS, recall_svm_LoRAS])
f1_knn_LoRAS,bal_acc_knn_LoRAS,precision_knn_LoRAS, recall_knn_LoRAS,mat_knn_LoRAS=knn(LoRAS_train,LoRAS_labels,testing_folds_feats[i],testing_folds_labels[i])
KNN_tLoRAS.append([f1_knn_LoRAS,bal_acc_knn_LoRAS,precision_knn_LoRAS, recall_knn_LoRAS])
def stats(arr):
x=np.mean(np.asarray(arr), axis = 0)
y=np.std(np.asarray(arr), axis = 0)
return(x,y)
print('F1|Balanced Accuracy|precision|recall :: mean|sd')
print('Without Oversampling')
LR_m, LR_sd=stats(LR)
print('lr:',LR_m, LR_sd)
SVM_m, SVM_sd=stats(SVM)
print('svm:',SVM_m, SVM_sd)
KNN_m, KNN_sd= stats(KNN)
print('knn:',KNN_m, KNN_sd)
print('SMOTE Oversampling')
LR_SM_m, LR_SM_sd=stats(LR_SM)
print('lr:',LR_SM_m, LR_SM_sd)
SVM_SM_m, SVM_SM_sd=stats(SVM_SM)
print('svm:',SVM_SM_m, SVM_SM_sd)
KNN_SM_m, KNN_SM_sd=stats(KNN_SM)
print('knn:',KNN_SM_m, KNN_SM_sd)
print('SMOTE-Bl1 Oversampling')
LR_SMBL1_m, LR_SMBL1_sd=stats(LR_SMBL1)
print('lr:',LR_SMBL1_m, LR_SMBL1_sd)
SVM_SMBL1_m,SVM_SMBL1_sd=stats(SVM_SMBL1)
print('svm:',SVM_SMBL1_m,SVM_SMBL1_sd)
KNN_SMBL1_m, KNN_SMBL1_sd= stats(KNN_SMBL1)
print('knn:',KNN_SMBL1_m, KNN_SMBL1_sd)
print('SMOTE-Bl2 Oversampling')
LR_SMBL2_m, LR_SMBL2_sd=stats(LR_SMBL2)
print('lr:',LR_SMBL2_m, LR_SMBL2_sd)
SVM_SMBL2_m, SVM_SMBL2_sd=stats(SVM_SMBL2)
print('svm:',SVM_SMBL2_m, SVM_SMBL2_sd)
KNN_SMBL2_m, KNN_SMBL2_sd= stats(KNN_SMBL2)
print('knn:',KNN_SMBL2_m, KNN_SMBL2_sd)
print('SMOTE-SVM Oversampling')
LR_SMSVM_m, LR_SMSVM_sd=stats(LR_SMSVM)
print('lr:',LR_SMSVM_m, LR_SMSVM_sd)
SVM_SMSVM_m, SVM_SMSVM_sd=stats(SVM_SMSVM)
print('svm:',SVM_SMSVM_m, SVM_SMSVM_sd)
KNN_SMSVM_m, KNN_SMSVM_sd= stats(KNN_SMSVM)
print('knn:',KNN_SMSVM_m, KNN_SMSVM_sd)
print('ADASYN Oversampling')
LR_ADA_m, LR_ADA_sd=stats(LR_ADA)
print('lr:',LR_ADA_m, LR_ADA_sd)
SVM_ADA_m, SVM_ADA_sd=stats(SVM_ADA)
print('svm:',SVM_ADA_m, SVM_ADA_sd)
KNN_ADA_m, KNN_ADA_sd=stats(KNN_ADA)
print('knn:',KNN_ADA_m, KNN_ADA_sd)
print('LoRAS Oversampling')
LR_LoRAS_m, LR_LoRAS_sd=stats(LR_LoRAS)
print('lr:',LR_LoRAS_m, LR_LoRAS_sd)
SVM_LoRAS_m, SVM_LoRAS_sd=stats(SVM_LoRAS)
print('svm:',SVM_LoRAS_m, SVM_LoRAS_sd)
KNN_LoRAS_m, KNN_LoRAS_sd=stats(KNN_LoRAS)
print('knn:',KNN_LoRAS_m, KNN_LoRAS_sd)
print('tLoRAS Oversampling')
LR_tLoRAS_m, LR_tLoRAS_sd=stats(LR_tLoRAS)
print('lr:',LR_tLoRAS_m, LR_tLoRAS_sd)
SVM_tLoRAS_m, SVM_tLoRAS_sd=stats(SVM_tLoRAS)
print('svm:',SVM_tLoRAS_m, SVM_tLoRAS_sd)
KNN_tLoRAS_m, KNN_tLoRAS_sd=stats(KNN_tLoRAS)
print('knn:',KNN_tLoRAS_m, KNN_tLoRAS_sd)
!jupyter nbconvert --to html CV.ipynb
```
| github_jupyter |
# Using `photoeccentric` on a Real Kepler Light Curve
I'm fairly sure this code works (i.e. accurately recovers (e, w) for most light curves. A little spotty for w = 0 and e != 0, but I think this is to be expected.) Now I want to see if this works for a real Kepler light curve instead of noiseless transit models.
Notes:
1. There's no way to actually know if this works if I don't know the planet's true eccentricity (and I probably won't). I am just checking for obvious problems here, but I won't be able to see if (e, w) is actually correct
2. I am going to test `photoeccentric` more thoroughly on different transit models, thinking about the best way to do that
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
from astropy.table import Table
import astropy.units as u
from astropy.io import fits
import astropy.stats as stats
# Using `batman` to create & fit fake transit
import batman
# Using astropy BLS and scipy curve_fit to fit transit
from astropy.timeseries import BoxLeastSquares
from scipy.optimize import curve_fit
# Using emcee & corner to find and plot (e, w) distribution
import emcee
import corner
# And importing `photoeccentric`
import photoeccentric as ph
import everest
%load_ext autoreload
%autoreload 2
```
I'll define the conversions between solar mass -> kg and solar radius -> meters for convenience.
```
smass_kg = 1.9885e30 # Solar mass (kg)
srad_m = 696.34e6 # Solar radius (m)
lc_path = '/Users/sheilasagear/Dropbox (UFL)/Research/MetallicityProject/photoeccentric/notebooks/MAST_2021-02-10T1313/Kepler/kplr005868793_lc_Q000000111100000000/kplr005868793-2011177032512_llc.fits'
hdul = fits.open(lc_path)
data = hdul[1].data
time = data['TIME']
flux = data['SAP_FLUX']
plt.scatter(time, flux, s=2)
```
A different planet
```
star = everest.Everest(201912552)
star.plot();
time = star.time
flux = star.flux
plt.plot(star.time, star.flux)
flux_sclip = stats.sigma_clip(flux, 2)
plt.plot(time, flux_sclip)
import scipy.signal as sig
median = sig.medfilt(flux_sclip, 151)
len(flux_sclip)
len(time)
plt.plot(time, median)
nflux = flux_sclip-median
len(time)
len(nflux)
plt.plot(time, nflux)
```
## Fitting the transit
```
nflux = np.asarray(nflux)
time = np.asarray(time)
nanind = np.argwhere(np.isnan(nflux))
nflux = np.delete(nflux, nanind)
time = np.delete(time, nanind)
mod = BoxLeastSquares(time*u.day, nflux, dy=0.01)
periodogram = mod.autopower(0.2, objective="snr")
per_guess = np.asarray(periodogram.period)[int(np.median(np.argmax(periodogram.power)))]
# Inital guess: period, rprs, a/Rs, i, w
p0 = [32.939623, 0.05295, 83.83, 89.5785, -5.7]
# Priors (bounds) on some parameters; not using this right now
priors = ((-np.inf, -np.inf, 0.0, 0.0, -90.0), (np.inf, np.inf, 150.0, 90.0, 300.0))
popt, pcov = curve_fit(ph.planetlc_fitter, xdata=time, ydata=nflux, p0=p0, bounds=priors)
# Create a light curve with the fit parameters
fit = ph.planetlc_fitter(time, popt[0], popt[1], popt[2], popt[3], popt[4])
# Defining variables based on the fit parameters
p_f = popt[0]*86400 #days to seconds
perr_f = 0.001*86400 #days to seconds
rprs_f = popt[1]
rprserr_f = 0.001
a_f = popt[2]
i_f = popt[3]
w_f = popt[4]
plt.plot(time, nflux, c='blue', alpha=0.5, label='Original LC')
plt.plot(time, fit, c='red', alpha=1.0, label='Fit LC')
#plt.xlim(1990, 1992)
plt.legend()
print('Fit params:')
print('Period (days): ', p_f/86400., 'Rp/Rs: ', rprs_f)
print('a/Rs: ', a_f)
print('i (deg): ', i_f)
print('w (deg): ', w_f)
```
### Determining T14 and T23
A crucial step to determining the $(e, w)$ distribution from the transit is calculating the total and full transit durations. T14 is the total transit duration (the time between first and fourth contact). T23 is the full transit duration (i.e. the time during which the entire planet disk is in front of the star, the time between second and third contact.)
Here, I'm using equations 14 and 15 from [this textbook](https://sites.astro.caltech.edu/~lah/review/transits_occultations.winn.pdf). We calculate T14 and T23 assuming the orbit must be circular, and using the fit parameters assuming the orbit is circular. (If the orbit is not circular, T14 and T23 will not be correct -- but this is what we want, because they will differ from the true T14 and T23 in a way that reveals the eccentricity of the orbit.)
```
T14 = ph.get_T14(p_f, rprs_f, a_f, i_f)
T14err = 0.0001*86400 #I'm assuming a T14 error here
T23 = ph.get_T23(p_f, rprs_f, a_f, i_f)
T23err = 0.0001*86400 #I'm assuming a T23 error here
```
# Get $g$
```
gs, rho_c, rho_s_spec, T14s, T23s = ph.get_g_distribution(rho_star, p_f, perr_f, rprs_f, rprserr_f, T14, T14err, T23, T23err)
g_mean = np.mean(gs)
g_sigma = np.mean(np.abs(ph.get_sigmas(gs)))
```
Print $g$ and $\sigma_{g}$:
```
g_mean
g_sigma
```
The mean of $g$ is about 1.0, which means that $\rho_{circ}$ agrees with $\rho_{star}$ and the eccentricity of this transit must be zero, which is exactly what we input! We can take $g$ and $\sigma_{g}$ and use MCMC (`emcee`) to determine the surface of most likely $(e,w)$.
`photoeccentric` has the probability function for $(e,w)$ from $g$ built in to `ph.log_probability()`.
```
#Guesses
w_guess = 0.0
e_guess = 0.0
solnx = (w_guess, e_guess)
pos = solnx + 1e-4 * np.random.randn(32, 2)
nwalkers, ndim = pos.shape
sampler = emcee.EnsembleSampler(nwalkers, ndim, ph.log_probability, args=(g_mean, g_sigma), threads=4)
sampler.run_mcmc(pos, 5000, progress=True);
flat_samples = sampler.get_chain(discard=100, thin=15, flat=True)
fig = corner.corner(flat_samples, labels=labels)
```
And here is the corner plot for the most likely values of $(e, w)$ that correspond to $g = 1$. The $e$ distribution peaks at 0!
| github_jupyter |
```
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
import random
import warnings
import requests
from io import BytesIO
from zipfile import ZipFile
warnings.filterwarnings("ignore")
data_url = 'http://files.grouplens.org/datasets/movielens/ml-latest.zip'
res = requests.get(data_url)
file = ZipFile(BytesIO(res.content)).open('ml-latest/ratings.csv')
ratings = pd.read_csv(file)
```
## Exploratory Data Analysis
```
ratings.head()
# Number of Movies
ratingsGroupedByMovie = ratings.groupby(by=["movieId"]).count().reset_index()
#Number of Users
ratingsGroupedByusers = ratings.groupby(by=["userId"]).count().reset_index()
TotalMovies = ratingsGroupedByMovie.shape[0]
TotalUsers = ratingsGroupedByusers.shape[0]
print("The total number of users are",TotalUsers,"and the total number of movies are",TotalMovies)
user_freq=ratings.groupby('userId', as_index=False).agg(num_movies=('movieId','count'))
movie_freq=ratings.groupby('movieId', as_index=False).agg(num_users=('userId','count'))
user_freq['num_movies'].to_frame().describe()
```
The average number of movies rated per user is 98 and 50% of the users rated less then or equal to 30 movies while 75% of them have rated less than or equal to 95 movies.
```
movie_freq['num_users'].to_frame().describe()
```
Total movies = ~54k. On an average a movie has been rated by 515 users, 50% of the movies have been rated by less than or equal to 7 users while 75% of the movies have been rated by less than or equal to 48 users
```
plt.figure(figsize=(15,5))
plt.hist(user_freq['num_movies'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,25000,2000))
plt.xlabel('Number of ratings')
plt.ylabel('Number of users')
plt.show()
plt.figure(figsize=(15,5))
plt.hist(movie_freq['num_users'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,110000,10000))
plt.xlabel('Number of ratings')
plt.ylabel('Number of movies')
plt.show()
df_mv_gp = ratings[['movieId','rating']].groupby('movieId').agg(mean_rating=('rating','mean'))
df_mv_gp.hist(bins=30, grid=False, edgecolor='b', density=True, figsize=(10,5))
df_mv_gp['mean_rating'].plot(grid=False, alpha=10, kind='kde')
plt.title('Average rating per movie')
plt.show()
```
Density plot of mean rating of movies indicate a multimodal distribution achieving its bimodal peaks around the centre of rating scale
```
df_ur_gp = ratings[['userId','rating']].groupby('userId').agg(mean_rating=('rating','mean'))
df_ur_gp.hist(bins=30, grid=False, edgecolor='b', density=True, figsize=(10,5))
df_ur_gp['mean_rating'].plot(grid=False, alpha=10, kind='kde')
plt.title('Average rating per user')
plt.show()
```
Density plot of mean rating per user indicates a left skewed distribution with mean approximately 3.6
### Filtering users who have rated more than 10 movies and movies that have more than 1000 ratings
```
# Only keeping Users who have rated more than 10 movies
ratings1 = ratings[ratings.groupby("userId")['userId'].transform('size')>10]
# Only keeping Movies which have been rated more than 1000 times
ratings1 = ratings1[ratings1.groupby("movieId")['movieId'].transform('size')>1000]
# Number of Movies after filtering
ratingsGroupedByMovie_filtered = ratings1.groupby(by=["movieId"]).count().reset_index()
#Number of Users after filtering
ratingsGroupedByusers_filtered = ratings1.groupby(by=["userId"]).count().reset_index()
TotalMovies_filtered = ratingsGroupedByMovie_filtered.shape[0]
TotalUsers_filtered = ratingsGroupedByusers_filtered.shape[0]
print("The total number of users after filtering are",TotalUsers_filtered,"and the total number of movies after filtering are",TotalMovies_filtered)
```
# Data Sampling
## Method 1 : Stratified Sampling : Preserving the total number of movies depending upon the number of times they have been rated (Preserving the proportion/distribution of our original dataset)
```
def create_stratified_sample(n=100):
np.random.seed(10)
# N --> Total Sample size desired
N = 1000000
final_ratings = ratings1.groupby('movieId', group_keys=False).apply(lambda x: x.sample(int(np.rint(N*len(x)/len(ratings1))))).sample(frac=1).reset_index(drop=True)
return final_ratings
final_ratings1 = create_stratified_sample()
print("The total number of users after stratified sampling are", final_ratings1.groupby(by=["userId"]).count().shape[0])
print("The total number of movies after stratified sampling are", final_ratings1.groupby(by=["movieId"]).count().shape[0])
final_ratings1_movie_grouping = final_ratings1.groupby(by=["movieId"]).count().reset_index()
print("Minimum number of ratings per movie: ",final_ratings1_movie_grouping["userId"].mean())
user_freq1=final_ratings1.groupby('userId', as_index=False).agg(num_movies=('movieId','count'))
movie_freq1 = final_ratings1.groupby('movieId', as_index=False).agg(num_users=('userId','count'))
plt.figure(figsize=(15,5))
plt.hist(user_freq1['num_movies'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,200,10))
plt.xlabel('Number of ratings')
plt.ylabel('Number of users')
plt.show()
plt.figure(figsize=(15,5))
plt.hist(movie_freq1['num_users'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,4000,200))
plt.xlabel('Number of ratings')
plt.ylabel('Number of movies')
plt.show()
df_ur_gp1 = final_ratings1[['userId','rating']].groupby('userId').agg(mean_rating=('rating','mean'))
df_ur_gp1.hist(bins=30, grid=False, edgecolor='b', density=True, figsize=(10,5))
df_ur_gp1['mean_rating'].plot(grid=False, alpha=10, kind='kde')
plt.title('Average rating per user')
plt.show()
df_mv_gp1 = final_ratings1[['movieId','rating']].groupby('movieId').agg(mean_rating=('rating','mean'))
df_mv_gp1.hist(bins=30, grid=False, edgecolor='b', density=True, figsize=(10,5))
df_mv_gp1['mean_rating'].plot(grid=False, alpha=10, kind='kde')
plt.title('Average rating per movie')
plt.show()
```
## Method 2 : Sampling Based on Timestamp
### Observing the trend of of movies rated for per given years
```
import matplotlib.pyplot as plt
from datetime import datetime
ratings1_with_date = ratings1
ratings1_with_date['date'] = [datetime.fromtimestamp(x) for x in ratings1_with_date['timestamp']]
ratings1_with_date['date'] = pd.to_datetime(ratings1_with_date['date'])
ratings1_with_date['year'] = ratings1_with_date['date'].dt.year
ratings1_with_date
# Printing frequencey of movies rated every year
df = ratings1_with_date.groupby(by=["year","movieId"])['userId'].count()
df=pd.DataFrame(df)
df = df.reset_index()
plt.xlabel('Year')
plt.ylabel('Frequency')
plt.plot(df.groupby("year")['movieId'].count())
plt.title("Frequency of rating of movies per year")
```
We observe that the number of movie ratings have an increasing trend. We therefore, decide to sample our data with the movie ratings from the most recent years in this timestamp-based sampling.
```
def create_timestamp_based_sample(n=100):
# Random sampling to be used as a part of timestamp-based sampling
def gen_sample(df,var,size):
np.random.seed(10)
user_cnt=df.groupby([var], as_index=False).size()
user_cnt['decile'] = pd.qcut(user_cnt['size'], 20, labels=False,duplicates='drop')
sample_df = user_cnt.groupby('decile').sample(frac=(size+5)/df[var].nunique())
return(sample_df[var].to_frame().reset_index(drop=True))
# Create new columns date and year extracted from timestamp
ratings1_with_date = ratings1
ratings1_with_date['date'] = [datetime.fromtimestamp(x) for x in ratings1_with_date['timestamp']]
ratings1_with_date['date'] = pd.to_datetime(ratings1_with_date['date'])
ratings1_with_date['year'] = ratings1_with_date['date'].dt.year
# Sorting the ratings table with the latest dates at the top
ratings1_with_date = ratings1_with_date.sort_values(by='date',ascending=False).reset_index().drop(columns='index')
# Filtering for ratings given between 2005 and 2018
ratings1_with_date_sample = ratings1_with_date[(ratings1_with_date['year']>=2005) & (ratings1_with_date['year']<=2018) ]
ratings1_with_date_sample = ratings1_with_date_sample.drop(['date','year'],axis=1)
# Print the number of users and movies for all ratings between 2005 and 2018
#print("No of users between 2005 and 2018: ",ratings1_with_date_sample['userId'].nunique())
#print("No of movies rated between 2005 and 2018: " ,ratings1_with_date_sample['movieId'].nunique())
ratings_with_most_rated_movies = ratings1_with_date_sample
"""
Since the number of movies is way above the 1000 movies we need, reducing number of unique movies by :
1. aggregating number of movies per user
2. selecting 3000 movies with highest number of user ratings
3. joining the ratings1_with_date_sample table with the movieIds found by steps 1. and 2. to retrieve a sample with 20000+ users and most rated movies.
"""
# Number of Movies
ratings2GroupedByMovie = ratings1_with_date_sample.groupby(by=["movieId"]).count().reset_index()
# Choosing top 3000 movies with maximum number of user ratings
ratings2GroupedByMovie = ratings2GroupedByMovie.sort_values('userId', ascending=False).head(3000)
# Mapping the movieIds obtained from above grouping table with original ratings table
ratings_with_most_rated_movies = ratings1_with_date_sample.merge(ratings2GroupedByMovie['movieId'],how='inner',on='movieId')
# Print the number of users and movies for most rated movies between 2005 and 2018
#print("No of users for highly rated movies between 2005 and 2018: ", ratings_with_most_rated_movies['userId'].nunique())
#print("No of movies for highly rated movies rated between 2005 and 2018: ", ratings_with_most_rated_movies['movieId'].nunique())
# Method 2 : Random sampling to reduce the sample data set size
number_of_users = 21000 * (n/100)
number_of_movies = 1100 * (n/100)
ratings_with_most_rated_movies_user_sample=gen_sample(ratings_with_most_rated_movies,'userId', number_of_users)
ratings_with_most_rated_movies_movie_sample=gen_sample(ratings_with_most_rated_movies,'movieId', number_of_movies)
ratings_with_most_rated_movies_sample=pd.merge(pd.merge(ratings1, ratings_with_most_rated_movies_user_sample, on=['userId'],how='inner'),\
ratings_with_most_rated_movies_movie_sample,on=['movieId'],how='inner')
final_ratings = ratings_with_most_rated_movies_sample
# print("Shape of final_ratings: ", final_ratings.shape)
return final_ratings
final_ratings2 = create_timestamp_based_sample(100)
final_ratings2.to_csv('/data/final_dataset.csv')
# Number of Movies rated per user
final_ratings2_users_grouping = final_ratings2.groupby(by=["userId"]).count().reset_index()
print("Minimum number of ratings per user: ",final_ratings2_users_grouping["userId"].min())
print("Average number of ratings per user: ",final_ratings2_users_grouping["userId"].mean())
print("The total number of users after timestamp based sampling are",final_ratings2.groupby(by=["userId"]).count().shape[0])
print("The total number of movies after timestamp based sampling are", final_ratings2.groupby(by=["movieId"]).count().shape[0])
final_ratings2_movie_grouping = final_ratings2.groupby(by=["movieId"]).count().reset_index()
print("Minimum number of ratings per movie: ",final_ratings2_movie_grouping["userId"].min())
print("Average number of ratings per movie: ",final_ratings2_movie_grouping["userId"].mean())
user_freq2=final_ratings2.groupby('userId', as_index=False).agg(num_movies=('movieId','count'))
movie_freq2 = final_ratings2.groupby('movieId', as_index=False).agg(num_users=('userId','count'))
plt.figure(figsize=(15,5))
plt.hist(user_freq2['num_movies'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,1000,100))
plt.xlabel('Number of ratings')
plt.ylabel('Number of users')
plt.show()
plt.figure(figsize=(15,5))
plt.hist(movie_freq2['num_users'], bins=100, edgecolor='b', log=True)
plt.xlim(0,)
plt.xticks(np.arange(0,10000,1000))
plt.xlabel('Number of ratings')
plt.ylabel('Number of users')
plt.show()
df_ur_gp2 = final_ratings2[['userId','rating']].groupby('userId').agg(mean_rating=('rating','mean'))
df_ur_gp2.hist(bins=30, grid=False, edgecolor='b', density=True, figsize=(10,5))
df_ur_gp2['mean_rating'].plot(grid=False, alpha=10, kind='kde')
plt.title('Average rating per user')
plt.show()
```
| github_jupyter |
<center>
<h1><b>Word Embedding Based Answer Evaluation System for Online Assessments (WebAES)</b></h1>
<h3>A smart system to automate the process of answer evaluation in online assessments.</h3>
<h5>LDA Model for topic extraction</h5>
```
# For training LDA model using text8 corpus
from gensim import corpora, models
import gensim.downloader as api
# To perform text pre-processing
import string
# Natural Language Toolkit
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
# Set of stopwords in English
en_stopwords = set(stopwords.words('english'))
# Load text8 corpus and convert to list of documents
text8_corpus = api.load('text8')
text8_corpus = [doc for doc in text8_corpus]
# List containing list of tokens from each document of text8 corpus
list_of_list_of_tokens = []
# For each document in the text8 corpus
for i in range(len(text8_corpus)):
# Remove stopwords from each document
text8_corpus[i] = [w for w in text8_corpus[i] if w not in en_stopwords]
# Add list of tokens for document to list of list of tokens
list_of_list_of_tokens.append(text8_corpus[i])
# Create a text corpus using list of list of tokens
dictionary_LDA = corpora.Dictionary(list_of_list_of_tokens)
corpus = [dictionary_LDA.doc2bow(list_of_tokens) for list_of_tokens in list_of_list_of_tokens]
# LDA model to extract 100 topics from the text corpus
num_topics = 100
%time lda_model = models.LdaModel(corpus, num_topics=num_topics, id2word=dictionary_LDA, passes=4, alpha=[0.01]*num_topics, eta=[0.01]*len(dictionary_LDA.keys()))
# Save trained LDA model
lda_model.save('WebAES_LDA_Model.model')
# Load previously trained LDA model
lda_model = models.LdaModel.load('WebAES_LDA_Model.model')
# Pre-process text
new_text = 'The different domains of Artificial Intelligence include machine learning, neural networks, robotics, expert systems, fuzzy logic, and natural language processing. Machine Learning is the science of getting computers to act by feeding them data so that they can learn a few tricks on their own, without being explicitly programmed to do so. Neural Networks are a set of algorithms and techniques, modelled in accordance with the human brain. Neural Networks are designed to solve complex and advanced machine learning problems. Robotics is a subset of AI, which includes different branches and application of robots. These Robots are artificial agents acting in a real-world environment. An AI Robot works by manipulating the objects in its surrounding, by perceiving, moving and taking relevant actions. An expert system is a computer system that mimics the decision-making ability of a human. It is a computer program that uses artificial intelligence (AI) technologies to simulate the judgment and behaviour of a human or an organization that has expert knowledge and experience in a particular field. Fuzzy logic is an approach to computing based on “degrees of truth” rather than the usual “true or false” (1 or 0) Boolean logic on which the modern computer is based. Fuzzy logic Systems can take imprecise, distorted, noisy input information. Natural Language Processing (NLP) refers to the Artificial Intelligence method that analyses natural human language to derive useful insights in order to solve problems.'
# Remove punctuations
new_text = new_text.translate(str.maketrans('', '', string.punctuation)).lower()
# Remove stopwords
new_text = ' '.join([w for w in new_text.split() if not w.lower() in en_stopwords])
# Create list of tokens
new_text_tokens = new_text.split()
# Get probability of belonging to each topic using LDA model
topic_probs = lda_model[dictionary_LDA.doc2bow(new_text_tokens)]
# Display all topics and their probability
print('All topics: ', topic_probs)
# Select index of topic with maximum topic probability
max_prob = 0
max_prob_topic = 0
for topic in topic_probs:
topic_index, topic_prob = topic[0], topic[1]
if topic_prob > max_prob:
max_prob = topic_prob
max_prob_topic = topic_index
# Display topic index with maximum topic probability
print('Index of topic with max. probability: ', max_prob_topic)
# Pre-process text
new_text = 'The different domains of Artificial Intelligence include machine learning, neural networks, robotics, expert systems, fuzzy logic, and natural language processing.'
# Remove punctuations
new_text = new_text.translate(str.maketrans('', '', string.punctuation)).lower()
# Remove stopwords
new_text = ' '.join([w for w in new_text.split() if not w.lower() in en_stopwords])
# Create list of tokens
new_text_tokens = new_text.split()
# Get probability of belonging to each topic using LDA model
topic_probs = lda_model[dictionary_LDA.doc2bow(new_text_tokens)]
# Display all topics and their probability
print('All topics: ', topic_probs)
# Select index of topic with maximum topic probability
max_prob = 0
max_prob_topic = 0
for topic in topic_probs:
topic_index, topic_prob = topic[0], topic[1]
if topic_prob > max_prob:
max_prob = topic_prob
max_prob_topic = topic_index
# Display topic index with maximum topic probability
print('Index of topic with max. probability: ', max_prob_topic)
# Pre-process text
new_text = 'Human Computer Interaction is the study of the interaction between human users and computer systems.'
# Remove punctuations
new_text = new_text.translate(str.maketrans('', '', string.punctuation)).lower()
# Remove stopwords
new_text = ' '.join([w for w in new_text.split() if not w.lower() in en_stopwords])
# Create list of tokens
new_text_tokens = new_text.split()
# Get probability of belonging to each topic using LDA model
topic_probs = lda_model[dictionary_LDA.doc2bow(new_text_tokens)]
# Display all topics and their probability
print('All topics: ', topic_probs)
# Select index of topic with maximum topic probability
max_prob = 0
max_prob_topic = 0
for topic in topic_probs:
topic_index, topic_prob = topic[0], topic[1]
if topic_prob > max_prob:
max_prob = topic_prob
max_prob_topic = topic_index
# Display topic index with maximum topic probability
print('Index of topic with max. probability: ', max_prob_topic)
```
| github_jupyter |
```
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 权值
def weight_variable(shape):
initial = tf.truncated_normal(shape=shape, stddev=0.1)
return tf.Variable(initial_value=initial)
# 偏置值
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial_value=initial)
# 卷积层
def conv2d(x, W):
# x: ` [batch, in_height, in_width, in_channels]`
# [批次大小, 输入图片的长和宽, 通道数 (黑白:2; 彩色: 3)]
# W: `[filter_height, filter_width, in_channels, out_channels]`
# [滤波器长, 宽,输入通道数, 输出通道数]
# strides: `[1, stride, stride, 1]`
# [固定为1, x/y方向的步长, 固定为1]
# padding: 是否在外部补零
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化层
def max_pool_2x2(x):
# x: ` [batch, in_height, in_width, in_channels]`
# [批次大小, 输入图片的长和宽, 通道数 (黑白:2; 彩色: 3)]
# ksize: [固定为1, 窗口大小, 固定为1]
# strides: `[1, stride, stride, 1]`
# [固定为1, x/y方向的步长, 固定为1]
# padding: 是否在外部补零
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# Place Holder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# Learn Rate学习率
lr = tf.Variable(0.001, dtype = tf.float32)
# 将 x的转化为 4D向量
# [batch, in_height, in_width, in_channels]
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 初始化第一个卷积层 权值和偏置值
# 5*5 的采样窗口,32个卷积核(输出channels数) 从1个平面(输入channels数) 抽取特征,获得 32个特征平面
W_conv1 = weight_variable([5, 5, 1, 32])
# 32个卷积核,每个卷积核对应一个偏置值
b_conv1 = bias_variable([32])
# 执行卷积采样操作,并加上偏置值
conv2d_1 = conv2d(x_image, W_conv1) + b_conv1
# ReLU激活函数,获得第一个卷积层,计算得到的结果
h_conv1 = tf.nn.relu(conv2d_1)
# 执行 pooling池化操作
h_pool1 = max_pool_2x2(h_conv1)
# 第二个卷积层 + 激活函数 + 池化层
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
conv2d_2 = conv2d(h_pool1, W_conv2) + b_conv2
h_conv2 = tf.nn.relu(conv2d_2)
h_pool2 = max_pool_2x2(h_conv2)
# 第一次卷积操作后,28 * 28图片仍然是 28 * 28
# 第一次池化之后,因为 2 * 2的窗口,所以变成了 14 * 14
# 第二次卷积之后,仍然保持 14 * 14的平面大小
# 第二次池化之后,因为 2 * 2的窗口,所以变成了 7 * 7
# 全连接层一共有 1000个神经元,连接上一层的 7 * 7* 64 = 3136个神经元
W_fc1 = weight_variable([7 * 7 * 64, 1000])
b_fc1 = bias_variable([1000])
# 把上一层的池化层,转化为 1维 (-1代表任意值)
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
# 矩阵相乘,并加上偏置值
wx_plus_b1 = tf.matmul(h_pool2_flat, W_fc1) + b_fc1
# ReLU激活函数
h_fc1 = tf.nn.relu(wx_plus_b1)
# dropout正则化
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 第二个全连接层
W_fc2 = weight_variable([1000, 10])
b_fc2 = bias_variable([10])
# 计算输出
wx_plus_b2 = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
prediction = tf.nn.softmax(wx_plus_b2)
# 交叉熵 Loss Function
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
# Adam优化器,配合一个不断下降的学习率
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)
# argmax方法,会返回一维张量中最大值所在的位置
# 计算正确率
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.device('/gpu:0'):
with tf.Session() as sess:
tf.global_variables_initializer().run()
batch_size = 100
batch = (int) (60000 / batch_size)
for _ in range(101):
sess.run(tf.assign(lr, 0.0001 * (0.95 ** _)))
for batch_step in range(batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.68})
if _ % 20 == 0:
test_acc = sess.run(accuracy, feed_dict = {x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0})
print("Iterator: ", _, "Accuracy:", test_acc)
```
| github_jupyter |
## Segment a sparse 3D image with a single material component
The goal of this notebook is to develop a 3D segmentation algorithm that improves segmentation where features are detected.
**Data:** AM parts from Xuan Zhang.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import os
import h5py
import sys
from tomo_encoders import Patches, DataFile
import tensorflow as tf
sys.path.append('/data02/MyArchive/aisteer_3Dencoders/TomoEncoders/tomo_encoders/tasks/sparse_segmenter/')
import time
from sparse_segmenter import SparseSegmenter
from tomo_encoders.misc_utils.feature_maps_vis import view_midplanes
# load vols here and quick look
# fpath = '/data02/MyArchive/AM_part_Xuan/data/AM316_L205_fs_tomo_L5_rec_1x1_uint16.hdf5'
# fpath_y = '/data02/MyArchive/AM_part_Xuan/CTSegNet_masks/AM316_L205_fs_tomo_L5.hdf5'
fpath = '/data02/MyArchive/AM_part_Xuan/data/mli_L206_HT_650_L3_rec_1x1_uint16.hdf5'
fpath_y = '/data02/MyArchive/AM_part_Xuan/CTSegNet_masks/mli_L206_HT_650_L3.hdf5'
X = DataFile(fpath, tiff = False, data_tag = "data", VERBOSITY = 0).read_full().astype(np.float32)
Y = DataFile(fpath_y, tiff = False, data_tag = "SEG", VERBOSITY = 0).read_full()
syx = slice(650,-650,None)
# sz = slice(100,-100,None)
sz = slice(None,None,None)
# view_midplanes(X[:,syx,syx])
X = X[sz,syx,syx]
Y = Y[sz,syx,syx]
fig, ax = plt.subplots(1,3, figsize = (16,6))
view_midplanes(vol = X, ax = ax)
fig, ax = plt.subplots(1,3, figsize = (16,6))
view_midplanes(vol = Y, ax = ax)
```
## Test it
```
bin_size = (64,64,64)
descriptor_tag = 'test_noblanks_pt2cutoff'
model_names = {"segmenter" : "segmenter_Unet_%s"%descriptor_tag}
model_path = '/data02/MyArchive/aisteer_3Dencoders/models/AM_part_segmenter'
## Need to write the stitch function
max_stride = 4 # do reconstruction at this binning
fe = SparseSegmenter(model_initialization = 'load-model', model_names = model_names, model_path = model_path)
patches = Patches(X.shape, initialize_by = "grid", \
patch_size = fe.model_size, stride = max_stride)
Yp = np.zeros(X.shape, dtype = np.uint8)
Yp = fe._segment_patches(X, Yp, patches, upsample = max_stride)
## binning back down
sbin = slice(None,None,max_stride)
padding = [X.shape[i]%max_stride for i in range(3)]
## edge detection
Y_edge = fe._edge_map(Yp[sbin,sbin,sbin].copy())
fig, ax = plt.subplots(1,3, figsize = (16,6))
view_midplanes(vol = Y_edge, ax = ax)
## select patches containing edges
new_patch_size = tuple(np.asarray(fe.model_size)//max_stride)
p_sel = Patches(Y_edge.shape, initialize_by = "regular-grid", patch_size = new_patch_size, stride = 1)
def plot_grid(p):
fig, ax = plt.subplots(1,3, figsize = (20,8))
ivals = [(0, 1, 2), (1, 0, 2), (2, 0, 1)]
for ival in ivals:
ip, i1, i2 = ival
ax[ip].scatter(p.centers()[:,i1], p.centers()[:,i2])
ax[ip].set_xlim([0, p.vol_shape[i1]])
ax[ip].set_ylim([0, p.vol_shape[i2]])
return
sub_vols = p_sel.extract(Y_edge, new_patch_size)
tmp = (np.sum(sub_vols, axis = (1,2,3))>3).astype(np.uint8)
p_sel.add_features(tmp.reshape(-1,1), names = ['has_edges'])
p_edges = p_sel.filter_by_condition(p_sel.features_to_numpy(['has_edges']))
## rescale patches
p_edges = p_edges.rescale(max_stride, X.shape)
p_edges.points[:5]
p_edges.widths[:5]
len1 = len(p_sel.points)
len0 = len(p_edges.points)
t_save = (len1-len0)/len1*100.0
print("compute time saving %.2f pc"%t_save)
## segment these patches only
Yp = fe._segment_patches(X, Yp, p_edges, arr_split_infer=10)
fig, ax = plt.subplots(1,3,figsize = (16,8))
view_midplanes(Yp[100:-100,1000:-1000,1000:-1000], ax)
# fig, ax = plt.subplots(1,3,figsize = (16,8))
# view_midplanes(Yp[100:-100,1000:-1000,1000:-1000], ax)
fig, ax = plt.subplots(1,3,figsize = (16,8))
view_midplanes(Y[100:-100,1000:-1000,1000:-1000], ax)
# fig, ax = plt.subplots(1,3,figsize = (16,8))
# view_midplanes(Y_pred[100:-100,1000:-1000,1000:-1000], ax)
fig, ax = plt.subplots(1,3)
idx = 0
s = [slice(100,-100), slice(1000,-1000), slice(1000,-1000)]
# seg_plot()
# ax[idx]
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import cv2
import os
import matplotlib.pyplot as plt
from tqdm import tqdm
from pdb import *
from pathlib import Path
from skimage.io import imread
from fastai.torch_basics import *
from fastai.data.all import *
from fastai.vision.all import *
# from PIL import Images
from nuclei import *
DATA_PATH = Path('../data/datasciencebowl')
TRAIN_PATH = DATA_PATH/'stage1_train'
torch.cuda.set_device(1)
```
## Point annotations
```
pt_annotations = get_pt_annotations(DATA_PATH)
```
## Create gaussian mask
```
def get_x(idx):
return TRAIN_PATH/images[idx]
def get_y(idx, r=14, sz=256):
w,h = PILImage.create(TRAIN_PATH/images[idx]).shape
# r = int(r * w / sz)
mask = np.zeros((w,h))
for x,y in points[idx]:
draw_umich_gaussian(mask, (x,y), r)
return PILMask.create(mask.astype(float))
images, points = zip(*pt_annotations)
idxs = range(len(images))
train_idxs = [idx for idx,image in enumerate(images) if image.stem not in set(VAL_IMAGE_IDS)]
valid_idxs = [idx for idx,image in enumerate(images) if image.stem in set(VAL_IMAGE_IDS)]
tfms = [[get_x, PILImage.create], [get_y]]
dsets = Datasets(items=idxs, tfms=tfms, splits=[train_idxs, valid_idxs])
idx = 21
ctx = dsets[idx][0].show(figsize=(6,6))
dsets[idx][1].show(ctx=ctx, cmap='Greens', alpha = 0.5)
idx += 1
import matplotlib as mpl
cmap = mpl.cm.tab20
cmap.set_under('k', 0.0)
# currently augmentation transform screws with the padding
batch_tfms = [*aug_transforms(), Normalize.from_stats(*imagenet_stats)]
sz_mthd = RandomCrop
# sz_mthd = Resize
dls = dsets.dataloaders(bs=16, after_item=[sz_mthd(256), ToTensor, IntToFloatTensor], after_batch=batch_tfms, num_workers=8)
dls.c = 1
xb, yb = dls.one_batch()
xb.shape, yb.shape
dls.show_batch(cmap="Greens", alpha=0.5)
```
## Learner
```
def acc_nuclei(input, target):
target = target[:, None]
target = F.interpolate(target, size=64)
mask = target > 0.1
acc = (input[mask] > 0.1) == (target[mask] > 0.1)
return acc.float().mean()
def _neg_loss(pred, gt):
''' Modified focal loss. Exactly the same as CornerNet.
Runs faster and costs a little bit more memory
Arguments:
pred (batch x c x h x w)
gt_regr (batch x c x h x w)
'''
pos_inds = gt.gt(0.98).float()
neg_inds = gt.lt(0.98).float()
neg_weights = torch.pow(1 - gt, 4)
loss = 0
pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds
neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_weights * neg_inds
num_pos = pos_inds.float().sum()
pos_loss = pos_loss.sum()
neg_loss = neg_loss.sum()
if num_pos == 0:
loss = loss - neg_loss
else:
loss = loss - (pos_loss + neg_loss) / num_pos
return loss
class FocalLoss(nn.Module):
'''nn.Module warpper for focal loss'''
def __init__(self):
super().__init__()
self.neg_loss = _neg_loss
def forward(self, out, target):
target = target.data[:, None]
target = F.interpolate(target, size=64)
bs = target.shape[0]
loss = self.neg_loss(torch.sigmoid(out), target)
return loss / bs
def activation(self, x): return torch.sigmoid(x)
loss_func = FocalLoss()
metrics=acc_nuclei
import hourglass
heads = {
'hm': 1,
# 'reg': 2,
# 'wh': 2
}
m = hourglass.HourglassNet(heads, num_stacks=2)
learn = Learner(dls, m, metrics=metrics, loss_func=loss_func)
learn.path = DATA_PATH
learn.fit_one_cycle(60, 1e-3, wd=1e-4)
learn.save('centernet_hourglass_104')
learn.load('centernet_hourglass_104')
learn.fit_one_cycle(60, 1e-4, wd=1e-4)
learn.save('centernet_hourglass_104_run2')
learn.load('centernet_hourglass_104_run2')
def max_px(box, targ):
targ = targ[0]
m = np.zeros_like(targ)
# x,y,w,h = box
y,x,h,w = box
m[x:x+w,y:y+h] = 1
ind = np.unravel_index(np.argmax(targ*m, axis=None), targ.shape)
# if ind == (0,0): pdb.set_trace()
return ind
def ed(pt1, pt2):
(xA,yA), (xB,yB) = pt1, pt2
return ((xB-xA)**2 + (yB-yA)**2)**0.5
def calc_pr_area(lbls, preds, pmaxs, min_area=1, max_dist=5, iou_thresh=0.1):
tps = []
fps = []
scores = []
n_gts = []
for lbl,pred,pmax in zip(lbls,preds,pmaxs):
contours,hierarchy = cv2.findContours(pmax.max(0).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
pboxes = [cv2.boundingRect(cnt) for cnt in contours if cv2.contourArea(cnt) >= min_area]
pboxes = [max_px(pbox, pred) for pbox in pboxes]
pboxes = list(sorted(pboxes, key=lambda x: pred[0][x], reverse=True)) # sort by scores
contours,hierarchy = cv2.findContours((lbl>=0.9).max(0).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
lboxes = [max_px(cv2.boundingRect(cnt), lbl) for cnt in contours]
detected = []
dists = []
for pb in pboxes:
calc = [(ed(lb, pb), lb) for lb in lboxes if lb not in detected]
if len(calc) == 0:
dists.append(1e10)
else:
dist, lb = min(calc)
# print(dist)
detected.append(lb)
dists.append(dist)
tp = (np.array(dists) <= max_dist)
fp = ~tp
s = np.array([pred[0, pb[0],pb[1]] for pb in pboxes])
n_gts.append(len(lboxes))
tps.extend(tp.astype(np.uint8).tolist())
fps.extend(fp.astype(np.uint8).tolist())
scores.extend(s.tolist())
res = sorted(zip(scores, tps, fps), key=lambda x: x[0], reverse=True)
res = np.array(res)
if len(res) == 0: res = np.zeros((1, 3))
tp = res[:,1].cumsum(0)
fp = res[:,2].cumsum(0)
precision = tp / (tp + fp + 1e-8)
recall = tp / sum(n_gts)
return precision, recall
preds, lbls = learn.get_preds()
preds = F.interpolate(preds, size=256)
preds = preds.detach().cpu().numpy()
lbls = lbls[:, None]
# lbls = F.interpolate(lbls, size=64)
lbls = lbls.detach().cpu().numpy()
lbls.shape, preds.shape
for dist in [2, 5, 10]:
aps = []
for s in [1, 2, 5, 8]:
for sz in [1,2,4]:
score_thresh = s/10
pmaxs = (preds >= score_thresh).astype(np.uint8)
precision, recall = calc_pr_area(lbls, preds, pmaxs, max_dist=dist, min_area=sz)
F1 = (2 * (precision * recall) / (precision + recall))[-1]
aps.append((compute_ap(precision, recall),sz,score_thresh,F1))
# aps.append((compute_ap(precision, recall),score_thresh,sz,F1))
print(dist, max(aps))
for dist in [2, 5, 10]:
aps = []
for s in [1, 2, 5, 8]:
for sz in [1,2,4]:
score_thresh = s/10
pmaxs = (preds >= score_thresh).astype(np.uint8)
precision, recall = calc_pr_area(lbls, preds, pmaxs, max_dist=dist, min_area=sz)
aps.append((compute_ap(precision, recall),sz,score_thresh))
print(dist, max(aps))
preds, lbls = learn.get_preds()
# preds = F.interpolate(preds, size=256)
preds = preds.detach().cpu().numpy()
lbls = lbls[:, None]
lbls = F.interpolate(lbls, size=64)
lbls = lbls.detach().cpu().numpy()
lbls.shape, preds.shape
for dist in [2, 5, 10]:
aps = []
for s in [1, 2, 5, 8]:
for sz in [1,2,4]:
score_thresh = s/10
pmaxs = (preds >= score_thresh).astype(np.uint8)
precision, recall = calc_pr_area(lbls, preds, pmaxs, max_dist=dist*2, min_area=sz)
aps.append((compute_ap(precision, recall),sz,score_thresh))
print(dist, max(aps))
preds, lbls = learn.get_preds()
preds = preds.detach().cpu().numpy()
lbls = lbls[:, None].detach().cpu().numpy()
count_parameters(learn.model)
PILImage.create(lbls[2, 0] > score_thresh).show()
PILImage.create(preds[2, 0] > score_thresh).show()
import matplotlib as mpl
cmap = mpl.cm.Greens
# cmap = mpl.cm.Dark2
cmap.set_under('k', 0.0)
# cmap.set_bad('k', 0.0)
# mask.show(cmap=cmap, vmin=1, alpha=1.0)
learn.show_results(figsize=(16,20), cmap=cmap, vmin=0.1, max_n=4, alpha=1.0, shuffle=True)
```
| github_jupyter |
# Checkpointing DataFrames
Sometimes execution plans can get pretty long and Spark might run into trouble. Common scenarios are iterative algorithms like ML or graph algorithms, which contain a big outer loop and iteratively transform a DataFrame over and over again. This would result in a really huge execution plan.
In these cases you could use `cache()` or `persist()` in order to improve performance (otherwise all steps of the loop would be executed again from the very beginning leading to a runtime of O(n^2)). But this will not cut off the lineage.
Checkpointing is the right solution for these cases. It will persist the data of a DataFrame in a reliable distributed storage (most commonly HDFS) and cut off the lineage.
# 1 Load Data
We will load the weather data again for this example.
```
storageLocation = "s3://dimajix-training/data/weather"
```
## 1.1 Load Measurements
```
from pyspark.sql.functions import *
raw_weather = spark.read.text(storageLocation + "/2003").withColumn("year", lit(2003))
```
### Extract Measurements
Measurements were stored in a proprietary text based format, with some values at fixed positions. We need to extract these values with a simple `SELECT` statement.
```
weather = raw_weather.select(
col("year"),
substring(col("value"),5,6).alias("usaf"),
substring(col("value"),11,5).alias("wban"),
substring(col("value"),16,8).alias("date"),
substring(col("value"),24,4).alias("time"),
substring(col("value"),42,5).alias("report_type"),
substring(col("value"),61,3).alias("wind_direction"),
substring(col("value"),64,1).alias("wind_direction_qual"),
substring(col("value"),65,1).alias("wind_observation"),
(substring(col("value"),66,4).cast("float") / lit(10.0)).alias("wind_speed"),
substring(col("value"),70,1).alias("wind_speed_qual"),
(substring(col("value"),88,5).cast("float") / lit(10.0)).alias("air_temperature"),
substring(col("value"),93,1).alias("air_temperature_qual")
)
weather.limit(10).toPandas()
```
## 1.2 Load Station Metadata
```
stations = spark.read \
.option("header", True) \
.csv(storageLocation + "/isd-history")
# Display first 10 records
stations.limit(10).toPandas()
```
# 2 Join Data
Now we perform the join between the station master data and the measurements, as we did before.
```
joined_weather = weather.join(stations, (weather["usaf"] == stations["usaf"]) & (weather["wban"] == stations["wban"]))
```
# 3 Truncating Execution Plans
Now we want to understand the effect of checkpointing. First we will use the traditional aggregation and print the execution plan.
## 3.1 Traditional Aggregation
```
result = joined_weather.groupBy(joined_weather["ctry"], joined_weather["year"]).agg(
min(when(joined_weather.air_temperature_qual == lit(1), joined_weather.air_temperature)).alias('min_temp'),
max(when(joined_weather.air_temperature_qual == lit(1), joined_weather.air_temperature)).alias('max_temp')
)
result.explain(True)
```
## 3.2 Reliable Checkpointing
Now we first checkpoint the joined weather data set and then perform the aggregation on the checkpointed DataFrame.
### Set Checkpoint directory
First we need to specify a checkpoint directory on a reliable shared file system.
```
spark.sparkContext.setCheckpointDir("/tmp/checkpoints")
```
### Create checkpoint
Now we can create a checkpoint for the joined weather. Note that this takes some time, as checkpointing is not a lazy operation, it will be executed immediately. This is also conceptionally neccessary, because one aspect of checkpointing is that the whole lineage gets cut off. So there is no way around executing the computation for materializing the DataFrame inside the checkpoint directory
```
cp_weather = joined_weather.checkpoint(eager=True)
```
### Inspect Checkpoint directory
```
%%bash
hdfs dfs -ls /tmp/checkpoints
```
### Inspect execution plan
Let us have a look at the execution plan of the checkpointed DataFrame
```
cp_weather.explain(True)
```
As you can see, the lineage got lost and is replaced by a `Scan ExistingRDD` which refers to the data in the checkpoint directory.
### Perform aggregation
Now we can perform the aggregation with the checkpointed variant of the joined weather DataFrame.
```
result = cp_weather.groupBy(cp_weather["ctry"], cp_weather["year"]).agg(
min(when(cp_weather.air_temperature_qual == lit(1), cp_weather.air_temperature)).alias('min_temp'),
max(when(cp_weather.air_temperature_qual == lit(1), cp_weather.air_temperature)).alias('max_temp')
)
result.explain(True)
```
As expected, the execution plan now essentially only contains the aggregation in three steps (partial aggregation, shuffle, final aggregation). The lineage of the join is not present any more.
## 3.3 Unreliable Checkpointing
In addition to *reliable* checkpointing, Spark also supports *unreliable* checkpointing, where the data is not stored in HDFS but on the local worker nodes instead using the caching backend.
Note that it is stronlgly discouraged to use unreliable checkpointing with dynamic execution mode, where executors can be freed up again.
```
cpu_weather = joined_weather.localCheckpoint(eager=True)
```
### Inspect Checkpoint data
Now you can see the checkpointed data in the "Storage" section of the web interface.
### Perform aggregation
Now we can perform the aggregation with the checkpointed variant of the joined weather DataFrame.
```
result = cpu_weather.groupBy(cpu_weather["ctry"], cpu_weather["year"]).agg(
min(when(cpu_weather.air_temperature_qual == lit(1), cpu_weather.air_temperature)).alias('min_temp'),
max(when(cpu_weather.air_temperature_qual == lit(1), cpu_weather.air_temperature)).alias('max_temp')
)
result.explain(True)
result.limit(5).toPandas()
```
## 3.4 Checkpoint cleanup
Spark can automatically remove checkpoint directories, if the configuration property `spark.cleaner.referenceTracking.cleanCheckpoints` is set to `True` (default is `False` as of Spark 2.3). Otherwise you have to manually remove checkpoint data from HDFS.
| github_jupyter |
<a href="https://colab.research.google.com/github/mohan-mj/KNN_K-Nearest-Neighbor/blob/master/KNN-Iris.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# import libs
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
# import some data to play with
irisData = datasets.load_iris()
irisData.data
```
**Attribute Information**
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
- class:
- Iris-Setosa
- Iris-Versicolour
- Iris-Virginica
```
# we only take the first two features for learning purpose
X = irisData.data[:, :2]
y = irisData.target
n_neighbors = 15
```
The basic nearest neighbors classification uses uniform weights: that is, the value assigned to a query point is computed from a simple majority vote of the nearest neighbors. Under some circumstances, it is better to weight the neighbors such that nearer neighbors contribute more to the fit. <br>
This can be accomplished through the weights keyword. <br>
The default value, **weights = 'uniform'**, assigns uniform weights to each neighbor. <br>
**weights = 'distance'** assigns weights proportional to the inverse of the distance from the query point.
```
step = .01 # step size in the mesh
for weights in ['uniform', 'distance']:
# we create an instance of Neighbours Classifier and fit the data.
classifier = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
classifier.fit(X, y)
print('KNN classifier accuracy - "%s" - %.3f' % (weights,classifier.score(X,y)))
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x_grid, y_grid = np.meshgrid(np.arange(x_min, x_max, step = step),
np.arange(y_min, y_max, step = step))
Z = classifier.predict(np.c_[x_grid.ravel(), y_grid.ravel()])
# Put the result into a color plot
Z = Z.reshape(x_grid.shape)
plt.figure()
plt.pcolormesh(x_grid, y_grid, Z, cmap=ListedColormap(['lightblue', 'lightgreen', 'lightyellow']) )
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y,
edgecolor='k', s=20)
plt.xlim(x_grid.min(), x_grid.max())
plt.ylim(y_grid.min(), y_grid.max())
plt.title("KNN 3-Class Classification (k = %d, weights = '%s')"
% (n_neighbors, weights))
plt.show()
```
### Visualization - Detailed
```
weights ='uniform'
# we create an instance of Neighbours Classifier and fit the data.
classifier = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
classifier.fit(X, y)
print('KNN classifier accuracy - "%s" - %.3f' % (weights,classifier.score(X,y)))
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x_grid, y_grid = np.meshgrid(np.arange(x_min, x_max, step = step),
np.arange(y_min, y_max, step = step))
x_grid
y_grid
Z = classifier.predict(np.array([x_grid.ravel(), y_grid.ravel()]).T).reshape(x_grid.shape)
np.array([x_grid.ravel(), y_grid.ravel()])
np.array([x_grid.ravel(), y_grid.ravel()]).shape
np.array([x_grid.ravel(), y_grid.ravel()]).T
classifier.predict(np.array([x_grid.ravel(), y_grid.ravel()]).T)
classifier.predict(np.array([x_grid.ravel(), y_grid.ravel()]).T).reshape(x_grid.shape)
plt.figure()
plt.contourf(x_grid, y_grid, Z, cmap=ListedColormap(['lightblue', 'lightgreen', 'lightyellow']) )
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y,
edgecolor='k', s=20)
plt.xlim(x_grid.min(), x_grid.max())
plt.ylim(y_grid.min(), y_grid.max())
plt.title("KNN 3-Class Classification (k = %d, weights = '%s')"
% (n_neighbors, weights))
plt.show()
```
| github_jupyter |
# Dark matter spatial and spectral models
## Introduction
Gammapy has some convenience methods for dark matter analyses in `~gammapy.astro.darkmatter`. These include J-Factor computation and calculation the expected gamma flux for a number of annihilation channels. They are presented in this notebook.
The basic concepts of indirect dark matter searches, however, are not explained. So this is aimed at people who already know what the want to do. A good introduction to indirect dark matter searches is given for example in https://arxiv.org/pdf/1012.4515.pdf (Chapter 1 and 5)
## Setup
As always, we start with some setup for the notebook, and with imports.
```
from gammapy.astro.darkmatter import (
profiles,
JFactory,
PrimaryFlux,
DarkMatterAnnihilationSpectralModel,
)
from gammapy.maps import WcsGeom, WcsNDMap
from astropy.coordinates import SkyCoord
from matplotlib.colors import LogNorm
from regions import CircleSkyRegion
import astropy.units as u
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
```
## Profiles
The following dark matter profiles are currently implemented. Each model can be scaled to a given density at a certain distance. These parameters are controlled by ``profiles.DMProfile.LOCAL_DENSITY`` and ``profiles.DMProfile.DISTANCE_GC``
```
profiles.DMProfile.__subclasses__()
for profile in profiles.DMProfile.__subclasses__():
p = profile()
p.scale_to_local_density()
radii = np.logspace(-3, 2, 100) * u.kpc
plt.plot(radii, p(radii), label=p.__class__.__name__)
plt.loglog()
plt.axvline(8.5, linestyle="dashed", color="black", label="local density")
plt.legend()
print("LOCAL_DENSITY:", profiles.DMProfile.LOCAL_DENSITY)
print("DISTANCE_GC:", profiles.DMProfile.DISTANCE_GC)
```
## J Factors
There are utilities to compute J-Factor maps that can serve as a basis to compute J-Factors for certain regions. In the following we compute a J-Factor map for the Galactic Centre region
```
profile = profiles.NFWProfile()
# Adopt standard values used in HESS
profiles.DMProfile.DISTANCE_GC = 8.5 * u.kpc
profiles.DMProfile.LOCAL_DENSITY = 0.39 * u.Unit("GeV / cm3")
profile.scale_to_local_density()
position = SkyCoord(0.0, 0.0, frame="galactic", unit="deg")
geom = WcsGeom.create(binsz=0.05, skydir=position, width=3.0, frame="galactic")
jfactory = JFactory(
geom=geom, profile=profile, distance=profiles.DMProfile.DISTANCE_GC
)
jfact = jfactory.compute_jfactor()
jfact_map = WcsNDMap(geom=geom, data=jfact.value, unit=jfact.unit)
ax = jfact_map.plot(cmap="viridis", norm=LogNorm(), add_cbar=True)
plt.title(f"J-Factor [{jfact_map.unit}]")
# 1 deg circle usually used in H.E.S.S. analyses
sky_reg = CircleSkyRegion(center=position, radius=1 * u.deg)
pix_reg = sky_reg.to_pixel(wcs=geom.wcs)
pix_reg.plot(ax=ax, facecolor="none", edgecolor="red", label="1 deg circle")
plt.legend()
# NOTE: https://arxiv.org/abs/1607.08142 quote 2.67e21 without the +/- 0.3 deg band around the plane
total_jfact = pix_reg.to_mask().multiply(jfact).sum()
print(
"J-factor in 1 deg circle around GC assuming a "
f"{profile.__class__.__name__} is {total_jfact:.3g}"
)
```
## Gamma-ray spectra at production
The gamma-ray spectrum per annihilation is a further ingredient for a dark matter analysis. The following annihilation channels are supported. For more info see https://arxiv.org/pdf/1012.4515.pdf
```
fluxes = PrimaryFlux(mDM="1 TeV", channel="eL")
print(fluxes.allowed_channels)
fig, axes = plt.subplots(4, 1, figsize=(6, 16))
mDMs = [0.01, 0.1, 1, 10] * u.TeV
for mDM, ax in zip(mDMs, axes):
fluxes.mDM = mDM
ax.set_title(rf"m$_{{\mathrm{{DM}}}}$ = {mDM}")
ax.set_yscale("log")
ax.set_ylabel("dN/dE")
for channel in ["tau", "mu", "b", "Z"]:
fluxes.channel = channel
fluxes.table_model.plot(
energy_bounds=[mDM / 100, mDM],
ax=ax,
label=channel,
yunits=u.Unit("1/GeV"),
)
axes[0].legend()
plt.subplots_adjust(hspace=0.5)
```
## Flux maps
Finally flux maps can be produced like this:
```
channel = "Z"
massDM = 10 * u.TeV
diff_flux = DarkMatterAnnihilationSpectralModel(mass=massDM, channel=channel)
int_flux = (
jfact * diff_flux.integral(energy_min=0.1 * u.TeV, energy_max=10 * u.TeV)
).to("cm-2 s-1")
flux_map = WcsNDMap(geom=geom, data=int_flux.value, unit="cm-2 s-1")
ax = flux_map.plot(cmap="viridis", norm=LogNorm(), add_cbar=True)
plt.title(
f"Flux [{int_flux.unit}]\n m$_{{DM}}$={fluxes.mDM.to('TeV')}, channel={fluxes.channel}"
);
```
| github_jupyter |
# How good is my Kriging model? - tests with IDW algorithm - tutorial
## Table of Contents:
1. Read point data,
2. Divide dataset into two sets: modeling and validation set,
3. Perform IDW and evaluate it,
4. Perform variogram modeling on the modeling set,
5. Validate Kriging and compare Kriging and IDW validation results,
6. Bonus scenario: only 5% of values are known!
## Level: Basic
## Changelog
| Date | Change description | Author |
|------|--------------------|--------|
| 2021-05-12 | First version of tutorial | @szymon-datalions |
## Introduction
In this tutorial we will learn about the one method of validation of our Kriging model. We'll compare it to the Inverse Distance Weighting function where the unknown point value is interpolated as the weighted mean of it's neighbours. Weights are assigned by the inverted distance raised to the n-th power.
(1) **GENERAL FORM OF IDW**
$$z(u) = \frac{\sum_{i}\lambda_{i}*z_{i}}{\sum_{i}\lambda_{i}}$$
where:
- $z(u)$: is the value at unknown location,
- $i$: is a i-th known location,
- $z_{i}$: is a value at known location $i$,
- $\lambda_{i}$: is a weight assigned to the known location $i$.
(2) **WEIGHTING PARAMETER**
$$\lambda_{i} = \frac{1}{d^{p}_{i}}$$
where:
- $d$: is a distance from known point $z_{i}$ to the unknown point $z(u)$,
- $p$: is a hyperparameter which controls how strong is a relationship between known point and unknown point. You may set large $p$ if you want to show strong relationship between closest point and very weak influence of distant points. On the other hand, you may set small $p$ to emphasize fact that points are influencing each other with the same power irrespectively of their distance.
---
As you noticed **IDW** is a simple but powerful technique. Unfortunately it has major drawback: **we must set `p` - power - manually** and it isn't derived from the data and variogram. That's why it can be used for other tasks. Example is to use IDW as a baseline for comparison to the other techniques.
## Import packages
```
import numpy as np
import matplotlib.pyplot as plt
from pyinterpolate.idw import inverse_distance_weighting # function for idw
from pyinterpolate.io_ops import read_point_data
from pyinterpolate.semivariance import calculate_semivariance # experimental semivariogram
from pyinterpolate.semivariance import TheoreticalSemivariogram # theoretical models
from pyinterpolate.kriging import Krige # kriging models
```
## 1) Read point data
```
dem = read_point_data('../sample_data/point_data/poland_dem_gorzow_wielkopolski', data_type='txt')
dem
```
## 2) Divide dataset into two sets: modeling and validation set
In this step we will divide our dataset into two sets:
- modeling set (50%): points used for variogram modeling,
- validation set (50%): points used for prediction and results validation.
Baseline dataset will be divided randomly.
```
# Create modeling and validation sets
def create_model_validation_sets(dataset: np.array, frac=0.5):
"""
Function divides base dataset into modeling and validation sets
INPUT:
:param dataset: (numpy array) array with rows of records,
:param frac: (float) number of elements in a validation set
OUTPUT:
return: modeling_set (numpy array), validation_set (numpy array)
"""
removed_idx = np.random.randint(0, len(dem)-1, size=int(frac * len(dem)))
validation_set = dem[removed_idx]
modeling_set = np.delete(dem, removed_idx, 0)
return modeling_set, validation_set
known_points, unknown_points = create_model_validation_sets(dem)
```
## 3) Perform IDW and evaluate it
Inverse Distance Weighting doesn't require variogram modeling or other steps. We pass power to which we want raise distance in weight denominator. Things to remember are:
- Large `power` -> closer neighbours are more important,
- `power` which is close to the **zero** -> all neighbours are important and we assume that distant process has the same effect on our variable as the closest events.
```
IDW_POWER = 2
NUMBER_OF_NEIGHBOURS = -1 # Include all points in weighting process (equation 1)
idw_predictions = []
for pt in unknown_points:
idw_result = inverse_distance_weighting(known_points, pt[:-1], NUMBER_OF_NEIGHBOURS, IDW_POWER)
idw_predictions.append(idw_result)
# Evaluation
idw_rmse = np.mean(np.sqrt((unknown_points[:, -1] - np.array(idw_predictions))**2))
print(f'Root Mean Squared Error of prediction with IDW is {idw_rmse}')
```
**Clarification:** Obtained Root Mean Squared Error could serve as a baseline for further model development. To build better reference, we create four IDW models of powers:
1. 0.5,
2. 1,
3. 2,
4. 4.
```
IDW_POWERS = [0.5, 1, 2, 4]
idw_rmse = {}
for pw in IDW_POWERS:
results = []
for pt in unknown_points:
idw_result = inverse_distance_weighting(known_points, pt[:-1], NUMBER_OF_NEIGHBOURS, pw)
results.append(idw_result)
idw_rmse[pw] = np.mean(np.sqrt((unknown_points[:, -1] - np.array(results))**2))
for pw in IDW_POWERS:
print(f'Root Mean Squared Error of prediction with IDW of power {pw} is {idw_rmse[pw]:.4f}')
```
## 4) Perform variogram modeling on the modeling set
In this step we will go through semivariogram modeling for Kriging interpolation.
```
search_radius = 0.01
max_range = 0.32
number_of_ranges = 32
exp_semivar = calculate_semivariance(data=known_points, step_size=search_radius, max_range=max_range)
semivar = TheoreticalSemivariogram(points_array=known_points, empirical_semivariance=exp_semivar)
semivar.find_optimal_model(weighted=False, number_of_ranges=number_of_ranges)
semivar.show_semivariogram()
```
## 5) Validate Kriging and compare Kriging and IDW validation results
In the last we perform Kriging interpolation and compare rersults to the **IDW** models. We use all points to weight values at unknown locations and semivariogram model chosen in the previous step.
```
# Set Kriging model
model = Krige(semivariogram_model=semivar, known_points=known_points)
kriging_preds = []
for pt in unknown_points:
result = model.ordinary_kriging(pt[:-1], number_of_neighbours=64, test_anomalies=False)
kriging_preds.append(result[0])
# Evaluation
kriging_rmse = np.mean(np.sqrt((unknown_points[:, -1] - np.array(kriging_preds))**2))
print(f'Root Mean Squared Error of prediction with Kriging is {kriging_rmse}')
```
**Clarification**: Kriging is better than any from the IDW models and we may assume that our modeling approach gives us more insights into the spatial process which we are observing. But this is not the end... let's consider more complex scenario!
## 6) Bonus scenario: only 5% of values are known!
Real world data are rarely as good as sample from the tutorial. It is too expensive to densily sample every location and usually we get only small percent of area covered by data. That's why it is good to compare **IDW vs Kriging** in this scenario! We repeat steps 1-5 with change in division for modeling / validation set. (I encourage you to try it do alone and then compare your code and results with those given in this notebook).
```
# Data preparation
known_points, unknown_points = create_model_validation_sets(dem, 0.95)
# IDW tests
IDW_POWERS = [0.5, 1, 2, 4]
idw_rmse = {}
for pw in IDW_POWERS:
results = []
for pt in unknown_points:
idw_result = inverse_distance_weighting(known_points, pt[:-1], NUMBER_OF_NEIGHBOURS, pw)
results.append(idw_result)
idw_rmse[pw] = np.mean(np.sqrt((unknown_points[:, -1] - np.array(results))**2))
# Variogram
search_radius = 0.01
max_range = 0.32
number_of_ranges = 32
exp_semivar = calculate_semivariance(data=known_points, step_size=search_radius, max_range=max_range)
semivar = TheoreticalSemivariogram(points_array=known_points, empirical_semivariance=exp_semivar)
semivar.find_optimal_model(weighted=False, number_of_ranges=number_of_ranges)
semivar.show_semivariogram()
# Set Kriging model
model = Krige(semivariogram_model=semivar, known_points=known_points)
kriging_preds = []
for pt in unknown_points:
result = model.ordinary_kriging(pt[:-1], number_of_neighbours=64, test_anomalies=False)
kriging_preds.append(result[0])
kriging_rmse = np.mean(np.sqrt((unknown_points[:, -1] - np.array(kriging_preds))**2))
# Comparison
for pw in IDW_POWERS:
print(f'Root Mean Squared Error of prediction with IDW of power {pw} is {idw_rmse[pw]:.4f}')
print(f'Root Mean Squared Error of prediction with Kriging is {kriging_rmse:.4f}')
```
Your results may be different but in the most cases Kriging will be better than IDW. What's even more important is the fact that for the single data source with low number of samples we don't have opportunity to perform validation step and we're not able to guess how big should be the power parameter. With Kriging we model variogram and _voila!_ - model works.
---
| github_jupyter |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-59152712-8');
</script>
# `interp_arbgrid_MO_ETK`: An Einstein Toolkit module for interpolation to arbitrary grids, at multiple interpolation orders, in Cartesian basis.
## (Includes notes on transformations to other coordinate bases.)
## Author: Zach Etienne
### Formatting improvements courtesy Brandon Clark
## This module is designed to interpolate arbitrary quantities on [Einstein Toolkit](https://einsteintoolkit.org/) Adaptive-Mesh Refinement (AMR) grids (using the [Carpet](https://carpetcode.org/) AMR infrastructure) to numerical grids with arbitrary sampling.
**Validation Status:** <font color='red'><b> In progress</b></font>
**Validation Notes:** This module is currently undergoing validation testing.
## Introduction:
Given some set of $N$ quantities $\mathbf{Q}=\{Q_0,Q_1,Q_2,...,Q_{N-2},Q_{N-1}\}$, this module performs the following for each $Q_i$:
1. Evaluate $Q_i$ at all gridpoints that are not ghost zones. Sometimes $Q_i$ is computed using finite difference derivatives, so this is necessary.
1. Call upon Carpet's interpolation and interprocessor synchronization functions to fill in $Q_i$ at all ghost zones, *except* at the outer boundary. We do not generally trust $Q_i$ at the outer boundary due to errors associated with the approximate outer boundary conditions.
1. At this point, $Q_i$ is set at all gridpoints except ghost zones at the outer boundary. Interpolate $Q_i$ to the desired output grids, **maintaining the Cartesian basis for all vectors and tensors**, and append the result to a file.
This tutorial notebook takes a three-part structure. First, all the needed core Einstein Toolkit (ETK) C routines for interpolation are presented. Second, NRPy+ is used to output gridfunctions needed on the output grids. Third, the needed files for interfacing this module with the rest of the Einstein Toolkit (ccl files) are specified.
<a id='toc'></a>
# Table of Contents:
$$\label{toc}$$
1. [Step 1](#etkmodule): Setting up the Core C Code for the Einstein Toolkit Module
1. [Step 1.a](#etk_interp): Low-Level Einstein Toolkit Interpolation Function
1. [Step 1.b](#fileformat): Outputting to File
1. [Step 1.c](#maininterpolator): The Main Interpolator Driver Function
1. [Step 1.d](#standalonerandompoints): Standalone C code to output random points data
1. [Step 2](#nrpy): Using NRPy+ to Generate C Code for Needed Gridfunctions
1. [Step 2.a](#nrpy_list_of_funcs_interp): Set up NRPy-based `list_of_functions_to_interpolate.h`
1. [Step 2.a.i](#nrpygrmhd): All GRMHD quantities, except vector potential $A_i$
1. [Step 2.a.ii](#unstaggera): Unstagger $A_i$ and add to "list of functions to interpolate"
1. [Step 2.a.iii](#nrpy4metric): Compute all 10 components of the 4-metric $g_{\mu\nu}$
1. [Step 2.a.iv](#nrpy4christoffels_cartesian):Compute all 40 4-Christoffels $\Gamma^{\mu}_{\nu\delta}$
1. [Step 2.a.v](#nrpy4christoffels_spherical): Notes on computing all 40 4-Christoffels $\Gamma^{\mu}_{\nu\delta}$ in the Spherical basis
1. [Step 2.a.vi](#nrpybasisxform): Notes on basis transforming all Cartesian basis quantities to spherical
1. [Step 2.a.vii](#psi4andfriends): Output Weyl scalars $\psi_0$ through $\psi_4$, as well as Weyl invariants $J$ and $I$, from the `WeylScal4` ETK thorn
1. [Step 2.b](#nrpy_c_calling_function): C code calling function for the NRPy+ C output
1. [Step 2.c](#nrpygetgfname): The `get_gf_name()` function
1. [Step 2.d](#nrpy_interp_counter): C Code for Initializing and incrementing `InterpCounter`
1. [Step 2.e](#validationagainstfm): Validation of interpolated data against exact Fishbone-Moncrief data
1. [Step 3](#cclfiles): Interfacing with the rest of the Einstein Toolkit; Setting up CCL files
1. [Step 3.a](#makecodedefn): `make.code.defn`
1. [Step 3.b](#interfaceccl): `interface.ccl`
1. [Step 3.c](#paramccl): `param.ccl`
1. [Step 3.d](#scheduleccl): `schedule.ccl`
1. [Step 4](#readingoutputfile): Python Script for Reading the Output File
1. [Step 5](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file
<a id='etkmodule'></a>
# Step 1: Setting up the Core C Code for the Einstein Toolkit Module \[Back to [top](#toc)\]
$$\label{etkmodule}$$
First we set up the output directories for the ETK module:
```
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
import shutil, os, sys, time # Standard Python modules for multiplatform OS-level functions, benchmarking
# Create C code output directory:
Ccodesdir = "interp_arbgrid_MO_ETK"
# First remove C code output directory and all subdirectories if they exist
# Courtesy https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty
shutil.rmtree(Ccodesdir, ignore_errors=True)
# Then create a fresh directory
cmd.mkdir(Ccodesdir)
cmd.mkdir(os.path.join(Ccodesdir,"src/"))
cmd.mkdir(os.path.join(Ccodesdir,"src","standalone/"))
```
<a id='etk_interp'></a>
## Step 1.a: Low-Level ETK Interpolation Function \[Back to [top](#toc)\]
$$\label{etk_interp}$$
We start by writing the low-level interpolation function **`Interpolate_to_dest_grid()`**, which to file.
**`Interpolate_to_dest_grid()`** takes as input
* **cctkGH**: Information about the underlying Cactus/Carpet grid hierarchy.
* **interp_num_points**: Number of destination interpolation points
* **point_x_temp, point_y_temp, point_z_temp**: Cartesian $(x,y,z)$ location for each of the **interp_num_points** interpolation points.
* **input_array_names[1]**: List of input gridfunction names to interpolate. We will do this only one gridfunction at a time, for gridfunction $Q_i$, as described above.
**`Interpolate_to_dest_grid()`** outputs:
* **output_f[1]**: The gridfunction **input_array_names[1]** interpolated to the set of **interp_num_points** specified in the input.
```
%%writefile $Ccodesdir/src/Interpolate_to_dest_grid.h
void Interpolate_to_dest_grid(const cGH *cctkGH,const CCTK_INT interp_num_points, const CCTK_INT interp_order,
const CCTK_REAL *point_x_temp,const CCTK_REAL *point_y_temp,const CCTK_REAL *point_z_temp,
const CCTK_STRING input_array_names[1], CCTK_REAL *output_f[1]) {
DECLARE_CCTK_PARAMETERS;
CCTK_INT ierr;
const CCTK_INT NUM_INPUT_ARRAYS=1;
const CCTK_INT NUM_OUTPUT_ARRAYS=1;
CCTK_STRING coord_system = "cart3d";
// Set up handles
const CCTK_INT coord_system_handle = CCTK_CoordSystemHandle(coord_system);
if (coord_system_handle < 0) {
CCTK_VWarn(0, __LINE__, __FILE__, CCTK_THORNSTRING,
"can't get coordinate system handle for coordinate system \"%s\"!",
coord_system);
}
const CCTK_INT operator_handle = CCTK_InterpHandle(interpolator_name);
if (operator_handle < 0)
CCTK_VWarn(0, __LINE__, __FILE__, CCTK_THORNSTRING,
"couldn't find interpolator \"%s\"!",
interpolator_name);
char interp_order_string[10];
snprintf(interp_order_string, 10, "order=%d", interp_order);
CCTK_STRING interpolator_pars = interp_order_string;
CCTK_INT param_table_handle = Util_TableCreateFromString(interpolator_pars);
if (param_table_handle < 0) {
CCTK_VWarn(0, __LINE__, __FILE__, CCTK_THORNSTRING,
"bad interpolator parameter(s) \"%s\"!",
interpolator_pars);
}
CCTK_INT operand_indices[NUM_INPUT_ARRAYS]; //NUM_OUTPUT_ARRAYS + MAX_NUMBER_EXTRAS];
for(int i = 0 ; i < NUM_INPUT_ARRAYS ; i++) {
operand_indices[i] = i;
}
Util_TableSetIntArray(param_table_handle, NUM_OUTPUT_ARRAYS,
operand_indices, "operand_indices");
CCTK_INT operation_codes[NUM_INPUT_ARRAYS];
for(int i = 0 ; i < NUM_INPUT_ARRAYS ; i++) {
operation_codes[i] = 0;
}
Util_TableSetIntArray(param_table_handle, NUM_OUTPUT_ARRAYS,
operation_codes, "operation_codes");
const void* interp_coords[3]
= { (const void *) point_x_temp,
(const void *) point_y_temp,
(const void *) point_z_temp };
CCTK_INT input_array_indices[NUM_INPUT_ARRAYS];
for(int i = 0 ; i < NUM_INPUT_ARRAYS ; i++) {
input_array_indices[i] = CCTK_VarIndex(input_array_names[i]);
if(input_array_indices[i] < 0) {
CCTK_VWarn(0, __LINE__, __FILE__, CCTK_THORNSTRING,
"COULD NOT FIND VARIABLE '%s'.",
input_array_names[i]);
exit(1);
}
}
CCTK_INT output_array_types[NUM_OUTPUT_ARRAYS];
for(int i = 0 ; i < NUM_OUTPUT_ARRAYS ; i++) {
output_array_types[i] = CCTK_VARIABLE_REAL;
}
void * output_arrays[NUM_OUTPUT_ARRAYS]
= { (void *) output_f[0] };
// actual interpolation call
ierr = CCTK_InterpGridArrays(cctkGH,
3, // number of dimensions
operator_handle,
param_table_handle,
coord_system_handle,
interp_num_points,
CCTK_VARIABLE_REAL,
interp_coords,
NUM_INPUT_ARRAYS, // Number of input arrays
input_array_indices,
NUM_OUTPUT_ARRAYS, // Number of output arrays
output_array_types,
output_arrays);
if (ierr<0) {
CCTK_WARN(1,"interpolation screwed up");
Util_TableDestroy(param_table_handle);
exit(1);
}
ierr = Util_TableDestroy(param_table_handle);
if (ierr != 0) {
CCTK_WARN(1,"Could not destroy table");
exit(1);
}
}
%%writefile $Ccodesdir/src/interpolate_set_of_points_in_file.h
#define ALLOCATE_2D_GENERIC(type,array,ni,nj) type **array=(type **)malloc(ni * sizeof(type *)); \
for(int cc = 0; cc < ni; cc++) array[cc]=(type * )malloc(nj * sizeof(type));
#define FREE_2D_GENERIC(type,array,ni,nj) for(int cc = 0; cc < ni;cc++) free((void *)array[cc]); \
/**/ free((void *)array);
#include "output_to_file.h"
// Calls the above function and output_to_file().
void interpolate_set_of_points_in_file(CCTK_ARGUMENTS,char filename_basename[100],char gf_name[100],int num_interp_orders,int *interp_orders_list) {
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS; // Needed for x_center,y_center,z_center
// Set up output array:
// The name of the input gridfunction is always "interp_arbgrid_MO_ETK::interped_gf":
const CCTK_STRING input_array_names[1] = { "interp_arbgrid_MO_ETK::interped_gf" };
CCTK_REAL *points_dest_grid_x,*points_dest_grid_y,*points_dest_grid_z; // Coordinates of points of destination grid
CCTK_REAL **output_f; // Output to be written to dataset, will be filled with NaNs at points out of bounds
// For benchmarking purposes:
time_t start_timer,end_timer;
time(&start_timer); // Resolution of one second...
CCTK_REAL time_in_seconds;
int num_dest_grid_points;
if(CCTK_MyProc(cctkGH)==0) {
// Step 1: Read list of desired interpolation destination points from file:
// Step 1.a: Read integer at top of file indicating number of points.
int num_dest_grid_pointsx,num_dest_grid_pointsy,num_dest_grid_pointsz;
char pointsx_filename[100]; snprintf(pointsx_filename,100,"%s-x.dat",filename_basename);
printf("Reading list of x data points from file %s...\n",pointsx_filename);
FILE *pointsx_file = fopen(pointsx_filename, "rb");
if(!pointsx_file) { printf("Error: Unable to open %s\n",pointsx_filename); exit(1); }
fread(&num_dest_grid_pointsx, sizeof(int), 1, pointsx_file);
char pointsy_filename[100]; snprintf(pointsy_filename,100,"%s-y.dat",filename_basename);
printf("Reading list of y data points from file %s...\n",pointsy_filename);
FILE *pointsy_file = fopen(pointsy_filename, "rb");
if(!pointsy_file) { printf("Error: Unable to open %s\n",pointsy_filename); exit(1); }
fread(&num_dest_grid_pointsy, sizeof(int), 1, pointsy_file);
char pointsz_filename[100]; snprintf(pointsz_filename,100,"%s-z.dat",filename_basename);
printf("Reading list of z data points from file %s...\n",pointsz_filename);
FILE *pointsz_file = fopen(pointsz_filename, "rb");
if(!pointsz_file) { printf("Error: Unable to open %s\n",pointsz_filename); exit(1); }
fread(&num_dest_grid_pointsz, sizeof(int), 1, pointsz_file);
// Step 1.a.i: Sanity check: make sure that num_dest_grid_pointsx == num_dest_grid_pointsy == num_dest_grid_pointsz
if(num_dest_grid_pointsx != num_dest_grid_pointsy || num_dest_grid_pointsy != num_dest_grid_pointsz) {
printf("Error: Failed sanity check. Number of interpolation points different in %s-{x,y,z}.dat data files!\n",
filename_basename);
exit(1);
} else {
// If sanity check passes:
num_dest_grid_points = num_dest_grid_pointsx;
} // END sanity check
// Step 1.b: Allocate memory for destination grids and interpolation output
if(num_dest_grid_points <= 0 || num_dest_grid_points > 2000000000) {
printf("Error: Failed sanity check. Number of interpolation points was found to be: %d",num_dest_grid_points);
exit(1);
} // END sanity check
points_dest_grid_x = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
points_dest_grid_y = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
points_dest_grid_z = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
output_f = (CCTK_REAL **)malloc(1 * sizeof(CCTK_REAL *));
for(int cc = 0; cc < 1; cc++) output_f[cc]=(CCTK_REAL *)malloc(num_dest_grid_points * sizeof(CCTK_REAL));
// Step 1.c: Store cell-centered points to allocated memory.
fread(points_dest_grid_x, sizeof(CCTK_REAL), num_dest_grid_points, pointsx_file);
fread(points_dest_grid_y, sizeof(CCTK_REAL), num_dest_grid_points, pointsy_file);
fread(points_dest_grid_z, sizeof(CCTK_REAL), num_dest_grid_points, pointsz_file);
int magic_numberx; fread(&magic_numberx, sizeof(int), 1, pointsx_file);
int magic_numbery; fread(&magic_numbery, sizeof(int), 1, pointsy_file);
int magic_numberz; fread(&magic_numberz, sizeof(int), 1, pointsz_file);
int correct_magicnum = -349289480;
if(magic_numberx != correct_magicnum || magic_numbery != correct_magicnum || magic_numberz != correct_magicnum) {
printf("Error: Failed sanity check. Magic numbers in x,y,z data files were: %d %d %d, respectively, but should have been: %d",
magic_numberx,magic_numbery,magic_numberz,correct_magicnum);
exit(1);
}
fclose(pointsx_file);
fclose(pointsy_file);
fclose(pointsz_file);
time(&end_timer); time_in_seconds = difftime(end_timer,start_timer); time(&start_timer);
printf("Finished in %e seconds.\n",time_in_seconds);
// Step 1.d: Apply offset to x,y,z coordinates to ensure they are centered on (x_center,y_center,z_center)
// For example, if a black hole is situated at (x,y,z) = (1,2,3), then we set
// (x_center,y_center,z_center) = (1,2,3) in our ETK parameter file (i.e., with extension .par)
// and if we desire a point at (x_dest,y_dest,z_dest) = (0,0,0) on the *destination* grid,
// this will correspond to point (x_src,y_src,z_src) = (1,2,3) = (x_center,y_center,z_center)
// on the source grid. Thus the translation between source and destination grids is given by
// (x_src,y_src,z_src) = (x_dest+x_center, y_dest+y_center, z_dest+z_center),
// where (x_src,y_src,z_src) = (points_dest_grid_x[i],points_dest_grid_y[i],points_dest_grid_z[i]) for point i.
for(int point=0;point<num_dest_grid_points;point++) {
points_dest_grid_x[point] += x_center;
points_dest_grid_y[point] += y_center;
points_dest_grid_z[point] += z_center;
}
// Step 1.e: Look for the points that are out of bounds and set their coordinates to out_of_bounds_interp_xyz.
// At the end, we will replace the interpolation output at these points with NaNs.
printf("Looking for points that are out of bounds.\n");
int num_dest_grid_interp_points = 0;
for(int i=0;i<num_dest_grid_points;i++){
if(fabs(points_dest_grid_x[i])>out_of_bounds_interp_xyz ||
fabs(points_dest_grid_y[i])>out_of_bounds_interp_xyz ||
fabs(points_dest_grid_z[i])>out_of_bounds_interp_xyz) {
points_dest_grid_x[i] = out_of_bounds_interp_xyz;
points_dest_grid_y[i] = out_of_bounds_interp_xyz;
points_dest_grid_z[i] = out_of_bounds_interp_xyz;
num_dest_grid_interp_points++;
}
}
time(&end_timer); time_in_seconds = difftime(end_timer,start_timer); time(&start_timer);
printf("Finished in %e seconds, found %i points out of bounds.\n", time_in_seconds, (num_dest_grid_points-num_dest_grid_interp_points));
} // END if(CCTK_MyProc(cctkGH)==0)
// Step 1.f: Looping over interp order as desired, interpolate to destination points & output to file
for(int order_i=0; order_i<num_interp_orders; order_i++) {
int order = interp_orders_list[order_i];
printf("Interpolating\033[1m %s \033[0m... using interpolation order = %d\n",gf_name,order);
if(CCTK_MyProc(cctkGH)==0) {
Interpolate_to_dest_grid(cctkGH, num_dest_grid_points, order,
points_dest_grid_x,points_dest_grid_y,points_dest_grid_z, input_array_names, output_f);
// Step 1.f.i: Sanity check -- check for bad point:
#pragma omp parallel for
for(int i=0;i<num_dest_grid_points;i++) {
if(output_f[0][i] > 1e20) {
printf("BAD POINT: %s %d %e %e %e %e\n",gf_name,i,points_dest_grid_x[i],points_dest_grid_y[i],points_dest_grid_z[i], output_f[0][i]);
exit(1);
}
}
time(&end_timer); time_in_seconds = difftime(end_timer,start_timer); time(&start_timer);
printf("Finished in %d seconds. Next: Filling cells out of bounds with NaNs\n",time_in_seconds);
// Step 1.f.ii: Filling cells out of bounds with NaNs:
for(int i=0;i<num_dest_grid_points;i++){
if(fabs(points_dest_grid_x[i])==out_of_bounds_interp_xyz ||
fabs(points_dest_grid_y[i])==out_of_bounds_interp_xyz ||
fabs(points_dest_grid_z[i])==out_of_bounds_interp_xyz) {
output_f[0][i] = 0.0 / 0.0; // ie NaN
}
}
time(&end_timer); time_in_seconds = difftime(end_timer,start_timer); time(&start_timer);
printf("Finished in %e seconds. Next: Interpolate_to_dest_grid_main_function(): Outputting to file at iteration %d\n",time_in_seconds,cctk_iteration);
output_to_file(CCTK_PASS_CTOC,gf_name,&order,&num_dest_grid_points,output_f);
time(&end_timer); time_in_seconds = difftime(end_timer,start_timer); time(&start_timer);
printf("Finished in %e seconds. Interpolate_to_dest_grid_main_function(): Finished output to file at iteration %d\n",time_in_seconds,cctk_iteration);
} else {
// On all MPI processes that are nonzero, only call the interpolation function
// to ensure the MPI calls from the actual interpolation (driven by proc==0) are seen.
// Setting num_dest_grid_points to zero results in a segfault on certain (ahem, Frontera)
// systems. So we set num_dest_grid_points = 1 and interpolate to the origin
// only for MPI processes that are nonzero, leaving the heavy lifting to MPI process 0.
num_dest_grid_points = 1;
points_dest_grid_x = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
points_dest_grid_y = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
points_dest_grid_z = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_dest_grid_points);
output_f = (CCTK_REAL **)malloc(sizeof(CCTK_REAL *)*num_dest_grid_points);
for(int cc = 0; cc < 1; cc++) output_f[cc]=(CCTK_REAL *)malloc(num_dest_grid_points * sizeof(CCTK_REAL));
points_dest_grid_x[0] = points_dest_grid_y[0] = points_dest_grid_z[0] = 0.0;
Interpolate_to_dest_grid(cctkGH, num_dest_grid_points, order,
points_dest_grid_x,points_dest_grid_y,points_dest_grid_z, input_array_names, output_f);
output_f[0][0] = 0.0;
} // END if(CCTK_MyProc(cctkGH)==0)
} // END for(int order_i=0; order_i<num_interp_orders; order_i++)
// Step 1.g: Free memory for destination grids and interpolation output
free(points_dest_grid_x);
free(points_dest_grid_y);
free(points_dest_grid_z);
FREE_2D_GENERIC(CCTK_REAL,output_f,1,num_dest_grid_points);
} // END function
#undef ALLOCATE_2D_GENERIC
#undef FREE_2D_GENERIC
```
<a id='fileformat'></a>
## Step 1.b: Outputting to File (File format notes) \[Back to [top](#toc)\]
$$\label{fileformat}$$
Since they take almost no space relative to the data chunks, we attach the entire metadata to each interpolated function that is output:
```
%%writefile $Ccodesdir/src/output_to_file.h
#include "define_NumInterpFunctions.h"
// output_to_file() starts order and InterpCounter both with the value 1
void output_to_file(CCTK_ARGUMENTS,char gf_name[100],int *order,int *num_interp_points,CCTK_REAL *output_f[1]) {
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
char filename[100];
sprintf (filename, "%s/interp_dest_grids_MO.dat", out_dir);
FILE *file;
if(*InterpCounter == 1 && *order==1) {
file = fopen (filename,"w");
printf("WRITING to file %s\n",filename);
} else {
file = fopen (filename,"a+");
printf("Appending to file %s\n",filename);
}
if (! file) {
CCTK_VWarn (1, __LINE__, __FILE__, CCTK_THORNSTRING,
"interp_dest_grid__ET_thorn: Cannot open output file '%s'", filename);
exit(1);
}
fwrite(gf_name, 100*sizeof(char), 1, file);
fwrite(order, sizeof(CCTK_INT), 1, file);
fwrite(num_interp_points, sizeof(int),1,file);
CCTK_REAL magic_number = 1.130814081305130e-21;
fwrite(&magic_number, sizeof(CCTK_REAL), 1, file);
fwrite(&cctk_iteration, sizeof(CCTK_INT), 1, file);
fwrite(&cctk_time, sizeof(CCTK_REAL), 1, file);
for(CCTK_INT i=0;i<1;i++) {
fwrite(output_f[i], sizeof(CCTK_REAL)*(*num_interp_points), 1, file);
}
fclose(file);
}
```
<a id='maininterpolator'></a>
## Step 1.c: The Main Interpolation Driver Function \[Back to [top](#toc)\]
$$\label{maininterpolator}$$
The **`Interpolate_to_dest_grid_main_function()`** function calls the above functions as follows:
1. **`Interpolate_to_dest_grid()`** ([Above section](#etk_interp)): Interpolates to destination grid and calls
1. **`output_to_file()`** ([Above section](#fileformat)): Outputs information about interpolation, as well as interpolation result, to file
```
%%writefile $Ccodesdir/src/main_function.cc
// Include needed ETK & C library header files:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h> // for benchmarking
// Needed for dealing with Cactus/ETK infrastructure
#include "cctk.h"
#include "cctk_Arguments.h"
#include "cctk_Parameters.h"
// Needed for low-level interpolation functions
#include "util_Table.h"
#include "util_String.h"
// Include locally-defined C++ functions:
#include "Interpolate_to_dest_grid.h"
#include "get_gf_name.h"
#include "interpolate_set_of_points_in_file.h"
void Interpolate_to_dest_grid_main_function(CCTK_ARGUMENTS) {
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
// Perform interpolation only at iteration == interp_out_iteration:
if(cctk_iteration != interp_out_iteration) return;
// Perform interpolation!
// Process zero (CCTK_MyProc(cctkGH)==0) is responsible for directing the interpolation.
// All other processes must see the cctk_InterpGridArrays() within Interpolate_to_dest_grid(),
// so that the MPI calls work properly, but these nonzero processes can call
// Interpolate_to_dest_grid() with number of interpolated points set to zero, and
// without needing a malloc().
char gf_name[100]; get_gf_name(*InterpCounter,gf_name);
char filename_basename[100];
// The following "if" statement is destination-code dependent.
// In our case, since we are interpolating variables for harm3d,
// we interpolate the vector potential to the corners of each cell.
// Every other quantity is interpolated to the center of each cell.
if(strncmp(gf_name,"Unstaggered",11) == 0){
sprintf(filename_basename,"corner_points");
}
else{
sprintf(filename_basename,"cell_centered_points");
}
int num_interp_orders,*interp_orders_list;
// 4-metric & 4-Christoffels only output interpolation order==4.
if(strncmp(gf_name,"4-",2) == 0) {
num_interp_orders = 1;
interp_orders_list = (int *)malloc(sizeof(int)*num_interp_orders);
interp_orders_list[0] = 4;
} else {
num_interp_orders = 3;
interp_orders_list = (int *)malloc(sizeof(int)*num_interp_orders);
int count = 0; for(int order=1;order<=4;order*=2) { interp_orders_list[count] = order; count++; }
}
interpolate_set_of_points_in_file(CCTK_PASS_CTOC,filename_basename,gf_name,num_interp_orders,interp_orders_list);
free(interp_orders_list);
// Now perform interpolation of 4-metric on
// faces (i-1/2,j,k), (i,j-1/2,k), (i,j,k-1/2) and corners (i-1/2,j-1/2,k-1/2)
if(strncmp(gf_name,"4-metric",8) == 0) {
num_interp_orders = 1;
interp_orders_list = (int *)malloc(sizeof(int)*num_interp_orders);
interp_orders_list[0] = 4;
char gf_name_new[100];
sprintf(filename_basename,"faceim_points");
snprintf(gf_name_new,100,"faceim (i-1/2,j,k): %s",gf_name);
interpolate_set_of_points_in_file(CCTK_PASS_CTOC,filename_basename,gf_name_new,num_interp_orders,interp_orders_list);
sprintf(filename_basename,"facejm_points");
snprintf(gf_name_new,100,"facejm (i,j-1/2,k): %s",gf_name);
interpolate_set_of_points_in_file(CCTK_PASS_CTOC,filename_basename,gf_name_new,num_interp_orders,interp_orders_list);
sprintf(filename_basename,"facekm_points");
snprintf(gf_name_new,100,"facekm (i,j,k-1/2): %s",gf_name);
interpolate_set_of_points_in_file(CCTK_PASS_CTOC,filename_basename,gf_name_new,num_interp_orders,interp_orders_list);
sprintf(filename_basename,"corner_points");
snprintf(gf_name_new,100,"cornr (i-1/2,j-1/2,k-1/2): %s",gf_name);
interpolate_set_of_points_in_file(CCTK_PASS_CTOC,filename_basename,gf_name_new,num_interp_orders,interp_orders_list);
} // END if(strncmp(gf_name,"4-metric",8) == 0)
} // END function
```
<a id='standalonerandompoints'></a>
## Step 1.d: Standalone C code to output random points data \[Back to [top](#toc)\]
$$\label{standalonerandompoints}$$
```
%%writefile $Ccodesdir/src/standalone/standalone_C_code_genpoints.c
// Part P1: Import needed header files
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
const double xyzmin = -1000.0;
const double xyzmax = 1000.0;
void write_to_xyz_files(int num_interp_points, char filename_basename[100]) {
char filenamex[100],filenamey[100],filenamez[100];
snprintf(filenamex,100,"%s-x.dat",filename_basename);
snprintf(filenamey,100,"%s-y.dat",filename_basename);
snprintf(filenamez,100,"%s-z.dat",filename_basename);
FILE *filex = fopen(filenamex,"wb");
FILE *filey = fopen(filenamey,"wb");
FILE *filez = fopen(filenamez,"wb");
// Write file headers:
fwrite(&num_interp_points, sizeof(int), 1, filex);
fwrite(&num_interp_points, sizeof(int), 1, filey);
fwrite(&num_interp_points, sizeof(int), 1, filez);
// Write guts of file:
for(int ii=0;ii<num_interp_points;ii++) {
double rngx = xyzmin + (xyzmax - xyzmin)*drand48(); // drand48() returns between 0.0 & 1.0
double rngy = xyzmin + (xyzmax - xyzmin)*drand48();
double rngz = xyzmin + (xyzmax - xyzmin)*drand48();
fwrite(&rngx, sizeof(double), 1, filex);
fwrite(&rngy, sizeof(double), 1, filey);
fwrite(&rngz, sizeof(double), 1, filez);
}
// Write magic number as file footers:
int magic_number = -349289480;
fwrite(&magic_number, sizeof(int), 1, filex);
fwrite(&magic_number, sizeof(int), 1, filey);
fwrite(&magic_number, sizeof(int), 1, filez);
// Close files.
fclose(filex);
fclose(filey);
fclose(filez);
}
int main(int argc, const char *argv[]) {
// Step 0a: Read command-line input, error out if nonconformant
if(argc != 2 || atoi(argv[1]) < 1) {
printf("Error: Expected one command-line argument: ./standalone_C_code_genpoints [num_interp_points],\n");
exit(1);
}
const int num_interp_points = atoi(argv[1]);
char filename_basename[100];
sprintf(filename_basename,"cell_centered_points");
write_to_xyz_files(num_interp_points, filename_basename);
sprintf(filename_basename,"faceim_points");
write_to_xyz_files(num_interp_points, filename_basename);
sprintf(filename_basename,"facejm_points");
write_to_xyz_files(num_interp_points, filename_basename);
sprintf(filename_basename,"facekm_points");
write_to_xyz_files(num_interp_points, filename_basename);
sprintf(filename_basename,"corner_points");
write_to_xyz_files(num_interp_points, filename_basename);
return 0;
}
```
<a id='nrpy'></a>
# Step 2: Use NRPy+ C Output to Set All Output Gridfunctions \[Back to [top](#toc)\]
$$\label{nrpy}$$
```
# Step 1: Import needed NRPy+ parameters
import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import grid as gri # NRPy+: Functions having to do with numerical grids
import finite_difference as fin # NRPy+: Finite difference C code generation module
from outputC import lhrh # NRPy+: Core C code output module
import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends
import NRPy_param_funcs as par # NRPy+: Parameter interface
import loop as lp # NRPy+: Generate C code loops
par.set_parval_from_str("grid::GridFuncMemAccess","ETK")
from collections import namedtuple
gf_interp = namedtuple('gf_interp', 'gf_description')
gf_interp_list = []
gf_interp_list.append(gf_interp("dummy -- used because this is a 1-offset array"))
interped_gf = gri.register_gridfunctions("AUX","interped_gf")
def interp_fileout(which_InterpCounter, expression, filename):
kernel = fin.FD_outputC("returnstring",lhrh(lhs=gri.gfaccess("out_gfs","interped_gf"),rhs=expression),"outCverbose=False")
output_type="a"
if which_InterpCounter == 1:
# Write the file header, which includes #define's for GAMMA_SPEED_LIMIT and TINYDOUBLE:
with open(filename, "w") as file:
file.write("// Parameters needed to ensure velocity computations are robust:\n")
file.write("#define GAMMA_SPEED_LIMIT 20\n")
file.write("#define TINYDOUBLE 1e-100\n\n")
compute_xx0xx1xx2 = ""
if "SPHERICAL" in gf_interp_list[which_InterpCounter].gf_description:
compute_xx0xx1xx2 = """
// ONLY NEEDED/USED IF CONVERTING TO SPHERICAL BASIS:
const double Cartx = x[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)] - x_center;
const double Carty = y[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)] - y_center;
const double Cartz = z[CCTK_GFINDEX3D(cctkGH,i0,i1,i2)] - z_center;
const double xx0 = sqrt(Cartx*Cartx + Carty*Carty + Cartz*Cartz);
const double xx1 = acos(Cartz/xx0);
const double xx2 = atan2(Carty,Cartx);\n
"""
with open(filename, output_type) as file:
file.write("if(*InterpCounter == "+str(which_InterpCounter)+") {\n")
file.write(" // Interpolating: "+gf_interp_list[which_InterpCounter].gf_description+"\n")
file.write(lp.loop(["i2","i1","i0"],
["cctk_nghostzones[2]","cctk_nghostzones[1]","cctk_nghostzones[0]"],\
["cctk_lsh[2]-cctk_nghostzones[2]",
"cctk_lsh[1]-cctk_nghostzones[1]",
"cctk_lsh[0]-cctk_nghostzones[0]"],\
["1","1","1"],\
["#pragma omp parallel for","",""]," ",
compute_xx0xx1xx2+kernel))
file.write("}\n")
# If successful, return incremented which_InterpCounter:
return which_InterpCounter+1
```
<a id='nrpy_list_of_funcs_interp'></a>
## Step 2.a: Set up NRPy-based `list_of_functions_to_interpolate.h` \[Back to [top](#toc)\]
$$\label{nrpy_list_of_funcs_interp}$$
First specify NRPy+ output file and initialize `which_InterpCounter`, which keeps track of the number of interpolated functions on the grid
```
NRPyoutfilename = os.path.join(Ccodesdir,"src","list_of_functions_to_interpolate.h")
which_InterpCounter = 1
```
<a id='nrpygrmhd'></a>
### Step 2.a.i: GRMHD quantities \[Back to [top](#toc)\]
$$\label{nrpygrmhd}$$
These include
* $\rho_b$, the baryonic density (i.e., the HydroBase variable $\verb|rho|$)
* $P$, the total gas pressure (i.e., the HydroBase variable $\verb|press|$)
* $\Gamma v_{(n)}^i$, the Valencia 3-velocity times the Lorentz factor (i.e., the HydroBase 3-gridfuntion $\verb|vel|$, multiplied by the Lorentz factor). This definition of velocity has the advantage that after interpolation, it will not violate $u^\mu u_\mu = -1$. In terms of the IllinoisGRMHD 3-velocity $v^i = u^i / u^0$, the Valencia 3-velocity is given by (Eq. 11 of [Etienne *et al*](https://arxiv.org/pdf/1501.07276.pdf)):
$$
v_{(n)}^i = \frac{1}{\alpha} \left(v^i + \beta^i\right).
$$
Further, $\Gamma = \alpha u^0$ is given by (as shown [here](Tutorial-u0_smallb_Poynting-Cartesian.ipynb)):
$$
\Gamma = \alpha u^0 = \sqrt{\frac{1}{1 - \gamma_{ij}v^i_{(n)}v^j_{(n)}}}.
$$
Therefore, $\Gamma v_{(n)}^i$ is given by
$$
\Gamma v_{(n)}^i = \frac{1}{\alpha} \left(v^i + \beta^i\right) \sqrt{\frac{1}{1 - \gamma_{ij}v^i_{(n)}v^j_{(n)}}}.
$$
* $A_i$, the *unstaggered* magnetic vector potential.
* $B^i$, the *unstaggered* magnetic field vector (output only for validation purposes).
```
# INPUT GRIDFUNCTIONS: The AUX or EVOL designation is *not* used in diagnostic modules.
gammaDD = ixp.register_gridfunctions_for_single_rank2("AUX","gammaDD", "sym01")
alpha = gri.register_gridfunctions("AUX","alpha")
betaU = ixp.register_gridfunctions_for_single_rank1("AUX","betaU")
# Add a constant beta offset, to account for linear
# (i.e., constant velocity) coordinate drift.
# Note that beta_offsetU's are set in param.ccl.
# As beta_offsetU is constant in space, it has no
# impact on betaU_dD's.
beta_offsetU0,beta_offsetU1,beta_offsetU2 = par.Cparameters("REAL","modulenamedoesntmatter",
["beta_offsetU0","beta_offsetU1","beta_offsetU2"],
[0.0,0.0,0.0])
betaU[0] += beta_offsetU0
betaU[1] += beta_offsetU1
betaU[2] += beta_offsetU2
# Tensors are given in Cartesian basis:
# Derivatives of metric
gammaDD_dD = ixp.declarerank3("gammaDD_dD","sym01")
betaU_dD = ixp.declarerank2("betaU_dD","nosym")
alpha_dD = ixp.declarerank1("alpha_dD")
DIM=3
IGMvU = ixp.register_gridfunctions_for_single_rank1("AUX","IGMvU")
BU = ixp.register_gridfunctions_for_single_rank1("AUX","BU")
gf_interp_list.append(gf_interp("IGM density primitive"))
rho_b = gri.register_gridfunctions("AUX","rho_b")
interp_expr = rho_b
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
gf_interp_list.append(gf_interp("IGM pressure primitive"))
P = gri.register_gridfunctions("AUX","P")
interp_expr = P
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
Next we implement:
$$
v_{(n)}^i = \frac{1}{\alpha} \left(v^i + \beta^i\right),
$$
and
$$
\Gamma v_{(n)}^i = \sqrt{\frac{1}{1 - \gamma_{ij}v^i_{(n)}v^j_{(n)}}} v_{(n)}^i.
$$
We use expressions for $v_{(n)}^i$, $\Gamma v_{(n)}^i$, and $v^i$ as implemented [in the GRHD equations notebook](Tutorial-GRHD_Equations-Cartesian.ipynb#convertvtou) and corresponding [GRHD.equations Python module](../edit/GRHD/equations.py). These expressions enforce a speed limit on $\Gamma$ to ensure e.g., the denominator within the radical in the above expression for $\Gamma v_{(n)}^i$ is never negative, which would result in `NaN`s.
```
import GRHD.equations as Ge
Ge.u4U_in_terms_of_vU__rescale_vU_by_applying_speed_limit(alpha, betaU, gammaDD, IGMvU)
# ValenciavU = ixp.zerorank1()
# for i in range(DIM):
# ValenciavU[i] = 1/alpha * (IGMvU[i] + betaU[i])
# v_dot_v = sp.sympify(0)
# for i in range(DIM):
# for j in range(DIM):
# v_dot_v += gammaDD[i][j]*ValenciavU[i]*ValenciavU[j]
# u4Uzero = sp.sqrt(1/(1 - v_dot_v))/alpha # u^0 = LorentzGamma/alpha
u4Uzero = Ge.u4U_ito_vU[0]
gf_interp_list.append(gf_interp("u^0: zero (time) component of 4-velocity"))
interp_expr = u4Uzero
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
Gamma_times_ValenciavU = ixp.zerorank1()
Gamma = alpha*Ge.u4U_ito_vU[0]
ValenciavU = ixp.zerorank1()
for i in range(DIM):
ValenciavU[i] = (1/alpha * (Ge.rescaledvU[i] + betaU[i])) # simplify?
for i in range(DIM):
Gamma_times_ValenciavU[i] = Gamma*ValenciavU[i]
```
Next we'll basis transform $W^i = \Gamma v_{\rm n}^i$ from Cartesian to the spherical basis:
Within [`reference_metric.py`](../edit/reference_metric.py), the `compute_Jacobian_and_inverseJacobian_tofrom_Cartesian()` function defines Jacobians relative to the center of the source (reference metric) grid, at a point $x^j_{\rm src}=$(`xx0,xx1,xx2`)${}_{\rm src}$ on the source grid:
$$
{\rm Jac\_dUCart\_dDsrcUD[i][j]} = \frac{\partial x^i_{\rm Cart}}{\partial x^j_{\rm src}},
$$
via exact differentiation (courtesy SymPy), and the inverse Jacobian
$$
{\rm Jac\_dUsrc\_dDCartUD[i][j]} = \frac{\partial x^i_{\rm src}}{\partial x^j_{\rm Cart}},
$$
using NRPy+'s `generic_matrix_inverter3x3()` function.
In terms of these, the transformation of $W^i$ from Cartesian coordinates to `"reference_metric::CoordSystem=Spherical"`may be written:
\begin{align}
W^i_{\rm Sph} &= \frac{\partial x^i_{\rm Sph}}{\partial x^\ell_{\rm Cart}} W^\ell_{\rm Cart}
\end{align}
```
import reference_metric as rfm # NRPy+: Reference metric support
par.set_parval_from_str("reference_metric::CoordSystem","Spherical")
rfm.reference_metric()
# Step 2.a: Construct Jacobian & Inverse Jacobians:
Jac_dUCart_dDrfmUD,Jac_dUrfm_dDCartUD = rfm.compute_Jacobian_and_inverseJacobian_tofrom_Cartesian()
Sph_basis_Gamma_times_ValenciavU = ixp.zerorank1()
for i in range(DIM):
for l in range(DIM):
Sph_basis_Gamma_times_ValenciavU[i] += Jac_dUrfm_dDCartUD[i][l] * Gamma_times_ValenciavU[l]
for i in range(DIM):
gf_interp_list.append(gf_interp("*SPHERICAL BASIS* Lorentz factor, times Valencia vU"+str(i)))
interp_expr = Sph_basis_Gamma_times_ValenciavU[i]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
for i in range(DIM):
gf_interp_list.append(gf_interp("(speed-limited) Valencia 3-velocity vU"+str(i)))
interp_expr = ValenciavU[i]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
for i in range(DIM):
if i==0:
gf_interp_list.append(gf_interp("Local grid resolution dx=dy=dz"))
invdx0 = sp.symbols('invdx0', real=True)
interp_expr = 1/invdx0
else:
gf_interp_list.append(gf_interp("(speed-limited) IGM 3-velocity vU"+str(i)+" = u^i divided by u^0"))
interp_expr = Ge.u4U_ito_vU[i]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
# For testing:
# gf_interp_list.append(gf_interp("Lorentz factor"))
# interp_expr = v_dot_v
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
# for i in range(DIM):
# gf_interp_list.append(gf_interp("Valencia vU"+str(i)))
# interp_expr = Valenciav[i]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
for i in range(DIM):
gf_interp_list.append(gf_interp("IGM magnetic field component B"+str(i)))
interp_expr = BU[i]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
<a id='unstaggera'></a>
### Step 2.a.ii: Unstagger $A_i$ and add to "list of functions to interpolate" \[Back to [top](#toc)\]
$$\label{unstaggera}$$
First generate the C code needed to unstagger the A-fields.
```
%%writefile $Ccodesdir/src/unstagger_A_fields.cc
// Include needed ETK & C library header files:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Needed for dealing with Cactus/ETK infrastructure
#include "cctk.h"
#include "cctk_Arguments.h"
#include "cctk_Parameters.h"
void unstagger_A_fields(CCTK_ARGUMENTS) {
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
// Set Ai_unstaggered = Ai and exit the function if A fields are unstaggered already.
if(A_fields_are_staggered == 0) {
#pragma omp parallel for
for(int k=0;k<cctk_lsh[2];k++) for(int j=0;j<cctk_lsh[1];j++) for(int i=0;i<cctk_lsh[0];i++) {
int index=CCTK_GFINDEX3D(cctkGH,i,j,k);
Ax_unstaggered[index] = Ax[index];
Ay_unstaggered[index] = Ay[index];
Az_unstaggered[index] = Az[index];
}
return;
}
printf("Unstaggering A fields on grid with dx = %e!\n",CCTK_DELTA_SPACE(0));
// If A fields are staggered (IllinoisGRMHD-style), then unstagger them:
// First unstagger A_x, which is defined at (i, j+1/2, k+1/2). Unstaggering
// is as simple as A_x(i,j,k) = 1/4 * (A_x(i,j-1/2,k-1/2)+A_x(i,j-1/2,k+1/2)+A_x(i,j+1/2,k-1/2)+A_x(i,j+1/2,k+1/2))
#pragma omp parallel for
for(int k=1;k<cctk_lsh[2];k++) for(int j=1;j<cctk_lsh[1];j++) for(int i=0;i<cctk_lsh[0];i++) {
int index=CCTK_GFINDEX3D(cctkGH,i,j,k);
Ax_unstaggered[index] = 0.25*(Ax[CCTK_GFINDEX3D(cctkGH,i,j,k)] + Ax[CCTK_GFINDEX3D(cctkGH,i,j-1,k)] +
Ax[CCTK_GFINDEX3D(cctkGH,i,j-1,k-1)] + Ax[CCTK_GFINDEX3D(cctkGH,i,j,k-1)]);
}
#pragma omp parallel for
for(int k=1;k<cctk_lsh[2];k++) for(int j=0;j<cctk_lsh[1];j++) for(int i=1;i<cctk_lsh[0];i++) {
int index=CCTK_GFINDEX3D(cctkGH,i,j,k);
Ay_unstaggered[index] = 0.25*(Ay[CCTK_GFINDEX3D(cctkGH,i,j,k)] + Ay[CCTK_GFINDEX3D(cctkGH,i-1,j,k)] +
Ay[CCTK_GFINDEX3D(cctkGH,i-1,j,k-1)] + Ay[CCTK_GFINDEX3D(cctkGH,i,j,k-1)]);
}
#pragma omp parallel for
for(int k=0;k<cctk_lsh[2];k++) for(int j=1;j<cctk_lsh[1];j++) for(int i=1;i<cctk_lsh[0];i++) {
int index=CCTK_GFINDEX3D(cctkGH,i,j,k);
Az_unstaggered[index] = 0.25*(Az[CCTK_GFINDEX3D(cctkGH,i,j,k)] + Az[CCTK_GFINDEX3D(cctkGH,i-1,j,k)] +
Az[CCTK_GFINDEX3D(cctkGH,i-1,j-1,k)] + Az[CCTK_GFINDEX3D(cctkGH,i,j-1,k)]);
}
}
```
Next we instruct NRPy+ to interpolate the unstaggered gridfunctions.
```
Ax_unstaggered = gri.register_gridfunctions("AUX","Ax_unstaggered")
Ay_unstaggered = gri.register_gridfunctions("AUX","Ay_unstaggered")
Az_unstaggered = gri.register_gridfunctions("AUX","Az_unstaggered")
gf_interp_list.append(gf_interp("Unstaggered vector potential component Ax"))
interp_expr = Ax_unstaggered
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
gf_interp_list.append(gf_interp("Unstaggered vector potential component Ay"))
interp_expr = Ay_unstaggered
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
gf_interp_list.append(gf_interp("Unstaggered vector potential component Az"))
interp_expr = Az_unstaggered
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
<a id='nrpy4metric'></a>
### Step 2.a.iii: Compute all 10 components of the 4-metric $g_{\mu\nu}$ \[Back to [top](#toc)\]
$$\label{nrpy4metric}$$
We are given $\gamma_{ij}$, $\alpha$, and $\beta^i$ from ADMBase, and the 4-metric is given in terms of these quantities as
$$
g_{\mu\nu} = \begin{pmatrix}
-\alpha^2 + \beta^k \beta_k & \beta_i \\
\beta_j & \gamma_{ij}
\end{pmatrix}.
$$
```
# Eq. 2.121 in B&S
betaD = ixp.zerorank1()
for i in range(DIM):
for j in range(DIM):
betaD[i] += gammaDD[i][j]*betaU[j]
# Now compute the beta contraction.
beta2 = sp.sympify(0)
for i in range(DIM):
beta2 += betaU[i]*betaD[i]
# Eq. 2.122 in B&S
g4DD = ixp.zerorank2(DIM=4)
g4DD[0][0] = -alpha**2 + beta2
for i in range(DIM):
g4DD[i+1][0] = g4DD[0][i+1] = betaD[i]
for i in range(DIM):
for j in range(DIM):
g4DD[i+1][j+1] = gammaDD[i][j]
for mu in range(4):
for nu in range(mu,4):
gf_interp_list.append(gf_interp("4-metric component g4DD"+str(mu)+str(nu)))
interp_expr = g4DD[mu][nu]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
<a id='nrpy4christoffels_cartesian'></a>
### Step 2.a.iv: Compute all 40 4-Christoffels $\Gamma^{\mu}_{\nu\delta}$ in Cartesian coordinates \[Back to [top](#toc)\]
$$\label{nrpy4christoffels_cartesian}$$
$$
\Gamma^{\mu}_{\nu\delta} = \frac{1}{2} g^{\mu\eta} \left(g_{\eta\nu,\delta} + g_{\eta\delta,\nu} - g_{\nu\delta,\eta} \right)
$$
Recall that $g_{\mu\nu}$ is given from $\gamma_{ij}$, $\alpha$, and $\beta^i$ via
$$
g_{\mu\nu} = \begin{pmatrix}
-\alpha^2 + \beta^k \beta_k & \beta_i \\
\beta_j & \gamma_{ij}
\end{pmatrix}.
$$
The derivatives $g_{\mu\nu,\eta}$ are then computed in terms of finite-difference derivatives of the input ADM gridfunctions $\gamma_{ij}$, $\alpha$, and $\beta^i$, **assuming that the 4-metric is static, so that $\partial_t g_{\mu\nu}=0$ for all $\mu$ and $\nu$**.
To compute $g^{\mu\nu}$, we use the standard formula (Eq. 4.49 in [Gourgoulhon](https://arxiv.org/pdf/gr-qc/0703035.pdf)):
$$
g^{\mu\nu} = \begin{pmatrix}
-\frac{1}{\alpha^2} & \frac{\beta^i}{\alpha^2} \\
\frac{\beta^i}{\alpha^2} & \gamma^{ij} - \frac{\beta^i\beta^j}{\alpha^2}
\end{pmatrix},
$$
where $\gamma^{ij}$ is given by the inverse of $\gamma_{ij}$.
```
betaDdD = ixp.zerorank2()
for i in range(DIM):
for j in range(DIM):
for k in range(DIM):
# Recall that betaD[i] = gammaDD[i][j]*betaU[j] (Eq. 2.121 in B&S)
betaDdD[i][k] += gammaDD_dD[i][j][k]*betaU[j] + gammaDD[i][j]*betaU_dD[j][k]
# Eq. 2.122 in B&S
g4DDdD = ixp.zerorank3(DIM=4)
for i in range(DIM):
# Recall that g4DD[0][0] = -alpha^2 + betaU[i]*betaD[i]
g4DDdD[0][0][i+1] += -2*alpha*alpha_dD[i]
for j in range(DIM):
g4DDdD[0][0][i+1] += betaU_dD[j][i]*betaD[j] + betaU[j]*betaDdD[j][i]
for i in range(DIM):
for j in range(DIM):
# Recall that g4DD[i][0] = g4DD[0][i] = betaD[i]
g4DDdD[i+1][0][j+1] = g4DDdD[0][i+1][j+1] = betaDdD[i][j]
for i in range(DIM):
for j in range(DIM):
for k in range(DIM):
# Recall that g4DD[i][j] = gammaDD[i][j]
g4DDdD[i+1][j+1][k+1] = gammaDD_dD[i][j][k]
gammaUU, dummyDET = ixp.symm_matrix_inverter3x3(gammaDD)
g4UU = ixp.zerorank2(DIM=4)
g4UU[0][0] = -1 / alpha**2
for i in range(DIM):
g4UU[0][i+1] = g4UU[i+1][0] = betaU[i]/alpha**2
for i in range(DIM):
for j in range(DIM):
g4UU[i+1][j+1] = gammaUU[i][j] - betaU[i]*betaU[j]/alpha**2
```
Again, we are to compute:
$$
\Gamma^{\mu}_{\nu\delta} = \frac{1}{2} g^{\mu\eta} \left(g_{\eta\nu,\delta} + g_{\eta\delta,\nu} - g_{\nu\delta,\eta} \right)
$$
```
Gamma4UDD = ixp.zerorank3(DIM=4)
for mu in range(4):
for nu in range(4):
for delta in range(4):
for eta in range(4):
Gamma4UDD[mu][nu][delta] += sp.Rational(1,2)*g4UU[mu][eta]*\
(g4DDdD[eta][nu][delta] + g4DDdD[eta][delta][nu] - g4DDdD[nu][delta][eta])
# Now output the 4-Christoffels to file:
for mu in range(4):
for nu in range(4):
for delta in range(nu,4):
gf_interp_list.append(gf_interp("4-Christoffel GammaUDD"+str(mu)+str(nu)+str(delta)))
interp_expr = Gamma4UDD[mu][nu][delta]
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
<a id='nrpy4christoffels_spherical'></a>
### Step 2.a.v: Notes on computing all 40 4-Christoffels $\Gamma^{\mu}_{\nu\delta}$ in the Spherical basis \[Back to [top](#toc)\]
$$\label{nrpy4christoffels_spherical}$$
As explained in [Eq. 3.15 of Carroll's lecture notes on GR](https://ned.ipac.caltech.edu/level5/March01/Carroll3/Carroll3.html), while connection coefficients (a.k.a. Christoffel symbols) are not tensors, differences in connection coefficients are tensors.
Thus we may define
$$
\Delta^\mu_{\nu\delta} = \Gamma^\mu_{\nu\delta} - \hat{\Gamma}^\mu_{\nu\delta},
$$
where for example $\Gamma^\mu_{\nu\delta}$ is the connection related to the curved spacetime 4-metric in some basis and $\hat{\Gamma}^\mu_{\nu\delta}$ is the connection related to the flat spacetime 4-metric in the same basis.
We are given the 4-metric data in Cartesian coordinates, for which $\hat{\Gamma}^\mu_{\nu\delta}=0$. The basis transform to spherical coordinates is then straightforward:
\begin{align}
\Delta^\mu_{\text{Sph}\ \nu\delta} &= \Gamma^\mu_{\text{Sph}\ \nu\delta} - \hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta} \\
&= \frac{\partial x^\mu_{\rm Sph}}{\partial x^\alpha_{\rm Cart}}
\frac{\partial x^\beta_{\rm Cart}}{\partial x^\nu_{\rm Sph}}
\frac{\partial x^\gamma_{\rm Cart}}{\partial x^\delta_{\rm Sph}} \Delta^\alpha_{\text{Cart}\ \beta\gamma} \\
&= \frac{\partial x^\mu_{\rm Sph}}{\partial x^\alpha_{\rm Cart}}
\frac{\partial x^\beta_{\rm Cart}}{\partial x^\nu_{\rm Sph}}
\frac{\partial x^\gamma_{\rm Cart}}{\partial x^\delta_{\rm Sph}} \Gamma^\alpha_{\text{Cart}\ \beta\gamma} \\
\implies \Gamma^\mu_{\text{Sph}\ \nu\delta} &= \frac{\partial x^\mu_{\rm Sph}}{\partial x^\alpha_{\rm Cart}}
\frac{\partial x^\beta_{\rm Cart}}{\partial x^\nu_{\rm Sph}}
\frac{\partial x^\gamma_{\rm Cart}}{\partial x^\delta_{\rm Sph}} \Gamma^\alpha_{\text{Cart}\ \beta\gamma} +
\hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta}
\end{align}
**Define $\hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta}$.**
By definition,
$$
\hat{\Gamma}^{\mu}_{\nu\delta} = \frac{1}{2} \hat{g}^{\mu\eta} \left(\hat{g}_{\eta\nu,\delta} + \hat{g}_{\eta\delta,\nu} - \hat{g}_{\nu\delta,\eta} \right).
$$
In static spherical coordinates, $\hat{g}_{\nu\delta}$ is given by
$$
\hat{g}_{\mu\nu} = \begin{pmatrix}
-1 & 0 \\
0 & \hat{\gamma}_{ij}
\end{pmatrix},
$$
so the inverse is easy to compute:
$$
\hat{g}^{\mu\nu} = \begin{pmatrix}
-1 & 0 \\
0 & 1/\hat{\gamma}_{ij}
\end{pmatrix}.
$$
Here is the NRPy+ code implementation of $\hat{g}_{\mu\nu}$, $\hat{g}^{\mu\nu}$, and $\hat{g}_{\eta\nu,\delta}$:
```
# import reference_metric as rfm
# # Set the desired *output* coordinate system to Spherical:
# #par.set_parval_from_str("reference_metric::CoordSystem","NobleSphericalThetaOptionOne")
# par.set_parval_from_str("reference_metric::CoordSystem","Spherical")
# print("Calling reference_metric()...")
# rfm.reference_metric()
# print("Just finished calling reference_metric()...")
# g4hatDD = ixp.zerorank2(DIM=4)
# g4hatUU = ixp.zerorank2(DIM=4)
# g4hatDD[0][0] = sp.sympify(-1)
# g4hatUU[0][0] = sp.sympify(-1)
# for j in range(3):
# g4hatDD[j+1][j+1] = rfm.ghatDD[j][j]
# g4hatUU[j+1][j+1] = 1/rfm.ghatDD[j][j]
# g4hatDDdD = ixp.zerorank3(DIM=4)
# for eta in range(4):
# for nu in range(4):
# for j in range(3): # Time derivatives are all zero, so g4hatDDdD[eta][nu][0] = 0 (as initialized).
# g4hatDDdD[eta][nu][j+1] = sp.diff(g4hatDD[eta][nu],rfm.xx[j])
```
Next we compute the 4-Christoffels $\hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta}$.
```
# Gamma4hatSphUDD = ixp.zerorank3(DIM=4)
# for mu in range(4):
# for nu in range(4):
# for delta in range(4):
# for eta in range(4):
# Gamma4hatSphUDD[mu][nu][delta] += sp.Rational(1,2)*g4hatUU[mu][eta]* \
# ( g4hatDDdD[eta][nu][delta] + g4hatDDdD[eta][delta][nu] - g4hatDDdD[nu][delta][eta] )
# # Here are the results, cf. Eq 18 of https://arxiv.org/pdf/1211.6632.pdf
# sp.pretty_print(Gamma4hatSphUDD)
```
Finally, compute $\Gamma^\mu_{\text{Sph}\ \nu\delta}$. Recall from above that
\begin{align}
\Gamma^\mu_{\text{Sph}\ \nu\delta} &= \frac{\partial x^\mu_{\rm Sph}}{\partial x^\alpha_{\rm Cart}}
\frac{\partial x^\beta_{\rm Cart}}{\partial x^\nu_{\rm Sph}}
\frac{\partial x^\gamma_{\rm Cart}}{\partial x^\delta_{\rm Sph}} \Gamma^\alpha_{\text{Cart}\ \beta\gamma} +
\hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta}
\end{align}
<a id='nrpybasisxform'></a>
### Step 2.a.vi: Notes on basis transforming all Cartesian basis quantities to spherical \[Back to [top](#toc)\]
$$\label{nrpybasisxform}$$
All tensors and vectors are in the Cartesian coordinate basis $x^i_{\rm Cart} = (x,y,z)$, but we need them in the curvilinear coordinate basis $x^i_{\rm rfm}$=`(xx0,xx1,xx2)`=$(r,\theta,\phi)$ set by NRPy+'s `"reference_metric::CoordSystem"` variable (we'll set this parameter to `"Spherical"`).
Empirically speaking, it is usually easier to write `(x(xx0,xx1,xx2),y(xx0,xx1,xx2),z(xx0,xx1,xx2))` than the inverse, so we will compute the Jacobian matrix
$$
{\rm Jac\_dUSph\_dDrfmUD[i][j]} = \frac{\partial x^i_{\rm Cart}}{\partial x^j_{\rm rfm}},
$$
via exact differentiation (courtesy SymPy), and the inverse Jacobian
$$
{\rm Jac\_dUrfm\_dDSphUD[i][j]} = \frac{\partial x^i_{\rm rfm}}{\partial x^j_{\rm Cart}},
$$
using NRPy+'s `generic\_matrix\_inverter3x3()` function. In terms of these, the transformation of vectors and rank-2 fully covariant tensors from Cartesian to `"reference_metric::CoordSystem"` (Spherical) coordinates may be written:
\begin{align}
g^{\rm rfm}_{\mu\nu} &=
\frac{\partial x^{\alpha}_{\rm Cart}}{\partial x^{\mu}_{\rm rfm}}
\frac{\partial x^{\beta}_{\rm Cart}}{\partial x^{\nu}_{\rm rfm}} g^{\rm Cart}_{\alpha \beta} \\
\Gamma^\mu_{\text{Sph}\ \nu\delta} &= \frac{\partial x^\mu_{\rm Sph}}{\partial x^\alpha_{\rm Cart}}
\frac{\partial x^\beta_{\rm Cart}}{\partial x^\nu_{\rm Sph}}
\frac{\partial x^\gamma_{\rm Cart}}{\partial x^\delta_{\rm Sph}} \Gamma^\alpha_{\text{Cart}\ \beta\gamma} +
\hat{\Gamma}^\mu_{\text{Sph}\ \nu\delta}
\end{align}
```
# Jac_dUCart_dDrfmUD = ixp.zerorank2()
# for i in range(DIM):
# for j in range(DIM):
# Jac_dUCart_dDrfmUD[i][j] = sp.simplify(sp.diff(rfm.xx_to_Cart[i],rfm.xx[j]))
# Jac_dUrfm_dDCartUD, dummyDET = ixp.generic_matrix_inverter3x3(Jac_dUCart_dDrfmUD)
# Jac4_dUCart_dDrfmUD = ixp.zerorank2(DIM=4)
# Jac4_dUrfm_dDCartUD = ixp.zerorank2(DIM=4)
# for alp in range(4):
# for bet in range(4):
# if alp==0 or bet==0:
# Jac4_dUCart_dDrfmUD[alp][bet] = sp.sympify(1) # Time components unchanged
# Jac4_dUrfm_dDCartUD[alp][bet] = sp.sympify(1) # Time components unchanged
# else:
# Jac4_dUCart_dDrfmUD[alp][bet] = sp.simplify(Jac_dUCart_dDrfmUD[alp-1][bet-1])
# Jac4_dUrfm_dDCartUD[alp][bet] = sp.simplify(Jac_dUrfm_dDCartUD[alp-1][bet-1])
# Gamma4SphUDD = ixp.zerorank3(DIM=4)
# for mu in range(4):
# for nu in range(4):
# for delt in range(4):
# Gamma4SphUDD[mu][nu][delt] = Gamma4hatSphUDD[mu][nu][delt]
# for alp in range(4):
# for bet in range(4):
# for gam in range(4):
# Gamma4SphUDD[mu][nu][delt] += \
# Jac4_dUrfm_dDCartUD[mu][alp]*Jac4_dUCart_dDrfmUD[bet][nu]*Jac4_dUCart_dDrfmUD[gam][delt] * \
# Gamma4UDD[alp][bet][gam]
# # Now output the Spherical 4-Christoffels to file:
# for mu in range(4):
# for nu in range(4):
# for delt in range(nu,4):
# gf_interp_list.append(gf_interp("4-Christoffel component in SPHERICAL BASIS: GammaSphUDD"+str(mu)+str(nu)+str(delt)))
# interp_expr = Gamma4SphUDD[mu][nu][delt]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
Output the 4-metric in Spherical coordinates to file:
\begin{align}
g^{\rm rfm}_{\mu\nu} &=
\frac{\partial x^{\alpha}_{\rm Cart}}{\partial x^{\mu}_{\rm rfm}}
\frac{\partial x^{\beta}_{\rm Cart}}{\partial x^{\nu}_{\rm rfm}} g^{\rm Cart}_{\alpha \beta}
\end{align}
```
# g4SphDD = ixp.zerorank2(DIM=4)
# for mu in range(4):
# for nu in range(4):
# for alp in range(4):
# for bet in range(4):
# g4SphDD[mu][nu] += Jac4_dUCart_dDrfmUD[alp][mu]*Jac4_dUCart_dDrfmUD[bet][nu]*g4DD[alp][bet]
# for mu in range(4):
# for nu in range(mu,4):
# gf_interp_list.append(gf_interp("4-metric component in SPHERICAL BASIS: g4SphDD"+str(mu)+str(nu)))
# interp_expr = g4SphDD[mu][nu]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
Next output the various GRMHD 3-vectors in the Spherical basis
\begin{align}
v^i_{\rm Sph} &=
\frac{\partial x^{i}_{\rm Sph}}{\partial x^{j}_{\rm Cart}} v^j_{\rm Cart}
\end{align}
```
# IGMvSphU = ixp.zerorank1()
# ValenciavSphU = ixp.zerorank1()
# Gamma_times_ValenciavSphU = ixp.zerorank1()
# BSphU = ixp.zerorank1()
# for i in range(DIM):
# for j in range(DIM):
# IGMvSphU[i] += Jac_dUrfm_dDCartUD[i][j] * IGMvU[j]
# ValenciavSphU[i] += Jac_dUrfm_dDCartUD[i][j] * ValenciavU[j]
# Gamma_times_ValenciavSphU[i] += Jac_dUrfm_dDCartUD[i][j] * Gamma_times_ValenciavU[j]
# BSphU[i] += Jac_dUrfm_dDCartUD[i][j] * BU[j]
# for i in range(DIM):
# gf_interp_list.append(gf_interp("IGM 3-velocity vU"+str(i)+" = u^i/u^0 in SPHERICAL BASIS"))
# interp_expr = IGMvSphU[i]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
# for i in range(DIM):
# gf_interp_list.append(gf_interp("Valencia 3-velocity vU"+str(i)+" in SPHERICAL BASIS"))
# interp_expr = ValenciavSphU[i]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
# for i in range(DIM):
# gf_interp_list.append(gf_interp("Lorentz factor, times Valencia vU"+str(i)+" in SPHERICAL BASIS"))
# interp_expr = Gamma_times_ValenciavSphU[i]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
# for i in range(DIM):
# gf_interp_list.append(gf_interp("IGM magnetic field component B"+str(i)+" in SPHERICAL BASIS"))
# interp_expr = BSphU[i]
# which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
```
<a id='psi4andfriends'></a>
### Step 2.a.vii: ): Output Weyl scalars $\psi_0$ through $\psi_4$, as well as Weyl invariants $J$ and $I$, from the `WeylScal4` ETK thorn \[Back to [top](#toc)\]
$$\label{psi4andfriends}$$
```
Weylgfs = ["Psi0r","Psi0i","Psi1r","Psi1i","Psi2r","Psi2i","Psi3r","Psi3i","Psi4r","Psi4i",
"curvIr","curvIi","curvJr","curvJi"]
Psi0r,Psi0i,Psi1r,Psi1i,Psi2r,Psi2i,Psi3r,Psi3i,Psi4r,Psi4i,curvIr,curvIi,curvJr,curvJi = \
gri.register_gridfunctions("AUX",Weylgfs);
count = 0
for gf in [Psi0r,Psi0i,Psi1r,Psi1i,Psi2r,Psi2i,Psi3r,Psi3i,Psi4r,Psi4i,curvIr,curvIi,curvJr,curvJi]:
gf_interp_list.append(gf_interp("4-Weyl scalar or invariant "+Weylgfs[count]))
interp_expr = gf
which_InterpCounter = interp_fileout(which_InterpCounter,interp_expr,NRPyoutfilename)
count = count + 1
```
<a id='nrpy_c_calling_function'></a>
## Step 2.b: C code calling function for the NRPy+ C output \[Back to [top](#toc)\]
$$\label{nrpy_c_calling_function}$$
In the above blocks, we wrote and appended to a file `list_of_functions_to_interpolate.h`. Here we write the calling function for this C code.
```
%%writefile $Ccodesdir/src/construct_function_to_interpolate__store_to_interped_gf.cc
#include <stdio.h>
#include <stdlib.h>
#include "cctk.h"
#include "cctk_Arguments.h"
#include "cctk_Parameters.h"
// Set the gridfunction interped_gf, according to the interpolation counter variable interp_counter.
// For example, we might interpolate "IllinoisGRMHD::rho_b" if interp_counter==0. The following
// function takes care of these
void list_of_functions_to_interpolate(cGH *cctkGH,const CCTK_INT *cctk_lsh,const CCTK_INT *cctk_nghostzones,
const CCTK_REAL *x,const CCTK_REAL *y,const CCTK_REAL *z,
const CCTK_REAL invdx0,const CCTK_REAL invdx1,const CCTK_REAL invdx2,
const CCTK_INT *InterpCounter,
const CCTK_REAL *rho_bGF,const CCTK_REAL *PGF,
const CCTK_REAL *IGMvU0GF,const CCTK_REAL *IGMvU1GF,const CCTK_REAL *IGMvU2GF,
const CCTK_REAL *BU0GF,const CCTK_REAL *BU1GF,const CCTK_REAL *BU2GF,
const CCTK_REAL *gammaDD00GF,const CCTK_REAL *gammaDD01GF,const CCTK_REAL *gammaDD02GF,
const CCTK_REAL *gammaDD11GF,const CCTK_REAL *gammaDD12GF,const CCTK_REAL *gammaDD22GF,
const CCTK_REAL *betaU0GF,const CCTK_REAL *betaU1GF,const CCTK_REAL *betaU2GF,
const CCTK_REAL *alphaGF, CCTK_REAL *interped_gfGF,
CCTK_REAL *Ax_unstaggeredGF,CCTK_REAL *Ay_unstaggeredGF,CCTK_REAL *Az_unstaggeredGF,
const CCTK_REAL *Psi0rGF,const CCTK_REAL *Psi0iGF,const CCTK_REAL *Psi1rGF,const CCTK_REAL *Psi1iGF,
const CCTK_REAL *Psi2rGF,const CCTK_REAL *Psi2iGF,const CCTK_REAL *Psi3rGF,const CCTK_REAL *Psi3iGF,
const CCTK_REAL *Psi4rGF,const CCTK_REAL *Psi4iGF,
const CCTK_REAL *curvIrGF,const CCTK_REAL *curvIiGF,const CCTK_REAL *curvJrGF,const CCTK_REAL *curvJiGF) {
DECLARE_CCTK_PARAMETERS;
#include "list_of_functions_to_interpolate.h"
}
void construct_function_to_interpolate__store_to_interped_gf(CCTK_ARGUMENTS) {
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
printf("Called construct_function_to_interpolate__store_to_interped_gf() on grid with dx = %e!\n",CCTK_DELTA_SPACE(0));
const CCTK_REAL invdx0 = 1.0 / CCTK_DELTA_SPACE(0);
const CCTK_REAL invdx1 = 1.0 / CCTK_DELTA_SPACE(1);
const CCTK_REAL invdx2 = 1.0 / CCTK_DELTA_SPACE(2);
list_of_functions_to_interpolate(cctkGH,cctk_lsh,cctk_nghostzones,
x,y,z,
invdx0,invdx1,invdx2,
InterpCounter,
rho_b,P,
vx,vy,vz,
Bx,By,Bz,
gxx,gxy,gxz,gyy,gyz,gzz,
betax,betay,betaz,alp, interped_gf,
Ax_unstaggered,Ay_unstaggered,Az_unstaggered,
Psi0r,Psi0i,Psi1r,Psi1i,Psi2r,Psi2i,Psi3r,Psi3i,Psi4r,Psi4i,
curvIr,curvIi,curvJr,curvJi);
// interped_gf will be interpolated across AMR boundaries, meaning that
// it must be prointated. Only gridfunctions with 3 timelevels stored
// may be prointated (provided time_interpolation_order is set to the
// usual value of 2). We should only call this interpolation routine
// at iterations in which all gridfunctions are on the same timelevel
// (usually a power of 2), which will ensure that the following
// "filling of the timelevels" is completely correct.
#pragma omp parallel for
for(int i=0;i<cctk_lsh[0]*cctk_lsh[1]*cctk_lsh[2];i++) {
interped_gf_p[i] = interped_gf[i];
interped_gf_p_p[i] = interped_gf[i];
}
}
```
<a id='nrpygetgfname'></a>
## Step 2.c: The `get_gf_name()` function \[Back to [top](#toc)\]
$$\label{nrpygetgfname}$$
```
with open(os.path.join(Ccodesdir,"src","get_gf_name.h"), "w") as file:
file.write("void get_gf_name(const int InterpCounter,char gf_name[100]) {\n")
for i in range(1,which_InterpCounter):
file.write(" if(InterpCounter=="+str(i)+") { snprintf(gf_name,100,\""+gf_interp_list[i].gf_description+"\"); return; }\n")
file.write(" printf(\"Error. InterpCounter = %d unsupported. I should not be here.\\n\",InterpCounter); exit(1);\n")
file.write("}\n")
```
<a id='nrpy_interp_counter'></a>
## Step 2.d: C Code for Initializing and incrementing `InterpCounter` \[Back to [top](#toc)\]
$$\label{nrpy_interp_counter}$$
The gridfunctions are interpolated one at a time based on the current value of the index quantity `InterpCounter`. Here we write the C code needed for initializing and incrementing this variable.
```
with open(os.path.join(Ccodesdir,"src","define_NumInterpFunctions.h"), "w") as file:
file.write("#define NumInterpFunctions "+str(which_InterpCounter)+"\n")
%%writefile $Ccodesdir/src/interp_counter.cc
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include "cctk.h"
#include "cctk_Arguments.h"
#include "cctk_Parameters.h"
#include "define_NumInterpFunctions.h"
void ArbGrid_InitializeInterpCounterToZero(CCTK_ARGUMENTS)
{
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
*InterpCounter = 0;
if(verbose==2) printf("interp_arbgrid_MO_ETK: Just set InterpCounter to %d\n",*InterpCounter);
}
void ArbGrid_InitializeInterpCounter(CCTK_ARGUMENTS)
{
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
if(cctk_iteration == interp_out_iteration) {
*InterpCounter = 1;
if(verbose==2) printf("interp_arbgrid_MO_ETK: Just set InterpCounter to %d ; ready to start looping over interpolated gridfunctions!\n",
*InterpCounter);
}
}
// This function increments InterpCounter if we are at the interp_out_iteration until
// it hits NumInterpFunctions. At this iteration, InterpCounter is set to zero, which
// exits the loop.
void ArbGrid_IncrementInterpCounter(CCTK_ARGUMENTS)
{
DECLARE_CCTK_ARGUMENTS;
DECLARE_CCTK_PARAMETERS;
if(*InterpCounter == NumInterpFunctions-1) {
*InterpCounter = 0;
if(verbose==2) printf("interp_arbgrid_MO_ETK: Finished! Just zeroed InterpCounter.\n");
} else {
(*InterpCounter)++;
if(verbose==2) printf("interp_arbgrid_MO_ETK: Just incremented InterpCounter to %d of %d\n",*InterpCounter,NumInterpFunctions-1);
}
}
```
<a id='validationagainstfm'></a>
# Step 2.e: Validation of interpolated data against exact Fishbone-Moncrief data \[Back to [top](#toc)\]
$$\label{validationagainstfm}$$
```
# # Step 1c: Call the FishboneMoncriefID() function from within the
# # FishboneMoncriefID/FishboneMoncriefID.py module.
# import FishboneMoncriefID.FishboneMoncriefID as fmid
# old_glb_gridfcs_list = gri.glb_gridfcs_list
# # Step 1: Set up the Fishbone-Moncrief initial data. This sets all the ID gridfunctions.
# gri.glb_gridfcs_list = [] # Reset list of gridfunctions
# fmid.FishboneMoncriefID("Spherical")
# gammaDD = ixp.zerorank2()
# DIM = 3
# for i in range(DIM):
# for j in range(DIM):
# if i<=j:
# gammaDD[i][j] = fmid.IDgammaDD[i][j]
# else:
# gammaDD[i][j] = fmid.IDgammaDD[j][i]
# # gamma_{ij} v^i_{(n)} v^j_{(n)}
# Gammacontraction = sp.sympify(0)
# for i in range(DIM):
# for j in range(DIM):
# Gammacontraction += gammaDD[i][j] * fmid.IDValencia3velocityU[i] * fmid.IDValencia3velocityU[j]
# Gammafactor = sp.sqrt(1 / (1 - Gammacontraction))
# # -={ F-M quantities: Generate C code from expressions and output to file }=-
# FishboneMoncrief_to_print = [\
# lhrh(lhs="Gammafactor",rhs=Gammafactor),\
# lhrh(lhs="Gamma_times_ValenciavU0",rhs=Gammafactor*fmid.IDValencia3velocityU[0]),\
# lhrh(lhs="Gamma_times_ValenciavU1",rhs=Gammafactor*fmid.IDValencia3velocityU[1]),\
# lhrh(lhs="Gamma_times_ValenciavU2",rhs=Gammafactor*fmid.IDValencia3velocityU[2]),\
# ]
# fin.FD_outputC(os.path.join(Ccodesdir,"src","FM_Gamma__Gamma_times_Valenciavs_sphbasis.h"),FishboneMoncrief_to_print,
# params="outCverbose=False,CSE_enable=True")
# # Restore old gridfunctions list:
# gri.glb_gridfcs_list = old_glb_gridfcs_list
# %%writefile $Ccodesdir/src/FM_validation.cc
# #include <assert.h>
# #include <stdio.h>
# #include <stdlib.h>
# #include <string.h>
# #include <math.h>
# #include <ctype.h>
# // Needed for dealing with Cactus/ETK infrastructure
# #include "cctk.h"
# #include "cctk_Arguments.h"
# #include "cctk_Parameters.h"
# // Needed for low-level interpolation functions
# #include "util_Table.h"
# #include "util_String.h"
# // C++ function prototypes:
# extern void Interpolate_to_dest_grid(const cGH *cctkGH,const CCTK_INT interp_num_points, const CCTK_INT interp_order,
# const CCTK_REAL *point_x_temp,const CCTK_REAL *point_y_temp,const CCTK_REAL *point_z_temp,
# const CCTK_STRING input_array_names[1], CCTK_REAL *output_f[1]);
# extern void get_gf_name(const int InterpCounter,char gf_name[100]);
# #define FREE_2D_GENERIC(type,array,ni,nj) for(int cc = 0; cc < ni;cc++) free((void *)array[cc]); \
# /**/ free((void *)array);
# void FM_validation(CCTK_ARGUMENTS)
# {
# DECLARE_CCTK_ARGUMENTS;
# DECLARE_CCTK_PARAMETERS;
# const CCTK_INT sph_Nr = 3200;
# const CCTK_INT sph_Nth = 1;
# const CCTK_INT sph_Nph = 160;
# const CCTK_REAL sph_rmin = 0.1;
# const CCTK_REAL sph_rmax = 50.0;
# const CCTK_REAL sph_thmin = M_PI/2.0;
# const CCTK_REAL sph_thmax = M_PI/2.0;
# const CCTK_REAL sph_phmin = 0;
# const CCTK_REAL sph_phmax = 2.0*M_PI;
# const CCTK_INT num_interp_points = sph_Nr*sph_Nth*sph_Nph;
# // STEP 1: IF GAMMA*VALENCIA,PROCEED. IF RHO_B, OUTPUT FM FOR VEL DATA. ELSE RETURN.
# // Perform interpolation only at iteration == interp_out_iteration:
# if(cctk_iteration != interp_out_iteration) return;
# char gf_name[100]; get_gf_name(*InterpCounter,gf_name);
# // if(strncmp(gf_name,"Lorentz factor, times Valencia",30) == 0) {
# if(0 == 0) {
# // Perform interpolation!
# // Process zero (CCTK_MyProc(cctkGH)==0) is responsible for directing the interpolation.
# // All other processes must see the cctk_InterpGridArrays() within Interpolate_to_dest_grid(),
# // so that the MPI calls work properly, but these nonzero processes can call
# // Interpolate_to_dest_grid() with number of interpolated points set to zero, and
# // without needing a malloc().
# if(CCTK_MyProc(cctkGH)==0) {
# CCTK_REAL *points_x,*points_y,*points_z,**output_f;
# // The name of the input gridfunction is always "interp_arbgrid_MO_ETK::interped_gf":
# const CCTK_STRING input_array_names[1] = { "interp_arbgrid_MO_ETK::interped_gf" };
# // STEP 1: Construct list of desired interpolation destination points:
# points_x = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_interp_points);
# points_y = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_interp_points);
# points_z = (CCTK_REAL *)malloc(sizeof(CCTK_REAL)*num_interp_points);
# output_f = (CCTK_REAL **)malloc(1 * sizeof(CCTK_REAL *));
# for(int cc = 0; cc < 1; cc++) output_f[cc]=(CCTK_REAL *)malloc(num_interp_points * sizeof(CCTK_REAL));
# // STEP 2: ALLOCATE INTERPOLATION ARRAYS SET INTERPOLATION POINT ARRAYS
# CCTK_INT pointcount = 0;
# for(int ir=0;ir<sph_Nr;ir++) for(int ith=0;ith<sph_Nth;ith++) for(int iph=0;iph<sph_Nph;iph++) {
# const CCTK_REAL r = sph_rmin + (CCTK_REAL)ir /((CCTK_REAL)sph_Nr ) * (sph_rmax - sph_rmin);
# const CCTK_REAL th = sph_thmin + (CCTK_REAL)ith/((CCTK_REAL)sph_Nth) * (sph_thmax - sph_thmin);
# const CCTK_REAL ph = sph_phmin + (CCTK_REAL)iph/((CCTK_REAL)sph_Nph) * (sph_phmax - sph_phmin);
# points_x[pointcount] = r*sin(th)*cos(ph);
# points_y[pointcount] = r*sin(th)*sin(ph);
# points_z[pointcount] = r*cos(th);
# pointcount++;
# } // END for(int ir=0;ir<sph_Nr;ir++) for...
# // STEP 3: Looping over interp order as desired, interpolate to destination points & output to file
# for(int order=1;order<=4;order*=2) {
# printf("ASCII FM Validation: %d pts; Interpolating\033[1m %s \033[0m... using interpolation order = %d\n",num_interp_points,gf_name,order);
# //Interpolate_to_dest_grid(cGH *cctkGH,CCTK_INT interp_num_points, CCTK_INT interp_order,
# // CCTK_REAL *point_x_temp,CCTK_REAL *point_y_temp,CCTK_REAL *point_z_temp,
# // const CCTK_STRING input_array_names[1], CCTK_REAL *output_f[1])
# Interpolate_to_dest_grid(cctkGH, num_interp_points, order,
# points_x,points_y,points_z, input_array_names, output_f);
# // Step 1.d.i: Sanity check -- check for bad point:
# #pragma omp parallel for
# for(int i=0;i<num_interp_points;i++) {
# if(output_f[0][i] > 1e20) {
# printf("BAD POINT: %s %d %e %e %e %e\n",gf_name,i,points_x[i],points_y[i],points_z[i], output_f[0][i]);
# exit(1);
# } // END if(output_f[0][i] > 1e20)
# } // END for(int i=0;i<num_interp_points;i++)
# char filename[500];
# sprintf (filename, "%s/validation_points-%s-order%d.asc", out_dir,gf_name,order);
# FILE *file;
# file = fopen (filename,"w");
# printf("WRITING to file %s\n",filename);
# if (! file) {
# CCTK_VWarn (1, __LINE__, __FILE__, CCTK_THORNSTRING,
# "interp_dest_grid__ET_thorn: Cannot open ASCII output file '%s'", filename);
# exit(1);
# } // END if (! file)
# pointcount = 0;
# for(int ir=0;ir<sph_Nr;ir++) for(int ith=0;ith<sph_Nth;ith++) for(int iph=0;iph<sph_Nph;iph++) {
# const CCTK_REAL xx = points_x[pointcount];
# const CCTK_REAL yy = points_y[pointcount];
# const CCTK_REAL zz = points_z[pointcount];
# fprintf(file,"%e %e %e %e\n",xx,yy,zz,output_f[0][pointcount]);
# pointcount++;
# }
# fclose(file);
# } // END for(int order=1;order<=4;order*=2)
# // STEP 3: FREE THE MALLOCs for destination grids and interpolation output
# free(points_x);
# free(points_y);
# free(points_z);
# FREE_2D_GENERIC(CCTK_REAL,output_f,1,num_interp_points);
# } else if(CCTK_MyProc(cctkGH)!=0) {
# // On all MPI processes that are nonzero, only call the interpolation function
# CCTK_REAL *points_x,*points_y,*points_z,**output_f;
# // The name of the input gridfunction is always "interp_arbgrid_MO_ETK::interped_gf":
# const CCTK_STRING input_array_names[1] = { "interp_arbgrid_MO_ETK::interped_gf" };
# // to ensure the MPI calls from the actual interpolation (driven by proc==0) are seen.
# for(int order=1;order<=4;order*=2) {
# Interpolate_to_dest_grid(cctkGH, 0, order,points_x,points_y,points_z, input_array_names, output_f);
# } // END for(int order=1;order<=4;order*=2)
# } // END if(CCTK_MyProc(cctkGH)...)
# }
# if(strncmp(gf_name,"IGM density primitive",21) == 0 && CCTK_MyProc(cctkGH)==0) {
# char filename[500];
# sprintf (filename, "%s/FMvalidation_points.asc", out_dir);
# FILE *file;
# file = fopen (filename,"w");
# printf("WRITING to file %s\n",filename);
# for(int ir=0;ir<sph_Nr;ir++) for(int ith=0;ith<sph_Nth;ith++) for(int iph=0;iph<sph_Nph;iph++) {
# const CCTK_REAL xx0 = sph_rmin + (CCTK_REAL)ir /((CCTK_REAL)sph_Nr ) * (sph_rmax - sph_rmin);
# const CCTK_REAL xx1 = sph_thmin + (CCTK_REAL)ith/((CCTK_REAL)sph_Nth) * (sph_thmax - sph_thmin);
# const CCTK_REAL xx2 = sph_phmin + (CCTK_REAL)iph/((CCTK_REAL)sph_Nph) * (sph_phmax - sph_phmin);
# const CCTK_REAL xx = xx0*sin(xx1)*cos(xx2);
# const CCTK_REAL yy = xx0*sin(xx1)*sin(xx2);
# const CCTK_REAL zz = xx0*cos(xx1);
# if(xx0 < r_in) {
# fprintf(file,"%e %e %e %e %e %e %e\n",xx,yy,zz,
# 0.0,0.0,0.0,1.0);
# } else {
# CCTK_REAL Gammafactor,Gamma_times_ValenciavU0,Gamma_times_ValenciavU1,Gamma_times_ValenciavU2;
# #include "FM_Gamma__Gamma_times_Valenciavs_sphbasis.h"
# fprintf(file,"%e %e %e %e %e %e %e\n",xx,yy,zz,
# Gamma_times_ValenciavU0,Gamma_times_ValenciavU1,Gamma_times_ValenciavU2,Gammafactor);
# } // END if(xx0 < r_in)
# } // END for(int ir=0;ir<sph_Nr;ir++) for...
# fclose(file);
# return;
# } // END if(strncmp(gf_name,"Lorentz factor, times Valencia",30) == 0)
# } // END function
# #undef FREE_2D_GENERIC
```
<a id='cclfiles'></a>
# Step 3: Define how this module interacts and interfaces with the larger Einstein Toolkit infrastructure \[Back to [top](#toc)\]
$$\label{cclfiles}$$
Writing a module ("thorn") within the Einstein Toolkit requires that three "ccl" files be constructed, all in the root directory of the thorn:
1. `interface.ccl`: defines the gridfunction groups needed, and provides keywords denoting what this thorn provides and what it should inherit from other thorns.
1. `param.ccl`: specifies free parameters within the thorn.
1. `schedule.ccl`: allocates storage for gridfunctions, defines how the thorn's functions should be scheduled in a broader simulation, and specifies the regions of memory written to or read from gridfunctions.
<a id='makecodedefn'></a>
## Step 3.a: `make.code.defn` \[Back to [top](#toc)\]
$$\label{makecodedefn}$$
Before writing the "ccl" files, we first add Einstein Toolkit's equivalent of a Makefile, the `make.code.defn` file:
```
%%writefile $Ccodesdir/src/make.code.defn
# Main make.code.defn file for thorn interp_arbgrid_MO_ETK
# Source files in this directory
SRCS = main_function.cc unstagger_A_fields.cc interp_counter.cc \
construct_function_to_interpolate__store_to_interped_gf.cc # FM_validation.cc # <- For FishboneMoncriefID validation
```
<a id='interfaceccl'></a>
## Step 3.b: `interface.ccl` \[Back to [top](#toc)\]
$$\label{interfaceccl}$$
Let's now write `interface.ccl`. The [official Einstein Toolkit (Cactus) documentation](http://einsteintoolkit.org/usersguide/UsersGuide.html) defines what must/should be included in an `interface.ccl` file [**here**](http://einsteintoolkit.org/usersguide/UsersGuidech12.html#x17-178000D2.2).
```
%%writefile $Ccodesdir/interface.ccl
# With "implements", we give our thorn its unique name.
implements: interp_arbgrid_MO_ETK
# By "inheriting" other thorns, we tell the Toolkit that we
# will rely on variables/function that exist within those
# functions.
inherits: admbase IllinoisGRMHD Grid
inherits: WeylScal4 # Needed for Weyl scalars psi4, psi3, psi..., and Weyl invariants I & J.
# For FM ID comparisons:
# inherits: FishboneMoncriefID
# Tell the Toolkit that we want "interped_gf" and "InterpCounter"
# and invariants to NOT be visible to other thorns, by using
# the keyword "private". Note that declaring these
# gridfunctions here *does not* allocate memory for them;
# that is done by the schedule.ccl file.
private:
CCTK_REAL interpolation_gf type=GF timelevels=3 tags='Checkpoint="no"'
{
interped_gf
} "Gridfunction containing output from interpolation."
CCTK_REAL unstaggered_A_fields type=GF timelevels=3 tags='Checkpoint="no"'
{
Ax_unstaggered,Ay_unstaggered,Az_unstaggered
} "Unstaggered A-field components."
int InterpCounterVar type = SCALAR tags='checkpoint="no"'
{
InterpCounter
} "Counter that keeps track of which function we are interpolating."
```
<a id='paramccl'></a>
## Step 3.c: `param.ccl` \[Back to [top](#toc)\]
$$\label{paramccl}$$
We will now write the file `param.ccl`. This file allows the listed parameters to be set at runtime. We also give allowed ranges and default values for each parameter. More information on this file's syntax can be found in the [official Einstein Toolkit documentation](http://einsteintoolkit.org/usersguide/UsersGuidech12.html#x17-183000D2.3).
```
%%writefile $Ccodesdir/param.ccl
# Output the interpolated data to the IO::out_dir directory:
shares: IO
USES STRING out_dir
# For FM ID comparisons:
# shares: FishboneMoncriefID
# USES KEYWORD M
# USES KEYWORD a
# USES KEYWORD r_in
# USES KEYWORD r_at_max_density
restricted:
########################################
# BASIC THORN STEERING PARAMETERS
CCTK_INT interp_out_iteration "Which iteration to interpolate to destination grids?" STEERABLE=ALWAYS
{
0:* :: ""
} 960000
## Interpolator information
CCTK_STRING interpolator_name "Which interpolator to use?" STEERABLE=ALWAYS
{
".+" :: "Any nonempty string; an unsupported value will throw an error."
} "Lagrange polynomial interpolation"
CCTK_INT verbose "Set verbosity level: 1=useful info; 2=moderately annoying (though useful for debugging)" STEERABLE=ALWAYS
{
0:2 :: "0 = no output; 1=useful info; 2=moderately annoying (though useful for debugging)"
} 2
CCTK_INT A_fields_are_staggered "Are A fields staggered? 1 = yes; 0 = no. Default to yes." STEERABLE=ALWAYS
{
0:1 :: ""
} 1
##########
# Cartesian position of center of output grid (usually center of BH).
CCTK_REAL x_center "x-position of center." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
CCTK_REAL y_center "y-position of center." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
CCTK_REAL z_center "z-position of center." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
##########
# Shift offset:
CCTK_REAL beta_offsetU0 "Offset to betax, to account for coordinate drift in x direction." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
CCTK_REAL beta_offsetU1 "Offset to betay, to account for coordinate drift in y direction." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
CCTK_REAL beta_offsetU2 "Offset to betaz, to account for coordinate drift in z direction." STEERABLE=ALWAYS
{
*:* :: ""
} 0.0
CCTK_REAL out_of_bounds_interp_xyz "Do not interpolate points with fabs(xyz) > out_of_bounds_interp_xyz, where xyz are centered at xyz_center (usually center of BH). Fill dataset with NaN instead." STEERABLE=ALWAYS
{
0:* :: "Any positive number"
} 1E100
```
<a id='scheduleccl'></a>
## Step 3.d: `schedule.ccl` \[Back to [top](#toc)\]
$$\label{scheduleccl}$$
Finally, we will write the file `schedule.ccl`; its official documentation is found [here](http://einsteintoolkit.org/usersguide/UsersGuidech12.html#x17-186000D2.4).
This file declares storage for variables declared in the `interface.ccl` file and specifies when the various parts of the thorn will be run:
```
%%writefile $Ccodesdir/schedule.ccl
STORAGE: interpolation_gf[3]
STORAGE: unstaggered_A_fields[3]
STORAGE: InterpCounterVar
# STORAGE: interp_pointcoords_and_output_arrays
#############################
SCHEDULE ArbGrid_InitializeInterpCounterToZero AT CCTK_INITIAL
{
LANG: C
OPTIONS: GLOBAL
} "Initialize InterpCounter variable to zero"
SCHEDULE ArbGrid_InitializeInterpCounterToZero AT CCTK_POST_RECOVER_VARIABLES
{
LANG: C
OPTIONS: GLOBAL
} "Initialize InterpCounter variable to zero"
SCHEDULE ArbGrid_InitializeInterpCounter before ArbGrid_InterpGroup AT CCTK_ANALYSIS
{
LANG: C
OPTIONS: GLOBAL
} "Initialize InterpCounter variable"
##################
SCHEDULE GROUP ArbGrid_InterpGroup AT CCTK_ANALYSIS BEFORE CarpetLib_printtimestats BEFORE CarpetLib_printmemstats AFTER Convert_to_HydroBase WHILE interp_arbgrid_MO_ETK::InterpCounter
{
} "Perform all interpolations. This group is only actually scheduled at cctk_iteration==interp_out_iteration."
SCHEDULE unstagger_A_fields in ArbGrid_InterpGroup before construct_function_to_interpolate__store_to_interped_gf
{
STORAGE: unstaggered_A_fields[3]
OPTIONS: GLOBAL,LOOP-LOCAL
SYNC: unstaggered_A_fields
LANG: C
} "Unstagger A fields."
SCHEDULE construct_function_to_interpolate__store_to_interped_gf in ArbGrid_InterpGroup before DoSum
{
STORAGE: interpolation_gf[3],InterpCounterVar
OPTIONS: GLOBAL,LOOP-LOCAL
SYNC: interpolation_gf
LANG: C
} "Construct the function to interpolate"
SCHEDULE Interpolate_to_dest_grid_main_function in ArbGrid_InterpGroup after construct_function_to_interpolate__store_to_interped_gf
{
OPTIONS: GLOBAL
LANG: C
} "Perform interpolation and output result to file."
# For FishboneMoncriefID validation only.
# SCHEDULE FM_validation in ArbGrid_InterpGroup after Interpolate_to_dest_grid_main_function
# {
# OPTIONS: GLOBAL
# LANG: C
# } "Perform interpolation and output result to 2D ASCII file."
#######
SCHEDULE ArbGrid_IncrementInterpCounter in ArbGrid_InterpGroup after Interpolate_to_dest_grid_main_function
{
LANG: C
OPTIONS: GLOBAL
} "Increment InterpCounter variable, or set to zero once loop is complete."
##################
```
<a id='readingoutputfile'></a>
# Step 4: Python Script for Reading the Output File \[Back to [top](#toc)\]
$$\label{readingoutputfile}$$
Here is a Python code for reading the output file generated by this thorn. It is based on a collection of Python scripts written by Bernard Kelly, available [here](https://bitbucket.org/zach_etienne/nrpy/src/master/mhd_diagnostics/).
After generating the output file `interp_arbgrid_MO_ETK.dat` using the Einstein Toolkit thorn above, this script will read in all the data. Processing can then be done by straightforward modification of this script. Save the script as "Interp_Arb_ReadIn.py", and run it using the command
**`python Interp_Arb_ReadIn.py interp_arbgrid_MO_ETK.dat 58 outfile`**
Currently the last parameter "outfile" is required but not used.
```python
"""
interp_arbgrid_MO_ETK.dat File Reader. Compatible with Python 2.7+ and 3.6+ at least.
Zachariah B. Etienne
Based on Python scripts written by Bernard Kelly:
https://bitbucket.org/zach_etienne/nrpy/src/master/mhd_diagnostics/
Find the latest version of this reader at the bottom of this Jupyter notebook:
https://github.com/zachetienne/nrpytutorial/blob/master/Tutorial-ETK_thorn-Interpolation_to_Arbitrary_Grids_multi_order.ipynb
Usage instructions:
From the command-line, run via:
python Interp_Arb_ReadIn.py interp_arbgrid_MO_ETK.dat [number of gridfunctions (58 or so)] [outfile]
Currently the last parameter "outfile" is required but not actually used.
"""
import numpy as np
import struct
import sys
import argparse
parser = argparse.ArgumentParser(description='Read file.')
parser.add_argument("datafile", help="main data file")
parser.add_argument("number_of_gridfunctions", help="number of gridfunctions")
parser.add_argument("outfileroot", help="root of output file names")
args = parser.parse_args()
datafile = args.datafile
outfileroot = args.outfileroot
number_of_gridfunctions = int(args.number_of_gridfunctions)
print("reading from "+str(datafile))
"""
read_char_array():
Reads a character array of size="size"
from a file (with file handle = "filehandle")
and returns the character array as a proper
Python string.
"""
def read_char_array(filehandle,size):
reached_end_of_string = False
chartmp = struct.unpack(str(size)+'s', filehandle.read(size))[0]
#https://docs.python.org/3/library/codecs.html#codecs.decode
char_array_orig = chartmp.decode('utf-8',errors='ignore')
char_array = ""
for i in range(len(char_array_orig)):
char = char_array_orig[i]
# C strings end in '\0', which in Python-ese is '\x00'.
# As characters read after the end of the string will
# generally be gibberish, we no inter append
# to the output string after '\0' is reached.
if sys.version_info[0]==3 and bytes(char.encode('utf-8')) == b'\x00':
reached_end_of_string = True
elif sys.version_info[0]==2 and char == '\x00':
reached_end_of_string = True
if reached_end_of_string == False:
char_array += char
else:
pass # Continue until we've read 'size' bytes
return char_array
"""
read_header()
Reads the header from a file.
"""
def read_header(filehandle):
# This function makes extensive use of Python's struct.unpack
# https://docs.python.org/3/library/struct.html
# First store gridfunction name and interpolation order used:
# fwrite(gf_name, 100*sizeof(char), 1, file);
gf_name = read_char_array(filehandle,100)
# fwrite(order, sizeof(CCTK_INT), 1, file);
order = struct.unpack('i',filehandle.read(4))[0]
# Then the number of interpolation points (stored as an int)
num_interp_points = struct.unpack('i',filehandle.read(4))[0]
magic_number_check = 1.130814081305130e-21
# fwrite( & magic_number, sizeof(CCTK_REAL), 1, file);
magic_number = struct.unpack('d', filehandle.read(8))[0]
if magic_number != magic_number_check:
print("Error: Possible file corruption: Magic number mismatch. Found magic number = "+str(magic_number)+" . Expected "+str(magic_number_check))
exit(1)
# fwrite( & cctk_iteration, sizeof(CCTK_INT), 1, file);
cctk_iteration = struct.unpack('i', filehandle.read(4))[0]
# fwrite( & cctk_time, sizeof(CCTK_REAL), 1, file);
cctk_time = struct.unpack('d', filehandle.read(8))[0]
return gf_name,order,num_interp_points,cctk_iteration,cctk_time
# Now open the file and read all the data
with open(datafile,"rb") as f:
# Main loop over all gridfunctions
for i in range(number_of_gridfunctions):
# Data are output in chunks, one gridfunction at a time, with metadata
# for each gridfunction stored at the top of each chunk
# First read in the metadata:
gf_name, order, num_interp_points, cctk_iteration, cctk_time = read_header(f)
print("\nReading gridfunction "+gf_name+", stored at interp order = "+str(order))
data_chunk_size = num_interp_points*8 # 8 bytes per double-precision number
# Next read in the full gridfunction data
bytechunk = f.read(data_chunk_size)
# Process the data using NumPy's frombuffer() function:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html
buffer_res = np.frombuffer(bytechunk)
# Reshape the data into a 3D NumPy array:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
#this_data = buffer_res.reshape(N0,N1,N2)
# Sanity check: Output data at all points:
with open("output-gf"+str(i)+".txt","w") as file:
for ii in range(num_interp_points):
file.write(str(ii) + "\t" + str(buffer_res[ii])+"\n")
```
<a id='latex_pdf_output'></a>
# Step 5: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$
The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename
[Tutorial-ETK_thorn-Interpolation_to_Arbitrary_Grids_multi_order.pdf](Tutorial-ETK_thorn-Interpolation_to_Arbitrary_Grids_multi_order.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)
```
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-ETK_thorn-Interpolation_to_Arbitrary_Grids_multi_order")
```
| github_jupyter |
```
import pandas as pd
train = pd.read_csv("train.csv")
```
## Lets See What We Have
```
train.head()
train.describe()
train.info()
train.isnull().sum()
```
## Working On Training Data
### Object to Datetime, Datetime to Day, Month, Year
```
def time_extraction(df):
"""Function that changes object to datetime and after that
splits datetime into year, month, day, hour and weekday"""
df['datetime'] = pd.to_datetime(df['datetime'])
df['year'] = df['datetime'].dt.year
df['month'] = df['datetime'].dt.month
df['day'] = df['datetime'].dt.day
df['hour'] = df['datetime'].dt.hour
df['weekday'] = df['datetime'].dt.weekday
df.drop("datetime",inplace=True, axis=1)
time_extraction(train)
# Drop useless columns
# We dont have registered and casual in our test set this values also give info on count
train.drop("registered",inplace=True, axis=1)
train.drop("casual",inplace=True, axis=1)
```
### Quick Look On Distribution
```
%matplotlib inline
import matplotlib.pyplot as plt
train.hist(bins=50, figsize=(20,15))
plt.show()
```
At first glance we can see our categorical data such as:
Season, holiday, workingday, weather
For categories with more than 2 values I will use the idea in one hot encoding.
I will also not touch the categories I created
1.We can see that count has more values under 200.
2.Temp has a bell curve like distribution.
### Correlations Inside Our Data
```
correlation_matrix = train.corr()
correlation_matrix["count"].sort_values(ascending=False)
```
Correlation coefficent ranges from 1 to -1. If it is closer to 1 values have positive correlation if it is closer to -1 values have negative correlation.
We can see that hour and temp have positive correlation with count. But humidity and weather have negative correlation with count
```
train["hour_temp"] = train["hour"] * train["temp"]
train["humidty_temp"] = train["humidity"] / train["temp"]
correlation_matrix = train.corr()
correlation_matrix["count"].sort_values(ascending=False)
```
### Lets See Correlated Values
```
from pandas.plotting import scatter_matrix
attributes = ["count", "hour_temp", "humidty_temp"]
scatter_matrix(train[attributes], figsize=(12, 8))
```
### Encode and Scale
```
from sklearn.preprocessing import OneHotEncoder
hot_encoder = OneHotEncoder()
attributes = ["season","weather"]
encoded_values = hot_encoder.fit_transform(train[attributes])
encoded_df = pd.DataFrame(encoded_values.toarray(), columns=['season1', 'season2', 'season3', 'season4',
'weather1', 'weather2', 'weather3', 'weather4'])
train = pd.concat([train, encoded_df],axis=1).drop(["season","weather"], axis=1)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
attributes = train.columns.drop(['count'])
train[attributes] = scaler.fit_transform(train[attributes])
train.head()
```
### Creating Models
```
from sklearn.ensemble import BaggingRegressor
bagging_reg = BaggingRegressor()
bagging_reg.fit(train[attributes], train["count"])
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor()
tree_reg.fit(train[attributes], train["count"])
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor()
forest_reg.fit(train[attributes], train["count"])
from sklearn.neighbors import KNeighborsRegressor
kneighbor_reg = KNeighborsRegressor()
kneighbor_reg.fit(train[attributes], train["count"])
```
### Comparing Models
```
from sklearn.model_selection import cross_val_score
scores = cross_val_score(bagging_reg, train[attributes], train["count"],scoring="neg_mean_squared_log_error", cv=10)
print("Bagging Regression Score: ", -scores.mean())
scores = cross_val_score(tree_reg, train[attributes], train["count"],scoring="neg_mean_squared_log_error", cv=10)
print("Decision Tree Regression Score: ", -scores.mean())
scores = cross_val_score(forest_reg, train[attributes], train["count"],scoring="neg_mean_squared_log_error", cv=10)
print("Random Forest Regression Score: ", -scores.mean())
scores = cross_val_score(kneighbor_reg, train[attributes], train["count"],scoring="neg_mean_squared_log_error", cv=10)
print("KNeighbors Regression Score: ", -scores.mean())
```
### Finding Hyperparameters
```
from sklearn.model_selection import GridSearchCV
param_grid = [
# try 12 (3×4) combinations of hyperparameters
{'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},
# then try 6 (2×3) combinations with bootstrap set as False
{'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},
]
forest_reg = RandomForestRegressor(random_state=42)
# train across 5 folds, that's a total of (12+6)*5=90 rounds of training
grid_search = GridSearchCV(forest_reg, param_grid, cv=5,
scoring='neg_mean_squared_log_error',
return_train_score=True)
grid_search.fit(train[attributes], train["count"])
```
## Now Time To Prepare Test Data
```
test = pd.read_csv("test.csv")
submission_time = test.datetime
```
### Change Attributes According To Training
```
# Object to datetime, datetime to year, month, day, hour and weekday
time_extraction(test)
# Creating new attributes
test["hour_temp"] = test["hour"] * test["temp"]
test["humidty_temp"] = test["humidity"] / test["temp"]
```
### Encode And Scale Part 2
```
attributes = ["season","weather"]
encoded_values = hot_encoder.transform(test[attributes])
encoded_df = pd.DataFrame(encoded_values.toarray(), columns=['season1', 'season2', 'season3', 'season4',
'weather1', 'weather2', 'weather3', 'weather4'])
test = pd.concat([test, encoded_df],axis=1).drop(["season","weather"], axis=1)
test = scaler.transform(test)
```
### Using Best Model To Predict
```
final_model = grid_search.best_estimator_
final_predictions = final_model.predict(test)
```
### Create Submission File
```
submission = pd.DataFrame({ "datetime": submission_time, "count": final_predictions})
submission.to_csv('random_Forest_log.csv',index=False)
```
| github_jupyter |
# Experiment F
2) Implementar um framework de busca de hiperparâmetros.
2.1) Parâmetros específicos para cada método de processamento do ds.
2.2) N top colunas (`top_cols`) do dataset.
2.3) Parâmetro $L$ (`recomender(...,L,...)`).
5) Implementar como entrada uma empresa nova, conter mapeamento de valores.
Talvez criar o notebook da Second_View, com:
1) Verificar `sklearn.inspection.permutation_importance`.
- Author: Israel Oliveira [\[e-mail\]](mailto:'Israel%20Oliveira%20'<prof.israel@gmail.com>)
```
%load_ext watermark
from typing import NewType, List
from loguru import logger
import pandas as pd
import numpy as np
from time import time
from scipy.spatial.distance import cosine
from sklearn.decomposition import FactorAnalysis, FastICA, PCA, IncrementalPCA, NMF, TruncatedSVD
from collections import defaultdict, Counter
import functools
import operator
from copy import deepcopy
from tqdm import tqdm
# Run this cell before close.
%watermark -d --iversion -b -r -g -m -v
def Manhattan(X,vec):
return abs(X - vec).sum(-1)
def Camberra(X,vec):
return abs((X - vec)/(X + vec)).sum(-1)
def BrayCurtis(X,vec):
return abs((X - vec)).sum(-1) / abs((X - vec)).sum(-1).sum(-1)
def np_cossine(X,vec):
return np.array([sum(X[i]*vec) / sum(X[i]**2)*sum(vec**2) for i in range(X.shape[0])])
def npj_cossine(X,vec):
return npj.array([sum(X[i]*vec) / sum(X[i]**2)*sum(vec**2) for i in range(X.shape[0])])
def scy_cossine(X,vec):
return np.array([cosine(X[i],vec) for i in range(X.shape[0])])
dist_func = [Manhattan, Camberra, BrayCurtis, np_cossine, scy_cossine]
def Nothing(arg):
return arg
def npSVD(M):
u, _, _ = np.linalg.svd(M, full_matrices=False)
return u
def _PCA(M,n_components=None):
out = PCA(n_components=n_components)
return out.fit_transform(M)
def _FastICA(M,n_components=None):
out = FastICA(n_components=n_components)
return out.fit_transform(M)
def _FactorAnalysis(M,n_components=None):
out = FactorAnalysis(n_components=n_components)
return out.fit_transform(M)
def _IncrementalPCA(M,n_components=None):
out = IncrementalPCA(n_components=n_components)
return out.fit_transform(M)
def _TruncatedSVD(M,n_components=None):
out = TruncatedSVD(n_components=n_components)
return out.fit_transform(M)
def _NMF(M,n_components=None):
out = NMF(n_components=n_components)
return out.fit_transform(M)
redux_func = [Nothing, npSVD, _NMF, _TruncatedSVD, _IncrementalPCA, _FactorAnalysis, _FastICA, _PCA]
def escalaropt_missings(df: pd.DataFrame, score: dict):
df_score = pd.DataFrame(score.items(), columns=['col','score'])
df_score['escala_opt'] = 1-normalize((np.sqrt(df_score.score)))
df_score['escala_opt'] = df_score['escala_opt'].apply(lambda x: max(x,0.1))
for _,row in df_score.iterrows():
df[row.col] = row.escala_opt*df[row.col]
return df
def escalaropt_std(df: pd.DataFrame, score: dict):
df_score = pd.DataFrame(score.items(), columns=['col','score'])
df_score['escala_opt'] = normalize([np.sqrt(np.sqrt(np.sqrt(df[col].std()))) for col in df_score['col']])
df_score['escala_opt'] = df_score['escala_opt'].apply(lambda x: max(x,0.1))
for _,row in df_score.iterrows():
df[row.col] = row.escala_opt*df[row.col]
return df
def escalaropt_entropy(df: pd.DataFrame, score: dict):
df_score = pd.DataFrame(score.items(), columns=['col','score'])
df_score['escala_opt'] = normalize([(-sum((df[col]+1)*np.log(df[col]+1))) for col in df_score['col']])
df_score['escala_opt'] = df_score['escala_opt'].apply(lambda x: max(x,0.1))
for _,row in df_score.iterrows():
df[row.col] = row.escala_opt*df[row.col]
return df
def scalarop_nothing(arg, arg2):
return arg
procDS_func = [scalarop_nothing, escalaropt_missings, escalaropt_std, escalaropt_entropy]
!ls ../app
import sys
sys.path.insert(1, '../app/src/')
from train import *
from recommender import Recommender
from tqdm import tqdm
import pandas as pd
from time import time
df_train, df_test = load_dataset(path_data = '../app/data/', test_list = [0, 1], train_test_merged = False)
ds, score = feat_proc(df_train)
def Search(N=1, process_values = Nothing, factorize = Nothing, vector_distance_list = [Manhattan]):
ex_algo = ExMatrix(process_values = process_values, factorize = factorize)
ex_algo.fit(ds, score)
out = {}
for dist in vector_distance_list:
ex_algo.vector_distance = dist
print(dist.__name__)
tmp ={1: [], 2: []}
t = time()
for row in tqdm(df_test.iterrows()):
recs = ex_algo.recomender([row[1].id],k=N)
tmp[row[1].P].append(any([x in df_test.loc[df_test.P == row[1].P].id.to_list() for x in recs])*1)
t = time()-t
out[dist.__name__] = {i: (sum(val)/max(1,len(val)), sum(val), len(val)) for i,val in tmp.items()}
out[dist.__name__]['t'] = t
return out
def save_results(results,df_e):
df = pd.DataFrame(results, columns=['pre_proc','redux_func','n_components','dist','t','P1pp','P1_True','P1_len','P2pp','P2_True','P2_len'])
out = pd.concat([df_e, df])
#df_laoded.df_laodedto_csv('Results_redux_prepro.csv',index=False)
return out
n_components_dict = {Nothing.__name__ : False,
#_npSVDj.__name__: False,
npSVD.__name__: False,
_NMF.__name__ : True,
_TruncatedSVD.__name__ : True,
_IncrementalPCA.__name__ : True,
_FactorAnalysis.__name__ : True,
_FastICA.__name__ : True,
_PCA.__name__ : True}
dist_list = [Manhattan] #[Manhattan, scy_cossine, Camberra, BrayCurtis, np_cossine] #[Manhattan, Camberra, BrayCurtis] #dist_func
proc_list = procDS_func #procDS_func #[Nothing] #procDS_func
redux_list = [_NMF] #redux_func #[Nothing] #[Nothing, npSVD, _NMF, _PCA, _FactorAnalysis] #redux_func
n_components_list = [n for n in range(30,91,1)]
results_csv_name = 'Results_A1.csv'
df_laoded = pd.read_csv(results_csv_name)
n=0
for redux in redux_list:
for proc in proc_list:
if n_components_dict[redux.__name__]:
for n_components in n_components_list:
cond = (df_laoded['pre_proc'] == proc.__name__) & (df_laoded['redux_func'] == redux.__name__) & (df_laoded['n_components'] == n_components)
print("Done?: {}.".format([proc.__name__, redux.__name__, n_components]))
if (sum(cond) == 0) or (not all([d.__name__ in df_laoded.dist.loc[cond].unique() for d in dist_list])):
dist_list_tmp = [d for d in dist_list if d.__name__ not in df_laoded.dist.loc[cond].unique()]
def redux_tmp(M):
return redux(M,n_components=n_components)
tmp = Search(process_values = proc, factorize = redux_tmp, vector_distance_list = dist_list_tmp)
results = [[proc.__name__, redux.__name__, n_components] + r for r in [[key]+[tmp[key]['t']]+flat([list(tmp[key][i+1]) for i in range(2)]) for key in tmp.keys()]]
df_laoded = save_results(results,df_laoded)
df_laoded.to_csv(results_csv_name,index=False)
else:
print("Done: {}.".format([proc.__name__, redux.__name__, n_components]))
else:
n_components = ds.shape[1]
cond = (df_laoded['pre_proc'] == proc.__name__) & (df_laoded['redux_func'] == redux.__name__) & (df_laoded['n_components'] == n_components)
print("Done?: {}.".format([proc.__name__, redux.__name__, n_components]))
if (sum(cond) == 0) or (not all([d.__name__ in df_laoded.dist.loc[cond].unique() for d in dist_list])):
dist_list_tmp = [d for d in dist_list if d.__name__ not in df_laoded.dist.loc[cond].unique()]
tmp = Search(process_values = proc, factorize = redux, vector_distance_list= dist_list_tmp)
results = [[proc.__name__, redux.__name__, n_components] + r for r in [[key]+[tmp[key]['t']]+flat([list(tmp[key][i+1]) for i in range(2)]) for key in tmp.keys()]]
df_laoded = save_results(results,df_laoded)
df_laoded.to_csv(results_csv_name,index=False)
else:
print("Done: {}.".format([proc.__name__, redux.__name__, n_components]))
#df = pd.DataFrame(columns=['pre_proc','redux_func','n_components','dist','t','P1pp','P1_True','P1_len','P2pp','P2_True','P2_len'])
#df.to_csv(results_csv_name,index=False)
```
| github_jupyter |
```
import numpy as np
import scipy.stats
import matplotlib.pylab as plt
import os, sys
sys.path.insert(0, "../")
import geepee.aep_models as aep
import geepee.ep_models as ep
%matplotlib inline
np.random.seed(42)
import pdb
# We first define several utility functions
def kink_true(x):
fx = np.zeros(x.shape)
for t in range(x.shape[0]):
xt = x[t]
if xt < 4:
fx[t] = xt + 1
else:
fx[t] = -4*xt + 21
return fx
def kink(T, process_noise, obs_noise, xprev=None):
if xprev is None:
xprev = np.random.randn()
y = np.zeros([T, ])
x = np.zeros([T, ])
xtrue = np.zeros([T, ])
for t in range(T):
if xprev < 4:
fx = xprev + 1
else:
fx = -4*xprev + 21
xtrue[t] = fx
x[t] = fx + np.sqrt(process_noise)*np.random.randn()
xprev = x[t]
y[t] = x[t] + np.sqrt(obs_noise)*np.random.randn()
return xtrue, x, y
def plot_latent(model, y, plot_title=''):
# make prediction on some test inputs
N_test = 200
x_test = np.linspace(-4, 6, N_test)
x_test = np.reshape(x_test, [N_test, 1])
if isinstance(model, aep.SGPSSM_Linear):
zu = model.dyn_layer.zu
else:
zu = model.sgp_layer.zu
mu, vu = model.predict_f(zu)
mf, vf = model.predict_f(x_test)
# plot function
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x_test[:,0], kink_true(x_test[:,0]), '-', color='k')
ax.plot(zu, mu, 'ob')
ax.plot(x_test[:,0], mf[:,0], '-', color='b')
ax.fill_between(
x_test[:,0],
mf[:,0] + 2*np.sqrt(vf[:,0]),
mf[:,0] - 2*np.sqrt(vf[:,0]),
alpha=0.2, edgecolor='b', facecolor='b')
ax.plot(
y[0:model.N-1],
y[1:model.N],
'r+', alpha=0.5)
mx, vx = model.get_posterior_x()
ax.set_xlabel(r'$x_{t-1}$')
ax.set_ylabel(r'$x_{t}$')
ax.set_xlim([-4, 6])
ax.set_ylim([-7, 7])
plt.title(plot_title)
plt.savefig('/tmp/kink_'+plot_title+'.pdf')
# generate a dataset from the kink function above
T = 200
process_noise = 0.2
obs_noise = 0.1
(xtrue, x, y) = kink(T, process_noise, obs_noise)
y_train = np.reshape(y, [y.shape[0], 1])
# init hypers
Dlatent = 1
Dobs = 1
M = 15
C = 1*np.ones((1, 1))
R = np.ones(1)*np.log(obs_noise)/2
lls = np.reshape(np.log(2), [Dlatent, ])
lsf = np.reshape(np.log(2), [1, ])
zu = np.linspace(-1, 5, M)
zu = np.reshape(zu, [M, 1])
lsn = np.log(process_noise)/2
params = {'ls': lls, 'sf': lsf, 'sn': lsn, 'R': R, 'C': C, 'zu': zu}
# params = {'C': C}
alphas = [0.001, 0.05, 0.2, 0.5, 1.0]
for alpha in alphas:
print 'alpha = %.3f' % alpha
# create AEP model
model_aep = aep.SGPSSM_Linear(y_train, Dlatent, M,
lik='Gaussian', prior_mean=0, prior_var=1000)
hypers = model_aep.init_hypers_old(y_train)
for key in params.keys():
hypers[key] = params[key]
model_aep.update_hypers(hypers)
# optimise
model_aep.set_fixed_params(['C'])
model_aep.optimise(method='L-BFGS-B', alpha=alpha, maxiter=10000, reinit_hypers=False)
opt_hypers = model_aep.get_hypers()
plot_latent(model_aep, y, 'AEP %.3f'%alpha)
# create EP model
model_ep = ep.SGPSSM(y_train, Dlatent, M,
lik='Gaussian', prior_mean=0, prior_var=1000)
# init EP model using the AEP solution
model_ep.update_hypers(opt_hypers)
# run EP
if alpha == 1.0:
decay = 0.999
parallel = True
no_epochs = 200
elif alpha == 0.001 or alpha == 0.05 or alpha ==0.2:
decay = 0.5
parallel = True
no_epochs = 1000
else:
decay = 0.99
parallel = True
no_epochs = 500
model_ep.inference(no_epochs=no_epochs, alpha=alpha, parallel=parallel, decay=decay)
plot_latent(model_ep, y, 'PEP %.3f'%alpha)
# create EP model
model_ep = ep.SGPSSM(y_train, Dlatent, M,
lik='Gaussian', prior_mean=0, prior_var=1000)
# init EP model using the AEP solution
model_ep.update_hypers(opt_hypers)
aep_sgp_layer = model_aep.dyn_layer
Nm1 = aep_sgp_layer.N
model_ep.sgp_layer.t1 = 1.0/Nm1 * np.tile(
aep_sgp_layer.theta_2[np.newaxis, :, :], [Nm1, 1, 1])
model_ep.sgp_layer.t2 = 1.0/Nm1 * np.tile(
aep_sgp_layer.theta_1[np.newaxis, :, :, :], [Nm1, 1, 1, 1])
model_ep.x_prev_1 = np.copy(model_aep.x_factor_1)
model_ep.x_prev_2 = np.copy(model_aep.x_factor_2)
model_ep.x_next_1 = np.copy(model_aep.x_factor_1)
model_ep.x_next_2 = np.copy(model_aep.x_factor_2)
model_ep.x_up_1 = np.copy(model_aep.x_factor_1)
model_ep.x_up_2 = np.copy(model_aep.x_factor_2)
model_ep.x_prev_1[0, :] = 0
model_ep.x_prev_2[0, :] = 0
model_ep.x_next_1[-1, :] = 0
model_ep.x_next_2[-1, :] = 0
# run EP
if alpha == 1.0:
decay = 0.999
parallel = True
no_epochs = 200
elif alpha == 0.001 or alpha == 0.05 or alpha == 0.2:
decay = 0.5
parallel = True
no_epochs = 1000
else:
decay = 0.99
parallel = True
no_epochs = 500
model_ep.inference(no_epochs=no_epochs, alpha=alpha, parallel=parallel, decay=decay)
plot_latent(model_ep, y, 'PEP (AEP init) %.3f'%alpha)
```
| github_jupyter |
```
%matplotlib inline
import sys
import os
DATA_PATH = os.getenv('DATA_PATH')
CODE_PATH = os.getenv('CODE_PATH')
FIGURE_PATH = os.getenv('FIGURE_PATH')
sys.path.insert(0, os.path.join(CODE_PATH))
import pandas as pd
import numpy as np
import json
import re
import time
from src.load import EGRID, BA_DATA
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from calendar import month_abbr
import logging.config
logging.config.fileConfig(os.path.join(CODE_PATH, "src/logging.conf"))
logger = logging.getLogger(__name__)
cm_per_in = 0.393701
two_col_width = 17.8 * cm_per_in
os.makedirs(os.path.join(FIGURE_PATH, "main"), exist_ok=True)
os.makedirs(os.path.join(FIGURE_PATH, "si"), exist_ok=True)
plt.style.use('seaborn-paper')
plt.rcParams['figure.figsize'] = [6.99, 2.5]
plt.rcParams['grid.color'] = 'k'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.linestyle'] = ':'
plt.rcParams['grid.linewidth'] = 0.5
plt.rcParams["figure.dpi"] = 200
plt.rcParams["figure.dpi"] = 200
plt.rcParams['font.size'] = 10
import cmocean
cmap = cmocean.cm.cmap_d['phase']
COLORS = sns.color_palette('colorblind')
savePlots = False
def separate_imp_exp(data, ba):
partners = data.get_trade_partners(ba)
imp = 0.
exp = 0.
for ba2 in data.get_trade_partners(ba):
imp += data.df.loc[:, data.KEY["ID"] % (ba,ba2)].apply(lambda x: min(x, 0))
exp += data.df.loc[:, data.KEY["ID"] % (ba,ba2)].apply(lambda x: max(x, 0))
normalization = data.df.loc[:, data.KEY["D"] % ba] + exp
return imp, exp, normalization
barWidth = 0.7
margin = 0.01
co2 = BA_DATA(fileNm=os.path.join(DATA_PATH, "analysis/SEED_CO2_Y.csv"), variable="CO2")
so2 = BA_DATA(fileNm=os.path.join(DATA_PATH, "analysis/SEED_SO2_Y.csv"), variable="SO2")
nox = BA_DATA(fileNm=os.path.join(DATA_PATH, "analysis/SEED_NOX_Y.csv"), variable="NOX")
# Custom selection of exporters and importers
exporters = ['WACM', 'BPAT', 'SRP', 'SOCO', 'AZPS', 'NWMT', 'ERCO']
importers = ['NYIS', 'TVA', 'FPL', 'FPC', 'MISO', 'PJM', 'CISO']
regions = exporters + importers
n = len(regions)
f, axes = plt.subplots(1,3, figsize=(two_col_width, 3.7))
for ax, poll, scaling, xlabel, xlim, min_size_for_text, xticks in zip(
axes, [co2, so2, nox], [1e-6, 1e-3, 1e-3],
["CO2 (Mtons)", "SO2 (ktons)", "NOx (ktons)"],
[[-6, 22], [-6, 22], [-6, 22]],
[8, 6, 6],
[[0, 5, 10, 15, 20], [0, 10, 20], False]):
bgcolor = "#eeeeee"
color = COLORS[0] #"#777777"
color2 = COLORS[1] #"#bbbbbb"
df = poll.df
df.index = [2016]
for iba, ba in enumerate(regions):
imp, exp, norm = separate_imp_exp(poll, ba)
ax.barh(iba+barWidth/4, -imp.values * scaling,
color=color, height=barWidth/2, zorder=3)
ax.barh(iba-barWidth/4, exp.values * scaling,
color=color2, height=barWidth/2, zorder=3)
ha='right'
va = 'center'
x = -1
def myformat(n):
if n>1.:
return "%2.0f%%" % n
if n>0.1:
return "%2.1f%%" % n
else:
return "%2.2f%%" % n
ax.text(x,iba+barWidth/4+.05,
myformat(-(imp.values/norm).values[0]*100+0.),
fontsize="x-small", ha=ha, va=va)
ax.text(x,iba-barWidth/4-.05,
myformat((exp/norm).values[0]*100+0.),
fontsize="x-small", ha=ha, va=va)
ax.text(-6.5,iba, ba, ha=ha, va=va, fontsize="small")
if iba % 2 == 0:
ax.axhspan(iba-.5, iba+.5, color=bgcolor)
# ax.axhline(iba+.5, color='k')
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
ax.set_xlabel(xlabel)
ax.set_xlim(xlim)
ax.set_ylim([-.5, n-.5])
ax.set_yticks(range(len(exporters+importers)))
ax.set_yticklabels([])
ax.yaxis.set_ticks_position('none')
ax.yaxis.grid(False)
if xticks:
ax.set_xticks(xticks)
ax.set_yticklabels([]);
# legend
ax.barh([-10], [1], color=color, height=barWidth/2, zorder=3,
label="Imports")
ax.barh([-10], [1], color=color2, height=barWidth/2, zorder=3,
label="Exports")
ax.legend(loc='center right', framealpha=1.)
ax.xaxis.labelpad = 5
ax.tick_params(axis='x', which='major', pad=0)
axes[0].text(-14, .6*n, "Net Importers",
ha='center', rotation=90, fontsize=9)
axes[0].text(-14, .05*n, "Net Exporters",
ha='center', rotation=90, fontsize=9)
line = matplotlib.lines.Line2D(
(0.02, .1), (.455, .455), zorder=3, transform=f.transFigure, color='k', lw=.5)
f.lines.append(line)
plt.subplots_adjust(left=0.1, bottom=0.01, right=.99, top=.9, wspace=.25)
if savePlots:
f.savefig(os.path.join(FIGURE_PATH, 'main/fig4.pdf'))
```
| github_jupyter |
Before we begin, let's execute the cell below to display information about the CUDA driver and GPUs running on the server by running the `nvidia-smi` command. To do this, execute the cell block below by giving it focus (clicking on it with your mouse), and hitting Ctrl-Enter, or pressing the play button in the toolbar above. If all goes well, you should see some output returned below the grey cell.
```
!nvidia-smi
```
## Learning objectives
The **goal** of this lab is to:
- Learn how to find bottleneck and performance limiters using Nsight tools
- Learn about three levels of parallelism in OpenACC
- Learn how to use clauses to extract more parallelism in loops
In this section, we will optimize the parallel [RDF](../serial/rdf_overview.ipynb) application using OpenACC. Before we begin, feel free to have a look at the parallel version of the code and inspect it once again.
[RDF Parallel Code](../../source_code/openacc/SOLUTION/rdf_data_directive.f90)
Now, let's compile, and profile it with Nsight Systems first.
```
#compile the parallel code for Tesla GPU
!cd ../../source_code/openacc && nvfortran -acc -ta=tesla,lineinfo -Minfo=accel -o rdf nvtx.f90 SOLUTION/rdf_data_directive.f90 -L/opt/nvidia/hpc_sdk/Linux_x86_64/21.3/cuda/11.2/lib64 -lnvToolsExt
#profile and see output
!cd ../../source_code/openacc && nsys profile -t nvtx,openacc --stats=true --force-overwrite true -o rdf_parallel ./rdf
```
Let's checkout the profiler's report. [Download the profiler output](../../source_code/openacc/rdf_parallel.qdrep) and open it via the GUI.
### Further Optimization
Look at the profiler report from the previous section again. From the timeline, have a close look at the the kernel functions. Checkout the theoretical [occupancy](../GPU_Architecture_Terminologies.ipynb). As shown in the example screenshot below, `rdf_98_gpu` kernel has the theoretical occupancy of 62.5%. It clearly shows that the occupancy is a limiting factor. *Occupancy* is a measure of how well the GPU compute resources are being utilized. It is about how much parallelism is running / how much parallelism the hardware could run.
<img src="../images/f_data_thread.png">
NVIDIA GPUs are comprised of multiple [streaming multiprocessors (SMs)](../GPU_Architecture_Terminologies.ipynb) where it can manage up to 2048 concurrent threads (not actively running at the same time). Low occupancy shows that there are not enough active threads to fully utilize the computing resources. Higher occupancy implies that the scheduler has more active threads to choose from and hence achieves higher performance. So, what does this mean in OpenACC execution model?
**3 Levels of Parallelism: Gang, Worker, and Vector**
CUDA and OpenACC programming model use different terminologies for similar ideas. For example, in CUDA, parallel execution is organized into grids, blocks, and threads (checkout the [GPU Architecture Terminologies](../GPU_Architecture_Terminologies.ipynb) notebook to learn more about grids,blocks, threads). On the other hand, the OpenACC execution model has three levels of *Vector*, *Worker* and *Gang*. *Vector* threads work in lockstep, performing a single operation on multipler data (SIMD), whereas *Workers* computes one vector and *Gangs* have 1 or more workers and they all share resources such as cache, or SMs. Gangs run independent of each other.
OpenACC assumes the device has multiple processing elements (Streaming Multiprocessors on NVIDIA GPUs) running in parallel and mapping of OpenACC execution model on CUDA is as below:
- An OpenACC gang is a threadblock
- A worker is a warp
- An OpenACC vector is a CUDA thread
<img src="../images/diagram.png" width="50%" height="50%">
### Vector, Worker and Gang Clauses
So, in order to improve the occupancy, we have to increase the parallelism within the gang. In other words, we have to increase the number of threads that can be scheduled on the GPU to improve GPU thread occupancy.
As you can see from the profiler report's screenshot, the grid dimension is fairly small `<53,1,1>` which shows the small amount of parallelism within the gang. We can use specific clauses to control the level of parallelism so that the compiler would use to parallelise the next loop. Each of *Vector*, *Worker* and *Gang* clauses can take a parameter to specify the size of each level of parallelism. For example we can control the vector length by using the `vector_length (num)` clause or we can add more workers by using `num_workers(num)`.
```fortran
!$acc parallel loop gang worker num_workers(32) vector_length(32)
do i=1,N
!$acc loop vector
do j=1,N
...
```
Now, add `gang`, `vector` and/or `worker` clauses to the code and experiment with the number of vectors and workers. Make necessary changes to the loop directives. Once done, save the file, re-compile via `make`, and profile it again.
From the top menu, click on *File*, and *Open* `rdf.f90` from the current directory at `Fortran/source_code/openacc` directory. Remember to **SAVE** your code after changes, before running below cells.
```
#compile for Tesla GPU
!cd ../../source_code/openacc && make clean && make
```
Let us start inspecting the compiler feedback and see if it applied the optimizations. Below is the screenshot of expected compiler feedback after adding the `gang`and `vector` clause to the code with vector length of 128. You can also change the vector length to 32 or 256 and see how the profiler output changes. The line 101 would change to `101, !$acc loop vector(256) ! threadidx%x` or `101, !$acc loop vector(32) ! threadidx%x`.
<img src="../images/f_gang_vector.png">
Now, validate the output by running the executable, and then **Profile** your code with Nsight Systems command line `nsys`.
```
#Run on Nvidia GPU and check the output
!cd ../../source_code/openacc && ./rdf && cat Pair_entropy.dat
```
The output should be the following:
```
s2 : -2.452690945278331
s2bond : -24.37502820694527
```
```
#profile and see output
!cd ../../source_code/openacc && nsys profile -t nvtx,openacc --stats=true --force-overwrite true -o rdf_gang_vector ./rdf
```
Let's checkout the profiler's report. [Download the profiler output](../../source_code/openacc/rdf_gang_vector.qdrep) and open it via the GUI. Have a look at the example expected profiler report below:
<img src="../images/f_gang_128.png">
Checkout the kernel functions on the timeline and the occupancy. As you can see from the above screenshot, the theoretical occupancy is now 50% (slightly less than before). If we change the vector length to 32, the occupancy will not change as we do not have a lot of concurrent threads running.
<img src="../images/f_gang_32.png" width="30%" height="30%">
The loop iteration count inside the `rdf_98_gpu` function (line 98 according the above compiler feedback) is `natoms = 6720`. In this example, this number is the grid dimension of `<6720,1,1>`.
How much this optimization will speed-up the code will vary according to the application and the target accelerator, but it is not uncommon to see large speed-ups by using collapse on loop nests.
Feel free to checkout the [solution](../../source_code/openacc/SOLUTION/rdf_gang_vector_length.f90) to help you understand better.
### Collapse Clauses
In order to expose more parallelism and improve the occupancy, we can use an additional clause called `collapse` in the `!$acc loop` to optimize loops. The loop directive gives the compiler additional information about the next loop in the source code through several clauses. Apply the `collapse(N)` clause to a loop directive to collapse the next `N` tightly-nested loops to be collapsed into a single, flattened loop. This is useful if you have many nested loops or when you have really short loops. Sample usage of collapse clause is given as follows:
```fortran
!$acc parallel loop collapse (2)
do i=1,N
do j=1,N
< loop code >
```
When the loop count in any of some tightly nested loops is relatively small compared to the available number of threads in the device, creating a single iteration space across all the nested loops, increases the iteration count thus allowing the compiler to extract more parallelism.
**Tips on where to use:**
- Collapse outer loops to enable creating more gangs.
- Collapse inner loops to enable longer vector lengths.
- Collapse all loops, when possible, to do both
Now, add `collapse` clause to the code and make necessary changes to the loop directives. Once done, save the file, re-compile via `make`, and profile it again.
From the top menu, click on *File*, and *Open* `rdf.f90` from the current directory at `Fortran/source_code/openacc` directory. Remember to **SAVE** your code after changes, before running below cells.
```
#compile for Tesla GPU
!cd ../../source_code/openacc && make clean && make
```
Let us start inspecting the compiler feedback and see if it applied the optimizations. Below is the screenshot of expected compiler feedback after adding the `collapse`clause to the code. You can see that nested loops on line 184 has been successfully collapsed.
<img src="../images/f_collapse_feedback.png">
Now, validate the output by running the executable, and then **Profile** your code with Nsight Systems command line `nsys`.
```
#Run on Nvidia GPU and check the output
!cd ../../source_code/openacc && ./rdf && cat Pair_entropy.dat
```
The output should be the following:
```
s2 : -2.452690945278331
s2bond : -24.37502820694527
```
```
#profile and see output
!cd ../../source_code/openacc && nsys profile -t nvtx,openacc --stats=true --force-overwrite true -o rdf_collapse ./rdf
```
Let's checkout the profiler's report. [Download the profiler output](../../source_code/openacc/rdf_collapse.qdrep) and open it via the GUI. Have a look at the example expected profiler report below:
<img src="../images/f_collapse_thread.png">
Checkout the kernel functions on the timeline and the occupancy. As you can see from the above screenshot, the theoretical occupancy is now 62.5%.
The iteration count for the collapsed loop is `natoms * natoms` where `natoms = 6720` (in this example). So, the iteration count for this particular loop (collapse loop) inside the `rdf_98_gpu` function is 45158400 and this number divided by the vector length of *128* is 352800. The maximum grid size is 65535 blocks in each dimension and we can see that we have a grid dimension of `<65535,1,1>` in this example.
By creating a single iteration space across the nested loops and increasing the iteration count, we improved the occupancy and extracted more parallelism.
**Notes:**
- 100% occupancy is not required for, nor does it guarantee best performance.
- Less than 50% occupancy is often a red flag
How much this optimization will speed-up the code will vary according to the application and the target accelerator, but it is not uncommon to see large speed-ups by using collapse on loop nests.
Feel free to checkout the [solution](../../source_code/openacc/SOLUTION/rdf_collapse.f90) to help you understand better.
There is another clause which may be useful in optimizing loops. *Tile* clause breaks down the next loops into tiles before parallelising and it promotes data locality as the device can then use data from nearby tiles.
```fortran
!$acc parallel loop tile (4,4)
do i=1,N
do j=1,N
< loop code >
```
We do not cover this in the labs but this is something you can explore and compare with the explained methods of loop optimization.
## Post-Lab Summary
If you would like to download this lab for later viewing, it is recommend you go to your browsers File menu (not the Jupyter notebook file menu) and save the complete web page. This will ensure the images are copied down as well. You can also execute the following cell block to create a zip-file of the files you've been working on, and download it with the link below.
```
%%bash
cd ..
rm -f nways_files.zip
zip -r nways_files.zip *
```
**After** executing the above zip command, you should be able to download the zip file [here](../nways_files.zip). Let us now go back to parallelizing our code using other approaches.
**IMPORTANT**: If you wish to dig deeper and profile the kernel with the Nsight Computer profiler, go to the next notebook. Otherwise, please click on **HOME** to go back to the main notebook for *N ways of GPU programming for MD* code.
-----
# <p style="text-align:center;border:3px; border-style:solid; border-color:#FF0000 ; padding: 1em"> <a href=../../../nways_MD_start.ipynb>HOME</a> <a href=nways_openacc_opt_2.ipynb>NEXT</a></p>
-----
# Links and Resources
[NVIDIA Nsight System](https://docs.nvidia.com/nsight-systems/)
[NVIDIA Nsight Compute](https://developer.nvidia.com/nsight-compute)
[CUDA Toolkit Download](https://developer.nvidia.com/cuda-downloads)
**NOTE**: To be able to see the Nsight System profiler output, please download Nsight System latest version from [here](https://developer.nvidia.com/nsight-systems).
Don't forget to check out additional [OpenACC Resources](https://www.openacc.org/resources) and join our [OpenACC Slack Channel](https://www.openacc.org/community#slack) to share your experience and get more help from the community.
---
## Licensing
This material is released by OpenACC-Standard.org, in collaboration with NVIDIA Corporation, under the Creative Commons Attribution 4.0 International (CC BY 4.0).
| github_jupyter |
# Machine Learning Engineer Nanodegree
## Supervised Learning
## Project: Building a Student Intervention System
Welcome to the second project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
### Question 1 - Classification vs. Regression
*Your goal for this project is to identify students who might need early intervention before they fail to graduate. Which type of supervised learning problem is this, classification or regression? Why?*
**Answer: ** Classification - as the goal is only to identify the students who might need intervention, and not return a percentage or any other math calculation of such students.
## Exploring the Data
Run the code cell below to load necessary Python libraries and load the student data. Note that the last column from this dataset, `'passed'`, will be our target label (whether the student graduated or didn't graduate). All other columns are features about each student.
```
# Import libraries
import numpy as np
import pandas as pd
from time import time
from sklearn.metrics import f1_score
# Read student data
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
```
### Implementation: Data Exploration
Let's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following:
- The total number of students, `n_students`.
- The total number of features for each student, `n_features`.
- The number of those students who passed, `n_passed`.
- The number of those students who failed, `n_failed`.
- The graduation rate of the class, `grad_rate`, in percent (%).
```
dataset_size = student_data.shape #since the data is stored in a dataframe
# Calculate number of students
n_students = dataset_size[0]
# Calculate number of features
n_features = dataset_size[1]-1
# Calculate passing students
n_passed = len(student_data[student_data.passed == 'yes'])
# Calculate failing students
n_failed = len(student_data[student_data.passed == 'no'])
# Calculate graduation rate
grad_rate = float(n_passed)/float(n_students) * 100 #integer division issue
# Print the results
print "Total number of students: {}".format(n_students)
print "Number of features: {}".format(n_features)
print "Number of students who passed: {}".format(n_passed)
print "Number of students who failed: {}".format(n_failed)
print "Graduation rate of the class: {:.2f}%".format(grad_rate)
```
## Preparing the Data
In this section, we will prepare the data for modeling, training and testing.
### Identify feature and target columns
It is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.
Run the code cell below to separate the student data into feature and target columns to see if any features are non-numeric.
```
# Extract feature columns
feature_cols = list(student_data.columns[:-1])
# Extract target column 'passed'
target_col = student_data.columns[-1]
# Show the list of columns
print "Feature columns:\n{}".format(feature_cols)
print "\nTarget column: {}".format(target_col)
# Separate the data into feature data and target data (X_all and y_all, respectively)
X_all = student_data[feature_cols]
y_all = student_data[target_col]
# Show the feature information by printing the first five rows
print "\nFeature values:"
print X_all.head()
```
### Preprocess Feature Columns
As you can see, there are several non-numeric columns that need to be converted! Many of them are simply `yes`/`no`, e.g. `internet`. These can be reasonably converted into `1`/`0` (binary) values.
Other columns, like `Mjob` and `Fjob`, have more than two values, and are known as _categorical variables_. The recommended way to handle such a column is to create as many columns as possible values (e.g. `Fjob_teacher`, `Fjob_other`, `Fjob_services`, etc.), and assign a `1` to one of them and `0` to all others.
These generated columns are sometimes called _dummy variables_, and we will use the [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummies#pandas.get_dummies) function to perform this transformation. Run the code cell below to perform the preprocessing routine discussed in this section.
```
def preprocess_features(X):
''' Preprocesses the student data and converts non-numeric binary variables into
binary (0/1) variables. Converts categorical variables into dummy variables. '''
# Initialize new output DataFrame
output = pd.DataFrame(index = X.index)
# Investigate each feature column for the data
for col, col_data in X.iteritems():
# If data type is non-numeric, replace all yes/no values with 1/0
if col_data.dtype == object:
col_data = col_data.replace(['yes', 'no'], [1, 0])
# If data type is categorical, convert to dummy variables
if col_data.dtype == object:
# Example: 'school' => 'school_GP' and 'school_MS'
col_data = pd.get_dummies(col_data, prefix = col)
# Collect the revised columns
output = output.join(col_data)
return output
X_all = preprocess_features(X_all)
print "Processed feature columns ({} total features):\n{}".format(len(X_all.columns), list(X_all.columns))
```
### Implementation: Training and Testing Data Split
So far, we have converted all _categorical_ features into numeric values. For the next step, we split the data (both features and corresponding labels) into training and test sets. In the following code cell below, you will need to implement the following:
- Randomly shuffle and split the data (`X_all`, `y_all`) into training and testing subsets.
- Use 300 training points (approximately 75%) and 95 testing points (approximately 25%).
- Set a `random_state` for the function(s) you use, if provided.
- Store the results in `X_train`, `X_test`, `y_train`, and `y_test`.
```
# Import any additional functionality you may need here
from sklearn.cross_validation import train_test_split
# Set the number of training points
num_train = int(X_all.shape[0] * .76) # approx 75% set to training points
# Set the number of testing points
num_test = X_all.shape[0] - num_train
# Shuffle and split the dataset into the number of training and testing points above
X_train, X_test, y_train, y_test = train_test_split(X_all,y_all, test_size=num_test, stratify=y_all, random_state=20)
# Show the results of the split
print "Training set has {} samples.".format(X_train.shape[0])
print "Testing set has {} samples.".format(X_test.shape[0])
```
## Training and Evaluating Models
In this section, you will choose 3 supervised learning models that are appropriate for this problem and available in `scikit-learn`. You will first discuss the reasoning behind choosing these three models by considering what you know about the data and each model's strengths and weaknesses. You will then fit the model to varying sizes of training data (100 data points, 200 data points, and 300 data points) and measure the F<sub>1</sub> score. You will need to produce three tables (one for each model) that shows the training set size, training time, prediction time, F<sub>1</sub> score on the training set, and F<sub>1</sub> score on the testing set.
**The following supervised learning models are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**
- Gaussian Naive Bayes (GaussianNB)
- Decision Trees
- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)
- K-Nearest Neighbors (KNeighbors)
- Stochastic Gradient Descent (SGDC)
- Support Vector Machines (SVM)
- Logistic Regression
### Question 2 - Model Application
*List three supervised learning models that are appropriate for this problem. For each model chosen*
- Describe one real-world application in industry where the model can be applied. *(You may need to do a small bit of research for this — give references!)*
- What are the strengths of the model; when does it perform well?
- What are the weaknesses of the model; when does it perform poorly?
- What makes this model a good candidate for the problem, given what you know about the data?
**Answer: **
| | Adaboost(ensemble) | K-Nearest Neighbors | Support Vector Machines |
| ---------------------------- |:-------------------------------|:-------------------------------| :-----------------------------|
| Read world example: |Viola-Jones face detector | Famous Iris classification dataset |Detecting spam from emails |
| Strengths: | 1. No prior knowledge needed about weak learner 2. Simple and easy to program 3. During training, only selects features that improves predictive power of the model (by reducing dimension and speeding up execution power) 4. Detection is fast | 1. Simple & powerful 2. Doesn't make assumptions based on probability distribution of input set hence is more robust (also insensitive to outliers) 3. Lazy learning algorithm -therefore generalizes in the testing phase (meaning, can quickly adapt to change) |1. Works well on smaller, cleaner datasets 2. Great accuracy |
| Weaknesses: |1. Complex weak classifiers result to overfitting 2. If the weak classifiers are too weak, it can lead to low margin again causing overfitting 3. Sesitive to noisy data and outliers 4. Training is slow | 1. Expensive & slow - O(samples * dimensions) 2. Requires lot of memory | 1. Ignores sentence structures (as it techincally works with bag of words) 2. Requires lot of memory & CPU time (especially for larger datasets) 3. Heavily depends on choosing right kernel function 4. Less effective when you have noisy data with overlapping classes |
| Why a good fit for the problem? | Since we're planning to look at the data spanning next decade, we'll have plenty of data to help come up with a clear generalization. Also once training is done, it can predict faster resulting us help students before it's too late. | Since we're working with labeled dataset | Since the feature set is sparse and it's a text classification problem |
| References: | https://www.cs.ubc.ca/~lowe/425/slides/13-ViolaJones.pdf ; http://math.mit.edu/~rothvoss/18.304.3PM/Presentations/1-Eric-Boosting304FinalRpdf.pdf | https://ocw.mit.edu/courses/sloan-school-of-management/15-097-prediction-machine-learning-and-statistics-spring-2012/lecture-notes/MIT15_097S12_lec06.pdf ; https://brilliant.org/wiki/k-nearest-neighbors/ | http://u.cs.biu.ac.il/~haimga/Teaching/AI/saritLectures/svm.pdf ; http://www.kdnuggets.com/2016/07/support-vector-machines-simple-explanation.html |
### Setup
Run the code cell below to initialize three helper functions which you can use for training and testing the three supervised learning models you've chosen above. The functions are as follows:
- `train_classifier` - takes as input a classifier and training data and fits the classifier to the data.
- `predict_labels` - takes as input a fit classifier, features, and a target labeling and makes predictions using the F<sub>1</sub> score.
- `train_predict` - takes as input a classifier, and the training and testing data, and performs `train_clasifier` and `predict_labels`.
- This function will report the F<sub>1</sub> score for both the training and testing data separately.
```
def train_classifier(clf, X_train, y_train):
''' Fits a classifier to the training data. '''
# Start the clock, train the classifier, then stop the clock
start = time()
clf.fit(X_train, y_train)
end = time()
# Print the results
print "Trained model in {:.4f} seconds".format(end - start)
def predict_labels(clf, features, target):
''' Makes predictions using a fit classifier based on F1 score. '''
# Start the clock, make predictions, then stop the clock
start = time()
y_pred = clf.predict(features)
end = time()
# Print and return results
print "Made predictions in {:.4f} seconds.".format(end - start)
return f1_score(target.values, y_pred, pos_label='yes')
def train_predict(clf, X_train, y_train, X_test, y_test):
''' Train and predict using a classifer based on F1 score. '''
# Indicate the classifier and the training set size
print "Training a {} using a training set size of {}. . .".format(clf.__class__.__name__, len(X_train))
# Train the classifier
train_classifier(clf, X_train, y_train)
# Print the results of prediction for both training and testing
print "F1 score for training set: {:.4f}.".format(predict_labels(clf, X_train, y_train))
print "F1 score for test set: {:.4f}.".format(predict_labels(clf, X_test, y_test))
```
### Implementation: Model Performance Metrics
With the predefined functions above, you will now import the three supervised learning models of your choice and run the `train_predict` function for each one. Remember that you will need to train and predict on each classifier for three different training set sizes: 100, 200, and 300. Hence, you should expect to have 9 different outputs below — 3 for each model using the varying training set sizes. In the following code cell, you will need to implement the following:
- Import the three supervised learning models you've discussed in the previous section.
- Initialize the three models and store them in `clf_A`, `clf_B`, and `clf_C`.
- Use a `random_state` for each model you use, if provided.
- **Note:** Use the default settings for each model — you will tune one specific model in a later section.
- Create the different training set sizes to be used to train each model.
- *Do not reshuffle and resplit the data! The new training points should be drawn from `X_train` and `y_train`.*
- Fit each model with each training set size and make predictions on the test set (9 in total).
**Note:** Three tables are provided after the following code cell which can be used to store your results.
```
# Import the three supervised learning models from sklearn
from sklearn.ensemble import AdaBoostClassifier # AdaBoost
from sklearn.neighbors import KNeighborsClassifier # kNN
from sklearn.svm import SVC # SVM
# Initialize the three models
clf_A = AdaBoostClassifier(random_state = 20)
clf_B = KNeighborsClassifier()
clf_C = SVC(random_state = 20)
# Set up the training set sizes
X_train_100 = X_train[:100]
y_train_100 = y_train[:100]
X_train_200 = X_train[:200]
y_train_200 = y_train[:200]
X_train_300 = X_train
y_train_300 = y_train
# Execute the 'train_predict' function for each classifier and each training set size
train_predict(clf_A, X_train_100, y_train_100, X_test, y_test)
train_predict(clf_A, X_train_200, y_train_200, X_test, y_test)
train_predict(clf_A, X_train_300, y_train_300, X_test, y_test)
train_predict(clf_B, X_train_100, y_train_100, X_test, y_test)
train_predict(clf_B, X_train_200, y_train_200, X_test, y_test)
train_predict(clf_B, X_train_300, y_train_300, X_test, y_test)
train_predict(clf_C, X_train_100, y_train_100, X_test, y_test)
train_predict(clf_C, X_train_200, y_train_200, X_test, y_test)
train_predict(clf_C, X_train_300, y_train_300, X_test, y_test)
```
### Tabular Results
Edit the cell below to see how a table can be designed in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#tables). You can record your results from above in the tables provided.
** Classifer 1 - AdaBoost**
| Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
| :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: |
| 100 | 0.2880 | 0.0150 | 0.9403 | 0.6957 |
| 200 | 0.2640 | 0.0150 | 0.8623 | 0.7231 |
| 300 | 0.2630 | 0.0160 | 0.8505 | 0.7626 |
** Classifer 2 - kNN**
| Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
| :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: |
| 100 | 0.0000 | 0.0000 | 0.8299 | 0.7724 |
| 200 | 0.0160 | 0.0060 | 0.8472 | 0.7368 |
| 300 | 0.0050 | 0.0150 | 0.8565 | 0.7794 |
** Classifer 3 - SVM**
| Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
| :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: |
| 100 | 0.0000 | 0.0000 | 0.8609 | 0.7871 |
| 200 | 0.0150 | 0.0160 | 0.8696 | 0.8026 |
| 300 | 0.0160 | 0.0040 | 0.8633 | 0.7922 |
## Choosing the Best Model
In this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F<sub>1</sub> score.
### Question 3 - Choosing the Best Model
*Based on the experiments you performed earlier, in one to two paragraphs, explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?*
**Answer: ** **SVM** seems to perform the best.
From the previous table, it's clear that SVM is performing consistently better than the other 2 algorithms. It's not expensive based on the current size of the dataset. Also performance wise, F1-scores for test dataset doesn't increase for a larger dataset while the time taken to train and test takes slightly more than kNN with different dataset size (overall far consistent than Adaboost)
### Question 4 - Model in Layman's Terms
*In one to two paragraphs, explain to the board of directors in layman's terms how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical or technical jargon, such as describing equations or discussing the algorithm implementation.*
**Answer: **
We'll be using SVM (Support Vector Machine) algorithm to classify students into who needs internvention and who doesn't. After loading, cleaning and deciding feature and training set of the data, we split entire data into test and training set. Fitting the basic SVM on to the training set, it predicts features for both training and test set (meaning, F1 score). The same process is repeated with different sizes of dataset (100, 200, 300) and values and accuracy are compared.
Model tries to find a linear function such that it can significantly separate both the classes - where it can maximize the margin between the line and the closest point to both the classes. Though SVM wants to maximize the margin, when it comes between correctly classifying an item verses maximizing, it give classification higher priority (even if it means margin would be smaller). Often the problem isn't that simple hence we might have to come up with complex functions to separate the two classes. In such cases, instead of manually coming up with those functions, we have something called "kernel" trick that would find the same linear function in muti-dimensional space and help separate the classes. Eventually the model is trying to predict, given a new student data, which side of the boundary would they be placed and how accurate that prediction is.
### Implementation: Model Tuning
Fine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:
- Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).
- Create a dictionary of parameters you wish to tune for the chosen model.
- Example: `parameters = {'parameter' : [list of values]}`.
- Initialize the classifier you've chosen and store it in `clf`.
- Create the F<sub>1</sub> scoring function using `make_scorer` and store it in `f1_scorer`.
- Set the `pos_label` parameter to the correct value!
- Perform grid search on the classifier `clf` using `f1_scorer` as the scoring method, and store it in `grid_obj`.
- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_obj`.
```
# Import 'GridSearchCV' and 'make_scorer'
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer
# Create the parameters list you wish to tune
parameters = {'gamma':[0.12], 'C':[1,2,20]}
# Initialize the classifier
clf = SVC()
# TODO: Make an f1 scoring function using 'make_scorer'
def score_func():
return make_scorer(f1_score, pos_label='yes')
f1_scorer = score_func()
# TODO: Perform grid search on the classifier using the f1_scorer as the scoring method
grid_obj = GridSearchCV(clf, parameters, scoring=f1_scorer)
# TODO: Fit the grid search object to the training data and find the optimal parameters
grid_obj = grid_obj.fit(X_train, y_train)
# Get the estimator
clf = grid_obj.best_estimator_
# Report the final F1 score for training and testing after parameter tuning
print "Tuned model has a training F1 score of {:.4f}.".format(predict_labels(clf, X_train, y_train))
print "Tuned model has a testing F1 score of {:.4f}.".format(predict_labels(clf, X_test, y_test))
```
### Question 5 - Final F<sub>1</sub> Score
*What is the final model's F<sub>1</sub> score for training and testing? How does that score compare to the untuned model?*
**Answer: **
After tuning i got training F1 score to bump up to 98.77% while the testing F1 score slightly bumped up to 82%. It could mean that the model have now overfit the dataset that test's score cannot be improved
> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to
**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
| github_jupyter |
```
%run -i ../python/common.py
```
# Operating Systems and UNIX
We call the collection of software that we use to make a "computer" "useful" an operating system. But what exactly does this mean?
## Computer
Today a computer can take many forms from desktop Personal Computers (PCs), laptops, mobile phones, tablets, building scale super-computers, etc. In some sense the defining property we care about is that the device supports a classic model for programming it -- we call this model the von Neumann architecture. We will discuss this model in much more detail when we start considering exactly how software and hardware work with respect to [assembly language](../assembly/intro.ipynb). Below illustrates how we will visually represent a generic von Neumann based computer and summarizes what we need to know for now.
```
display(Markdown(htmlFig("../images/src/SLS_TheMachine.svg",
align="left",
margin="auto 3em 0 auto",
width="100%", id="fig:vnm",
caption="Figure: Our illustration of a von Neumann computer")))
```
**Central Processing Unit (CPU):**
- the smart bits that "execute" the instructions of software, also called the processor.
**Memory**
- the devices that hold the instructions and data that make up the running software
- physically connected to the CPU via direct wiring -- often referred to as RAM, main memory, etc
- fast, power hungry and volatile (values are lost when electricity is lost)
**I/O devices** -- for the moment we only consider two categories
- Storage devices:
- hard drives, ssd's, flash memory, flash drives/usb sticks, etc
- slow and large compared to main memory
- requires much more complicated programming to access its data compared to Memory
- non-volatile (keep their values even when they don't have electricity)
- Communication devices:
- allow connections to the outside world
- networks, terminals, usb devices -- keyboards, mice, etc.
For the moment it suffices to say that programming a computer means being able to apply your knowledge of a programming language and existing software to have the computer do something you want it to. For example, edit photos, play music, maintain a list of grocery items, calculate PI, send email, browse the web, test if a molecule might have promise as a new vaccine, automatically adjust the temperature of your home, control a car, etc.
### Programmer vs User
To be honest many people simply care that the computer can run existing programs -- we will call these folks "Users". However, "Programmers" are a special type of user. Programmers use Operating Systems, and other software tools to create new programs themselves. As a matter of fact some programmers simply focus on developing programs that make writing programs easier -- like the folks that develop the operating system software, programming languages, editors, etc.
## Useful
So from our perspective, the main aspects of the operating system, that we care about, is that it makes it ease for programmers to create new programs. In addition we would like an operating system that does not hide things from us so that we can explore how programs (and computers) work.
Operating Systems are designed and created with specific uses and hardware in mind. Some are designed for special purpose computers and the programs that are expected to run on them like computers built into an airplane to control its various parts or a super-computer which is expected to run complex and large scientific simulation programs. While other operating systems are designed primarily to enable users to install and run commercial grade programs on their personal devices. These operating systems while they do enable programmers to write new programs, they are designed to hide most of these aspects from their "normal" target user. Those users mainly just wants to use programs written by others. The interface of these operating systems tend to focus on graphics and visually oriented ways of interacting with programs.
## UNIX
<img align="right" src="../images/Unix.gif" width="25%" style="margin: auto auto auto auto">
UNIX on the other hand assumes that its users are primarily programmers. Its design and collection of tools are not meant to be particularly user friendly. Rather UNIX is designed to allow programmers to be very productive and to support a broad range of programming tools. Many of the concepts and mechanisms of UNIX underly, are in, other operating systems but have been hidden or obscured to make things easier for their non-programmer users.
### An operating System Built by Programmers for Programmers
The [UNIX](https://www.opengroup.org/membership/forums/platform/unix) operating system was built by master programmers who valued programmability and productivity. In some sense learning to work on the UNIX systems is a right of passage that not only teaches you how to be productive on a computer running the UNIX operating system but teaches you to think and act like a programmer.
Given its programming focus UNIX is organized around two categories of software -- kernel and user. The kernel is a component of the UNIX that users of UNIX do not directly interact with. It is the core software that is used to manage the various devices of the computer and construct an environment that allows programmers to create new users programs. The idea is that very little is really built into UNIX rather its users are encouraged to write lots of small programs that build on the functionality of the kernel to do useful things. The kernel's main job is to provide the ability to run new program, provide those programs with access to the hardware, and provide common ways for programs to interconnect, work together.
I know this all sounds a bit recursive -- welcome to computer science. As we start interacting with UNIX it will make more sense.
> <img style="margin: 1em auto 0 0;" align="left" width="60px" src="../images/history.png"> <p style="background-color:powderblue;"> Unix recently celebrated its 50th year Anniversary. <br>
[50 Years of Unix](https://www.bell-labs.com/about/history/innovation-stories/50-years-unix/#gref) <br>
The people and its history are a fascinating journey into how we have gotten to where we are today. <br>
[The Strange birth and long life of Unix](https://spectrum.ieee.org/the-strange-birth-and-long-life-of-unix#toggle-gdpr) <br>
UNIX and it's children literally make our digital world go around and will likely continue to do so for the quite some time.
</p>
<a id='UnixKernel_sec'></a>
### The Kernel
The Kernel is the bottom layer of software that has direct access to all the hardware. There is a single instance of the kernel that bootstraps the hardware. It provides a means for starting application programs (often also called user programs). The kernel performs and provides several important abilities.
1. The kernel enables several user programs to run at the same time.
2. The kernel keeps each running user program isolated from each other -- such that each program can behave as if it is the only program running.
3. The kernel provides facilities for managing the running programs, eg. listing, pausing, terminating, etc.
4. While user programs can be started and can end the kernel is always present and running. If it ends it means the your computer has crashed!
5. The kernel provides a collection of ever present functions and objects that programs/programmers can rely on:
- it provides core "software" "abstractions" packaged in the form of a library of kernel functions
- these functions make it easier for programs to use the hardware
- the kernel ensures that these functions, behaves consistently across different hardware
- these functions hides the details and complexity of the hardware devices from the programs and thus the programmers who wrote them. For example a Unix kernel provides programs with the generic abstraction of a ["file"](../unix/files.ipynb) that allows programs to create, store and recall data on storage devices without ever needing to know any details of the devices themselves.
<img style="margin: 10px 0px 0px 0px;" align="left" width="60" src="../images/warning.svg"> A critical point of the Unix design: **Humans do not and cannot directly interact with the kernel, only User Programs can interact with the kernel by invoking kernel functions**. This design promotes and encourages that the rest of the operating systems and for that matter all other software be viewed as separated from the kernel. As such it encourages a building block approach where several alternatives for any given OS feature, like human interface programs, can be added, supported and explored while the kernel remains without change. The goal is to empower programmers to grow and extend the system in a natural and seamless way.
It is worth noting most modern operating systems have adopted this basic organization where there is a base kernel component and a large collection of pre-packaged user programs.
<a id='UnixUser_sec'></a>
### User Programs
Largely what most people think of when they think of an OS is the large body of pre-packaged user programs that can be installed with the kernel of the OS. Typically there are at least three categories of user programs, including:
1. Display Servers: These are collections of programs designed to operate specific devices for human interaction such as graphical screens, keyboards, mice, touch pads, touch screens, etc. The first layer of this software (after the kernel) is typically some form of [Windowing System](https://en.wikipedia.org/wiki/Windowing_system#Display_server). Examples include Microsoft's [Desktop Window Manager](https://en.wikipedia.org/wiki/Desktop_Window_Manager), Apple's [Quartz Compositor](https://en.wikipedia.org/wiki/Quartz_Compositor) and the [X Window System](https://en.wikipedia.org/wiki/X_Window_System) traditionally used by Unix operating systems. Today we are also seeing the rise of using web-browsers to present a graphical interface system this includes [Jupyter Lab](https://en.wikipedia.org/wiki/Project_Jupyter#JupyterLab) which we make use of. However, as in the case of Unix, older systems they typically retain support for their rich older [ASCII terminal devices](../unix/terminal.ipynb) in the form of command line shell programs ([Shell](../unix/shellintro.ipynb)).
2. [File Managers](https://en.wikipedia.org/wiki/File_manager): Programs that work with a Display Server and provide a human the ability to explore and find information about the other programs and data installed. Examples include Apple's [Finder](https://en.wikipedia.org/wiki/Finder_(software)) and Microsoft's [File Manager](https://en.wikipedia.org/wiki/File_Manager_(Windows)).
3. Other: There is a highly variable collection of software that form the rest of the user programs. This body largely depending on the OS and its intended target audience. In the case of OS's that are geared to personal computers this set of software includes: media programs, web-browsers, productivity applications and more. While not always standard, the tools for developing new programs also fall in this category. These include program editors, programming languages and debuggers. A hallmark of Unix is the rich body of programming tools associated with it (including the tools to rebuild the kernel itself).
One of the distinguishing feature of Unix is its standard user command line programs that are geared to programmers (https://en.wikipedia.org/wiki/List_of_Unix_commands). While they lack graphical interfaces and are [ASCII](../unix/terminal.ipynb#ASCII_sec)/command line oriented they form a very rich and powerful set of building blocks that allow a knowledgeable programmer to rapidly create turnkey solutions including the; text searching and transformation, data wrangling, automation, as well as the development and debugging of large applications.
<a id='UnixViz_sec'></a>
### Visualizing a Unix system
```
display(Markdown(htmlFig("../images/UnixRunning.png",
caption="Figure: Running Unix system.",
width="50%", align="right",
margin="auto auto auto 1.5em") + '''
We visualized a running Unix system with the Hardware of the computer at the bottom, shaded
blue, and the running software, shaded in green, above it. The Unix Kernel is a persistent
program that forms the foundation for launching and running instances of user programs and
is illustrated as the green oval labeled "UNIX Kernel". The smaller green circles represent
the currently running programs that have been started. Each time a program is started we
visualize a new circle representing a new running instances of the program. In the diagram
each is labeled with the program that was used to start it. Each instance is independent and
has its own "life-time". If a specific running instance of a program ends, crashes or is
terminated (killed) by the user we would remove its circle. So while in reality we can't
physically see the programs running we none the less think of the running software as forming
a world of its own, inside the machine, with the kernel enabling its construction and management.
'''))
```
### Benefits to studying UNIX
UNIX's terminal interface and program development environment became the gold standard for university Computer Science education. The following are some of the reasons it became so and why it continues to be critical both academically, scientifically and industrially.
The most basic interface it presents, the [Shell](../unix/shellintro.ipynb), is a programmer oriented model for interacting with the computer. Furthermore Unix comes with a large collection of composable and extensible tools for processing ASCII documents that naturally integrate and extend the power of the Shell. These tools make it easy to write new programs including programs that translate ASCII documents, source code in one language, into source code of another language.
While it takes some effort to learn its strange command line interface, doing so teaches you to think like a programmer. Where you are encouraged to writing little re-usable programs that you incrementally evolve as needed and combine with others to get big tasks done. Generally trying to avoid any particular program from getting too complicated.
UNIX also does is not prescriptive on how you should do things. Rather it provides a large collection of simple building blocks that you can learn to creatively use to meet your needs. The investment in learning its building blocks and models for composing them minimizes time and effort in going from an idea to a prototype. UNIX's programming oriented nature leads to an environment in which almost anything about the OS and user experience can be customized and programmed. UNIX makes automation the name of the game -- largely everything you can do manually can be turned into a program that automates the task.
UNIX has instilled in generations of computer scientists a basic aesthetic for how to design and structure complicated collections of software. In particular one learns that the designers of UNIX tried to structure the system around a small core set of ideas, "abstractions", that once understood allows a programmer to understand the rest of the system and how to get things done. In UNIX this set includes: Files, Processes, I/O redirection, Users and Groups. All of which we will cover late in this book.
UNIX's programming friendly nature has lead to the development of a very large and rich body of existing software for UNIX. With contributions coming from researchers, industry, students and hobbyists alike. This body of software has come to be a large scale shared human repository that we rely on heavily. The computer servers that form the core of the Internet and the Cloud largely run a UNIX variant called Linux. Many of the computers embedded in the devices that surround us from wifi routers, medical devices, automobiles, and everything else also often run a version of Linux. But perhaps most critically UNIX, in the form of Linux, is a corner stone of the Open Source software ecosystem.
## Bottomline
UNIX comes with the kernel and a large collection of existing programs that permit a programmer to write more programs, that they and others can use. In this book we will focus on what a program really is, how they are constructed and along the way the core tools, skills and ideas that underly all of computing. Given UNIX's programmer focus and transparency it is a good choice for us. Furthermore, learning how to be productive in the UNIX environment will teach us a lot about being productive programmers period.
> <img style="display: inline; margin: 1em auto auto auto;" align="left" width="60px" src="../images/fyi.png"> <p style="background-color:powderblue;">
*What is LINUX?*: Linux or more formally GNU/Linux is an open source variant of the UNIX operating system that is in heavy use today. Every imaginable type of computer runs Linux. In some sense it has become the computing equivalent of both "The Force" and "Duct Tape". It is worth noting that Linux began its life because a University student got interested in Operating Systems and was frustrated with the current "Closed" state of the art.
<img align="right" width="60" src="../images/tux.png">
</p>
## HIDDEN FROM BOOK
This Markdown that I want to hide from the juputer book
| github_jupyter |
<a href="https://colab.research.google.com/github/DJCordhose/ml-workshop/blob/master/notebooks/intro/2021/intro-regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Regression
```
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (20, 8)
mpl.rcParams['axes.titlesize'] = 24
mpl.rcParams['axes.labelsize'] = 20
figsize_3d = (20, 10)
```
# Part I: The use case and data
## We begin with a plot of a dependent variable
```
#@title A noisy line of shape y = m*x + b { run: "auto", display-mode: "form" }
# https://colab.research.google.com/notebooks/forms.ipynb
n = 50 #@param {type:"slider", min:10, max:500, step:1}
m = -1 #@param {type:"slider", min:-10, max:10, step: 0.1}
b = 1 #@param {type:"slider", min:-10, max:10, step: 0.1}
noise_level = 0.1 #@param {type:"slider", min:0.0, max:1.0, step:0.1}
title = 'Predict y from x (based on a line with noise)' #@param {type:"string"}
x_label = 'x' #@param {type:"string"}
y_label = 'y' #@param {type:"string"}
import numpy as np
np.random.seed(42)
# sort is not necessary, but makes x easier to understand
x = np.sort(np.random.uniform(0, 1, n))
y = m*x+b + np.random.normal(0, noise_level, n)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
plt.scatter(x, y);
```
## Let's find a matching example
_Let's change the title and what is on the axis to match our application_
## _Challenge: How do we fit the best line possible?_
* Maybe to predict the future
* Or understand the nature of the data
_Having a **line** is our prior believe, we will later remove this assumption_
```
x, y
```
# Part II: Building a model (structure, architecture)
## Our model: linear
### ```y = m*x + b```
* `m` is the slope
* `b` is the y-intercept
```
class LinearModel:
def __init__(self, m=0, b=0):
self.m = m
self.b = b
def __call__(self, x):
y = self.m * x + self.b
return y
model = LinearModel()
y_pred = model(x)
plt.plot(x, y_pred, color='r')
plt.scatter(x, y_pred, color='r')
plt.scatter(x, y);
```
## How wrong are we?
### This is obviously wrong, but how wrong are we?
```
def error(y_true, y_pred):
return np.sum(y_true - y_pred)
error(y, y_pred)
def absolute_error(y_true, y_pred):
return np.sum(np.abs(y_true - y_pred))
absolute_error(y, y_pred)
def mean_absolute_error(y_true, y_pred):
return np.sum(np.abs(y_true - y_pred)) / len(y_true)
mean_absolute_error(y, y_pred)
```
### The loss/error depends on our model and its parameters
<img src='https://djcordhose.github.io/ml-workshop/img/loss.png'>
### Loss in 2d
<img src='https://github.com/DJCordhose/ml-workshop/raw/master/img/loss-2d.png'>
https://okai.brown.edu/chapter4.html
# Part III: Naive Training, bringing down the loss in a loop
Parameters to tweak
* m for the slope
* b for the y-intercept
naive implementation
1. if we bring m or b up or down, does this improve the loss?
1. if so, do it
1. rinse and repeat for a number of times
```
model = LinearModel()
EPOCHS = 500
learning_rate = 0.01
losses = []
for step in range(EPOCHS):
y_pred = model(x)
loss = mean_absolute_error(y, y_pred)
# just for logging
losses.append(loss)
# let's try m
new_model = LinearModel(m = model.m + learning_rate, b = model.b)
new_y_pred = new_model(x)
new_loss = mean_absolute_error(y, new_y_pred)
if new_loss < loss:
model.m += learning_rate
else:
model.m -= learning_rate
# then b
new_model = LinearModel(m = model.m, b = model.b + learning_rate)
new_y_pred = new_model(x)
new_loss = mean_absolute_error(y, new_y_pred)
if new_loss < loss:
model.b += learning_rate
else:
model.b -= learning_rate
"slope (m): {}, y-intercept (b): {}".format(model.m, model.b)
# plt.yscale('log')
plt.plot(losses);
y_pred = model(x)
plt.plot(x, y_pred, color='r')
plt.scatter(x, y_pred, color='r')
plt.scatter(x, y);
```
## We already have a working solution: But does this scale to an example with many more parameters and more inputs?
1. Calculating the output might be expensive
2. Trying out all parameters in a random way like we do would have a bad performance for a large problem
3. Wouldn't we also need to try them in combination?
# Part IV: Change our solution to become a state of the art neural network using TensorFlow
1. Replace our model with a fully connected layer
2. Use a standard loss function
3. Finding parameters to tune in a more efficient way
4. Changing parameters in a more subtle way
```
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
tf.__version__
tf.random.set_seed(42)
!nvidia-smi
```
## Step 1: use a dense layer instead of our simple model
* Scales well for as many neurons and inputs as we want
* Remember: for now we are assuming a line, but this is a prior that might not be necessary
* Efficient implementation on GPUs
### The Artificial Neuron: Foundation of Deep Neural Networks (simplified, more later)
<img src='https://djcordhose.github.io/ml-workshop/img/neuron-v2.png'>
```
from tensorflow.keras.layers import Dense
model = tf.keras.Sequential([
Dense(units=1, input_dim=1)
])
model.summary()
```
### Defining a dense layer with a random number of neurons and inputs
<img src='https://github.com/DJCordhose/ml-workshop/blob/master/notebooks/tf-intro/neuron-to-layer.png?raw=1'>
## Step 2: use standard loss and metric
* what we defined is called mean absolute error: mae
* mean squared error is more common, it squares the differences and gives high values a larger weight: mse
* both are pre-defined efficiently in TensorFlow 2
### Mean Absolute Error
what we had before implemented more efficiently
```
tf.losses.mean_absolute_error(y_true=tf.squeeze(y), y_pred=tf.squeeze(y_pred)).numpy()
```
### Mean Squared Error
emphasizes larger errors
$MSE = {\frac {1}{n}}\sum _{i=1}^{n}(Y_{i}-{\hat {Y_{i}}})^{2}$
https://en.wikipedia.org/wiki/Mean_squared_error
```
def mean_squared_error(y_true, y_pred):
return np.sum(np.square(y_true - y_pred)) / len(y_true)
mean_squared_error(y, y_pred)
tf.losses.mean_squared_error(y_true=tf.squeeze(y), y_pred=tf.squeeze(y_pred)).numpy()
```
### R2 Metric: MSE and MAE are not speaking
* Loss functions need to be differentiable (you will see later why)
* This often restricts how speaking they are in terms of business value
* Metrics do not have that resriction, but take the same parameters
* R^2 score, the closer to 1 the better
* loosely speaking: how much better is this than predicting the constant mean
* 0 would mean just as good
* 1 is perfect
* neg. would mean even worse
* it can become arbitrarily worse
<img src='https://github.com/DJCordhose/ml-workshop/blob/master/notebooks/tf-intro/r2.png?raw=1'>
<small>
CC BY-SA 3.0, https://commons.wikimedia.org/wiki/File:Coefficient_of_Determination.svg
</small>
https://en.wikipedia.org/wiki/Coefficient_of_determination
```
# https://keras.io/metrics/#custom-metrics
# https://www.tensorflow.org/tutorials/customization/performance
# ported to TF 2 from
# * https://stackoverflow.com/a/42351397/1756489 and
# * https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/discussion/34019 (for use of epsilon to avoid strange inf or -inf)
# only works properly on tensors
@tf.function
def r2_metric(y_true, y_pred):
total_error = tf.reduce_sum(tf.square(tf.subtract(y_true, tf.reduce_mean(y_true))))
unexplained_error = tf.reduce_sum(tf.square(tf.subtract(y_true, y_pred)))
R_squared = tf.subtract(1.0, tf.divide(unexplained_error, tf.add(total_error, tf.keras.backend.epsilon())))
return R_squared
x_tensor = tf.reshape(tf.constant(x, dtype=tf.float32), (n, 1))
y_tensor = tf.reshape(tf.constant(y, dtype=tf.float32), (n, 1))
y_pred_tensor = tf.reshape(tf.constant(y_pred, dtype=tf.float32), (n, 1))
r2_metric(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred_tensor)).numpy()
```
## Step 3: Finding parameters to tune
### Backpropagation algorithm: The core of how a neural network learns
_In a nutshell:_
1. Predict: Let the network make a prediction
1. Calculate the loss: how accurate was the predition
1. Record a function of how the trainable parameters affect the loss
1. partial derivations: find out in which direction to change all parameters to bring down the loss
1. Optimizer: Make changes to parameters based on learning rate and other parameters
### Loss depends on the trainable variables, in our case two parameters: weight and bias
This is how the loss function might change depending on those variables
<img src='https://djcordhose.github.io/ai/img/gradients.jpg'>
https://twitter.com/colindcarroll/status/1090266016259534848
### Looking at the loss surface for our problem
```
model.trainable_weights[0]
step = 0.1
w_space = np.arange(-2, 2, step)
b_space = np.arange(-2, 2, step)
sample_size = len(w_space)
losses = np.zeros((sample_size, sample_size))
min_loss = float('inf')
min_params = None
for wi in range(sample_size):
for bi in range(sample_size):
model.trainable_weights[0].assign(w_space[wi].reshape(1, 1))
model.trainable_weights[1].assign(b_space[bi].reshape(1, ))
y_pred = model(x_tensor)
loss = tf.losses.mean_squared_error(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred)).numpy()
if loss < min_loss:
min_loss = loss
min_params = (w_space[wi], b_space[bi])
# the order seems weird, but aparently this is what the 3d plot expects
losses[bi, wi] = loss
# min_loss, min_params
# https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
fig = plt.figure(figsize=figsize_3d)
ax = fig.add_subplot(111, projection='3d')
ax.set_title('Loss surface')
W, B = np.meshgrid(w_space, b_space)
# ax.plot_wireframe(W, B, losses)
surf = ax.plot_surface(W, B, losses, cmap=cm.coolwarm,
# linewidth=0,
alpha=0.8,
# antialiased=False
)
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlabel('w - slope')
ax.set_ylabel('b - y-intercept')
ax.scatter(min_params[0], min_params[1], min_loss, s=100, color='r')
# https://en.wikipedia.org/wiki/Azimuth
# ax.view_init(elev=30, azim=-60); # default
# ax.view_init(elev=50, azim=60);
ax.view_init(elev=10, azim=45);
```
### For this we need partial derivations
TensorFlow offers automatic differentiation: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/GradientTape
* tape will record operations for automatic differentiation
* either by making it record explicily (watch) or
* by declaring a varible to be trainable (which we did in the layer above)
```
from tensorflow import GradientTape
# GradientTape?
def tape_sample():
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x * x
print("x: {}, y:{}".format(x.numpy(), y.numpy()))
# how is y dependending on x
dy_dx = tape.gradient(y, x)
print("dy/dx: {}".format(dy_dx.numpy()))
# just a function in order not to interfere with x on the global scope
tape_sample()
```
## Step 4: Intermediate solution: applying all this to our training loop
```
model = tf.keras.Sequential([
Dense(units=1, input_dim=1)
])
EPOCHS = 1500
learning_rate = 0.01
losses = []
r2s = []
for step in range(EPOCHS):
with tf.GradientTape() as tape:
# forward pass, all data
# often we do not use all data to calculate the loss, but only a certain fraction, called the batch
# you could also push data through one by one, being an extreme version of a batched approached
# in our case we use all the data we have and calculate the combined error
y_pred = model(x_tensor)
# loss for this batch
loss = tf.losses.mean_squared_error(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred))
# just for logging
losses.append(loss)
# metrics
r2s.append(r2_metric(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred)))
# get gradients of weights wrt the loss
(dw, db) = tape.gradient(loss, model.trainable_weights)
# optimizer: backward pass, changing trainable weights in the direction of the mimimum
model.trainable_weights[0].assign_sub(learning_rate * dw)
model.trainable_weights[1].assign_sub(learning_rate * db)
plt.xlabel('epochs')
plt.ylabel('loss')
plt.title('loss over epochs (what we use for training)')
# plt.yscale('log')
plt.plot(losses);
plt.xlabel('epochs')
plt.ylabel('R2')
plt.title('R2 over epochs (what we are really interested in)')
plt.plot(r2s);
y_pred = model(x_tensor)
plt.plot(x, y_pred, color='r')
plt.scatter(x, y_pred, color='r')
plt.scatter(x, y);
```
## Step 5: Changing parameters
#### SGD: (Stochastic) Gradient Descent
_w = w - learning_rate * g_
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD?version=nightly
_Note: to make this stochastic it would require us to split our training data into batches and shuffle after each epoch_
### Prebuilt Optimizers do this job (but a bit more efficient and sohpisticated)
```
optimizer = tf.keras.optimizers.SGD(learning_rate=1e-2)
model = tf.keras.Sequential([
Dense(units=1, input_dim=1)
])
EPOCHS = 1500
losses = []
r2s = []
for step in range(EPOCHS):
with tf.GradientTape() as tape:
# forward pass, all data
y_pred = model(x_tensor)
# loss for this batch
loss = tf.losses.mean_squared_error(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred))
# just for logging
losses.append(loss)
# metrics
r2s.append(r2_metric(y_true=tf.squeeze(y_tensor), y_pred=tf.squeeze(y_pred)))
# Get gradients of weights wrt the loss.
gradients = tape.gradient(loss, model.trainable_weights)
# Update the weights of our linear layer.
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
# plt.yscale('log')
plt.ylabel("loss")
plt.xlabel("epochs")
plt.title('loss')
plt.plot(losses);
plt.xlabel('epochs')
plt.ylabel('R2')
plt.title('R2')
plt.plot(r2s);
y_pred = model(x_tensor)
plt.plot(x, y_pred, color='r')
plt.scatter(x, y_pred, color='r')
plt.scatter(x, y);
```
# Part V: The same solution using high level Keas API
## Keras vs TensorFlow
<img src='https://djcordhose.github.io/ml-workshop/img/tf-vs-keras.png'>
https://twitter.com/fchollet at http://scaledml.org/2020/
```
from tensorflow.keras.layers import Dense
model = tf.keras.Sequential([
Dense(units=1, input_dim=1)
])
model.summary()
%%time
model.compile(loss=tf.losses.mean_squared_error, # mean squared error, unchanged from low level example
optimizer=tf.keras.optimizers.SGD(learning_rate=1e-2), # SGD, unchanged from low level example
metrics=[r2_metric]) # we can track the r2 metric over time
# does a similar thing internally as our loop from above
history = model.fit(x, y, epochs=1000, verbose=0)
loss, r2 = model.evaluate(x, y, verbose=0)
loss, r2
# plt.yscale('log')
plt.ylabel("loss")
plt.xlabel("epochs")
plt.title('Loss over Epochs')
plt.plot(history.history['loss']);
plt.ylabel("r2")
plt.xlabel("epochs")
plt.title('R^2 over Epochs')
# plt.yscale('log')
plt.plot(history.history['r2_metric']);
y_pred = model.predict(x)
plt.plot(x, y_pred, color='red')
plt.scatter(x, y_pred, color='red')
plt.scatter(x, y);
```
# Part VI: Neural Networks with 2-3 Layers can learn to approximate any function
<img src='https://github.com/DJCordhose/ml-workshop/blob/master/notebooks/tf-intro/nn-from-layer-to-model.png?raw=1'>
```
%%time
# activation functions will be explained soon, for now just accept them to be necessary
model = tf.keras.Sequential([
Dense(units=100, activation='relu', input_dim=1),
Dense(units=100, activation='relu'),
Dense(units=100, activation='relu'),
Dense(units=1, activation='linear')
])
model.summary()
model.compile(loss=tf.losses.mean_squared_error, # mean squared error, unchanged from low level example
optimizer=tf.keras.optimizers.Adam(), # Adam is a bit more powerful, but this could also be SGD
metrics=[r2_metric]) # we can track the r2 metric over time
# does a similar thing internally as our loop from above
history = model.fit(x, y, epochs=1000, verbose=0)
loss, r2 = model.evaluate(x, y, verbose=0)
loss, r2
plt.yscale('log')
plt.ylabel("loss")
plt.xlabel("epochs")
plt.title('Loss over Epochs (log scale)')
plt.plot(history.history['loss']);
plt.ylabel("r2")
plt.xlabel("epochs")
plt.title('R^2 over Epochs')
# plt.yscale('log')
plt.plot(history.history['r2_metric']);
y_pred = model.predict(x)
plt.scatter(x, y_pred, color='red')
plt.scatter(x, y);
```
# Hands-On: Fitting arbitrary data
Choose between three options
1. Adapt the existing example by changing slope, adding noise etc.
1. Use the generator to create a noisy sine wave or any other function
1. Draw something by hand
* depending on complexity of function might requriw a lot tweaking
* so might be tricky, as hard as it gets
* it is likely you will fail, but you will see more powerful approaches later
## Option 1: Adapt original example
```
#@title A noisy line of shape y = m*x + b { run: "auto", display-mode: "form" }
# https://colab.research.google.com/notebooks/forms.ipynb
n = 50 #@param {type:"slider", min:10, max:500, step:1}
m = -1 #@param {type:"slider", min:-10, max:10, step: 0.1}
b = 1 #@param {type:"slider", min:-10, max:10, step: 0.1}
noise_level = 0.1 #@param {type:"slider", min:0.0, max:1.0, step:0.1}
title = 'Predict y from x (based on a line with noise)' #@param {type:"string"}
x_label = 'x' #@param {type:"string"}
y_label = 'y' #@param {type:"string"}
import numpy as np
np.random.seed(42)
# sort is not necessary, but makes x easier to understand
x = np.sort(np.random.uniform(0, 1, n))
y = m*x+b + np.random.normal(0, noise_level, n)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
plt.scatter(x, y);
# your code goes here
```
## Option 2: Generate data from non linear function
```
#@title A noisy sine curve { run: "auto", display-mode: "form" }
n = 50 #@param {type:"slider", min:10, max:500, step:1}
noise_level = 0.2 #@param {type:"slider", min:0.1, max:1.0, step:0.1}
scale = 10 #@param {type:"slider", min:1, max:100, step:1}
import numpy as np
x = np.random.uniform(0, 1, n)
y = np.sin(x*scale) + np.random.normal(0, noise_level, n)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sinus')
plt.scatter(x, y);
# your code goes here
```
## Option 3: Fitting hand drawn data
* https://twitter.com/fishnets88/status/1383333912470974470
* https://calmcode.io/labs/drawdata.html
* https://github.com/koaning/drawdata
```
!pip install -q drawdata
from drawdata import draw_line, draw_scatter, draw_histogram
draw_line()
drawdata_data = """
COPY CSV AND MANUALLY PASTE CSV DATA HERE
"""
from io import StringIO
import pandas as pd
df = pd.read_csv(StringIO(drawdata_data))
df.head()
x = df['x']
y = df['y']
# your code goes here
```
| github_jupyter |
This notebook is originally derived from [this notebook on Kaggle](https://www.kaggle.com/dgomonov/data-exploration-on-nyc-airbnb).
```
# {{NO LUX}}
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
import pandas as pd
numPoints=100
# {{NO LUX}}
airbnb=pd.read_csv("../../data/airbnb_250x.csv")
# airbnb=pd.read_csv("../../data/airbnb_nyc.csv")
airbnb = airbnb.sample(n=int(numPoints))
# {{NO LUX}}
airbnb.dtypes
# {{PRINT SERIES}}
airbnb.isnull().sum()
# {{NO LUX}}
airbnb.drop(['id','host_name','last_review'], axis=1, inplace=True)
# {{PRINT DF}}
airbnb
# {{PRINT DF}}
airbnb.fillna({'reviews_per_month':0}, inplace=True)
airbnb.reviews_per_month.isnull().sum()
# {{PRINT DF}}
airbnb
# {{NO LUX}}
airbnb.neighbourhood_group.unique()
# {{PRINT DF}}
airbnb
# {{NO LUX}}
len(airbnb.neighbourhood.unique())
# {{NO LUX}}
airbnb.room_type.unique()
# {{NO LUX}}
top_host=airbnb.host_id.value_counts()
# {{PRINT SERIES}}
top_host
# {{NO LUX}}
top_host_check=airbnb.calculated_host_listings_count.max()
# {{PRINT SERIES}}
top_host_check
# {{NO LUX}}
top_host_df=pd.DataFrame(top_host)
top_host_df.reset_index(inplace=True)
top_host_df.rename(columns={'index':'Host_ID', 'host_id':'P_Count'}, inplace=True)
# {{PRINT DF}}
top_host_df
# {{NO LUX}}
sub_1=airbnb.loc[airbnb['neighbourhood_group'] == 'Brooklyn']
price_sub1=sub_1[['price']]
sub_2=airbnb.loc[airbnb['neighbourhood_group'] == 'Manhattan']
price_sub2=sub_2[['price']]
sub_3=airbnb.loc[airbnb['neighbourhood_group'] == 'Queens']
price_sub3=sub_3[['price']]
sub_4=airbnb.loc[airbnb['neighbourhood_group'] == 'Staten Island']
price_sub4=sub_4[['price']]
sub_5=airbnb.loc[airbnb['neighbourhood_group'] == 'Bronx']
price_sub5=sub_5[['price']]
price_list_by_n=[price_sub1, price_sub2, price_sub3, price_sub4, price_sub5]
# {{PRINT DF}}
sub_1
# {{PRINT DF}}
sub_5
# {{PRINT SERIES}}
price_sub5
# {{PRINT DF}}
airbnb
# {{NO LUX}}
p_l_b_n_2=[]
nei_list=['Brooklyn', 'Manhattan', 'Queens', 'Staten Island', 'Bronx']
for x in price_list_by_n:
i=x.describe(percentiles=[.25, .50, .75])
i=i.iloc[3:]
i.reset_index(inplace=True)
i.rename(columns={'index':'Stats'}, inplace=True)
p_l_b_n_2.append(i)
# {{NO LUX}}
p_l_b_n_2[0].rename(columns={'price':nei_list[0]}, inplace=True)
p_l_b_n_2[1].rename(columns={'price':nei_list[1]}, inplace=True)
p_l_b_n_2[2].rename(columns={'price':nei_list[2]}, inplace=True)
p_l_b_n_2[3].rename(columns={'price':nei_list[3]}, inplace=True)
p_l_b_n_2[4].rename(columns={'price':nei_list[4]}, inplace=True)
stat_df=p_l_b_n_2
stat_df=[df.set_index('Stats') for df in stat_df]
stat_df=stat_df[0].join(stat_df[1:])
# {{PRINT DF}}
stat_df
# {{PRINT DF}}
airbnb
# {{PRINT SERIES}}
airbnb.price
# {{NO LUX}}
sub_6=airbnb[airbnb.price < 500]
# {{PRINT DF}}
sub_6
# {{PRINT SERIES}}
viz_2=sns.violinplot(data=sub_6, x='neighbourhood_group', y='price')
viz_2.set_title('Density and distribution of prices for each neighberhood_group')
# {{PRINT DF}}
airbnb
# {{PRINT SERIES}}
airbnb.neighbourhood.value_counts()
# {{NO LUX}}
sub_7=airbnb.loc[airbnb['neighbourhood'].isin(['Williamsburg','Bedford-Stuyvesant','Harlem','Bushwick',
'Upper West Side','Hell\'s Kitchen','East Village','Upper East Side','Crown Heights','Midtown'])]
# {{PRINT DF}}
sub_7
# {{NO LUX}}
top_reviewed_listings=airbnb.nlargest(10,'number_of_reviews')
# {{PRINT DF}}
top_reviewed_listings
# {{NO LUX}}
price_avrg=top_reviewed_listings.price.mean()
print('Average price per night: {}'.format(price_avrg))
```
| github_jupyter |
```
from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64decode
def take_photo(filename='photo.jpg', quality=0.8):
js = Javascript('''
async function takePhoto(quality) {
const div = document.createElement('div');
const capture = document.createElement('button');
capture.textContent = 'Capture';
div.appendChild(capture);
const video = document.createElement('video');
video.style.display = 'block';
const stream = await navigator.mediaDevices.getUserMedia({video: true});
document.body.appendChild(div);
div.appendChild(video);
video.srcObject = stream;
await video.play();
// Resize the output to fit the video element.
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
// Wait for Capture to be clicked.
await new Promise((resolve) => capture.onclick = resolve);
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
stream.getVideoTracks()[0].stop();
div.remove();
return canvas.toDataURL('image/jpeg', quality);
}
''')
display(js)
data = eval_js('takePhoto({})'.format(quality))
# == data = eval_js(f'takePhoto({quality})')
binary = b64decode(data.split(',')[1])
with open(filename, 'wb') as f:
f.write(binary)
return filename
from IPython.display import Image
try:
filename = take_photo()
print('Saved to {}'.format(filename))
# Show the image which was just taken.
display(Image(filename))
except Exception as err:
# Errors will be thrown if the user does not have a webcam or if they do not
# grant the page permission to access it.
print(str(err))
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('photo.jpg')
edges = cv2.Canny(img,100,200)
from matplotlib.pyplot import imshow, subplot, axis, title,show,tight_layout
subplot(1,2,1), title('Orignal Image'), axis(False)
imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGBA))
subplot(1,2,2), title('Edge Image'), axis(False)
imshow(edges,cmap = 'gray')
tight_layout()
show()
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('photo.jpg')
edges = cv2.Canny(img,100,200)
from matplotlib.pyplot import imshow, subplot, axis, title,show,tight_layout
subplot(1,2,1), title('Orignal Image'), axis(False)
imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGBA))
subplot(1,2,2), title('Edge Image'), axis(False)
imshow(edges,cmap = 'gray')
tight_layout()
show()
import cv2
import matplotlib.pyplot as plt
filename = take_photo()
img = cv2.imread('photo.jpg')
edges = cv2.Canny(img,100,200)
from matplotlib.pyplot import imshow, subplot, axis, title,show,tight_layout
subplot(1,2,1), title('Orignal Image'), axis(False)
imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGBA))
subplot(1,2,2), title('Edge Image'), axis(False)
imshow(edges,cmap = 'gray')
tight_layout()
show()
x=33
print('xx=',str(x))
x=33
print('xx={}'.format(x))
x=33
print(f'xx={x}')
from matplotlib.pyplot import imshow, subplot, axis, title,show,tight_layout
for i in range(2):
take_photo(f'p{i}.png')
img = cv2.imread(f'p{i}.png')
edges = cv2.Canny(img,100,200)
subplot(1,2,1), title('Orignal Image'), axis(False)
imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGBA))
subplot(1,2,2), title('Edge Image'), axis(False)
imshow(edges,cmap = 'gray')
tight_layout()
show()
```
| github_jupyter |
```
# In this cell, some libraries were imported
import cv2
import sys
import os
from PIL import Image, ImageDraw
import pylab
import time
from matplotlib import pyplot as plt
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
from pynq.overlays.base import BaseOverlay
from pynq.lib.video import *
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Xilinx_Hackathon_2017").sheet1
###### ORB
# imports for ORB
import numpy as np
import cv2
# Initiate ORB detector
orb = cv2.ORB_create()
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
import string
import re
####################################
###### Configurable items: ######
####################################
# arbitary number. Fine tune once you get here
thres_hold = 250
def capture(destination, image_number):
orig_img_path = destination + str(image_number)+'.JPG'
!fswebcam --no-banner --save {orig_img_path} -d /dev/video0 2> /dev/null
# Face Detection Function
def detectFaces(image_name):
#print ("Face Detection Start.")
# Read the image and convert to gray to reduce the data
img = cv2.imread(image_name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#Color => Gray
# The haarcascades classifier is used to train data
face_cascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml")
faces = face_cascade.detectMultiScale(gray, 1.3, 5)#1.3 and 5are the min and max windows of the treatures
result = []
for (x,y,width,height) in faces:
result.append((x,y,x+width,y+height))
#print ("Face Detection Complete.")
return result
def draw(image):
img_ori = Image.open(image)
plt.imshow(img_ori),plt.show()
#Crop faces and save them in the same directory
def crop():
filepath ="/home/xilinx/jupyter_notebooks/Final_presents/images/"
dir_path ="/home/xilinx/jupyter_notebooks/Final_presents/"
filecount = len(os.listdir(filepath))-1
image_count = 1#count is the number of images
face_cascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml")
for fn in os.listdir(filepath): #fn 表示的是文件名
start = time.time()
if image_count <= filecount:
image_name = str(image_count) + '.JPG'
image_path = filepath + image_name
image_new = dir_path + image_name
#print (image_path)
#print (image_new)
os.system('cp '+(image_path)+ (' /home/xilinx/jupyter_notebooks/Final_presents/'))
faces = detectFaces(image_name)
if not faces:
print ("There is no face!Trust me!!!")
if faces:
#All croped face images will be saved in a subdirectory
face_name = image_name.split('.')[0]
#os.mkdir(save_dir)
count = 0
for (x1,y1,x2,y2) in faces:
file_name = os.path.join(dir_path,face_name+str(count)+".jpg")
face_name = os.path.basename(file_name)
#print (face_name)
Image.open(image_name).crop((x1,y1,x2,y2)).save(file_name)
#os.system('rm -rf '+(image_path)+' /home/xilinx/jupyter_notebooks/OpenCV/Face_Detection/')
count+=1
print("Haha, Here is one face:")
draw(file_name)
#hdmi(file_name)
#print("The " + str(image_count) +" image were done.")
#print("Congratulation! The total of the " + str(count) + " faces in the " +str(image_count) + " image.")
# Integration START
# New face from the webcam
image = file_name
# Find the Key point
img = cv2.imread(image,0) # queryImage
# find the keypoints and descriptors with ORB
kp1, des1 = orb.detectAndCompute(img,None)
# Extract and print all of the values
all_faces_str = sheet.get_all_values()
# convert google doc strings to numbers
data = all_faces_str[1:]
face_order = 0
for row in data:
face_order += 1
myTotal = np.array([])
for element in row:
myArray = np.array(eval(element))
myTotal = np.vstack([myTotal,myArray]) if myTotal.size else myArray
# convert data type
myTotal_uint8 = np.uint8(myTotal)
# Add each image descriptor list from the database
clusters = np.array([myTotal_uint8])
bf.add(clusters)
# Train: Does nothing for BruteForceMatcher though.
bf.train()
matches = bf.match(des1,myTotal_uint8)
matches = sorted(matches, key = lambda x:x.distance)
facest_face = 0
numb_matches = (len(matches))
if numb_matches > facest_face:
facest_face = numb_matches
face_found = False
if facest_face > thres_hold:
face_found = True
found_face_order = face_order
# Add face to database if not found, otherwise report the face
if face_found == True:
print ("FACE FOUND! Face number:")
print (found_face_order)
else:
print ("Face NOT found. adding face to database")
sheet.append_row('')
col_in = 1
row_in = sheet.row_count
collumn_list = []
des_cnt = 0
des_per_cell = 100
for collumn in des1:
collumn_list.append(collumn.tolist())
# Append des_per_cell # of collumns into a single collumn and upload
if des_cnt >= des_per_cell -1:
print ("cloud")
sheet.update_cell(row_in, col_in, collumn_list)
collumn_list = []
col_in += 1
des_cnt = 0
else:
des_cnt += 1
# Integration END
os.system('rm -rf '+(image_path))
os.system('rm -rf '+(image_new))
end = time.time()
TimeSpan = end - start
if image_count <= filecount:
print ("The time of " + str(image_count) + " image is " +str(TimeSpan) + " s.")
image_count = image_count + 1
def hdmi(file_name):
base = BaseOverlay("base.bit")
# monitor configuration: 640*480 @ 60Hz
Mode = VideoMode(640,480,24)
hdmi_out = base.video.hdmi_out
hdmi_out.configure(Mode,PIXEL_BGR)
hdmi_out.start()
# monitor (output) frame buffer size
frame_out_w = 1920
frame_out_h = 1080
# camera (input) configuration
frame_in_w = 67
frame_in_h = 67
import cv2
videoIn = cv2.VideoCapture(file_name)
videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, frame_in_w);
videoIn.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_in_h);
print("Capture device is open: " + str(videoIn.isOpened()))
# Capture webcam image
import numpy as np
ret, frame_vga = videoIn.read()
# Display webcam image via HDMI Out
if (ret):
outframe = hdmi_out.newframe()
outframe[0:67,0:67,:] = frame_vga[0:67,0:67,:]
hdmi_out.writeframe(outframe)
else:
raise RuntimeError("Failed to read from camera.")
def main():
while(base.buttons[0].read()==0):
image_number = 1
filepath ="/home/xilinx/jupyter_notebooks/Final_presents/images/"
capture(filepath, image_number)
crop()
main()
```
| github_jupyter |
# Analyze archive
This notebook contains the code to analyse content of the PubMedCentral Author Manuscript Collection. \
See: https://www.ncbi.nlm.nih.gov/pmc/about/mscollection/
Files can be downloaded here: https://ftp.ncbi.nlm.nih.gov/pub/pmc/manuscript/ \
**Please ensure** that files are downloaded into `pmc_dataset` folder to proceed.
```
dict_articles = {}
with open("pmc_dataset/filelist.txt", 'r') as f:
for line in f:
filename, pmcid, pmid, mid = line.split()
if filename == 'File':
continue
dict_articles[pmid] = filename
len(dict_articles)
list(dict_articles.values())[:10]
!pip install lxml
from collections import Counter
def count_tags(node):
stat = Counter()
def dfs(root):
stat[root.tag] += 1
for child in root.getchildren():
dfs(child)
dfs(node)
return stat
from lxml import etree
tree = etree.parse("pmc_dataset/" + list(dict_articles.values())[0])
dir(tree.getroot())
tree.getroot().find("front").find("article-meta").find("title-group").find("article-title").text
def get_title(tree):
return etree.tostring(tree.getroot().find("front").find("article-meta").find("title-group").find("article-title"))
review_filenames = set()
for i, filename in enumerate(dict_articles.values()):
if i % 1000 == 0:
print(f"\r{i}", end="")
tree = etree.parse("pmc_dataset/" + filename)
title = str(get_title(tree))
if not title:
print(f"\r{filename}")
if "review" in title.lower():
review_filenames.add(filename)
print(len(review_filenames))
stats = count_tags(tree.getroot())
stats
tag_stat = {}
tag_stat['review'] = Counter()
tag_stat['ordinary'] = Counter()
for i, filename in enumerate(dict_articles.values()):
if i % 1000 == 0:
print(f"\r{i}", end="")
tree = etree.parse("pmc_dataset/" + filename)
cur_stat = count_tags(tree.getroot())
if filename in review_filenames:
tag_stat['review'] += cur_stat
else:
tag_stat['ordinary'] += cur_stat
for s, cnt in zip(['ordinary', 'review'], [649546 - 7270, 7270]):
with open(f'{s}_tag_stat.txt', 'w') as f:
srt = sorted(tag_stat[s].items(), key=lambda x: x[1])
srt = list(map(lambda x: (x[0], x[1]/cnt), srt))
print(f'Number: {cnt}', file=f)
for val, count in srt:
print(f'{val} {count}', file=f)
def tag_depth(node):
def dfs(root):
d = 1
for child in root.getchildren():
d = max(d, dfs(child) + 1)
return d
return dfs(node)
d_stat = {}
d_stat['review'] = {}
d_stat['ordinary'] = {}
for i, filename in enumerate(dict_articles.values()):
if i % 1000 == 0:
print(f"\r{i}", end="")
tree = etree.parse("pmc_dataset/" + filename)
cur_stat = tag_depth(tree.getroot())
if filename in review_filenames:
d_stat['review'][filename] = cur_stat
else:
d_stat['ordinary'][filename] = cur_stat
print(list(d_stat['review'].items())[:10])
for s in ['ordinary', 'review']:
with open(f'{s}_tag_depth.txt', 'w') as f:
srt = sorted(d_stat[s].items(), key=lambda x: x[1])
for val, count in srt:
print(f'{val} {count}', file=f)
!pip install matplotlib
import matplotlib.pyplot as plt
plt.hist(d_stat['review'].values(), bins=range(5, 20))
plt.show()
plt.hist(d_stat['ordinary'].values(), bins=range(5, 20))
plt.show()
tree = etree.parse("pmc_dataset/" + list(dict_articles.values())[0])
from collections import Counter
def get_paragraph_info(root):
num = 0
sum_pos = -1
disc_pos = -1
lens = Counter()
for ch in root.find('body').getchildren():
if ch.tag == 'sec':
num += 1
try:
lens[num] = len(etree.tostring(ch))
except Exception:
lens[num] = 0
print("\n!")
str_title = str(etree.tostring(ch.find('title'))).lower()
if 'summary' in str_title:
sum_pos = num
if 'discussion' in str_title:
disc_pos = num
return num, sum_pos, disc_pos, lens
review_filenames = set()
with open('review_tag_depth.txt', 'r') as f:
for line in f:
filename, _ = line.split()
review_filenames.add(filename)
with open("dataset_with_refs/review_files.csv", 'w') as f:
for filename in review_filenames:
for pmid, fname in dict_articles.items():
if fname == filename:
print(f'{pmid}\t{fname}', file=f)
break
para_stats = {}
para_stats['review'] = {}
para_stats['ordinary'] = {}
for i, filename in enumerate(dict_articles.values()):
if i % 1000 == 0:
print(f"\r{i}", end="")
tree = etree.parse("pmc_dataset/" + filename)
try:
cur_stat = get_paragraph_info(tree.getroot())
except Exception:
print(f"\n{filename}")
continue
if filename in review_filenames:
para_stats['review'][filename] = cur_stat
else:
para_stats['ordinary'][filename] = cur_stat
list(para_stats['review'].items())[:10]
import matplotlib.pyplot as plt
para_nums = list(map(lambda x: x[1][0], para_stats['review'].items()))
print(para_nums[:10])
plt.hist(para_nums, bins=range(1, 20))
plt.show()
para_nums = list(map(lambda x: x[1][0], para_stats['ordinary'].items()))
print(para_nums[:10])
plt.hist(para_nums, bins=range(1, 20))
plt.show()
sum_stat = list(map(lambda x: x[1][1], para_stats['review'].items()))
print(sum_stat[:10])
plt.hist(sum_stat, bins=range(1, 20))
plt.show()
sum_stat = list(map(lambda x: x[1][1], para_stats['ordinary'].items()))
print(sum_stat[:10])
plt.hist(sum_stat, bins=range(1, 20))
plt.show()
sum_stat = list(map(lambda x: x[1][2], para_stats['review'].items()))
print(sum_stat[:10])
plt.hist(sum_stat, bins=range(-1, 20))
plt.show()
sum_stat = list(map(lambda x: x[1][2], para_stats['ordinary'].items()))
print(sum_stat[:10])
plt.hist(sum_stat, bins=range(-1, 20))
plt.show()
import functools
len_stat = functools.reduce(lambda x, y: x + y, map(lambda x: x[1][3], para_stats['review'].items()))
plt.bar(len_stat.keys(), list(map(lambda x: x / len(para_stats['review'].items()), len_stat.values())))
plt.show()
len_stat = functools.reduce(lambda x, y: x + y, map(lambda x: x[1][3], para_stats['ordinary'].items()))
plt.bar(list(map(lambda x: min(35, x), len_stat.keys())), list(map(lambda x: x / len(para_stats['ordinary'].items()), len_stat.values())))
plt.show()
xml = '<tag>Some <a>example</a> text</tag>'
tree = etree.fromstring(xml)
print(''.join(tree.itertext()))
list(filter(lambda x: x[1][0] == 1, para_stats['ordinary'].items()))[:10]
from collections import Counter
def get_conc_info(root):
conc_pos = -1
num = 0
for ch in root.find('body').getchildren():
if ch.tag == 'sec':
num += 1
str_title = str(etree.tostring(ch.find('title'))).lower()
if 'conclusion' in str_title:
conc_pos = num
return conc_pos
conc_stats = {}
conc_stats['review'] = {}
conc_stats['ordinary'] = {}
for i, filename in enumerate(dict_articles.values()):
if i % 1000 == 0:
print(f"\r{i}", end="")
tree = etree.parse("pmc_dataset/" + filename)
try:
cur_stat = get_conc_info(tree.getroot())
except Exception:
print(f"\n{filename}")
continue
if filename in review_filenames:
conc_stats['review'][filename] = cur_stat
else:
conc_stats['ordinary'][filename] = cur_stat
import matplotlib.pyplot as plt
conc_stat = list(map(lambda x: x[1], conc_stats['review'].items()))
print(conc_stat[:10])
plt.hist(conc_stat, bins=range(-1, 20))
plt.show()
conc_stat = list(map(lambda x: x[1], conc_stats['ordinary'].items()))
print(conc_stat[:10])
plt.hist(conc_stat, bins=range(-1, 20))
plt.show()
def get_text(root):
text = root.find('body').itertext()
return ''.join(text)
tree = etree.parse("pmc_dataset/PMC0013XXXXX/PMC1351280.xml")
get_text(tree.getroot())
!pip install nltk
nltk.download('webtext')
nltk.download('punkt')
import nltk
text = nltk.tokenize.sent_tokenize(get_text(tree.getroot()))
text
```
| github_jupyter |
# Time series forecasting with ARIMA
In this notebook, we demonstrate how to:
- prepare time series data for training an ARIMA time series forecasting model
- implement a simple ARIMA model to forecast the next HORIZON steps ahead (time *t+1* through *t+HORIZON*) in the time series
- evaluate the model
The data in this example is taken from the GEFCom2014 forecasting competition<sup>1</sup>. It consists of 3 years of hourly electricity load and temperature values between 2012 and 2014. The task is to forecast future values of electricity load. In this example, we show how to forecast one time step ahead, using historical load data only.
<sup>1</sup>Tao Hong, Pierre Pinson, Shu Fan, Hamidreza Zareipour, Alberto Troccoli and Rob J. Hyndman, "Probabilistic energy forecasting: Global Energy Forecasting Competition 2014 and beyond", International Journal of Forecasting, vol.32, no.3, pp 896-913, July-September, 2016.
## Install Dependencies
Get started by installing some of the required dependencies. These libraries with their corresponding versions are known to work for the solution:
* `statsmodels == 0.12.2`
* `matplotlib == 3.4.2`
* `scikit-learn == 0.24.2`
```
!pip install statsmodels
import os
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
import math
from pandas.plotting import autocorrelation_plot
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.preprocessing import MinMaxScaler
from common.utils import load_data, mape
from IPython.display import Image
%matplotlib inline
pd.options.display.float_format = '{:,.2f}'.format
np.set_printoptions(precision=2)
warnings.filterwarnings("ignore") # specify to ignore warning messages
energy = load_data('./data')[['load']]
energy.head(10)
```
Plot all available load data (January 2012 to Dec 2014)
```
energy.plot(y='load', subplots=True, figsize=(15, 8), fontsize=12)
plt.xlabel('timestamp', fontsize=12)
plt.ylabel('load', fontsize=12)
plt.show()
```
## Create training and testing data sets
```
train_start_dt = '2014-11-01 00:00:00'
test_start_dt = '2014-12-30 00:00:00'
energy[(energy.index < test_start_dt) & (energy.index >= train_start_dt)][['load']].rename(columns={'load':'train'}) \
.join(energy[test_start_dt:][['load']].rename(columns={'load':'test'}), how='outer') \
.plot(y=['train', 'test'], figsize=(15, 8), fontsize=12)
plt.xlabel('timestamp', fontsize=12)
plt.ylabel('load', fontsize=12)
plt.show()
train = energy.copy()[(energy.index >= train_start_dt) & (energy.index < test_start_dt)][['load']]
test = energy.copy()[energy.index >= test_start_dt][['load']]
print('Training data shape: ', train.shape)
print('Test data shape: ', test.shape)
scaler = MinMaxScaler()
train['load'] = scaler.fit_transform(train)
train.head(10)
```
Original vs scaled data:
```
energy[(energy.index >= train_start_dt) & (energy.index < test_start_dt)][['load']].rename(columns={'load':'original load'}).plot.hist(bins=100, fontsize=12)
train.rename(columns={'load':'scaled load'}).plot.hist(bins=100, fontsize=12)
plt.show()
```
Let's also scale the test data
```
test['load'] = scaler.transform(test)
test.head()
```
## Implement ARIMA method
```
# Specify the number of steps to forecast ahead
HORIZON = 3
print('Forecasting horizon:', HORIZON, 'hours')
order = (4, 1, 0)
seasonal_order = (1, 1, 0, 24)
model = SARIMAX(endog=train, order=order, seasonal_order=seasonal_order)
results = model.fit()
print(results.summary())
```
## Evaluate the model
Create a test data point for each HORIZON step.
```
test_shifted = test.copy()
for t in range(1, HORIZON):
test_shifted['load+'+str(t)] = test_shifted['load'].shift(-t, freq='H')
test_shifted = test_shifted.dropna(how='any')
test_shifted.head(5)
```
Make predictions on the test data
```
%%time
training_window = 720 # dedicate 30 days (720 hours) for training
train_ts = train['load']
test_ts = test_shifted
history = [x for x in train_ts]
history = history[(-training_window):]
predictions = list()
# let's user simpler model for demonstration
order = (2, 1, 0)
seasonal_order = (1, 1, 0, 24)
for t in range(test_ts.shape[0]):
model = SARIMAX(endog=history, order=order, seasonal_order=seasonal_order)
model_fit = model.fit()
yhat = model_fit.forecast(steps = HORIZON)
predictions.append(yhat)
obs = list(test_ts.iloc[t])
# move the training window
history.append(obs[0])
history.pop(0)
print(test_ts.index[t])
print(t+1, ': predicted =', yhat, 'expected =', obs)
```
Compare predictions to actual load
```
eval_df = pd.DataFrame(predictions, columns=['t+'+str(t) for t in range(1, HORIZON+1)])
eval_df['timestamp'] = test.index[0:len(test.index)-HORIZON+1]
eval_df = pd.melt(eval_df, id_vars='timestamp', value_name='prediction', var_name='h')
eval_df['actual'] = np.array(np.transpose(test_ts)).ravel()
eval_df[['prediction', 'actual']] = scaler.inverse_transform(eval_df[['prediction', 'actual']])
eval_df.head()
```
Compute the **mean absolute percentage error (MAPE)** over all predictions
$$MAPE = \frac{1}{n} \sum_{t=1}^{n}|\frac{actual_t - predicted_t}{actual_t}|$$
```
if(HORIZON > 1):
eval_df['APE'] = (eval_df['prediction'] - eval_df['actual']).abs() / eval_df['actual']
print(eval_df.groupby('h')['APE'].mean())
print('One step forecast MAPE: ', (mape(eval_df[eval_df['h'] == 't+1']['prediction'], eval_df[eval_df['h'] == 't+1']['actual']))*100, '%')
print('Multi-step forecast MAPE: ', mape(eval_df['prediction'], eval_df['actual'])*100, '%')
```
Plot the predictions vs the actuals for the first week of the test set
```
if(HORIZON == 1):
## Plotting single step forecast
eval_df.plot(x='timestamp', y=['actual', 'prediction'], style=['r', 'b'], figsize=(15, 8))
else:
## Plotting multi step forecast
plot_df = eval_df[(eval_df.h=='t+1')][['timestamp', 'actual']]
for t in range(1, HORIZON+1):
plot_df['t+'+str(t)] = eval_df[(eval_df.h=='t+'+str(t))]['prediction'].values
fig = plt.figure(figsize=(15, 8))
ax = plt.plot(plot_df['timestamp'], plot_df['actual'], color='red', linewidth=4.0)
ax = fig.add_subplot(111)
for t in range(1, HORIZON+1):
x = plot_df['timestamp'][(t-1):]
y = plot_df['t+'+str(t)][0:len(x)]
ax.plot(x, y, color='blue', linewidth=4*math.pow(.9,t), alpha=math.pow(0.8,t))
ax.legend(loc='best')
plt.xlabel('timestamp', fontsize=12)
plt.ylabel('load', fontsize=12)
plt.show()
```
| github_jupyter |
# Bayesian Regression - Inference Algorithms (Part 2)
In [Part I](bayesian_regression.ipynb), we looked at how to perform inference on a simple Bayesian linear regression model using SVI. In this tutorial, we'll explore more expressive guides as well as exact inference techniques. We'll use the same dataset as before.
```
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
from torch.distributions import constraints
import pyro
import pyro.distributions as dist
from pyro.infer import EmpiricalMarginal, SVI, Trace_ELBO
from pyro.contrib.autoguide import AutoMultivariateNormal
from pyro.infer.mcmc.api import MCMC
from pyro.infer.mcmc import NUTS
import pyro.optim as optim
pyro.set_rng_seed(1)
assert pyro.__version__.startswith('0.3.4')
%matplotlib inline
logging.basicConfig(format='%(message)s', level=logging.INFO)
# Enable validation checks
pyro.enable_validation(True)
smoke_test = ('CI' in os.environ)
pyro.set_rng_seed(1)
DATA_URL = "https://d2fefpcigoriu7.cloudfront.net/datasets/rugged_data.csv"
rugged_data = pd.read_csv(DATA_URL, encoding="ISO-8859-1")
```
## Bayesian Linear Regression
Our goal is once again to predict log GDP per capita of a nation as a function of two features from the dataset - whether the nation is in Africa, and its Terrain Ruggedness Index, but we will explore more expressive guides.
## Model + Guide
We will write out the model again, similar to that in [Part I](bayesian_regression.ipynb), but explicitly without the use of `nn.Module`. We will write out each term in the regression, using the same priors. `bA` and `bR` are regression coefficients corresponding to `is_cont_africa` and `ruggedness`, `a` is the intercept, and `bAR` is the correlating factor between the two features.
Writing down a guide will proceed in close analogy to the construction of our model, with the key difference that the guide parameters need to be trainable. To do this we register the guide parameters in the ParamStore using `pyro.param()`. Note the positive constraints on scale parameters.
```
def model(is_cont_africa, ruggedness, log_gdp):
a = pyro.sample("a", dist.Normal(8., 1000.))
b_a = pyro.sample("bA", dist.Normal(0., 1.))
b_r = pyro.sample("bR", dist.Normal(0., 1.))
b_ar = pyro.sample("bAR", dist.Normal(0., 1.))
sigma = pyro.sample("sigma", dist.Uniform(0., 10.))
mean = a + b_a * is_cont_africa + b_r * ruggedness + b_ar * is_cont_africa * ruggedness
with pyro.plate("data", len(ruggedness)):
pyro.sample("obs", dist.Normal(mean, sigma), obs=log_gdp)
def guide(is_cont_africa, ruggedness, log_gdp):
a_loc = pyro.param('a_loc', torch.tensor(0.))
a_scale = pyro.param('a_scale', torch.tensor(1.),
constraint=constraints.positive)
sigma_loc = pyro.param('sigma_loc', torch.tensor(1.),
constraint=constraints.positive)
weights_loc = pyro.param('weights_loc', torch.randn(3))
weights_scale = pyro.param('weights_scale', torch.ones(3),
constraint=constraints.positive)
a = pyro.sample("a", dist.Normal(a_loc, a_scale))
b_a = pyro.sample("bA", dist.Normal(weights_loc[0], weights_scale[0]))
b_r = pyro.sample("bR", dist.Normal(weights_loc[1], weights_scale[1]))
b_ar = pyro.sample("bAR", dist.Normal(weights_loc[2], weights_scale[2]))
sigma = pyro.sample("sigma", dist.Normal(sigma_loc, torch.tensor(0.05)))
mean = a + b_a * is_cont_africa + b_r * ruggedness + b_ar * is_cont_africa * ruggedness
# Utility function to print latent sites' quantile information.
def summary(samples):
site_stats = {}
for site_name, values in samples.items():
marginal_site = pd.DataFrame(values)
describe = marginal_site.describe(percentiles=[.05, 0.25, 0.5, 0.75, 0.95]).transpose()
site_stats[site_name] = describe[["mean", "std", "5%", "25%", "50%", "75%", "95%"]]
return site_stats
# Prepare training data
df = rugged_data[["cont_africa", "rugged", "rgdppc_2000"]]
df = df[np.isfinite(df.rgdppc_2000)]
df["rgdppc_2000"] = np.log(df["rgdppc_2000"])
train = torch.tensor(df.values, dtype=torch.float)
```
## SVI
As before, we will use SVI to perform inference.
```
svi = SVI(model,
guide,
optim.Adam({"lr": .005}),
loss=Trace_ELBO(),
num_samples=1000)
is_cont_africa, ruggedness, log_gdp = train[:, 0], train[:, 1], train[:, 2]
pyro.clear_param_store()
num_iters = 10000 if not smoke_test else 2
for i in range(num_iters):
elbo = svi.step(is_cont_africa, ruggedness, log_gdp)
if i % 500 == 0:
logging.info("Elbo loss: {}".format(elbo))
svi_diagnorm_posterior = svi.run(log_gdp, is_cont_africa, ruggedness)
```
Let us observe the posterior distribution over the different latent variables in the model.
```
sites = ["a", "bA", "bR", "bAR", "sigma"]
svi_samples = {site: EmpiricalMarginal(svi_diagnorm_posterior, sites=site)
.enumerate_support().detach().cpu().numpy()
for site in sites}
for site, values in summary(svi_samples).items():
print("Site: {}".format(site))
print(values, "\n")
```
## HMC
In contrast to using variational inference which gives us an approximate posterior over our latent variables, we can also do exact inference using [Markov Chain Monte Carlo](http://docs.pyro.ai/en/dev/mcmc.html) (MCMC), a class of algorithms that in the limit, allow us to draw unbiased samples from the true posterior. The algorithm that we will be using is called the No-U Turn Sampler (NUTS) \[1\], which provides an efficient and automated way of running Hamiltonian Monte Carlo. It is slightly slower than variational inference, but provides an exact estimate.
```
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_samples=1000, warmup_steps=200)
mcmc.run(is_cont_africa, ruggedness, log_gdp)
hmc_samples = {k: v.detach().cpu().numpy() for k, v in mcmc.get_samples().items()}
for site, values in summary(hmc_samples).items():
print("Site: {}".format(site))
print(values, "\n")
```
## Comparing Posterior Distributions
Let us compare the posterior distribution of the latent variables that we obtained from variational inference with those from Hamiltonian Monte Carlo. As can be seen below, for Variational Inference, the marginal distribution of the different regression coefficients is under-dispersed w.r.t. the true posterior (from HMC). This is an artifact of the *KL(q||p)* loss (the KL divergence of the true posterior from the approximate posterior) that is minimized by Variational Inference.
This can be better seen when we plot different cross sections from the joint posterior distribution overlaid with the approximate posterior from variational inference. Note that since our variational family has diagonal covariance, we cannot model any correlation between the latents and the resulting approximation is overconfident (under-dispersed)
```
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))
fig.suptitle("Marginal Posterior density - Regression Coefficients", fontsize=16)
for i, ax in enumerate(axs.reshape(-1)):
site = sites[i]
sns.distplot(svi_samples[site], ax=ax, label="SVI (DiagNormal)")
sns.distplot(hmc_samples[site], ax=ax, label="HMC")
ax.set_title(site)
handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper right');
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
fig.suptitle("Cross-section of the Posterior Distribution", fontsize=16)
sns.kdeplot(hmc_samples["bA"], hmc_samples["bR"], ax=axs[0], shade=True, label="HMC")
sns.kdeplot(svi_samples["bA"], svi_samples["bR"], ax=axs[0], label="SVI (DiagNormal)")
axs[0].set(xlabel="bA", ylabel="bR", xlim=(-2.5, -1.2), ylim=(-0.5, 0.1))
sns.kdeplot(hmc_samples["bR"], hmc_samples["bAR"], ax=axs[1], shade=True, label="HMC")
sns.kdeplot(svi_samples["bR"], svi_samples["bAR"], ax=axs[1], label="SVI (DiagNormal)")
axs[1].set(xlabel="bR", ylabel="bAR", xlim=(-0.45, 0.05), ylim=(-0.15, 0.8))
handles, labels = axs[1].get_legend_handles_labels()
fig.legend(handles, labels, loc='upper right');
```
## MultivariateNormal Guide
As comparison to the previously obtained results from Diagonal Normal guide, we will now use a guide that generates samples from a Cholesky factorization of a multivariate normal distribution. This allows us to capture the correlations between the latent variables via a covariance matrix. If we wrote this manually, we would need to combine all the latent variables so we could sample a Multivarite Normal jointly.
```
from pyro.contrib.autoguide.initialization import init_to_mean
guide = AutoMultivariateNormal(model, init_loc_fn=init_to_mean)
svi = SVI(model,
guide,
optim.Adam({"lr": .005}),
loss=Trace_ELBO(),
num_samples=1000)
is_cont_africa, ruggedness, log_gdp = train[:, 0], train[:, 1], train[:, 2]
pyro.clear_param_store()
for i in range(num_iters):
elbo = svi.step(is_cont_africa, ruggedness, log_gdp)
if i % 500 == 0:
logging.info("Elbo loss: {}".format(elbo))
```
Let's look at the shape of the posteriors again. You can see the multivariate guide is able to capture more of the true posterior.
```
svi_mvn_posterior = svi.run(log_gdp, is_cont_africa, ruggedness)
svi_mvn_samples = {site: EmpiricalMarginal(svi_mvn_posterior, sites=site).enumerate_support()
.detach().cpu().numpy()
for site in sites}
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 10))
fig.suptitle("Marginal Posterior density - Regression Coefficients", fontsize=16)
for i, ax in enumerate(axs.reshape(-1)):
site = sites[i]
sns.distplot(svi_mvn_samples[site], ax=ax, label="SVI (Multivariate Normal)")
sns.distplot(hmc_samples[site], ax=ax, label="HMC")
ax.set_title(site)
handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper right');
```
Now let's compare the posterior computed by the Diagonal Normal guide vs the Multivariate Normal guide. Note that the multivariate distribution is more dispresed than the Diagonal Normal.
```
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
fig.suptitle("Cross-sections of the Posterior Distribution", fontsize=16)
sns.kdeplot(svi_samples["bA"], svi_samples["bR"], ax=axs[0], label="HMC")
sns.kdeplot(svi_mvn_samples["bA"], svi_mvn_samples["bR"], ax=axs[0], shade=True, label="SVI (Multivariate Normal)")
axs[0].set(xlabel="bA", ylabel="bR", xlim=(-2.5, -1.2), ylim=(-0.5, 0.1))
sns.kdeplot(svi_samples["bR"], svi_samples["bAR"], ax=axs[1], label="SVI (Diagonal Normal)")
sns.kdeplot(svi_mvn_samples["bR"], svi_mvn_samples["bAR"], ax=axs[1], shade=True, label="SVI (Multivariate Normal)")
axs[1].set(xlabel="bR", ylabel="bAR", xlim=(-0.45, 0.05), ylim=(-0.15, 0.8))
handles, labels = axs[1].get_legend_handles_labels()
fig.legend(handles, labels, loc='upper right');
```
and the Multivariate guide with the posterior computed by HMC. Note that the Multivariate guide better captures the true posterior.
```
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))
fig.suptitle("Cross-sections of the Posterior Distribution", fontsize=16)
sns.kdeplot(hmc_samples["bA"], hmc_samples["bR"], ax=axs[0], shade=True, label="HMC")
sns.kdeplot(svi_mvn_samples["bA"], svi_mvn_samples["bR"], ax=axs[0], label="SVI (Multivariate Normal)")
axs[0].set(xlabel="bA", ylabel="bR", xlim=(-2.5, -1.2), ylim=(-0.5, 0.1))
sns.kdeplot(hmc_samples["bR"], hmc_samples["bAR"], ax=axs[1], shade=True, label="HMC")
sns.kdeplot(svi_mvn_samples["bR"], svi_mvn_samples["bAR"], ax=axs[1], label="SVI (Multivariate Normal)")
axs[1].set(xlabel="bR", ylabel="bAR", xlim=(-0.45, 0.05), ylim=(-0.15, 0.8))
handles, labels = axs[1].get_legend_handles_labels()
fig.legend(handles, labels, loc='upper right');
```
## References
[1] Hoffman, Matthew D., and Andrew Gelman. "The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo." Journal of Machine Learning Research 15.1 (2014): 1593-1623. https://arxiv.org/abs/1111.4246.
| github_jupyter |
### # VIPatAINEAI
# Virtual Internship Program by AINE.AI
<img src="images.jpg" width="100" height="100" align="left"/>
<img src="data science.png" width="150" height="150" align="left"/>
<img src="cookiescat.png" width="100" height="100" align="left"/>
# Statistical Analysis and Hypothesis Testing
## Project:
## Increasing YoY revenue from game purchases by increasing retention rate of gamers
### Submitted By : Manjiri Harishchandra Sawant
## About the Project
* The project involves working on data related to **Cookie Cats** – a hugely popular puzzle game.
* As players progress through the levels of the game, they will occasionally encounter gates that force them to wait a non-trivial amount of time or make an in-app purchase to progress.
* In addition to driving in-app purchases, these gates serve the important purpose of giving players an enforced break from playing the game, hopefully resulting in the player's enjoyment of the game being increased and prolonged.
* But where should the gates be placed and how the placement of the gates can retain the players for more time.
#### Retention Rate?
- The term **"retention rate"** is used in a variety of fields, including marketing, investing, education, in the workplace and in clinical trials. Maintaining retention in each of these fields often results in a positive outcome for the overall organization or school, or pharmacological study.
- Basically, **game retention** is a measure of how many people are still playing the game after a certain period of time from their first login date.
- For example: if 10000 people download game today and 5700 of them are still playing tomorrow, it means they have a retention of 57 percent on day 1.
<img src="screen-4.jpg" width="220" height="220" align="left"/>
<img src="screen-0.jpg" width="220" height="250" align="left"/>
<img src="screen-13.jpg" width="220" height="280" align="left"/>
<img src="643x0w.jpg" width="250" height="280" align="left"/>
**Tool Used** : Python Jupyter Notebook
**Aim** : Even though the overall subscription for the game is growing, the revenue from in-game purchases has been declining and many players are uninstalling the game after playing for a few days. **Give suggestions to increase the in-game purchase and retaining the players.**
**Objectives**:
1. The overall objective of the project is to test the **company’s CEO’s hypothesis** that moving the first gate from **level 30 to level 40** increases retention rate and the number of game rounds played.
2. The CEO believes that players are churning because the first gate encountered at level 30 is too early which forces players to wait before they can proceed further in the game.
3. In order to increase **player retention rate**, the main objective is to run **AB-test** by moving the first gate from level 30 to level 40 for some players i.e.,
- group A would encounter the gate at level 30, and
- group B would encounter the gate at level 40
#### A/B Testing?
1. A/B testing **(also known as split testing or bucket testing)** is a method of comparing two versions of a webpage or app against each other to determine which one performs better.
2. A/B testing for mobile apps works by segmenting an audience into two (or more) groups and seeing how a variable affects user behavior.
3. It is used to identify the best possible user experience and deliver the best possible results.
## Packages and setup
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
from scipy.stats import shapiro
import scipy.stats as stats
#parameter settings
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import warnings
warnings.filterwarnings("ignore")
warnings.simplefilter(action='ignore',category=FutureWarning)
```
## Performing Initial Data Preparation
### Reading data and initial processing
```
#Read data using pandas
user_df=pd.read_csv("cookie_cats.csv")
#Check data types of each column using "dtypes" function
print("Data types for the data set:")
user_df.dtypes
#Check dimension of data i.e. # of rows and #column using pandas "shape" funtion
print("Shape of the data i.e. no. of rows and columns")
user_df.shape
#display first 5 rows of the data using "head" function
print("First 5 rows of the raw data:")
user_df.head(5)
```
<img src="shot 1.png" width="700" height="700" align="left"/>
## Detect and resolve problems in the data (Missing value, Outliers, etc.)
### 1. Identify missing value
```
#Check for any missing values in the data using isnull() function
user_df.isnull().sum()
```
### 2. Identify outliers
```
#Check for outlier values in sum_gamerounds column
plt.title("Total gamerounds played")
plt.xlabel("Index")
plt.ylabel("sum_gamerounds")
plt.plot(user_df.sum_gamerounds)
#Based on the plot, filter out the outlier from sum_gamerounds played; Use max() fucntion to find the index of the outlier
user_df['sum_gamerounds'].max()
display(user_df.loc[user_df.sum_gamerounds == 49854])
user_df.drop([user_df.index[57702]], inplace = True)
#Plot the graph for sum_gamerounds player after removing the outlier
plt.title("Total gamerounds played")
plt.xlabel("Index")
plt.ylabel("sum_gamerounds")
plt.plot(user_df.sum_gamerounds)
```
## Generate Statistical Summary
### 1. What is the overall 7-day retention rate of the game?
```
#Insert calculation for 7-day retention rate
retention_rate_7= (user_df.retention_7.sum()/user_df.shape[0] * 100).round(2)
print("Overal 7 days retention rate of the game for both versions is: " ,retention_rate_7,"%")
```
<mark>__Ans__
#### Overall 7-day retention rate of the game is 18.61%.
### 2. How many players never played the game after installing?
```
# Find number of customers with sum_gamerounds is equal to zero
No_of_customers = user_df.loc[user_df.sum_gamerounds == 0]['sum_gamerounds'].count()
print("The number of customers with sum_gamerounds is equal to zero : ", No_of_customers)
```
<mark>__Ans.__
#### Total 3994 number of players never played the game after installing.
### 3. Does the number of users decrease as the level progresses highlighting the difficulty of the game?
```
#Group by sum_gamerounds and count the number of users for the first 200 gamerounds
#Use plot() function on the summarized stats to visualize the chart
new_data = user_df[["userid","sum_gamerounds"]].groupby("sum_gamerounds").count().reset_index().rename(columns = {"userid":"count"})[0:200]
plt.xlabel("sum_gamerounds")
plt.ylabel("count of players")
plt.title("Count of Player Vs sum_gamerouds")
plt.plot(new_data["sum_gamerounds"],new_data["count"])
```
## Generate crosstab for two groups of players to understand if there is a difference in 7 days retention rate & total number of game rounds played
### 1. Seven days retention rate summary for different game versions
```
#Create cross tab for game version and retention_7 flag counting number of users for each possible categories
pd.crosstab(user_df.version, user_df.retention_7).apply(lambda r: r/r.sum(), axis=1)
```
<mark>__Analsysis Results:__
#### There is negligible difference among the two groups. In both the case, majority of the players(~ 80%) quit the game after 7 days period.
### 2. Gamerounds summary for different game versions
```
#use pandas group by to calculate average game rounds played summarized by different versions
user_df.groupby(['version']).agg({'sum_gamerounds': ['mean']})
```
<mark>__Analsysis Results:__
Do total number of gamerounds played in total by each player differ based on different versions of the game?
#### There is no much a difference in the total number of gamerounds of two different versions of the game played by each player.
## Perform two-sample test for groups A and B to test statistical significance amongst the groups in the sum of game rounds played i.e., if groups A and B are statistically different
#### Hypothesis Testing?
1. **Hypothesis testing** is a part of statistical analysis, where we test the assumptions made regarding a population parameter.It is generally used when we were to compare:
- a single group with an external standard
- two or more groups with each other
2. Terminology Used:
- Null Hypothesis
- Alternate Hypothesis
- Level of significance
- p-value
### Initial data processing
```
#Define A/B groups for hypothesis testing
# user_df["version"] = np.where(user_df.version == "gate_30", "A","B")
user_df["version"] = user_df["version"].replace(["gate_30","gate_40"],["A","B"])
group_A=pd.DataFrame(user_df[user_df.version=="A"]['sum_gamerounds'])
group_B=pd.DataFrame(user_df[user_df.version=="B"]['sum_gamerounds'])
```
### 1. Shapiro test of Normality
* The Shapiro-Wilks test for normality is one of three general normality tests designed to detect all departures from normality.
* The test rejects the hypothesis of normality when the p-value is less than or equal to 0.05.
```
#---------------------- Shapiro Test ----------------------
# NULL Hypothesis H0: Distribution is normal
# ALTERNATE Hypothesis H1: Distribution is not normal
#test for group_A
stats.shapiro(group_A)
#test for group_B
stats.shapiro(group_B)
```
<mark>__Analsysis Results:__
are the two groups normally distributed?
#### According to Shapiro test of Normality, Null hypothesis is rejected ie distribution is normal because p-value is less than 0.05.
#### Yes Distribution is not normal H1 is accepted.
### 2. Test of homegienity of variance
* Levene's test is used to test if k samples have equal variances. Equal variances across samples is called homogeneity of variance.
* The Levene test can be used to verify that assumption.
```
#---------------------- Leven's Test ----------------------
# NULL Hypothesis H0: Two groups have equal variances
# ALTERNATE Hypothesis H1: Two groups do not have equal variances
#perform levene's test and accept or reject the null hypothesis based on the results
from scipy.stats import levene
levene(group_A.sum_gamerounds,group_B.sum_gamerounds)
```
<mark>__Analsysis Results:__
#### The p-value suggest that we fail to reject the null hypothesis that, group A and B both have equal vairances.
### 3. Test of significance: Two sample test
* The two-sample t-test (also known as the independent samples t-test) is a method used to test whether the unknown population means of two groups are equal or not.
* A two-sample t-test is used to analyze the results from A/B tests.
```
#---------------------- Two samples test ----------------------
# NULL Hypothesis H0: Two samples are equal
# ALTERNATE Hypothesis H1: Two samples are different
#Apply relevant two sample test to accept or reject the NULL hypothesis
stats.mannwhitneyu(group_A.sum_gamerounds, group_B.sum_gamerounds)
#---------------------- Two samples test ----------------------
# NULL Hypothesis H0: Two samples are equal
# ALTERNATE Hypothesis H1: The first sample is greater than the second sample
#Apply relevant two sample test to accept or reject the NULL hypothesis
stats.mannwhitneyu(group_A.sum_gamerounds, group_B.sum_gamerounds, alternative = "greater")
```
<mark>__Analsysis Results:__
- We have used mann-whitney u test to check the null hypothesis, whether the two groups are similar or different.
- We have repeated the mann-whitney u test with the same null hypothesis but with the alternate hypothesis being whether the first group is greater than the second group.
-The results make it clear that the group_A and group_B are statistically different.
## Based on significance testing results, if groups A and B are statistically different, which level has more advantage in terms of player retention and number of game rounds played.
```
#Analyze the 1 day and 7 days retention rate for two different groups using group by function
user_df[["version","retention_7","retention_1"]].groupby("version").agg("mean")
```
<mark>__Analsysis Results:__
#### Based on the significance test we can conclude that gate level 30 has higher retention rate.
## Using bootstrap resampling, plot the retention rate distribution for both the groups inorder to visualize effect of different version of the game on retention.
* The bootstrapping is a way of sampling data.
* Bootstrapping is a statistical method that uses data resampling with replacement.
```
list_1d = []
list_2d = []
for i in range(500):
boot_mean1 = user_df.sample(frac = 0.7, replace = True).groupby('version')['retention_1'].mean()
list_1d.append(boot_mean1.values)
boot_mean2 = user_df.sample(frac = 0.7, replace = True).groupby('version')['retention_7'].mean()
list_2d.append(boot_mean2.values)
# Transforming the list to a DataFrame
list_1d = pd.DataFrame(list_1d, columns = ['gate_30','gate_40'])
list_2d = pd.DataFrame(list_2d, columns = ['gate_30','gate_40'])
# Adding a column with the % difference between the two AB groups
list_1d['diff'] = (list_1d['gate_30'] - list_1d['gate_40']) / list_1d['gate_30'] * 100
list_2d['diff'] = (list_2d['gate_30'] - list_2d['gate_40']) / list_2d['gate_30'] * 100
# Ploting the bootstrap % difference
ax = list_1d['diff'].plot(kind = 'kde')
ax.set_xlabel("% difference in means")
ax = list_2d['diff'].plot(kind = 'kde')
ax.set_xlabel("% difference in means")
# Calculating the probability that 7-day retention is greater when the gate is at level 30
prob_1 = (list_1d['diff'] > 0).sum() / len(list_1d)
prob_2 = (list_2d['diff'] > 0).sum() / len(list_2d)
# printing the probability
'{:.1%}'.format(prob_1)
'{:.1%}'.format(prob_2)
```
### The Conclusion:
* There is strong evidence that 7-day retention is higher when the gate is at level 30 than when it is at level 40.
* The conclusion is: If we want to keep retention high — both 1-day and 7-day retention — we should not move the gate from level 30 to level 40.
| github_jupyter |
```
#hide
#skip
! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab
#default_exp data.external
#export
from fastai.torch_basics import *
from fastdownload import FastDownload
from functools import lru_cache
import fastai.data
```
# External data
> Helper functions to download the fastai datasets
To download any of the datasets or pretrained weights, simply run `untar_data` by passing any dataset name mentioned above like so:
```python
path = untar_data(URLs.PETS)
path.ls()
>> (#7393) [Path('/home/ubuntu/.fastai/data/oxford-iiit-pet/images/keeshond_34.jpg'),...]
```
To download model pretrained weights:
```python
path = untar_data(URLs.PETS)
path.ls()
>> (#2) [Path('/home/ubuntu/.fastai/data/wt103-bwd/itos_wt103.pkl'),Path('/home/ubuntu/.fastai/data/wt103-bwd/lstm_bwd.pth')]
```
## Datasets
A complete list of datasets that are available by default inside the library are:
### Main datasets
1. **ADULT_SAMPLE**: A small of the [adults dataset](https://archive.ics.uci.edu/ml/datasets/Adult) to predict whether income exceeds $50K/yr based on census data.
- **BIWI_SAMPLE**: A [BIWI kinect headpose database](https://www.kaggle.com/kmader/biwi-kinect-head-pose-database). The dataset contains over 15K images of 20 people (6 females and 14 males - 4 people were recorded twice). For each frame, a depth image, the corresponding rgb image (both 640x480 pixels), and the annotation is provided. The head pose range covers about +-75 degrees yaw and +-60 degrees pitch.
1. **CIFAR**: The famous [cifar-10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset which consists of 60000 32x32 colour images in 10 classes, with 6000 images per class.
1. **COCO_SAMPLE**: A sample of the [coco dataset](http://cocodataset.org/#home) for object detection.
1. **COCO_TINY**: A tiny version of the [coco dataset](http://cocodataset.org/#home) for object detection.
- **HUMAN_NUMBERS**: A synthetic dataset consisting of human number counts in text such as one, two, three, four.. Useful for experimenting with Language Models.
- **IMDB**: The full [IMDB sentiment analysis dataset](https://ai.stanford.edu/~amaas/data/sentiment/).
- **IMDB_SAMPLE**: A sample of the full [IMDB sentiment analysis dataset](https://ai.stanford.edu/~amaas/data/sentiment/).
- **ML_SAMPLE**: A movielens sample dataset for recommendation engines to recommend movies to users.
- **ML_100k**: The movielens 100k dataset for recommendation engines to recommend movies to users.
- **MNIST_SAMPLE**: A sample of the famous [MNIST dataset](http://yann.lecun.com/exdb/mnist/) consisting of handwritten digits.
- **MNIST_TINY**: A tiny version of the famous [MNIST dataset](http://yann.lecun.com/exdb/mnist/) consisting of handwritten digits.
- **MNIST_VAR_SIZE_TINY**:
- **PLANET_SAMPLE**: A sample of the planets dataset from the Kaggle competition [Planet: Understanding the Amazon from Space](https://www.kaggle.com/c/planet-understanding-the-amazon-from-space).
- **PLANET_TINY**: A tiny version of the planets dataset from the Kaggle competition [Planet: Understanding the Amazon from Space](https://www.kaggle.com/c/planet-understanding-the-amazon-from-space) for faster experimentation and prototyping.
- **IMAGENETTE**: A smaller version of the [imagenet dataset](http://www.image-net.org/) pronounced just like 'Imagenet', except with a corny inauthentic French accent.
- **IMAGENETTE_160**: The 160px version of the Imagenette dataset.
- **IMAGENETTE_320**: The 320px version of the Imagenette dataset.
- **IMAGEWOOF**: Imagewoof is a subset of 10 classes from Imagenet that aren't so easy to classify, since they're all dog breeds.
- **IMAGEWOOF_160**: 160px version of the ImageWoof dataset.
- **IMAGEWOOF_320**: 320px version of the ImageWoof dataset.
- **IMAGEWANG**: Imagewang contains Imagenette and Imagewoof combined, but with some twists that make it into a tricky semi-supervised unbalanced classification problem
- **IMAGEWANG_160**: 160px version of Imagewang.
- **IMAGEWANG_320**: 320px version of Imagewang.
### Kaggle competition datasets
1. **DOGS**: Image dataset consisting of dogs and cats images from [Dogs vs Cats kaggle competition](https://www.kaggle.com/c/dogs-vs-cats).
### Image Classification datasets
1. **CALTECH_101**: Pictures of objects belonging to 101 categories. About 40 to 800 images per category. Most categories have about 50 images. Collected in September 2003 by Fei-Fei Li, Marco Andreetto, and Marc 'Aurelio Ranzato.
1. CARS: The [Cars dataset](https://ai.stanford.edu/~jkrause/cars/car_dataset.html) contains 16,185 images of 196 classes of cars.
1. **CIFAR_100**: The CIFAR-100 dataset consists of 60000 32x32 colour images in 100 classes, with 600 images per class.
1. **CUB_200_2011**: Caltech-UCSD Birds-200-2011 (CUB-200-2011) is an extended version of the CUB-200 dataset, with roughly double the number of images per class and new part location annotations
1. **FLOWERS**: 17 category [flower dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/) by gathering images from various websites.
1. **FOOD**:
1. **MNIST**: [MNIST dataset](http://yann.lecun.com/exdb/mnist/) consisting of handwritten digits.
1. **PETS**: A 37 category [pet dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/) with roughly 200 images for each class.
### NLP datasets
1. **AG_NEWS**: The AG News corpus consists of news articles from the AG’s corpus of news articles on the web pertaining to the 4 largest classes. The dataset contains 30,000 training and 1,900 testing examples for each class.
1. **AMAZON_REVIEWS**: This dataset contains product reviews and metadata from Amazon, including 142.8 million reviews spanning May 1996 - July 2014.
1. **AMAZON_REVIEWS_POLARITY**: Amazon reviews dataset for sentiment analysis.
1. **DBPEDIA**: The DBpedia ontology dataset contains 560,000 training samples and 70,000 testing samples for each of 14 nonoverlapping classes from DBpedia.
1. **MT_ENG_FRA**: Machine translation dataset from English to French.
1. **SOGOU_NEWS**: [The Sogou-SRR](http://www.thuir.cn/data-srr/) (Search Result Relevance) dataset was constructed to support researches on search engine relevance estimation and ranking tasks.
1. **WIKITEXT**: The [WikiText language modeling dataset](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) is a collection of over 100 million tokens extracted from the set of verified Good and Featured articles on Wikipedia.
1. **WIKITEXT_TINY**: A tiny version of the WIKITEXT dataset.
1. **YAHOO_ANSWERS**: YAHOO's question answers dataset.
1. **YELP_REVIEWS**: The [Yelp dataset](https://www.yelp.com/dataset) is a subset of YELP businesses, reviews, and user data for use in personal, educational, and academic purposes
1. **YELP_REVIEWS_POLARITY**: For sentiment classification on YELP reviews.
### Image localization datasets
1. **BIWI_HEAD_POSE**: A [BIWI kinect headpose database](https://www.kaggle.com/kmader/biwi-kinect-head-pose-database). The dataset contains over 15K images of 20 people (6 females and 14 males - 4 people were recorded twice). For each frame, a depth image, the corresponding rgb image (both 640x480 pixels), and the annotation is provided. The head pose range covers about +-75 degrees yaw and +-60 degrees pitch.
1. **CAMVID**: Consists of driving labelled dataset for segmentation type models.
1. **CAMVID_TINY**: A tiny camvid dataset for segmentation type models.
1. **LSUN_BEDROOMS**: [Large-scale Image Dataset](https://arxiv.org/abs/1506.03365) using Deep Learning with Humans in the Loop
1. **PASCAL_2007**: [Pascal 2007 dataset](http://host.robots.ox.ac.uk/pascal/VOC/voc2007/) to recognize objects from a number of visual object classes in realistic scenes.
1. **PASCAL_2012**: [Pascal 2012 dataset](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/) to recognize objects from a number of visual object classes in realistic scenes.
### Audio classification
1. **MACAQUES**: [7285 macaque coo calls](https://datadryad.org/stash/dataset/doi:10.5061/dryad.7f4p9) across 8 individuals from [Distributed acoustic cues for caller identity in macaque vocalization](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4806230).
2. **ZEBRA_FINCH**: [3405 zebra finch calls](https://ndownloader.figshare.com/articles/11905533/versions/1) classified [across 11 call types](https://link.springer.com/article/10.1007/s10071-015-0933-6). Additional labels include name of individual making the vocalization and its age.
### Medical imaging datasets
1. **SIIM_SMALL**: A smaller version of the [SIIM dataset](https://www.kaggle.com/c/siim-acr-pneumothorax-segmentation/overview) where the objective is to classify pneumothorax from a set of chest radiographic images.
2. **TCGA_SMALL**: A smaller version of the [TCGA-OV dataset](http://doi.org/10.7937/K9/TCIA.2016.NDO1MDFQ) with subcutaneous and visceral fat segmentations. Citations:
Holback, C., Jarosz, R., Prior, F., Mutch, D. G., Bhosale, P., Garcia, K., … Erickson, B. J. (2016). Radiology Data from The Cancer Genome Atlas Ovarian Cancer [TCGA-OV] collection. The Cancer Imaging Archive. http://doi.org/10.7937/K9/TCIA.2016.NDO1MDFQ
Clark K, Vendt B, Smith K, Freymann J, Kirby J, Koppel P, Moore S, Phillips S, Maffitt D, Pringle M, Tarbox L, Prior F. The Cancer Imaging Archive (TCIA): Maintaining and Operating a Public Information Repository, Journal of Digital Imaging, Volume 26, Number 6, December, 2013, pp 1045-1057. https://link.springer.com/article/10.1007/s10278-013-9622-7
### Pretrained models
1. **OPENAI_TRANSFORMER**: The GPT2 Transformer pretrained weights.
1. **WT103_FWD**: The WikiText-103 forward language model weights.
1. **WT103_BWD**: The WikiText-103 backward language model weights.
## Config
```
# export
@lru_cache(maxsize=None)
def fastai_cfg() -> Config: # Config that contains default download paths for `data`, `model`, `storage` and `archive`
"`Config` object for fastai's `config.ini`"
return Config(Path(os.getenv('FASTAI_HOME', '~/.fastai')), 'config.ini', create=dict(
data = 'data', archive = 'archive', storage = 'tmp', model = 'models'))
```
This is a basic `Config` file that consists of `data`, `model`, `storage` and `archive`.
All future downloads occur at the paths defined in the config file based on the type of download. For example, all future fastai datasets are downloaded to the `data` while all pretrained model weights are download to `model` unless the default download location is updated.
```
cfg = fastai_cfg()
cfg.data,cfg.path('data')
# export
def fastai_path(folder:str) -> Path:
"Local path to `folder` in `Config`"
return fastai_cfg().path(folder)
fastai_path('archive')
```
## URLs -
```
#export
class URLs():
"Global constants for dataset and model URLs."
LOCAL_PATH = Path.cwd()
MDL = 'http://files.fast.ai/models/'
GOOGLE = 'https://storage.googleapis.com/'
S3 = 'https://s3.amazonaws.com/fast-ai-'
URL = f'{S3}sample/'
S3_IMAGE = f'{S3}imageclas/'
S3_IMAGELOC = f'{S3}imagelocal/'
S3_AUDI = f'{S3}audio/'
S3_NLP = f'{S3}nlp/'
S3_COCO = f'{S3}coco/'
S3_MODEL = f'{S3}modelzoo/'
# main datasets
ADULT_SAMPLE = f'{URL}adult_sample.tgz'
BIWI_SAMPLE = f'{URL}biwi_sample.tgz'
CIFAR = f'{URL}cifar10.tgz'
COCO_SAMPLE = f'{S3_COCO}coco_sample.tgz'
COCO_TINY = f'{S3_COCO}coco_tiny.tgz'
HUMAN_NUMBERS = f'{URL}human_numbers.tgz'
IMDB = f'{S3_NLP}imdb.tgz'
IMDB_SAMPLE = f'{URL}imdb_sample.tgz'
ML_SAMPLE = f'{URL}movie_lens_sample.tgz'
ML_100k = 'https://files.grouplens.org/datasets/movielens/ml-100k.zip'
MNIST_SAMPLE = f'{URL}mnist_sample.tgz'
MNIST_TINY = f'{URL}mnist_tiny.tgz'
MNIST_VAR_SIZE_TINY = f'{S3_IMAGE}mnist_var_size_tiny.tgz'
PLANET_SAMPLE = f'{URL}planet_sample.tgz'
PLANET_TINY = f'{URL}planet_tiny.tgz'
IMAGENETTE = f'{S3_IMAGE}imagenette2.tgz'
IMAGENETTE_160 = f'{S3_IMAGE}imagenette2-160.tgz'
IMAGENETTE_320 = f'{S3_IMAGE}imagenette2-320.tgz'
IMAGEWOOF = f'{S3_IMAGE}imagewoof2.tgz'
IMAGEWOOF_160 = f'{S3_IMAGE}imagewoof2-160.tgz'
IMAGEWOOF_320 = f'{S3_IMAGE}imagewoof2-320.tgz'
IMAGEWANG = f'{S3_IMAGE}imagewang.tgz'
IMAGEWANG_160 = f'{S3_IMAGE}imagewang-160.tgz'
IMAGEWANG_320 = f'{S3_IMAGE}imagewang-320.tgz'
# kaggle competitions download dogs-vs-cats -p {DOGS.absolute()}
DOGS = f'{URL}dogscats.tgz'
# image classification datasets
CALTECH_101 = f'{S3_IMAGE}caltech_101.tgz'
CARS = f'{S3_IMAGE}stanford-cars.tgz'
CIFAR_100 = f'{S3_IMAGE}cifar100.tgz'
CUB_200_2011 = f'{S3_IMAGE}CUB_200_2011.tgz'
FLOWERS = f'{S3_IMAGE}oxford-102-flowers.tgz'
FOOD = f'{S3_IMAGE}food-101.tgz'
MNIST = f'{S3_IMAGE}mnist_png.tgz'
PETS = f'{S3_IMAGE}oxford-iiit-pet.tgz'
# NLP datasets
AG_NEWS = f'{S3_NLP}ag_news_csv.tgz'
AMAZON_REVIEWS = f'{S3_NLP}amazon_review_full_csv.tgz'
AMAZON_REVIEWS_POLARITY = f'{S3_NLP}amazon_review_polarity_csv.tgz'
DBPEDIA = f'{S3_NLP}dbpedia_csv.tgz'
MT_ENG_FRA = f'{S3_NLP}giga-fren.tgz'
SOGOU_NEWS = f'{S3_NLP}sogou_news_csv.tgz'
WIKITEXT = f'{S3_NLP}wikitext-103.tgz'
WIKITEXT_TINY = f'{S3_NLP}wikitext-2.tgz'
YAHOO_ANSWERS = f'{S3_NLP}yahoo_answers_csv.tgz'
YELP_REVIEWS = f'{S3_NLP}yelp_review_full_csv.tgz'
YELP_REVIEWS_POLARITY = f'{S3_NLP}yelp_review_polarity_csv.tgz'
# Image localization datasets
BIWI_HEAD_POSE = f"{S3_IMAGELOC}biwi_head_pose.tgz"
CAMVID = f'{S3_IMAGELOC}camvid.tgz'
CAMVID_TINY = f'{URL}camvid_tiny.tgz'
LSUN_BEDROOMS = f'{S3_IMAGE}bedroom.tgz'
PASCAL_2007 = f'{S3_IMAGELOC}pascal_2007.tgz'
PASCAL_2012 = f'{S3_IMAGELOC}pascal_2012.tgz'
# Audio classification datasets
MACAQUES = f'{GOOGLE}ml-animal-sounds-datasets/macaques.zip'
ZEBRA_FINCH = f'{GOOGLE}ml-animal-sounds-datasets/zebra_finch.zip'
# Medical Imaging datasets
#SKIN_LESION = f'{S3_IMAGELOC}skin_lesion.tgz'
SIIM_SMALL = f'{S3_IMAGELOC}siim_small.tgz'
TCGA_SMALL = f'{S3_IMAGELOC}tcga_small.tgz'
#Pretrained models
OPENAI_TRANSFORMER = f'{S3_MODEL}transformer.tgz'
WT103_FWD = f'{S3_MODEL}wt103-fwd.tgz'
WT103_BWD = f'{S3_MODEL}wt103-bwd.tgz'
def path(
url:str='.', # File to download
c_key:str='archive' # Key in `Config` where to save URL
) -> Path:
"Local path where to download based on `c_key`"
fname = url.split('/')[-1]
local_path = URLs.LOCAL_PATH/('models' if c_key=='models' else 'data')/fname
if local_path.exists(): return local_path
return fastai_path(c_key)/fname
```
The default local path is at `~/.fastai/archive/` but this can be updated by passing a different `c_key`. Note: `c_key` should be one of `'archive', 'data', 'model', 'storage'`.
```
url = URLs.PETS
local_path = URLs.path(url)
test_eq(local_path.parent, fastai_path('archive'))
local_path
local_path = URLs.path(url, c_key='model')
test_eq(local_path.parent, fastai_path('model'))
local_path
```
## untar_data -
```
#export
def untar_data(
url:str, # File to download
archive:Path=None, # Optional override for `Config`'s `archive` key
data:Path=None, # Optional override for `Config`'s `data` key
c_key:str='data', # Key in `Config` where to extract file
force_download:bool=False # Setting to `True` will overwrite any existing copy of data
) -> Path: # Path to extracted file(s)
"Download `url` to `fname` if `dest` doesn't exist, and extract to folder `dest`"
d = FastDownload(fastai_cfg(), module=fastai.data, archive=archive, data=data, base='~/.fastai')
return d.get(url, force=force_download, extract_key=c_key)
```
`untar_data` is a thin wrapper for `FastDownload.get`. It downloads and extracts `url`, by default to subdirectories of `~/.fastai`, and returns the path to the extracted data. Setting the `force_download` flag to 'True' will overwrite any existing copy of the data already present. For an explanation of the `c_key` parameter, see `URLs`.
```
untar_data(URLs.MNIST_SAMPLE)
#hide
#Check all URLs are in the download_checks.py file and match for downloaded archives
# from fastdownload import read_checks
# fd = FastDownload(fastai_cfg(), module=fastai.data)
# _whitelist = "MDL LOCAL_PATH URL WT103_BWD WT103_FWD GOOGLE".split()
# checks = read_checks(fd.module)
# for d in dir(URLs):
# if d.upper() == d and not d.startswith("S3") and not d in _whitelist:
# url = getattr(URLs, d)
# assert url in checks,f"""{d} is not in the check file for all URLs.
# To fix this, you need to run the following code in this notebook before making a PR (there is a commented cell for this below):
# url = URLs.{d}
# fd.get(url, force=True)
# fd.update(url)
# """
# f = fd.download(url)
# assert fd.check(url, f),f"""The log we have for {d} in checks does not match the actual archive.
# To fix this, you need to run the following code in this notebook before making a PR (there is a commented cell for this below):
# url = URLs.{d}
# _add_check(url, URLs.path(url))
# """
```
## Export -
```
#hide
from nbdev.export import notebook2script
notebook2script()
```
| github_jupyter |
# ***EDA ON DATA ANALYST'S DATA***
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
df=pd.read_csv('Cleaned DS data.csv')
df.head()
df.columns
df=df.drop('Unnamed: 0',axis=1)
df.describe()
df.info()
df.isnull().sum()
df.corr()
```
### ***Visualization of the data***
```
df.hist(figsize=(20,10))
plt.show()
plt.figure(figsize=(10,5))
c= df.corr()
sns.heatmap(c,cmap='BrBG',annot=True)
c
df.columns
plt.figure(figsize=(10,5))
sns.countplot(x=df['Title_Simplified'],order = df['Title_Simplified'].value_counts().index,palette='RdPu')
```
### ***-Analyst is most number job posted on glassdoor (analyst is where they have not defined any specific analytics process to be taken by the people)***
```
plt.figure(figsize=(10,5))
sns.countplot(x=df['Location'],order = df['Location'].value_counts()[:20].index,palette='flare')
plt.xticks(rotation=90)
plt.show
```
### ***- New York is leading in term of data analyst jobs on glassdoor***
### ***- Plano is least recruting in term of data analyst jobs on glassdoor***
```
plt.figure(figsize=(10,5))
sns.countplot(x=df['Type of ownership'],order = df['Type of ownership'].value_counts()[:20].index,palette='autumn_r')
plt.xticks(rotation=70)
plt.show
```
### ***- Private are the one who are hiring most analyst***
```
plt.figure(figsize=(10,5))
sns.countplot(y=df['Sector'],order = df['Sector'].value_counts()[:20].index,palette='RdBu')
plt.xticks(rotation=80)
plt.show
```
### ***- IT and Business Service is sector who is hiring most number of analyst***
### ***- Real Estate is sector who hire least number of analyst***
```
plt.figure(figsize=(10,5))
sns.countplot(x=df['Level'],order = df['Level'].value_counts().index,palette='Set3')
plt.show
```
### ***- Most of the job description doesnt show the seniority so NA is highest level and Senior is second most in seniority level***
```
plt.figure(figsize=(10,5))
sns.countplot(x=df['Easy Apply'],order = df['Easy Apply'].value_counts().index,palette='RdPu')
plt.show
```
### ***- Most of the job searcher has not used Easy Apply function to apply (or) most of recruiter has not given easy apply function***
```
plt.figure(figsize=(10,5))
sns.countplot(x=df['Revenue'],order = df['Revenue'].value_counts().index,palette='CMRmap_r')
plt.xticks(rotation=70)
plt.show
plt.figure(figsize=(10,5))
sns.countplot(x=df['Industry'],order = df['Industry'].value_counts()[:20].index,palette='RdPu')
plt.xticks(rotation=90)
plt.show
df['avg_salary'] = (df['Min_salary']+df['Max_salary'])/2
df['company_txt'] = df.apply(lambda x: x['Company Name'] if x['Rating'] <0 else x['Company Name'][:-3], axis = 1)
df.to_csv('Cleaned DS data.csv')
plt.figure(figsize=(10,5))
sns.countplot(x=df['company_txt'],order = df['company_txt'].value_counts()[:20].index,palette='RdPu')
plt.xticks(rotation=90)
plt.show
df.columns
pd.pivot_table(df, index = 'Title_Simplified', values = 'avg_salary')
pd.pivot_table(df, index = ['Title_Simplified','Level'], values = 'avg_salary')
pd.pivot_table(df, index = ['job_location','Title_Simplified'], values = 'avg_salary', aggfunc = 'count').sort_values('job_location', ascending = False)
pd.pivot_table(df, index = 'company_txt', values = 'avg_salary')
pd.pivot_table(df, index = 'job_location', values = 'avg_salary')
pd.pivot_table(df, index = 'Revenue', values = 'avg_salary')
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
words = " ".join(df['Job Description'])
def punctuation_stop(text):
"""remove punctuation and stop words"""
filtered = []
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(text)
for w in word_tokens:
if w not in stop_words and w.isalpha():
filtered.append(w.lower())
return filtered
words_filtered = punctuation_stop(words)
text = " ".join([ele for ele in words_filtered])
wc= WordCloud(background_color="white", random_state=1,stopwords=STOPWORDS, max_words = 1000, width =800, height = 1500)
wc.generate(text)
plt.figure(figsize=[10,10])
plt.imshow(wc,interpolation="bilinear")
plt.axis('off')
plt.show()
```
## ***THANK YOU!!!***
| github_jupyter |
```
import torch
import os
import cv2
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torchvision import transforms
transform_data = transforms.Compose(
[
transforms.ToPILImage(),
transforms.RandomVerticalFlip(),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop((112)),
transforms.ToTensor(),
]
)
def load_data(img_size=112):
data = []
labels = {}
index = -1
for label in os.listdir('./data/'):
index += 1
labels[label] = index
print(len(labels))
X = []
y = []
for label in labels:
for file in os.listdir(f'./data/{label}/'):
path = f'./data/{label}/{file}'
img = cv2.imread(path)
img = cv2.resize(img,(img_size,img_size))
data.append([np.array(transform_data(np.array(img))),labels[label]])
X.append(np.array(transform_data(np.array(img))))
y.append(labels[label])
np.random.shuffle(data)
np.save('./data.npy',data)
VAL_SPLIT = 0.25
VAL_SPLIT = len(X)*VAL_SPLIT
VAL_SPLIT = int(VAL_SPLIT)
X_train = X[:-VAL_SPLIT]
y_train = y[:-VAL_SPLIT]
X_test = X[-VAL_SPLIT:]
y_test = y[-VAL_SPLIT:]
X = torch.from_numpy(np.array(X))
y = torch.from_numpy(np.array(y))
X_train = np.array(X_train)
X_test = np.array(X_test)
y_train = np.array(y_train)
y_test = np.array(y_test)
X_train = torch.from_numpy(X_train)
X_test = torch.from_numpy(X_test)
y_train = torch.from_numpy(y_train)
y_test = torch.from_numpy(y_test)
return X,y,X_train,X_test,y_train,y_test
X,y,X_train,X_test,y_train,y_test = load_data()
```
## Modelling
```
import torch.nn as nn
import torch.nn.functional as F
class BaseLine(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3,32,5)
self.conv2 = nn.Conv2d(32,64,5)
self.conv2batchnorm = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64,128,5)
self.fc1 = nn.Linear(128*10*10,256)
self.fc2 = nn.Linear(256,128)
self.fc3 = nn.Linear(128,50)
self.relu = nn.ReLU()
def forward(self,X):
preds = F.max_pool2d(self.relu(self.conv1(X)))
preds = F.max_pool2d(self.relu(self.conv2batchnorm(self.conv2(preds))))
preds = F.max_pool2d(self.relu(self.conv3(preds)))
preds = preds.view(-1,128*10*10)
preds = self.relu(self.fc1(preds))
preds = self.relu(self.fc2(preds))
preds = self.relu(self.fc3(preds))
return preds
device = torch.device('cuda')
model = BaseLine().to(device)
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr=1e-03)
PROJECT_NAME = 'Car-Brands-Images-Clf'
import wandb
EPOCHS = 100
BATCH_SIZE = 32
wandb.init(project=PROJECT_NAME,name='custom-model-baseline')
f
```
| github_jupyter |
# Q1. Explain the difference between greedy and non-greedy syntax with visual terms in as few words as possible. What is the bare minimum effort required to transform a greedy pattern into a non-greedy one? What characters or characters can you introduce or change?
```
# Ans : Greedy version, Python matches the longest possible string
import re
text = "<Robot is the latest addition to the tech items> <Robot is very advanced> <Robot is a machine>"
greedyregobj=re.compile(r'<.*>')
match=greedyregobj.search(text)
print(match.group())
#the Non-greedy version of the regex, Python matches the shortest possible string
nongreedyregobj=re.compile(r'<Ro.*?>')
match1=nongreedyregobj.search(text)
match1.group()
```
# Q2. When exactly does greedy versus non-greedy make a difference? What if you're looking for a non-greedy match but the only one available is greedy?
In the non-greedy version of the regex, Python matches the shortest possible string. In the greedy version, Python matches the longest possible string. If only non greedy match is available, we can use other filtering or pattern matching methods of regex and further identify the required pattern.
# Q3. In a simple match of a string, which looks only for one match and does not do any replacement, is the use of a nontagged group likely to make any practical difference?
```
# Ans :
import re
phoneNumRegex = re.compile(r'\d\d\d')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print('Phone number found: ' + mo.group()) # non tagged group
print('Phone number found: ' + mo.group(0))
```
# Q4. Describe a scenario in which using a nontagged category would have a significant impact on the program's outcomes.
```
# Ans : Non tagged category :
import re
text='135.135'
pattern=r'(\d+)(?:.)(\d+)'
regobj=re.compile(pattern)
matobj=regobj.search(text)
matobj.groups()
# Here the '.' decimal is not tagged or captured.
# It will useful in scenarios where the separator of value in a string is of no use and we need to capture only the
# values.
```
# Q5. Unlike a normal regex pattern, a look-ahead condition does not consume the characters it examines. Describe a situation in which this could make a difference in the results of your programme.
While counting the number of multiple lines or mulytiple sentence in a string the positive look ahead makes a difference, without which we wont get the correct count of lines or sentences in a string.
# Q6. In standard expressions, what is the difference between positive look-ahead and negative look-ahead?
```
# Ans : Positive look ahead is an assertion continuing the search and extending the string e.g.pattern= r'abc(?=[A-Z])''.
# Here after 'abc', ? is extending the search and says that in the remaining string, first identify the next
# charater should be capitalized character between A and Z, but doesnt consume it.
# Example of Positive lookahead
import re
pat=r'abc(?=[A-Z])'
text="abcABCEF"
regobj=re.compile(pat)
matobj=regobj.findall(text)
print("Positive lookahead:",matobj)
# Negative look head is also an assertion to exclude certain patterns e.g. pattern = r'abc(?!abc)', means
# identify a substring containing
# 'abc' which is not followed by another 'abc'
# Example of Negative lookahead
import re
pat1=r'abc(?!abc)'
text1="aeiouabcabc"
regobj1=re.compile(pat1)
matobj1=regobj1.findall(text)
print("Negative look ahead:",matobj1)
```
# Q7. What is the benefit of referring to groups by name rather than by number in a standard expression?
The benifit of referring to the groups by name is that
* The code is clear
* It is easier to maimtain the code.
# Q8. Can you identify repeated items within a target string using named groups, as in "The cow jumped over the moon"?
```
# Ans :
import re
text = "The cow jumped over the moon"
regobj=re.compile(r'(?P<w1>The)',re.I)
regobj.findall(text)
```
# Q9. When parsing a string, what is at least one thing that the Scanner interface does for you that the re.findall feature does not?
re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data,whereas Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left to right, and matches are returned in the order found.
# Q10. Does a scanner object have to be named scanner?
The scanner object need not be named scanner. It may have any name.
| github_jupyter |
# Welcom to Tabint
> NB: this is on development process, many things we want to develop but have not yet done. If you want to contribute please feel free to do so. We are according to nbdev style. So if you do contribute, please do so accordingly. For more information about nbdev style, please visit [nbdev document](https://nbdev.fast.ai/)
## Installing
```
git clone https://github.com/KienVu2368/tabint
cd tabint
conda env create -f environment.yml
conda activate tabint
```
## Pre-processing
```
import pandas as pd
df = pd.read_csv('df_sample.csv')
df_proc, y, pp_outp = tabular_proc(df, 'TARGET', [fill_na(), app_cat(), dummies()])
```
Unify class for pre processing class.
```
class cls(TBPreProc):
@staticmethod
def func(df, pp_outp, na_dict = None):
...
return df
```
For example, fill_na class
```
class fill_na(TBPreProc):
@staticmethod
def func(df, pp_outp, na_dict = None):
na_dict = {} if na_dict is None else na_dict.copy()
na_dict_initial = na_dict.copy()
for n,c in df.items(): na_dict = fix_missing(df, c, n, na_dict)
if len(na_dict_initial.keys()) > 0:
df.drop([a + '_na' for a in list(set(na_dict.keys()) - set(na_dict_initial.keys()))], axis=1, inplace=True)
pp_outp['na_dict'] = na_dict
return df
```
## Dataset
Dataset class contain training set, validation set and test set.
Dataset can be built by split method of SKlearn
```
ds = TBDataset.from_SKSplit(df_proc, y, cons, cats, ratio = 0.2)
```
Or by split method of tabint. This method will try to keep the same distribution of categorie variables between training set and validation set.
```
ds = TBDataset.from_TBSplit(df_proc, y, cons, cats, ratio = 0.2)
```
Dataset class have method that can simultaneously edit training set, validation set and test set.
Drop method can drop one or many columns in training set, validation set and test set.
```
ds.drop('DAYS_LAST_PHONE_CHANGE_na')
```
Or if we need to keep only importance columns that we found above. Just use keep method from dataset.
```
mpt_features = impt.top_features(24)
ds.keep(impt_features)
```
Dataset class in tabint also can simultaneously apply a funciton to training set, validation set and test set
```
ds.apply('DAYS_BIRTH', lambda df: -df['DAYS_BIRTH']/365)
```
Or we can pass many transformation function at once.
```
tfs = {'drop 1': ['AMT_REQ_CREDIT_BUREAU_HOUR_na', 'AMT_REQ_CREDIT_BUREAU_YEAR_na'],
'apply':{'DAYS_BIRTH': lambda df: -df['DAYS_BIRTH']/365,
'DAYS_EMPLOYED': lambda df: -df['DAYS_EMPLOYED']/365,
'NEW_EXT_SOURCES_MEAN': lambda df: df[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].mean(axis=1, skipna=True),
'NEW_EXT_SOURCES_GEO': lambda df: (df['EXT_SOURCE_1']*df['EXT_SOURCE_2']*df['EXT_SOURCE_3'])**(1/3),
'AMT_CREDIT/AMT_GOODS_PRICE': lambda df: df['AMT_CREDIT']/df['AMT_GOODS_PRICE'],
'AMT_CREDIT/AMT_CREDIT': lambda df: df['AMT_CREDIT']/df['AMT_CREDIT'],
'DAYS_EMPLOYED/DAYS_BIRTH': lambda df: df['DAYS_EMPLOYED']/df['DAYS_BIRTH'],
'DAYS_BIRTH*EXT_SOURCE_1_na': lambda df: df['DAYS_BIRTH']*df['EXT_SOURCE_1_na']},
'drop 2': ['AMT_ANNUITY', 'AMT_CREDIT', 'AMT_GOODS_PRICE']}
ds.transform(tfs)
```
## Learner
Learner class unify training method from sklearn model
```
learner = LGBLearner()
params = {'task': 'train', 'objective': 'binary', 'metric':'binary_logloss'}
learner.fit(params, *ds.trn, *ds.val)
```
LGBM model
```
learner = SKLearner(RandomForestClassifier())
learner.fit(*ds.trn, *ds.val)
```
and XGB model (WIP)
## Feature correlation
tabint use đenogram for easy to see and pick features with high correlation
```
ddg = Dendogram.from_df(ds.x_trn)
ddg.plot()
```
## Feature importance
tabint use [permutation importance](https://explained.ai/rf-importance/index.html). Each column or group of columns in validation set in dataset will be permute to calculate the importance.
```
group_cols = [['AMT_CREDIT', 'AMT_GOODS_PRICE', 'AMT_ANNUITY'], ['FLAG_OWN_CAR_N', 'OWN_CAR_AGE_na']]
impt = Importance.from_Learner(learner, ds, group_cols)
impt.plot()
```
We can easily get the most importance feature by method in Importance class
```
impt.top_features(24)
```
## Model performance
### Classification problem
#### Receiver operating characteristic
```
roc = ReceiverOperatingCharacteristic.from_learner(learner, ds)
roc.plot()
```
#### Probability distribution
```
kde = KernelDensityEstimation.from_learner(learner, ds)
kde.plot()
```
#### Precision and Recall
```
pr = PrecisionRecall.from_series(y_true, y_pred)
pr.plot()
```
### Regression problem
#### Actual vs Predict
```
avp = actual_vs_predict.from_learner(learner, ds)
avp.plot(hue = 'Height')
```
## Interpretation and explaination
### Partial dependence
tabint use [PDPbox](https://github.com/SauceCat/PDPbox) library to visualize partial dependence.
```
pdp = PartialDependence.from_Learner(learner, ds)
```
### info target plot
```
pdp.info_target_plot('EXT_SOURCE_3')
```
We can see result as table
```
pdp.info_target_data()
```
### isolate plot
```
pdp.isolate_plot('EXT_SOURCE_3')
```
### Tree interpreter
```
Tf = Traterfall.from_SKTree(learner, ds.x_trn, 3)
Tf.plot(formatting = "$ {:,.3f}")
```
We can see and filter result table
```
Tf.data.pos(5)
Tf.data.neg(5)
```
### SHAP
tabint visual SHAP values from [SHAP](https://github.com/slundberg/shap) library. SHAP library use red and blue for default color. tabint change these color to green and blue for easy to see and consistence with pdpbox library.
```
Shap = SHAP.from_Tree(learner, ds)
```
#### force plot
```
Shap.one_force_plot(3)
```
And we can see table result also.
```
Shap.one_force_data.pos(5)
Shap.one_force_data.neg(5)
```
#### dependence plot
```
Shap.dependence_plot('EXT_SOURCE_2')
```
| github_jupyter |
# Plots to generate supplementary figures for TP53 classifier figure
**Gregory Way, 2018**
The figures consist of TP53 classifier scores stratified by TP53 inactivation status and cancer-type.
There are two sets of plots generated:
1. Cancer-types for which TP53 loss of function events are on either extreme of proportions.
* OV and UCS have a high percentage of TP53 loss events
* THCA and UVM have a low percentage of TP53 loss events
* The figure demonstrates that even in cancer-types with extreme values (and that they were not even included in model training) the classifier can detect TP53 inactivation
2. Cancer-types for which TP53 loss events are enriched in specific subtypes.
* Basal BRCA subtype tumors often have TP53 mutations
* UCEC subtypes have different proportions of TP53 loss events as well.
* The figure shows how subtype assignments do not confound TP53 classifier predictions within cancer-types
```
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('seaborn-notebook')
sns.set(style='white')
sns.set_context('paper', rc={'font.size':16, 'axes.titlesize':11, 'axes.labelsize':20,
'xtick.labelsize':18, 'ytick.labelsize':14})
def random_guess_line(**kwargs):
plt.axhline(y=0.5, color='k', ls='dashed', linewidth=0.7)
# The prediction file stores the TP53 classifier scores for all samples
prediction_file = os.path.join('..', 'classifiers', 'TP53', 'tables',
'mutation_classification_scores.tsv')
prediction_df = pd.read_table(prediction_file, index_col=0)
prediction_df.head(2)
```
## Predictions for cancer-types with extreme proportions of TP53 loss of function events
* Samples that are heavily TP53 mutated or copy number lost: OV, UCS
* Samples that are heavily TP53 wild-type: THCA, UVM
Note that these samples were not used in training the classifier.
```
extreme_types = ['OV', 'UCS', 'THCA', 'UVM']
extreme_df = prediction_df[prediction_df['DISEASE'].isin(extreme_types)]
figure_name = os.path.join('..', 'figures', 'TP53_opposite_spectrum_cancertypes.pdf')
plt.figure(figsize=(2, 6))
g = sns.factorplot(x='total_status', y='weight', col='DISEASE', data=extreme_df,
palette="hls", col_order=extreme_types, kind='strip', jitter=0.4,
alpha=0.8)
g.map(random_guess_line)
(g.set_axis_labels('', 'TP53 Classifier Score')
.set_xticklabels(['Wild Type', 'Other'])
.set_titles("{col_name}")
.set(ylim=(0, 1)))
plt.tight_layout()
plt.savefig(figure_name, dpi=600, bbox_inchex='tight');
```
## Predictions for cancer-types that have differential proportions of TP53 alterations according to subtype
These include: BRCA and UCEC
```
brca_df = prediction_df[prediction_df['DISEASE'] == 'BRCA']
ucec_df = prediction_df[prediction_df['DISEASE'] == 'UCEC']
def plot_subtype(df, title):
ax = sns.stripplot(x='SUBTYPE', y='weight', hue='total_status',
data=df, dodge=True,
palette='hls', edgecolor='black',
jitter=0.3, alpha=0.8)
plt.axhline(0.5, color='black', linestyle='dashed', linewidth=1)
ax.set_ylabel('TP53 Classifier Score')
ax.legend_.remove()
ax.set_title(title, size=19)
sns.despine()
plt.tight_layout()
brca_file_name = os.path.join('..', 'figures', 'TP53_BRCA_subtype_confounding.pdf')
plot_subtype(brca_df, 'BRCA')
plt.savefig(brca_file_name, dpi=600, bbox_inchex='tight')
ucec_file_name = os.path.join('..', 'figures', 'TP53_UCEC_subtype_confounding.pdf')
plot_subtype(ucec_df, 'UCEC')
plt.savefig(ucec_file_name, dpi=600, bbox_inchex='tight')
```
| github_jupyter |
# Plots for logistic regression, consistent vs inconsistent
```
import numpy as np
import matplotlib.pyplot as plt
import dotenv
import pandas as pd
import mlflow
import plotly
import plotly.graph_objects as go
import plotly.express as px
import plotly.subplots
import plotly.io as pio
import matplotlib.lines
import typing
import os
import shutil
import sys
import warnings
EXPORT = False
SHOW_TITLES = not EXPORT
EXPORT_NAME = 'logistic_regression_inconsistent_consistent'
INCREASING_D_EXPERIMENT_NAME = 'logistic_regression_inconsistent_consistent_increase_d'
INCREASING_EPS_EXPERIMENT_NAME = 'logistic_regression_inconsistent_consistent_increase_epsilon'
# Load environment variables
dotenv.load_dotenv()
# Enable loading of the project module
MODULE_DIR = os.path.join(os.path.abspath(os.path.join(os.path.curdir, os.path.pardir, os.pardir)), 'src')
sys.path.append(MODULE_DIR)
%load_ext autoreload
%autoreload 2
import interpolation_robustness as ir
FIGURE_SIZE = (2.6, 1.4)
LEGEND_FONT_SIZE = ir.plots.FONT_SIZE_SMALL_PT
LEGEND_FIGURE_SIZE = (2.6, 0.55)
ir.plots.setup_matplotlib(show_titles=SHOW_TITLES)
if EXPORT:
EXPORT_DIR = os.path.join(ir.util.REPO_ROOT_DIR, 'logs', f'export_{EXPORT_NAME}')
print('Using export directory', EXPORT_DIR)
if os.path.exists(EXPORT_DIR):
shutil.rmtree(EXPORT_DIR)
os.makedirs(EXPORT_DIR)
def export_fig(fig: plt.Figure, filename: str):
# If export is disabled then do nothing
if EXPORT:
export_path = os.path.join(EXPORT_DIR, filename)
fig.savefig(export_path)
print('Exported figure at', export_path)
```
## Load experiment data
```
client = mlflow.tracking.MlflowClient()
experiment_d_increase = client.get_experiment_by_name(INCREASING_D_EXPERIMENT_NAME)
experiment_eps_increase = client.get_experiment_by_name(INCREASING_EPS_EXPERIMENT_NAME)
runs_d_increase = mlflow.search_runs(experiment_d_increase.experiment_id)
runs_eps_increase = mlflow.search_runs(experiment_eps_increase.experiment_id)
def prepare_runs(runs: pd.DataFrame) -> pd.DataFrame:
runs = runs.set_index('run_id', drop=False) # set index, but keep column to not break stuff depending on it
# Convert some parameters to numbers and sort accordingly
runs['params.data_dim'] = runs['params.data_dim'].astype(int)
runs['params.data_num_train_samples'] = runs['params.data_num_train_samples'].astype(int)
runs['params.train_attack_epsilon'] = runs['params.train_attack_epsilon'].astype(np.float)
runs['params.test_attack_epsilon'] = runs['params.test_attack_epsilon'].astype(np.float)
runs['params.l2_lambda'] = runs['params.l2_lambda'].astype(np.float)
runs['params.label_noise'] = runs['params.label_noise'].astype(np.float)
runs = runs.sort_values(['params.data_dim', 'params.l2_lambda'])
assert runs['status'].eq('FINISHED').all()
return runs
runs_d_increase = prepare_runs(runs_d_increase)
print('Loaded', len(runs_d_increase), 'runs of experiment', INCREASING_D_EXPERIMENT_NAME)
runs_eps_increase = prepare_runs(runs_eps_increase)
print('Loaded', len(runs_eps_increase), 'runs of experiment', INCREASING_EPS_EXPERIMENT_NAME)
assert runs_eps_increase['params.l2_lambda'].eq(0).all()
assert runs_eps_increase['params.label_noise'].eq(0).all()
assert runs_d_increase['params.label_noise'].eq(0).all()
grouping_keys = ['params.data_dim', 'params.l2_lambda', 'params.train_consistent_attacks', 'params.train_attack_epsilon', 'params.data_num_train_samples']
aggregate_metrics = ('metrics.true_robust_risk', 'metrics.training_loss')
runs_d_increase_agg = runs_d_increase.groupby(grouping_keys, as_index=False).aggregate({metric: ['mean', 'std'] for metric in aggregate_metrics})
runs_eps_increase_agg = runs_eps_increase.groupby(grouping_keys, as_index=False).aggregate({metric: ['mean', 'std'] for metric in aggregate_metrics})
```
## Plot
```
robust_consistent_color_idx = 1
robust_inconsistent_color_idx = 2
noreg_linestyle = '-'
bestreg_linestyle = '--'
BASELINE_LAMBDA = 0
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)
warnings.simplefilter(action='ignore', category=UserWarning)
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
num_samples, = runs_d_increase['params.data_num_train_samples'].unique()
train_attack_epsilon, = runs_d_increase['params.train_attack_epsilon'].unique()
current_consistent_runs = runs_d_increase_agg[runs_d_increase_agg['params.train_consistent_attacks'] == 'True']
current_inconsistent_runs = runs_d_increase_agg[runs_d_increase_agg['params.train_consistent_attacks'] == 'False']
consistent_noreg_runs = current_consistent_runs[current_consistent_runs['params.l2_lambda'] == BASELINE_LAMBDA]
inconsistent_noreg_runs = current_inconsistent_runs[current_inconsistent_runs['params.l2_lambda'] == BASELINE_LAMBDA]
consistent_bestreg_runs = current_consistent_runs.sort_values(('metrics.true_robust_risk', 'mean')).groupby(['params.data_dim'], as_index=False).first()
inconsistent_bestreg_runs = current_inconsistent_runs.sort_values(('metrics.true_robust_risk', 'mean')).groupby(['params.data_dim'], as_index=False).first()
ax.errorbar(
consistent_noreg_runs['params.data_dim'] / float(num_samples),
consistent_noreg_runs[('metrics.true_robust_risk', 'mean')],
yerr=consistent_noreg_runs[('metrics.true_robust_risk', 'std')],
label=fr'Consistent, $\lambda \to 0$',
c=f'C{robust_consistent_color_idx}',
ls=noreg_linestyle,
zorder=2
)
ax.errorbar(
consistent_bestreg_runs['params.data_dim'] / float(num_samples),
consistent_bestreg_runs[('metrics.true_robust_risk', 'mean')],
yerr=consistent_bestreg_runs[('metrics.true_robust_risk', 'std')],
label=r'Consistent, $\lambda_{\textnormal{opt}}$',
c=f'C{robust_consistent_color_idx}',
ls=bestreg_linestyle,
zorder=2
)
ax.errorbar(
inconsistent_noreg_runs['params.data_dim'] / float(num_samples),
inconsistent_noreg_runs[('metrics.true_robust_risk', 'mean')],
yerr=inconsistent_noreg_runs[('metrics.true_robust_risk', 'std')],
label=fr'Inconsistent, $\lambda \to 0$',
c=f'C{robust_inconsistent_color_idx}',
ls=noreg_linestyle,
zorder=1
)
ax.errorbar(
inconsistent_bestreg_runs['params.data_dim'] / float(num_samples),
inconsistent_bestreg_runs[('metrics.true_robust_risk', 'mean')],
yerr=inconsistent_bestreg_runs[('metrics.true_robust_risk', 'std')],
label=r'Inconsistent, $\lambda_{\textnormal{opt}}$',
c=f'C{robust_inconsistent_color_idx}',
ls=bestreg_linestyle,
zorder=1
)
ax.set_xlabel('d/n')
ax.set_ylabel('Robust risk')
ax.set_ylim(bottom=0)
ax.set_xlim(left=1)
if SHOW_TITLES:
fig.suptitle(f'Consistent vs inconsistent AT, fixed epsilon {train_attack_epsilon} and n {num_samples}')
export_fig(fig, f'logreg_inconsistent_vs_consistent_d_increase.pdf')
plt.show()
# Legend
legend_fig = plt.figure(figsize=LEGEND_FIGURE_SIZE)
handles, labels = ax.get_legend_handles_labels()
ir.plots.errorbar_legend(
legend_fig,
handles,
labels,
loc='center',
ncol=2,
mode='expand',
frameon=True,
fontsize=LEGEND_FONT_SIZE,
borderpad=0.5
)
export_fig(legend_fig, f'logreg_inconsistent_vs_consistent_d_increase_legend.pdf')
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
num_samples_map = {
1000: ir.plots.LINESTYLE_MAP[0],
200: ir.plots.LINESTYLE_MAP[3]
}
data_dim, = runs_eps_increase['params.data_dim'].unique()
eps_increase_consistent_runs = runs_eps_increase_agg[runs_eps_increase_agg['params.train_consistent_attacks'] == 'True']
eps_increase_inconsistent_runs = runs_eps_increase_agg[runs_eps_increase_agg['params.train_consistent_attacks'] == 'False']
for num_samples, linestyle in num_samples_map.items():
current_consistent_runs = eps_increase_consistent_runs[eps_increase_consistent_runs['params.data_num_train_samples'] == num_samples]
ax.errorbar(
current_consistent_runs['params.train_attack_epsilon'],
current_consistent_runs[('metrics.true_robust_risk', 'mean')],
yerr=current_consistent_runs[('metrics.true_robust_risk', 'std')],
label=fr'Cons., $n = {num_samples}$',
c=f'C{robust_consistent_color_idx}',
ls=linestyle,
zorder=2
)
for num_samples, linestyle in num_samples_map.items():
current_inconsistent_runs = eps_increase_inconsistent_runs[eps_increase_inconsistent_runs['params.data_num_train_samples'] == num_samples]
ax.errorbar(
current_inconsistent_runs['params.train_attack_epsilon'],
current_inconsistent_runs[('metrics.true_robust_risk', 'mean')],
yerr=current_inconsistent_runs[('metrics.true_robust_risk', 'std')],
label=fr'Incons., $n = {num_samples}$',
c=f'C{robust_inconsistent_color_idx}',
ls=linestyle,
zorder=1
)
ax.set_xlabel('Train and test $\epsilon$')
ax.set_ylabel('Robust risk')
ax.set_ylim(bottom=-0.005)
ax.set_xlim(left=-0.001)
if SHOW_TITLES:
fig.suptitle(f'Consistent vs inconsistent AT, fixed d {data_dim}')
export_fig(fig, f'logreg_inconsistent_vs_consistent_eps_increase.pdf')
plt.show()
# Legend
legend_fig = plt.figure(figsize=LEGEND_FIGURE_SIZE)
handles, labels = ax.get_legend_handles_labels()
ir.plots.errorbar_legend(
legend_fig,
handles,
labels,
loc='center',
ncol=2,
mode='expand',
frameon=True,
fontsize=LEGEND_FONT_SIZE,
borderpad=0.5
)
export_fig(legend_fig, f'logreg_inconsistent_vs_consistent_eps_increase_legend.pdf')
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
population_linestyle = ir.plots.LINESTYLE_MAP[0]
training_linestyle = ir.plots.LINESTYLE_MAP[2]
target_num_samples = 1000
current_runs = runs_eps_increase_agg[runs_eps_increase_agg['params.data_num_train_samples'] == target_num_samples]
assert current_runs['params.l2_lambda'].eq(0).all()
data_dim, = current_runs['params.data_dim'].unique()
current_consistent_runs = current_runs[current_runs['params.train_consistent_attacks'] == 'True']
current_inconsistent_runs = current_runs[current_runs['params.train_consistent_attacks'] == 'False']
ax.errorbar(
current_consistent_runs['params.train_attack_epsilon'],
current_consistent_runs[('metrics.true_robust_risk', 'mean')],
yerr=current_consistent_runs[('metrics.true_robust_risk', 'std')],
label=fr'Robust risk, cons.',
c=f'C{robust_consistent_color_idx}',
ls=population_linestyle,
zorder=2
)
ax.errorbar(
current_inconsistent_runs['params.train_attack_epsilon'],
current_inconsistent_runs[('metrics.true_robust_risk', 'mean')],
yerr=current_inconsistent_runs[('metrics.true_robust_risk', 'std')],
label=fr'Robust risk, incons.',
c=f'C{robust_inconsistent_color_idx}',
ls=population_linestyle,
zorder=2
)
ax.errorbar(
current_consistent_runs['params.train_attack_epsilon'],
current_consistent_runs[('metrics.training_loss', 'mean')],
yerr=current_consistent_runs[('metrics.training_loss', 'std')],
label=fr'Training loss, cons.',
c=f'C{robust_consistent_color_idx}',
ls=training_linestyle,
zorder=2
)
ax.errorbar(
current_inconsistent_runs['params.train_attack_epsilon'],
current_inconsistent_runs[('metrics.training_loss', 'mean')],
yerr=current_inconsistent_runs[('metrics.training_loss', 'std')],
label=fr'Training loss, incons.',
c=f'C{robust_inconsistent_color_idx}',
ls=training_linestyle,
zorder=2
)
ax.set_xlabel('Train and test $\epsilon$')
ax.set_ylim(bottom=-0.005)
ax.set_xlim(left=-0.001)
if SHOW_TITLES:
fig.suptitle(f'Consistent vs inconsistent AT, fixed d {data_dim} and n {target_num_samples}')
export_fig(fig, f'logreg_inconsistent_vs_consistent_eps_increase_alt.pdf')
plt.show()
# Legend
legend_fig = plt.figure(figsize=LEGEND_FIGURE_SIZE)
handles, labels = ax.get_legend_handles_labels()
ir.plots.errorbar_legend(
legend_fig,
handles,
labels,
loc='center',
ncol=2,
mode='expand',
frameon=True,
fontsize=LEGEND_FONT_SIZE,
borderpad=0.5
)
export_fig(legend_fig, f'logreg_inconsistent_vs_consistent_eps_increase_alt_legend.pdf')
```
| github_jupyter |
# Synthetic Dataset Example
The synthetic data set is a small 2D data set meant for plotting and visualizing effects of decision functions. It contains two unprotected numerical features generated from two gaussians and one protected binary feature assigned based on the discrimination factor. It is implemented as AIF360 BinaryLabelDataset and includes a ``plot`` function.
```
import sys
import numpy as np
sys.path.append("../")
```
## 1. Load Synthetic Data Set with Default Parameters
```
# import tha data set
from fairensics.data.synthetic_dataset import SyntheticDataset
# load the data set
syn_data = SyntheticDataset()
# print some stats
print(type(syn_data))
print()
print("Data shape:\t\t\t", syn_data.features.shape)
print()
print("Feature names:\t\t\t", syn_data.feature_names)
print("Protected feature names:\t", syn_data.protected_attribute_names)
print()
print("Protected feature values:\t", np.unique(syn_data.protected_attributes))
print("\tPriviliged class:\t", syn_data.privileged_protected_attributes)
print("\tUnpriviliged class:\t", syn_data.unprivileged_protected_attributes)
print()
print("Label values :\t\t\t", np.unique(syn_data.labels))
print("\tPriviliged label:\t", syn_data.favorable_label)
print("\tUnpriviliged label:\t", syn_data.unfavorable_label)
# plot the data
syn_data.plot()
```
## 2. Load Synthetic Data Set with Custom Parameters
The parameters should be self explaining.
``n_samples`` refers to the number of points per group.
``initial_discrimination`` is the discrimination factor used to assign the protected attribute to one of the two clusters.
```
syn_data = SyntheticDataset (n_samples=10, label_name='new_label', feature_one_name="feature_one",
feature_two_name="feature_two", favorable_label=10, unfavorable_label=-10,
protected_attribute_name="age", privileged_class=1,
unprivileged_class=-1, sd=1234, mu_1=[0, 0], sigma_1=[[1, 0], [0, 2]],
mu_2=[3, 3], sigma_2=[[1, 0], [0, 1]], initial_discrimination=3.0)
syn_data.plot()
# print some stats
print("Data shape:\t\t\t", syn_data.features.shape)
print()
print("Feature names:\t\t\t", syn_data.feature_names)
print("Protected feature names:\t", syn_data.protected_attribute_names)
print()
print("Protected feature values:\t", np.unique(syn_data.protected_attributes))
print("\tPriviliged class:\t", syn_data.privileged_protected_attributes)
print("\tUnpriviliged class:\t", syn_data.unprivileged_protected_attributes)
print()
print("Label values :\t\t\t", np.unique(syn_data.labels))
print("\tPriviliged label:\t", syn_data.favorable_label)
print("\tUnpriviliged label:\t", syn_data.unfavorable_label)
print()
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
```
# Text generation with an RNN
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/text/text_generation"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/text/text_generation.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
This tutorial demonstrates how to generate text using a character-based RNN. You will work with a dataset of Shakespeare's writing from Andrej Karpathy's [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Given a sequence of characters from this data ("Shakespear"), train a model to predict the next character in the sequence ("e"). Longer sequences of text can be generated by calling the model repeatedly.
Note: Enable GPU acceleration to execute this notebook faster. In Colab: *Runtime > Change runtime type > Hardware accelerator > GPU*.
This tutorial includes runnable code implemented using [tf.keras](https://www.tensorflow.org/programmers_guide/keras) and [eager execution](https://www.tensorflow.org/programmers_guide/eager). The following is sample output when the model in this tutorial trained for 30 epochs, and started with the prompt "Q":
<pre>
QUEENE:
I had thought thou hadst a Roman; for the oracle,
Thus by All bids the man against the word,
Which are so weak of care, by old care done;
Your children were in your holy love,
And the precipitation through the bleeding throne.
BISHOP OF ELY:
Marry, and will, my lord, to weep in such a one were prettiest;
Yet now I was adopted heir
Of the world's lamentable day,
To watch the next way with his father with his face?
ESCALUS:
The cause why then we are all resolved more sons.
VOLUMNIA:
O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,
And love and pale as any will to that word.
QUEEN ELIZABETH:
But how long have I heard the soul for this world,
And show his hands of life be proved to stand.
PETRUCHIO:
I say he look'd on, if I must be content
To stay him from the fatal of our country's bliss.
His lordship pluck'd from this sentence then for prey,
And then let us twain, being the moon,
were she such a case as fills m
</pre>
While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:
* The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.
* The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.
* As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure.
## Setup
### Import TensorFlow and other libraries
```
import tensorflow as tf
from tensorflow.keras.layers.experimental import preprocessing
tf.config.experimental.set_memory_growth(tf.config.experimental.list_physical_devices('GPU')[0], True)
import numpy as np
import os
import time
from IPython.display import Image
```
### Download the Shakespeare dataset
Change the following line to run this code on your own data.
```
path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')
```
### Read the data
First, look in the text:
```
# Read, then decode for py2 compat.
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# length of text is the number of characters in it
print('Length of text: {} characters'.format(len(text)))
# Take a look at the first 250 characters in text
print(text[:250])
# The unique characters in the file
vocab = sorted(set(text))
print('{} unique characters'.format(len(vocab)))
```
## Process the text
### Vectorize the text
Before training, you need to convert the strings to a numerical representation.
The `preprocessing.StringLookup` layer can convert each character into a numeric ID. It just needs the text to be
split into tokens first.
```
example_texts = ['abcdefg', 'xyz']
chars = tf.strings.unicode_split(example_texts, input_encoding='UTF-8')
chars
```
Now create the `preprocessing.StringLookup` layer:
```
ids_from_chars = preprocessing.StringLookup(vocabulary=list(vocab))
```
It converts form tokens to character IDs, padding with `0`:
```
ids = ids_from_chars(chars)
ids
```
Since the goal of this tutorial is to generate text, it will also be important to invert this representation and recover human-readable strings from it. For this you can use `preprocessing.StringLookup(..., invert=True)`.
Note: Here instead of passing the original vocabulary generated with `sorted(set(text))` use the `get_vocabulary()` method of the `preprocessing.StringLookup` layer so that the padding and `[UNK]` tokens are set the same way.
```
chars_from_ids = tf.keras.layers.experimental.preprocessing.StringLookup(
vocabulary=ids_from_chars.get_vocabulary(), invert=True)
```
This layer recovers the characters from the vectors of IDs, and returns them as a `tf.RaggedTensor` of characters:
```
chars = chars_from_ids(ids)
chars
```
You can `tf.strings.reduce_join` to join the characters back into strings.
```
tf.strings.reduce_join(chars, axis=-1).numpy()
def text_from_ids(ids):
return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)
```
### The prediction task
Given a character, or a sequence of characters, what is the most probable next character? This is the task you're
training the model to perform. The input to the model will be a sequence of characters, and you train the model
to predict the output—the following character at each time step.
Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters
computed until this moment, what is the next character?
### Create training examples and targets
Next divide the text into example sequences. Each input sequence will contain `seq_length` characters from the text.
For each input sequence, the corresponding targets contain the same length of text, except shifted one character
to the right.
So break the text into chunks of `seq_length+1`. For example, say `seq_length` is 4 and our text is "Hello". The
input sequence would be "Hell", and the target sequence "ello".
To do this first use the `tf.data.Dataset.from_tensor_slices` function to convert the text vector into a stream
of character indices.
```
all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8'))
all_ids
ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids)
for ids in ids_dataset.take(10):
print(chars_from_ids(ids).numpy().decode('utf-8'))
seq_length = 100
examples_per_epoch = len(text)//(seq_length+1)
```
The `batch` method lets you easily convert these individual characters to sequences of the desired size.
```
sequences = ids_dataset.batch(seq_length+1, drop_remainder=True)
for seq in sequences.take(1):
print(chars_from_ids(seq))
```
It's easier to see what this is doing if you join the tokens back into strings:
```
for seq in sequences.take(5):
print(text_from_ids(seq).numpy())
```
For training, you'll need a dataset of `(input, label)` pairs. Where `input` and
`label` are sequences. At each time step the input is the current character, and the label is the next character.
Here's a function that takes a sequence as input, duplicates, and shifts it to align the input and label for
each timestep:
```
def split_input_target(sequence):
input_text = sequence[:-1]
target_text = sequence[1:]
return input_text, target_text
split_input_target(list("Tensorflow"))
dataset = sequences.map(split_input_target)
for input_example, target_example in dataset.take(1):
print("Input :", text_from_ids(input_example).numpy())
print("Target:", text_from_ids(target_example).numpy())
```
### Create training batches
You used `tf.data` to split the text into manageable sequences. But before feeding this data into the model, you
need to shuffle the data and pack it into batches.
```
# Batch size
BATCH_SIZE = 256
# Buffer size to shuffle the dataset
# (TF data is designed to work with possibly infinite sequences,
# so it doesn't attempt to shuffle the entire sequence in memory. Instead,
# it maintains a buffer in which it shuffles elements).
BUFFER_SIZE = 10000
dataset = (
dataset
.shuffle(BUFFER_SIZE)
.batch(BATCH_SIZE, drop_remainder=True)
.prefetch(tf.data.experimental.AUTOTUNE))
dataset
```
## Build The Model
This section defines the model as a `keras.Model` subclass (For details see
[Making new Layers and Models via subclassing](https://www.tensorflow.org/guide/keras/custom_layers_and_models)).
This model has three layers:
* `tf.keras.layers.Embedding`: The input layer. A trainable lookup table that will map each character-ID to a
vector with `embedding_dim` dimensions;
* `tf.keras.layers.GRU`: A type of RNN with size `units=rnn_units` (You can also use an LSTM layer here.)
* `tf.keras.layers.Dense`: The output layer, with `vocab_size` outputs. It outpts one logit for each character
in the vocabulary. These are the log-liklihood of each character according to the model.
```
# Length of the vocabulary in chars
vocab_size = len(vocab)
# The embedding dimension
embedding_dim = 256
# Number of RNN units
rnn_units = 1024
class MyModel(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, rnn_units):
super().__init__(self)
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(rnn_units,
return_sequences=True,
return_state=True)
self.dense = tf.keras.layers.Dense(vocab_size)
def call(self, inputs, states=None, return_state=False, training=False):
x = inputs
x = self.embedding(x, training=training)
if states is None:
states = self.gru.get_initial_state(x)
x, states = self.gru(x, initial_state=states, training=training)
x = self.dense(x, training=training)
if return_state:
return x, states
else:
return x
model = MyModel(
# Be sure the vocabulary size matches the `StringLookup` layers.
vocab_size=len(ids_from_chars.get_vocabulary()),
embedding_dim=embedding_dim,
rnn_units=rnn_units)
```
For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and
applies the dense layer to generate logits predicting the log-likelihood of the next character:

```
Image('./images/text_generation_training.png')
```
Note: For training you could use a `keras.Sequential` model here. To generate text later you'll need to manage
the RNN's internal state. It's simpler to include the state input and output options upfront, than it is to
rearrange the model architecture later. For more details asee the
[Keras RNN guide](https://www.tensorflow.org/guide/keras/rnn#rnn_state_reuse).
## Try the model
Now run the model to see that it behaves as expected.
First check the shape of the output:
```
for input_example_batch, target_example_batch in dataset.take(1):
example_batch_predictions = model(input_example_batch)
print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)")
```
In the above example the sequence length of the input is `100` but the model can be run on inputs of any length:
```
model.summary()
```
To get actual predictions from the model you need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.
Note: It is important to _sample_ from this distribution as taking the _argmax_ of the distribution can easily get the model stuck in a loop.
Try it for the first example in the batch:
```
sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)
sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()
```
This gives us, at each timestep, a prediction of the next character index:
```
sampled_indices
```
Decode these to see the text predicted by this untrained model:
```
print("Input:\n", text_from_ids(input_example_batch[0]).numpy())
print()
print("Next Char Predictions:\n", text_from_ids(sampled_indices).numpy())
```
## Train the model
At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character.
### Attach an optimizer, and a loss function
The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions.
Because your model returns logits, you need to set the `from_logits` flag.
```
loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)
example_batch_loss = loss(target_example_batch, example_batch_predictions)
mean_loss = example_batch_loss.numpy().mean()
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")
print("Mean loss: ", mean_loss)
```
A newly initialized model shouldn't be to sure of itself, the output logits should all have similar magnitudes. To
confirm this you can check that the exponential of the mean loss is approximately equal to the vocabulary size. A
much higher loss means the model is sure of its wrong answers, and is badly initialized:
```
tf.exp(mean_loss).numpy()
```
Configure the training procedure using the `tf.keras.Model.compile` method. Use `tf.keras.optimizers.Adam` with default arguments and the loss function.
```
model.compile(optimizer='adam', loss=loss)
```
### Configure checkpoints
Use a `tf.keras.callbacks.ModelCheckpoint` to ensure that checkpoints are saved during training:
```
# Directory where the checkpoints will be saved
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_prefix,
save_weights_only=True)
```
### Execute the training
To keep training time reasonable, use 10 epochs to train the model. In Colab, set the runtime to GPU for faster training.
```
EPOCHS = 20
history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])
```
## Generate text
The simplest way to generate text with this model is to run it in a loop, and keep track of the model's internal
state as you execute it.
```
Image('./images/text_generation_sampling.png')
# 
```
Each time you call the model you pass in some text and an internal state. The model returns a prediction for the
next character and its new state. Pass the prediction and state back in to continue generating text.
The following makes a single step prediction:
```
class OneStep(tf.keras.Model):
def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
super().__init__()
self.temperature=temperature
self.model = model
self.chars_from_ids = chars_from_ids
self.ids_from_chars = ids_from_chars
# Create a mask to prevent "" or "[UNK]" from being generated.
skip_ids = self.ids_from_chars(['','[UNK]'])[:, None]
sparse_mask = tf.SparseTensor(
# Put a -inf at each bad index.
values=[-float('inf')]*len(skip_ids),
indices = skip_ids,
# Match the shape to the vocabulary
dense_shape=[len(ids_from_chars.get_vocabulary())])
self.prediction_mask = tf.sparse.to_dense(sparse_mask)
@tf.function
def generate_one_step(self, inputs, states=None):
# Convert strings to token IDs.
input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
input_ids = self.ids_from_chars(input_chars).to_tensor()
# Run the model.
# predicted_logits.shape is [batch, char, next_char_logits]
predicted_logits, states = self.model(inputs=input_ids,
states=states,
return_state=True)
# Only use the last prediction.
predicted_logits = predicted_logits[:, -1, :]
predicted_logits = predicted_logits/self.temperature
# Apply the prediction mask: prevent "" or "[UNK]" from being generated.
predicted_logits = predicted_logits + self.prediction_mask
# Sample the output logits to generate token IDs.
predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
predicted_ids = tf.squeeze(predicted_ids, axis=-1)
# Convert from token ids to characters
predicted_chars = self.chars_from_ids(predicted_ids)
# Return the characters and model state.
return predicted_chars, states
one_step_model = OneStep(model, chars_from_ids, ids_from_chars)
```
Run it in a loop to generate some text. Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences.
```
start = time.time()
states = None
next_char = tf.constant(['ROMEO:'])
result = [next_char]
for n in range(1000):
next_char, states = one_step_model.generate_one_step(next_char, states=states)
result.append(next_char)
result = tf.strings.join(result)
end = time.time()
print(result[0].numpy().decode('utf-8'), '\n\n' + '_'*80)
print(f"\nRun time: {end - start}")
```
The easiest thing you can do to improve the results is to train it for longer (try `EPOCHS = 30`).
You can also experiment with a different start string, try adding another RNN layer to improve the model's accuracy, or adjust the temperature parameter to generate more or less random predictions.
If you want the model to generate text *faster* the easiest thing you can do is batch the text generation. In the example below the model generates 5 outputs in about the same time it took to generate 1 above.
```
start = time.time()
states = None
next_char = tf.constant(['ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:'])
result = [next_char]
for n in range(1000):
next_char, states = one_step_model.generate_one_step(next_char, states=states)
result.append(next_char)
result = tf.strings.join(result)
end = time.time()
print(result, '\n\n' + '_'*80)
print(f"\nRun time: {end - start}")
```
## Export the generator
This single-step model can easily be [saved and restored](https://www.tensorflow.org/guide/saved_model), allowing
you to use it anywhere a `tf.saved_model` is accepted.
```
tf.saved_model.save(one_step_model, 'one_step')
# one_step_reloaded = tf.saved_model.load('one_step')
# one_step_reloaded
states = None
next_char = tf.constant(['ROMEO:'])
result = [next_char]
for n in range(100):
next_char, states = one_step_model.generate_one_step(next_char, states=states)
result.append(next_char)
print(tf.strings.join(result)[0].numpy().decode("utf-8"))
```
## Advanced: Customized Training
The above training procedure is simple, but does not give you much control.
It uses teacher-forcing which prevents bad predictions from being fed back to the model so the model never learns
to recover from mistakes.
So now that you've seen how to run the model manually next you'll implement the training loop. This gives a starting
point if, for example, you want to implement _curriculum learning_ to help stabilize the model's open-loop output.
The most important part of a custom training loop is the train step function.
Use `tf.GradientTape` to track the gradients. You can learn more about this approach by reading the
[eager execution guide](https://www.tensorflow.org/guide/eager).
The basic procedure is:
1. Execute the model and calculate the loss under a `tf.GradientTape`.
2. Calculate the updates and apply them to the model using the optimizer.
```
class CustomTraining(MyModel):
@tf.function
def train_step(self, inputs):
inputs, labels = inputs
with tf.GradientTape() as tape:
predictions = self(inputs, training=True)
loss = self.loss(labels, predictions)
grads = tape.gradient(loss, model.trainable_variables)
self.optimizer.apply_gradients(zip(grads, model.trainable_variables))
return {'loss': loss}
```
The above implementation of the `train_step` method follows
[Keras' `train_step` conventions](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). This
is optional, but it allows you to change the behavior of the train step and still use keras' `Model.compile`
and `Model.fit` methods.
```
model = CustomTraining(
vocab_size=len(ids_from_chars.get_vocabulary()),
embedding_dim=embedding_dim,
rnn_units=rnn_units)
model.compile(optimizer = tf.keras.optimizers.Adam(),
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
model.fit(dataset, epochs=1)
```
Or if you need more control, you can write your own complete custom training loop:
```
EPOCHS = 10
mean = tf.metrics.Mean()
for epoch in range(EPOCHS):
start = time.time()
mean.reset_states()
for (batch_n, (inp, target)) in enumerate(dataset):
logs = model.train_step([inp, target])
mean.update_state(logs['loss'])
if batch_n % 50 == 0:
template = 'Epoch {} Batch {} Loss {}'
print(template.format(epoch + 1, batch_n, logs['loss']))
# saving (checkpoint) the model every 5 epochs
if (epoch + 1) % 5 == 0:
model.save_weights(checkpoint_prefix.format(epoch=epoch))
print()
print('Epoch {} Loss: {:.4f}'.format(epoch + 1, mean.result().numpy()))
print('Time taken for 1 epoch {} sec'.format(time.time() - start))
print("_" * 80)
model.save_weights(checkpoint_prefix.format(epoch=epoch))
```
| github_jupyter |

# The One-Dimensional Particle in a Box
## 🥅 Learning Objectives
- Determine the energies and eigenfunctions of the particle-in-a-box.
- Learn how to normalize a wavefunction.
- Learn how to compute expectation values for quantum-mechanical operators.
- Learn the postulates of quantum mechanics
## Cyanine Dyes

Cyanine dye molecules are often modelled as one-dimension particles in a box. To understand why, start by thinking classically. You learn in organic chemistry that electrons can more “freely” along alternating double bonds. If this is true, then you can imagine that the electrons can more from one Nitrogen to the other, almost without resistance. On the other hand, there are sp<sup>3</sup>-hybridized functional groups attached to the Nitrogen atom, so once the electron gets to Nitrogen atom, it has to turn around and go back whence it came. A very, very, very simple model would be to imagine that the electron is totally free between the Nitrogen atoms, and totally forbidden from going much beyond the Nitrogen atoms. This suggests modeling these systems a potential energy function like:
$$
V(x) =
\begin{cases}
+\infty & x\leq 0\\
0 & 0\lt x \lt a\\
+\infty & a \leq x
\end{cases}
$$
where $a$ is the length of the box. A reasonable approximate formula for $a$ is
$$
a = \left(5.67 + 2.49 (k + 1)\right) \cdot 10^{-10} \text{ m}
$$
## Postulate: The squared magnitude of the wavefunction is proportional to probability
What is the interpretation of the wavefunction? The Born postulate indicates that the squared magnitude of the wavefunction is proportional to the probability of observing the system at that location. E.g., if $\psi(x)$ is the wavefunction for an electron as a function of $x$, then
$$
p(x) = |\psi(x)|^2
$$
is the probability of observing an electron at the point $x$. This is called the Born Postulate.
## The Wavefunctions of the Particle in a Box (boundary conditions)

The nice thing about this “particle in a box” model is that it is easy to solve the time-independent Schrödinger equation in this case. Because there is no chance that the particle could ever “escape” an infinite box like this (such an electron would have infinite potential energy!), $|\psi(x)|^2$ must equal zero outside the box. Therefore the wavefunction can only be nonzero inside the box. In addition, the wavefunction should be zero at the edges of the box, because otherwise the wavefunction will not be continuous. So we should have a wavefunction like
$$
\psi(x) =
\begin{cases}
0& x\le 0\\
\text{?????} & 0 < x < a\\
0 & a \le x
\end{cases}
$$
## Postulate: The wavefunction of a system is determined by solving the Schrödinger equation
How do we find the wavefunction for the particle-in-a-box or, for that matter, any other system? The wavefunction can be determined by solving the time-independent (when the potential is time-independent) or time-dependent (when the potential is time-dependent) Schrödinger equation.

## The Wavefunctions of the Particle in a Box (solution)
To find the wavefunctions for a system, one solves the Schrödinger equation. For a particle of mass $m$ in a one-dimensional box, the (time-independent) Schrödinger equation is:
$$
\left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} + V(x) \right)\psi_n(x) = E_n \psi_n(x)
$$
where
$$
V(x) =
\begin{cases}
+\infty & x\leq 0\\
0 & 0\lt x \lt a\\
+\infty & a \leq x
\end{cases}
$$
We already deduced that $\psi(x) = 0$ except when the electron is inside the box ($0 < x < a$), so we only need to consider the Schrödinger equation inside the box:
$$
\left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} \right)\psi_n(x) = E_n \psi_n(x)
$$
There are systematic ways to solve this equation, but let's solve it by inspection. That is, we need to know:
> Question: What function(s), when differentiated twice, are proportional to themselves?
This suggests that the eigenfunctions of the 1-dimensional particle-in-a-box must be some linear combination of sine and cosine functions,
$$
\psi_n(x) = A \sin(cx) + B \cos(dx)
$$
We know that the wavefunction must be zero at the edges of the box, $\psi(0) = 0$ and $\psi(a) = 0$. These are called the *boundary conditions* for the problem. Examining the first boundary condition,
$$
0 = \psi(0) = A \sin(0) + B \cos(0) = 0 + B
$$
indicates that $B=0$. The second boundary condition
$$
0 = \psi(a) = A \sin(ca)
$$
requires us to recall that $\sin(x) = 0$ whenever $x$ is an integer multiple of $\pi$. So $c=n\pi$ where $n=1,2,3,\ldots$. The wavefunction for the particle in a box is thus,
$$
\psi_n(x) = A_n \sin\left(\tfrac{n \pi x}{a}\right) \qquad \qquad n=1,2,3,\ldots
$$
## Normalization of Wavefunctions
As seen in the previous section, if a wavefunction solves the Schrödinger equation, any constant multiple of the wavefunction also solves the Schrödinger equation,
$$
\hat{H} \psi(x) = E \psi(x) \quad \longleftrightarrow \quad \hat{H} \left(A\psi(x)\right) = E \left(A\psi(x)\right)
$$
Owing to the Born postulate, the complex square of the wavefunction can be interpreted as probability. Since the probability of a particle being at *some* point in space is one, we can define the normalization constant, $A$, for the wavefunction through the requirement that:
$$
\int_{-\infty}^{\infty} \left|\psi(x)\right|^2 dx = 1.
$$
In the case of a particle in a box, this is:
$$
\begin{align}
1 &= \int_{-\infty}^{\infty} \left|\psi_n(x)\right|^2 dx \\
&= \int_0^a \psi_n(x) \psi_n^*(x) dx \\
&= \int_0^a A_n \sin\left(\tfrac{n \pi x}{a}\right) \left(A_n \sin\left(\tfrac{n \pi x}{a}\right) \right)^* dx \\
&= \left|A_n\right|^2\int_0^a \sin^2\left(\tfrac{n \pi x}{a}\right) dx
\end{align}
$$
To evaluate this integral, it is useful to remember some [trigonometric identities](https://en.wikipedia.org/wiki/List_of_trigonometric_identities). (You can learn more about how I remember trigonometric identities [here](../linkedFiles/TrigIdentities.md).) The specific identity we need here is $\sin^2 x = \tfrac{1}{2}(1-\cos 2x)$:
$$
\begin{align}
1 &= \left|A_n\right|^2\int_0^a \sin^2\left(\tfrac{n \pi x}{a}\right) \,dx \\
&= \left|A_n\right|^2\int_0^a \tfrac{1}{2}\left(1-\cos \left(\tfrac{2n \pi x}{a}\right)\right) \,dx \\
&=\tfrac{\left|A_n\right|^2}{2} \left( \int_0^a 1 \,dx - \int_0^a \cos \left(\tfrac{2n \pi x}{a}\right)\,dx \right) \\
&=\tfrac{\left|A_n\right|^2}{2} \left( \left[ x \right]_0^a - \left[\frac{-a}{2 n \pi}\sin \left(\tfrac{2n \pi x}{a}\right) \right]_0^a \right) \\
&=\tfrac{\left|A_n\right|^2}{2} \left( a - 0 \right)
\end{align}
$$
So
$$
\left|A_n\right|^2 = \tfrac{2}{a}
$$
Note that this does not completely determine $A_n$. For example, any of the following normalization constants are allowed,
$$
A_n = \sqrt{\tfrac{2}{a}}
= - \sqrt{\tfrac{2}{a}}
= i \sqrt{\tfrac{2}{a}}
= -i \sqrt{\tfrac{2}{a}}
$$
In general, any [square root of unity](https://en.wikipedia.org/wiki/Root_of_unity) can be used,
$$
A_n = \left(\cos(\theta) \pm i \sin(\theta) \right) \sqrt{\tfrac{2}{a}}
$$
where $k$ is any real number. The arbitrariness of the *phase* of the wavefunction is an important feature. Because the wavefunction can be imaginary (e.g., if you choose $A_n = i \sqrt{\tfrac{2}{a}}$), it is obvious that the wavefunction is not an observable property of a system. **The wavefunction is only a mathematical tool for quantum mechanics; it is not a physical object.**
Summarizing, the (normalized) wavefunction for a particle with mass $m$ confined to a one-dimensional box with length $a$ can be written as:
$$
\psi_n(x) = \sqrt{\tfrac{2}{a}} \sin\left(\tfrac{n \pi x}{a}\right) \qquad \qquad n=1,2,3,\ldots
$$
Note that in this case, the normalization condition is the same for all $n$; that is an unusual property of the particle-in-a-box wavefunction.
While this normalization convention is used 99% of the time, there are some cases where it is more convenient to make a different choice for the amplitude of the wavefunctions. I say this to remind you that normalization the wavefunction is something we do for convenience; it is not required by physics!
## Normalization Check
One advantage of using Jupyter is that we can easily check our (symbolic) mathematics. Let's confirm that the wavefunction is normalized by evaluating,
$$
\int_0^a \left| \psi_n(x) \right|^2 \, dx
$$
```
# Execute this code block to import required objects.
# Note: The numpy library from autograd is imported, which behaves the same as
# importing numpy directly. However, to make automatic differentiation work,
# you should NOT import numpy directly by `import numpy as np`.
import autograd.numpy as np
from autograd import elementwise_grad as egrad
# import numpy as np
from scipy.integrate import trapz, quad
from scipy import constants
import ipywidgets as widgets
import matplotlib.pyplot as plt
# set the size of the plot
# plt.rcParams['figure.figsize'] = [10, 5]
# Define a function for the wavefunction
def compute_wavefunction(x, n, a):
"""Compute 1-dimensional particle-in-a-box wave-function value(s).
Parameters
----------
x: float or np.ndarray
Position of the particle.
n: int
Quantum number value.
a: float
Length of the box.
"""
# check argument n
if not (isinstance(n, int) and n > 0):
raise ValueError("Argument n should be a positive integer.")
# check argument a
if a <= 0.0:
raise ValueError("Argument a should be positive.")
# check argument x
if not (isinstance(x, float) or hasattr(x, "__iter__")):
raise ValueError("Argument x should be a float or an array!")
# compute wave-function
value = np.sqrt(2 / a) * np.sin(n * np.pi * x / a)
# set wave-function values out of the box equal to zero
if hasattr(x, "__iter__"):
value[x > a] = 0.0
value[x < 0] = 0.0
else:
if x < 0.0 or x > a:
value = 0.0
return value
# Define a function for the wavefunction squared
def compute_probability(x, n, a):
"""Compute 1-dimensional particle-in-a-box probablity value(s).
See `compute_wavefunction` parameters.
"""
return compute_wavefunction(x, n, a)**2
#This next bit of code just prints out the normalization error
def check_normalization(a, n):
#check the computed values of the moments against the analytic formula
normalization,error = quad(compute_probability, 0, a, args=(n, a))
print("Normalization of wavefunction = ", normalization)
#Principle quantum number:
n = 1
#Box length:
a = 1
check_normalization(a, n)
```
## The Energies of the Particle in a Box
How do we compute the energy of a particle in a box? All we need to do is substitute the eigenfunctions of the Hamiltonian, $\psi_n(x)$ back into the Schrödinger equation to determine the eigenenergies, $E_n$. That is, from
$$
\hat{H} \psi_n(x) = E_n \psi_n(x)
$$
we deduce
$$
\begin{align}
-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} \left( A_n \sin \left( \frac{n \pi x}{a}\right) \right)
&= E_n \left( A_n \sin \left( \frac{n \pi x}{a}\right) \right) \\
-A_n \frac{\hbar^2}{2m} \frac{d}{dx} \left( \frac{n \pi}{a} \cos \left( \frac{n \pi x}{a}\right) \right)
&= E_n \left( A_n \sin \left( \frac{n \pi x}{a}\right) \right) \\
A_n \frac{\hbar^2}{2m} \left( \frac{n \pi}{a} \right)^2 \sin \left( \frac{n \pi x}{a}\right)
&= E_n \left( A_n \sin \left( \frac{n \pi x}{a}\right) \right) \\
\frac{\hbar^2 n^2 \pi^2}{2ma^2}
&= E_n
\end{align}
$$
Using the definition of $\hbar$, we can rearrange this to:
$$
\begin{align}
E_n &= \frac{\hbar^2 n^2 \pi^2}{2ma^2} \qquad \qquad n=1,2,3,\ldots\\
&= \frac{h^2 n^2}{8ma^2}
\end{align}
$$
Notice that only certain energies are allowed. This is a fundamental principle of quantum mechanics, and it is related to the "waviness" of particles. Certain "frequencies" are resonant, and other "frequencies" cannot be observed. *The **only** energies that can be observed for a particle-in-a-box are the ones given by the above formula.*
## Zero-Point Energy
Naïvely, you might expect that the lowest-energy state of a particle in a box has zero energy. (The potential in the box is zero, after all, so shouldn't the lowest-energy state be the state with zero kinetic energy? And if the kinetic energy were zero and the potential energy were zero, then the total energy would be zero.)
But this doesn't happen. It turns out that you can never "stop" a quantum particle; it always has a zero-point motion, typically a resonant oscillation about the lowest-potential-energy location(s). Indeed, the more you try to confine a particle to stop it, the bigger its kinetic energy becomes. This is clear in the particle-in-a-box, which has only kinetic energy. There the (kinetic) energy increases rapidly, as $a^{-2}$, as the box becomes smaller:
$$
T_n = E_n = \frac{h^2n^2}{8ma^2}
$$
The residual energy in the electronic ground state is called the **zero-point energy**,
$$
E_{\text{zero-point energy}} = \frac{h^2}{8ma^2}
$$
The existence of the zero-point energy, and the fact that zero-point kinetic energy is always positive, is a general feature of quantum mechanics.
> **Zero-Point Energy Principle:** Let $V(x)$ be a nonnegative potential. The ground-state energy is always greater than zero.
More generally, for any potential that is bound from below,
$$
V_{\text{min}}= \min_x V(x)
$$
the ground-state energy of the system satisfies $E_{\text{zero-point energy}} > V_{\text{min}}$.
>Nuance: There is a tiny mathematical footnote here; there are some $V(x)$ for which there are *no* bound states. In such cases, e.g., $V(x) = \text{constant}$, it is possible for $E = V_{\text{min}}$.)
## Atomic Units
Because Planck's constant and the electron mass are tiny numbers, it is often useful to use [atomic units](https://en.wikipedia.org/wiki/Hartree_atomic_units) when performing calculations. We'll learn more about atomic units later but, for now, we only need to know that, in atomic units, $\hbar$, the mass of the electron, $m_e$, the charge of the electron, $e$, and the average (mean) distance of an electron from the nucleus in the Hydrogen atom, $a_0$, are all defined to be equal to 1.0 in atomic units.
$$
\begin{align}
\hbar &= \frac{h}{2 \pi} = 1.0545718 \times 10^{-34} \text{ J s}= 1 \text{ a.u.} \\
m_e &= 9.10938356 \times 10^{-31} \text{ kg} = 1 \text{ a.u.} \\
e &= 1.602176634 \times 10^-19 \text{ C} = 1 \text{ a.u.} \\
a_0 &= 5.291772109 \times 10^{-11} \text{ m} = 1 \text{ Bohr} = 1 \text{ a.u.}
\end{align}
$$
The unit of energy in atomic units is called the Hartree,
$$
E_h =4.359744722 \times 10^{-18} \text{ J} = 1 \text{ Hartree} = 1 \text{ a.u.}
$$
and the ground-state (zero-point) energy of the Hydrogen atom is $-\tfrac{1}{2} E_h$.
We can now define functions for the eigenenergies of the 1-dimensional particle in a box:
```
# Define a function for the energy of a particle in a box
# with length a and quantum number n [in atomic units!]
# The length is input in Bohr (atomic units)
def compute_energy(n, a):
"Compute 1-dimensional particle-in-a-box energy."
return n**2 * np.pi**2 / (2 * a**2)
# Define a function for the energy of an electron in a box
# with length a and quantum number n [in SI units!].
# The length is input in meters.
def compute_energy_si(n, a):
"Compute 1-dimensional particle-in-a-box energy."
return n**2 * constants.h**2 / (8 * constants.m_e* a**2)
#Define variable for atomic unit of length in meters
a0 = constants.value('atomic unit of length')
#This next bit of code just prints out the energy in atomic and SI units
def print_energy(a, n):
print(f'The energy of an electron in a box of length {a:.2f} a.u. with '
f'quantum number {n} is {compute_energy(n, a):.2f} a.u..')
print(f'The energy of an electron in a box of length {a*a0:.2e} m with '
f'quantum number {n} is {compute_energy_si(n, a*a0):.2e} Joules.')
#Principle quantum number:
n = 1
#Box length:
a = 0.1
print_energy(a, n)
```
#### 📝 Exercise: Write a function that returns the length, $a$, of a box for which the lowest-energy-excitation of the ground state, $n = 1 \rightarrow n=2$, corresponds to the system absorbing light with a given wavelength, $\lambda$. The input is $\lambda$; the output is $a$.
## Postulate: The wavefunction contains all the physically meaningful information about a system.
While the wavefunction is not itself observable, all observable properties of a system can be determined from the wavefunction. However, just because the wavefunction encapsulates all the *observable* properties of a system does not mean that it contains *all information* about a system. In quantum mechanics, some things are not observable. Consider that for the ground ($n=1$) state of the particle in a box, the root-mean-square average momentum,
$$
\bar{p}_{rms} = \sqrt{2m \cdot T} = \sqrt{(2m)\frac{h^2n^2}{8ma^2}} = \frac{hn}{2a}
$$
increases as you squeeze the box. That is, the more you try to constrain the particle in space, the faster it moves. You can't "stop" the particle no matter how hard you squeeze it, so it's impossible to exactly know where the particle is located. You can only determine its *average* position.
## Postulate: Observable Quantities Correspond to Linear, Hermitian Operators.
The *correspondence* principle says that for every classical observable there is a linear, Hermitian, operator that allows computation of the quantum-mechanical observable. An operator, $\hat{C}$ is linear if for any complex numbers $a$ and $b$, and any wavefunctions $\psi_1(x)$ and $\psi_2(x)$,
$$
\hat{C} \left(a \psi_1(x,t) + b \psi_2(x,t) \right) = a \hat{C} \psi_1(x,t) + b \hat{C} \psi_2(x,t)
$$
Similarly, an operator is Hermitian if it satisfies the relation,
$$
\int \psi_1^*(x,t) \hat{C} \psi_2(x,t) \, dx = \int \left( \hat{C}\psi_1(x,t) \right)^* \psi_2(x,t) \, dx
$$
or, equivalently,
$$
\int \psi_1^*(x,t) \left( \hat{C} \psi_2(x,t) \right) \, dx = \int \psi_2(x,t)\left( \hat{C} \psi_1(x,t) \right)^* \, dx
$$
That is for a linear operator, the linear operator applied to a sum of wavefunctions is equal to the sum of the linear operators directly applied to the wavefunctions separately, and the linear operator applied to a constant times a wavefunction is the constant times the linear operator applied directly to the wavefunction. A Hermitian operator can apply forward (towards $\psi_2(x,t)$) or backwards (towards $\psi_1(x,t)$). This is very useful, because sometimes it is much easier to apply an operator in one direction.
We've already been introduced to the quantum-mechanical operators for the momentum,
$$
\hat{p} = -i \hbar \tfrac{d}{dx}
$$
and the kinetic energy,
$$
\hat{T} = -\tfrac{\hbar^2}{2m} \tfrac{d^2}{dx^2}
$$
These operators are linear because the derivative of a sum is the sum of the derivatives, and the derivative of a constant times a function is that constant times the derivative of the function. These operators are also Hermitian. For example, to show that the momentum operator is Hermitian:
$$
\begin{align}
\int_{-\infty}^{\infty} \psi_1^*(x,t) \hat{p} \psi_2(x,t) dx &= \int_{-\infty}^{\infty} \psi_1^*(x,t) \left( -i \hbar \tfrac{d}{dx} \right) \psi_2(x,t) dx \\
&= -i \hbar \int_{-\infty}^{\infty} \tfrac{d}{dx} \left(\psi_1^*(x,t)\psi_2(x,t) \right) - \left(
\psi_2(x,t) \tfrac{d}{dx} \psi_1^*(x,t)\right) dx
\end{align}
$$
Here we used the product rule for derivatives, $f(x)\tfrac{dg}{dx} = \tfrac{d f(x) g(x)}{dx} - g(x) \tfrac{df}{dx}$. Using the fundamental theorem of calculus and the fact the probability of observing a particle at $\pm \infty$ is zero, and therefore the wavefunctions at infinity are also zero, one knows that
$$
\int_{-\infty}^{\infty} \tfrac{d}{dx} \left(\psi_1^*(x,t)\psi_2(x,t) \right) = \left[ \psi_1^*(x,t)\psi_2(x,t)\right]_{-\infty}^{\infty} = 0
$$
Therefore the above equation can be simplified to
$$
\begin{align}
\int_{-\infty}^{\infty} \psi_1^*(x,t) \hat{p} \psi_2(x,t) dx &=i \hbar \int_{-\infty}^{\infty} \psi_2(x,t) \tfrac{d}{dx} \psi_1^*(x,t) dx \\
&= \int_{-\infty}^{\infty} \psi_2(x,t) i \hbar \tfrac{d}{dx} \psi_1^*(x,t) dx \\
&= \int_{-\infty}^{\infty} \psi_2(x,t) \left( -i \hbar \tfrac{d}{dx} \psi_1^*(x,t)\right) dx \\
&= \int_{-\infty}^{\infty} \psi_2(x,t) \left( \hat{p} \psi_1(x,t)\right)^* dx
\end{align}
$$
The expectation value of the momentum of a particle-in-a-box is always zero. This is intuitive, since electrons (on average) are neither moving to the right nor to the left inside the box: if they were, then the box itself would need to be moving. Indeed, for any real wavefunction, the average momentum is always zero. This follows directly from the previous derivation with $\psi_1^*(x,t) = \psi_2(x,t)$. Thus:
$$
\begin{align}
\int_{-\infty}^{\infty} \psi_2(x,t) \hat{p} \psi_2(x,t) dx
&=i \hbar \int_{-\infty}^{\infty} \psi_2(x,t) \tfrac{d}{dx} \psi_2(x,t) dx \\
&=-i \hbar \int_{-\infty}^{\infty} \psi_2(x,t) \left( \tfrac{d}{dx} \psi_2(x,t)\right) dx \\
&= 0
\end{align}
$$
The last line follows because the only number that is equal to its negative is zero. (That is, $x=-x$ if and only if $x=0$.) It is a subtle feature that the eigenfunctions of a real-valued Hamiltonian operator can always be chosen to be real-valued themselves, so their average momentum is clearly zero. We often denote quantum-mechanical expectation values with the shorthand,
$$
\langle \hat{p} \rangle =0
$$
The momentum-squared of the particle-in-a-box is easily computed from the kinetic energy,
$$
\langle \hat{p}^2 \rangle = \int_0^a \psi_n(x) \hat{p}^2 \psi_n(x) dx = \int_0^a \psi_n(x) \left(2m\hat{T}\right) \psi_n(x) dx = 2m E_n = \frac{h^2n^2}{4a^2}
$$
Intuitively, since the box is symmetric about $x=\tfrac{a}{2}$, the particle has equal probability of being in the first-half and the second-half of the box. So the average position is expected to be
$$
\langle x \rangle =\tfrac{a}{2}
$$
We can confirm this by explicit integration,
$$
\begin{align}
\langle x \rangle &= \int_0^a \psi_n^*(x)\, x \,\psi_n(x) dx \\
&= \int_0^a \left(\sqrt{\tfrac{2}{a}} \sin\left(\tfrac{n \pi x}{a} \right)\right) x \left(\sqrt{\tfrac{2}{a}}\sin\left(\tfrac{n \pi x}{a} \right)\right) dx \\
&= \tfrac{2}{a} \int_0^a x \sin^2\left(\tfrac{n \pi x}{a} \right) dx \\
&= \tfrac{2}{a} \left[ \tfrac{x^2}{4} - x \tfrac{\sin \tfrac{2n \pi x}{a}}{\tfrac{4 n \pi}{a}}
- \tfrac{\cos \tfrac{2n \pi x}{a}}{\tfrac{8 n^2 \pi^2}{a^2}}
\right]_0^a \\
&= \tfrac{2}{a} \left[ \tfrac{a^2}{4} - 0 - 0 \right] \\
&= \tfrac{a}{2}
\end{align}
$$
Similarly, we expect that the expectation value of $\langle x^2 \rangle$ will be proportional to $a^2$. We can confirm this by explicit integration,
$$
\begin{align}
\langle x^2 \rangle &= \int_0^a \psi_n^*(x)\, x^2 \,\psi_n(x) dx \\
&= \int_0^a \left(\sqrt{\tfrac{2}{a}} \sin\left(\tfrac{n \pi x}{a} \right)\right) x^2 \left(\sqrt{\tfrac{2}{a}}\sin\left(\tfrac{n \pi x}{a} \right)\right) dx \\
&= \tfrac{2}{a} \int_0^a x^2 \sin^2\left(\tfrac{n \pi x}{a} \right) dx \\
&= \tfrac{2}{a} \left[ \tfrac{x^3}{6}
- x^2 \tfrac{\sin \tfrac{2n \pi x}{a}}{\tfrac{4 n \pi}{a}}
- x \tfrac{\cos \tfrac{2n \pi x}{a}}{\tfrac{4 n^2 \pi^2}{a^2}}
- \tfrac{\sin \tfrac{2n \pi x}{a}}{\tfrac{8 n^3 \pi^3}{a^3}}
\right]_0^a \\
&= \tfrac{2}{a} \left[ \tfrac{a^3}{6} - 0 - \tfrac{a}{{\tfrac{4 n^2 \pi^2}{a^2}}} - 0 \right] \\
&= \tfrac{2}{a} \left[ \tfrac{a^3}{6} - \tfrac{a^3}{4 n^2 \pi^2} \right] \\
&= a^2\left[ \tfrac{1}{3} - \tfrac{1}{2 n^2 \pi^2} \right]
\end{align}
$$
We can verify these formulas by explicit integration.
```
#Compute <x^power>, the expectation value of x^power
def compute_moment(x, n, a, power):
"""Compute the x^power moment of the 1-dimensional particle-in-a-box.
See `compute_wavefunction` parameters.
"""
return compute_probability(x, n, a)*x**power
#This next bit of code just prints out the values.
def check_moments(a, n):
#check the computed values of the moments against the analytic formula
avg_r,error = quad(compute_moment, 0, a, args=(n, a, 1))
avg_r2,error = quad(compute_moment, 0, a, args=(n, a, 2))
print(f"<r> computed = {avg_r:.5f}")
print(f"<r> analytic = {a/2:.5f}")
print(f"<r^2> computed = {avg_r2:.5f}")
print(f"<r^2> analytic = {a**2*(1/3 - 1./(2*n**2*np.pi**2)):.5f}")
#Principle quantum number:
n = 1
#Box length:
a = 1
check_moments(a, n)
```
## Heisenberg Uncertainty Principle
The previous example gives a first example of the more general [Heisenberg Uncertainty Principle](https://en.wikipedia.org/wiki/Uncertainty_principle). One specific manifestation of the Heisenberg Uncertaity Principle is that the variance of the position, $\sigma_x^2 = \langle x^2 \rangle - \langle x \rangle^2$, times the variance of the momentum. $\sigma_p^2 = \langle \hat{p}^2 \rangle - \langle \hat{p} \rangle^2$ is greater than $\tfrac{\hbar^2}{4}$. We can verify this formula for the particle in a box.
$$
\begin{align}
\tfrac{\hbar^2}{4} &\le \sigma_x^2 \sigma_p^2 \\
&= \left( a^2\left[ \tfrac{1}{3} - \tfrac{1}{2 n^2 \pi^2} \right] - \tfrac{a^2}{4} \right)
\left( \frac{h^2n^2}{4a^2} - 0 \right) \\
&= \left( a^2\left[ \tfrac{1}{3} - \tfrac{1}{2 n^2 \pi^2} \right] - \tfrac{a^2}{4} \right)
\left( \frac{\hbar^2 \pi^2 n^2}{a^2} \right) \\
&= \hbar^2 \pi^2 n^2 \left(\tfrac{1}{12} - \tfrac{1}{2 n^2 \pi^2} \right)
\end{align}
$$
The right-hand-side gets larger and larger as $n$ increases, so the largest value occurs where:
$$
\begin{align}
\tfrac{\hbar^2}{4} &\le \hbar^2 \pi^2 \left(\tfrac{1}{12} - \tfrac{1}{2 \pi^2} \right) \\
&= 0.32247 \hbar^2
\end{align}
$$
## Double-Checking the Energy of a Particle-in-a-Box
To check the energy of the particle in a box, we can compute the kinetic energy density, then integrate it over all space. That is, we define:
$$
\tau_n(x) = \psi_n^*(x) \left(-\tfrac{\hbar^2}{2m}\tfrac{d^2}{dx^2}\right) \psi_n(x)
$$
and then the kinetic energy (which is the energy for the particle in a box) is
$$
T_n = \int_0^a \tau_n(x) dx
$$
> *Note:* In fact there are several different equivalent definitions of the kinetic energy density, but this is not very important in an introductory quantum chemistry course. All of the kinetic energy densities give the same total kinetic energy. However, because the kinetic energy density, $\tau(x)$, represents the kinetic energy of a particle at the point $x$, and it is impossible to know the momentum (or the momentum-squared, ergo the kinetic energy) exactly at a given point in space according to the Heisenberg uncertainty principle), there can be no unique definition for $\tau(x)$.
```
#The next few lines just set up the sliders for setting parameters.
#Principle quantum number slider:
def compute_wavefunction_derivative(x, n, a, order=1):
"""Compute 1-dimensional particle-in-a-box kinetic energy density.
"""
if not (isinstance(order, int) and n > 0):
raise ValueError("Argument order is expected to be a positive integer!")
def wavefunction(x):
v = np.sqrt(2 / a) * np.sin(n * np.pi * x / a)
return v
# compute derivative
deriv = egrad(wavefunction)
for _ in range(order - 1):
deriv = egrad(deriv)
# return zero for x values out of the box
deriv = deriv(x)
# deriv[x < 0] = 0.0
# deriv[x > a] = 0.0
if hasattr(x, "__iter__"):
deriv[x > a] = 0.0
deriv[x < 0] = 0.0
else:
if x < 0.0 or x > a:
deriv = 0.0
return deriv
def compute_kinetic_energy_density(x, n, a):
"""Compute 1-dimensional particle-in-a-box kinetic energy density.
See `compute_wavefunction` parameters.
"""
# evaluate wave-function and its 2nd derivative w.r.t. x
wf = compute_wavefunction(x, n, a)
d2 = compute_wavefunction_derivative(x, n, a, order=2)
return -0.5 * wf * d2
#This next bit of code just prints out the values.
def check_energy(a, n):
#check the computed values of the moments against the analytic formula
ke,error = quad(compute_kinetic_energy_density, 0, a, args=(n, a))
energy = compute_energy(n, a)
print(f"The energy computed by integrating the k.e. density is {ke:.5f}")
print(f"The energy computed directly is {energy:.5f}")
#Principle quantum number:
n = 1
#Box length:
a = 17
check_energy(a, n)
```
## Visualizing the Particle-in-a-Box Wavefunctions, Probabilities, etc.
In the next code block, the wavefunction, probability density, derivative, second-derivative, and kinetic energy density for the particle-in-a-box are shown. Notice that the kinetic-energy-density is proportional to the probability density, and that the first and second derivatives are not zero at the edge of the box, but the wavefunction and probability density are. It's useful to change the parameters in the below figures to build your intuition for the particle-in-a-box.
```
#This next bit of code makes the plots and prints out the energy
def make_plots(a, n):
#check the computed values of the moments against the analytic formula
energy = compute_energy(n, a)
print(f"The energy computed directly is {energy:.5f}")
# sample x coordinates
x = np.arange(-0.6, a + 0.6, 0.01)
# evaluate wave-function & probability
wf = compute_wavefunction(x, n, a)
pr = compute_probability(x, n, a)
# evaluate 1st & 2nd derivative of wavefunction w.r.t. x
d1 = compute_wavefunction_derivative(x, n, a, order=1)
d2 = compute_wavefunction_derivative(x, n, a, order=2)
# evaluate kinetic energy density
kin = compute_kinetic_energy_density(x, n, a)
#print("Integrate KED = ", trapz(kin, x))
# set the size of the plot
plt.rcParams['figure.figsize'] = [15, 10]
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['font.serif'] = ['Times New Roman']
plt.rcParams['mathtext.fontset'] = 'stix'
plt.rcParams['xtick.labelsize'] = 15
plt.rcParams['ytick.labelsize'] = 15
# define four subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
fig.suptitle(f'a={a} n={n} E={compute_energy(n, a):.4f} a.u.', fontsize=35, fontweight='bold')
# plot 1
ax1.plot(x, wf, linestyle='--', label=r'$\psi(x)$', linewidth=3)
ax1.plot(x, pr, linestyle='-', label=r'$\|\psi(x)\|^2$', linewidth=3)
ax1.legend(frameon=False, fontsize=20)
ax1.set_xlabel('x coordinates', fontsize=20)
# plot 2
ax2.plot(x, d1, linewidth=3, c='k')
ax2.set_xlabel('x coordinates', fontsize=20)
ax2.set_ylabel(r'$\frac{d\psi(x)}{dx}$', fontsize=30, rotation=0, labelpad=25)
# plot 3
ax3.plot(x, d2, linewidth=3, c='g', )
ax3.set_xlabel('x coordinates', fontsize=20)
ax3.set_ylabel(r'$\frac{d^2\psi(x)}{dx^2}$', fontsize=25, rotation=0, labelpad=25)
# plot 4
ax4.plot(x, kin, linewidth=3, c='r')
ax4.set_xlabel('x coordinates', fontsize=20)
ax4.set_ylabel('Kinetic Energy Density', fontsize=16)
# adjust spacing between plots
plt.subplots_adjust(left=0.125,
bottom=0.1,
right=0.9,
top=0.9,
wspace=0.35,
hspace=0.35)
#Show Plot
plt.show()
#Principle quantum number slider:
n = 1
#Box length slider:
a = 1
make_plots(a, n)
```
## 🪞 Self-Reflection
- Can you think of other physical or chemical systems where the particle-in-a-box Hamiltonian would be appropriate?
- Can you think of another property density, besides the kinetic energy density, that cannot be uniquely defined in quantum mechanics?
## 🤔 Thought-Provoking Questions
- How would the wavefunction and ground-state energy change if you made a small change in the particle-in-a-box Hamiltonian, so that the right-hand-side of the box was a little higher than the left-hand-side?
- Any system with a zero-point energy of zero is classical. Why?
- How would you compute the probability of observing an electron at the center of a box if the box contained 2 electrons? If it contained 4 electrons? If it contained 8 electrons? The probability of observing an electron at the center of a box with 3 electrons is sometimes *lower* than the probability of observing an electron at the center of a box with 2 electrons. Why?
- Demonstrate that the kinetic energy operator is linear and Hermitian.
- What is the lowest-energy excitation energy for the particle-in-a-box?
- Suppose you wanted to design a one-dimensional box containing a single electron that absorbed blue light? How long would the box be?
## ❓ Knowledge Tests
- Questions about the Particle-in-a-Box and related concepts. [GitHub Classroom Link](https://classroom.github.com/a/1Y48deKP)
## 👩🏽‍💻 Assignments
- Compute and understand expectation values by computing moments of the particle-in-a-box [assignment](https://github.com/McMasterQM/PinBox-Moments/blob/main/moments.ipynb). [Github classroom link]https://classroom.github.com/a/9yzWI5Vt.
- This [assignment](https://github.com/McMasterQM/Sudden-Approximation/blob/main/SuddenPinBox.ipynb) on the sudden approximation provides an introduction to time-dependent phenomena. [Github classroom link](https://classroom.github.com/a/yBzABlb-).
## 🔁 Recapitulation
- Write the Hamiltonian, time-independent Schrödinger equation, eigenfunctions, and eigenvalues for the one-dimensional particle in a box.
- Play around with the eigenfunctions and eigenenergies of the particle-in-a-box to build intuition for them.
- How would you compute the uncertainty in $x^4$?
- Practice your calculus by explicitly computing, using integration by parts, $\langle x \rangle$ and $\langle x^2 \rangle$. This can be implemented in a [Jupyter notebook](x4_mocked.ipynb).
## 🔮 Next Up...
- Postulates of Quantum Mechanics
- Multielectron particle-in-a-box.
- Multidimensional particle-in-a-box.
- Harmonic Oscillator
## 📚 References
My favorite sources for this material are:
- [Randy's book](https://github.com/PaulWAyers/IntroQChem/blob/main/documents/DumontBook.pdf) has an excellent treatment of the particle-in-a-box model, including several extensions to the material covered here. (Chapter 3)
- Also see my (pdf) class [notes](https://github.com/PaulWAyers/IntroQChem/blob/main/documents/PinBox.pdf).
- Also see my notes on the [mathematical structure of quantum mechanics](https://github.com/PaulWAyers/IntroQChem/blob/main/documents/LinAlgAnalogy.pdf).
- [Davit Potoyan's](https://www.chem.iastate.edu/people/davit-potoyan) Jupyter-book covers the particle-in-a-box in [chapter 4](https://dpotoyan.github.io/Chem324/intro.html) are especially relevant here.
- D. A. MacQuarrie, Quantum Chemistry (University Science Books, Mill Valley California, 1983)
- [An excellent explanation of the link to the spectrum of cyanine dyes](https://pubs.acs.org/doi/10.1021/ed084p1840)
- Chemistry Libre Text: [one dimensional](https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Map%3A_Physical_Chemistry_for_the_Biosciences_(Chang)/11%3A_Quantum_Mechanics_and_Atomic_Structure/11.08%3A_Particle_in_a_One-Dimensional_Box)
and [multi-dimensional](https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Supplemental_Modules_(Physical_and_Theoretical_Chemistry)/Quantum_Mechanics/05.5%3A_Particle_in_Boxes/Particle_in_a_3-Dimensional_box)
- [McQuarrie and Simon summary](https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Map%3A_Physical_Chemistry_(McQuarrie_and_Simon)/03%3A_The_Schrodinger_Equation_and_a_Particle_in_a_Box)
There are also some excellent wikipedia articles:
- [Particle in a Box](https://en.wikipedia.org/wiki/Particle_in_a_box)
- [Particle on a Ring](https://en.wikipedia.org/wiki/Particle_in_a_ring)
- [Postulates of Quantum Mechanics](https://en.wikipedia.org/wiki/Mathematical_formulation_of_quantum_mechanics#Postulates_of_quantum_mechanics)
| github_jupyter |
# Title: msticpy - IoC Extraction
## Description:
This class allows you to extract IoC patterns from a string or a DataFrame.
Several patterns are built in to the class and you can override these or supply new ones.
You must have msticpy installed to run this notebook:
```
%pip install --upgrade msticpy
```
<a id='toc'></a>
## Table of Contents
- [Looking for IoC in a String](#cmdlineiocs)
- [Search DataFrame for IoCs](#dataframeiocs)
- [IoCExtractor API](#iocextractapi)
- [Predefined Regex Patterns](#regexpatterns)
- [Adding your own pattern(s)](#addingpatterns)
- [extract() method](#extractmethod)
- [Merge the results with the input DataFrame](#mergeresults)
```
# Imports
import sys
MIN_REQ_PYTHON = (3,6)
if sys.version_info < MIN_REQ_PYTHON:
print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')
print('or later is selected as the active kernel.')
sys.exit("Python %s.%s or later is required.\n" % MIN_REQ_PYTHON)
from IPython import get_ipython
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 50)
pd.set_option('display.max_colwidth', 100)
# Load test data
process_tree = pd.read_csv('data/process_tree.csv')
process_tree[['CommandLine']].head()
```
<a id='cmdlineiocs'></a>[Contents](#toc)
## Looking for IoC in a String
Here we:
- Get a commandline from our data set.
- Pass it to the IoC Extractor
- View the results
```
# get a commandline from our data set
cmdline = process_tree['CommandLine'].loc[78]
cmdline
# Instantiate an IoCExtract object
from msticpy.sectools import IoCExtract
ioc_extractor = IoCExtract()
# any IoCs in the string?
iocs_found = ioc_extractor.extract(cmdline)
if iocs_found:
print('\nPotential IoCs found in alert process:')
display(iocs_found)
```
<a id='dataframeiocs'></a>[Contents](#toc)
## If we have a DataFrame, look for IoCs in the whole data set
You can replace the ```data=``` parameter to ioc_extractor.extract() to pass other data frames.
Use the ```columns``` parameter to specify which column or columns that you want to search.
```
ioc_extractor = IoCExtract()
ioc_df = ioc_extractor.extract(data=process_tree, columns=['CommandLine'])
if len(ioc_df):
display(HTML("<h3>IoC patterns found in process tree.</h3>"))
display(ioc_df)
```
<a id='iocextractapi'></a>[Contents](#toc)
## IoCExtractor API
```
# IoCExtract docstring
ioc_extractor.extract?
```
<a id='regexpatterns'></a>[Contents](#toc)
### Predefined Regex Patterns
```
from html import escape
extractor = IoCExtract()
for ioc_type, pattern in extractor.ioc_types.items():
esc_pattern = escape(pattern.comp_regex.pattern.strip())
display(HTML(f'<b>{ioc_type}</b>'))
display(HTML(f'<div style="margin-left:20px"><pre>{esc_pattern}</pre></div>'))
```
<a id='addingpatterns'></a>[Contents](#toc)
### Adding your own pattern(s)
Docstring:
```
Add an IoC type and regular expression to use to the built-in set.
Parameters
----------
ioc_type : str
A unique name for the IoC type
ioc_regex : str
A regular expression used to search for the type
priority : int, optional
Priority of the regex match vs. other ioc_patterns. 0 is
the highest priority (the default is 0).
group : str, optional
The regex group to match (the default is None,
which will match on the whole expression)
Notes
-----
Pattern priorities.
If two IocType patterns match on the same substring, the matched
substring is assigned to the pattern/IocType with the highest
priority. E.g. `foo.bar.com` will match types: `dns`, `windows_path`
and `linux_path` but since `dns` has a higher priority, the expression
is assigned to the `dns` matches.
```
```
import re
rcomp = re.compile(r'(?P<pipe>\\\\\.\\pipe\\[^\s\\]+)')
extractor.add_ioc_type(ioc_type='win_named_pipe', ioc_regex=r'(?P<pipe>\\\\\.\\pipe\\[^\s\\]+)')
# Check that it added ok
print(extractor.ioc_types['win_named_pipe'])
# Use it in our data set
ioc_extractor.extract(data=process_tree, columns=['CommandLine']).query('IoCType == \'win_named_pipe\'')
```
<a id='extractmethod'></a>[Contents](#toc)
### extract() method
```
Parameters
----------
src : str, optional
source string in which to look for IoC patterns
(the default is None)
data : pd.DataFrame, optional
input DataFrame from which to read source strings
(the default is None)
columns : list, optional
The list of columns to use as source strings,
if the `data` parameter is used. (the default is None)
Other Parameters
----------------
ioc_types : list, optional
Restrict matching to just specified types.
(default is all types)
include_paths : bool, optional
Whether to include path matches (which can be noisy)
(the default is false - excludes 'windows_path'
and 'linux_path'). If `ioc_types` is specified
this parameter is ignored.
Returns
-------
Any
dict of found observables (if input is a string) or
DataFrame of observables
Notes
-----
Extract takes either a string or a pandas DataFrame as input.
When using the string option as an input extract will
return a dictionary of results.
When using a DataFrame the results will be returned as a new
DataFrame with the following columns:
- IoCType: the mnemonic used to distinguish different IoC Types
- Observable: the actual value of the observable
- SourceIndex: the index of the row in the input DataFrame from
which the source for the IoC observable was extracted.
IoCType Pattern selection
The default list is: ['ipv4', 'ipv6', 'dns', 'url',
'md5_hash', 'sha1_hash', 'sha256_hash'] plus any
user-defined types.
'windows_path', 'linux_path' are excluded unless `include_paths`
is True or explicitly included in `ioc_paths`.
```
```
# You can specify multiple columns
ioc_extractor.extract(data=process_tree, columns=['NewProcessName', 'CommandLine']).head(10)
```
### extract_df()
`extract_df` functions identically to `extract` with a `data` parameter.
It may be more convenient to use this when you know that your
input is a DataFrame
```
ioc_extractor.extract_df(process_tree, columns=['NewProcessName', 'CommandLine']).head(10)
```
<a id='mergeresults'></a>[Contents](#toc)
### SourceIndex column allows you to merge the results with the input DataFrame
Where an input row has multiple IoC matches the output of this merge will result in duplicate rows from the input (one per IoC match). The previous index is preserved in the second column (and in the SourceIndex column).
Note: you will need to set the type of the SourceIndex column. In the example below case we are matching with the default numeric index so we force the type to be numeric. In cases where you are using an index of a different dtype you will need to convert the SourceIndex (dtype=object) to match the type of your index column.
```
input_df = data=process_tree.head(20)
output_df = ioc_extractor.extract(data=input_df, columns=['NewProcessName', 'CommandLine'])
# set the type of the SourceIndex column. In this case we are matching with the default numeric index.
output_df['SourceIndex'] = pd.to_numeric(output_df['SourceIndex'])
merged_df = pd.merge(left=input_df, right=output_df, how='outer', left_index=True, right_on='SourceIndex')
merged_df.head()
```
## IPython magic
You can use the line magic `%ioc` or cell magic `%%ioc` to extract IoCs from text pasted directly into a cell
The ioc magic supports the following options:
```
--out OUT, -o OUT
The variable to return the results in the variable `OUT`
Note: the output variable is a dictionary iocs grouped by IoC Type
--ioc_types IOC_TYPES, -i IOC_TYPES
The types of IoC to search for (comma-separated string)
```
```
%%ioc --out ioc_capture
netsh start capture=yes IPv4.Address=1.2.3.4 tracefile=C:\Users\user\AppData\Local\Temp\bzzzzzz.txt
hostname customers-service.ddns.net Feb 5, 2020, 2:20:35 PM 7
URL https://two-step-checkup.site/securemail/secureLogin/challenge/url?ucode=d50a3eb1-9a6b-45a8-8389-d5203bbddaa1&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;service=mailservice&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;type=password Feb 5, 2020, 2:20:35 PM 1
hostname mobile.phonechallenges-submit.site Feb 5, 2020, 2:20:35 PM 8
hostname youtube.service-activity-checkup.site Feb 5, 2020, 2:20:35 PM 8
hostname www.drive-accounts.com Feb 5, 2020, 2:20:35 PM 7
hostname google.drive-accounts.com Feb 5, 2020, 2:20:35 PM 7
domain niaconucil.org Feb 5, 2020, 2:20:35 PM 11
domain isis-online.net Feb 5, 2020, 2:20:35 PM 11
domain bahaius.info Feb 5, 2020, 2:20:35 PM 11
domain w3-schools.org Feb 5, 2020, 2:20:35 PM 12
domain system-services.site Feb 5, 2020, 2:20:35 PM 11
domain accounts-drive.com Feb 5, 2020, 2:20:35 PM 8
domain drive-accounts.com Feb 5, 2020, 2:20:35 PM 10
domain service-issues.site Feb 5, 2020, 2:20:35 PM 8
domain two-step-checkup.site Feb 5, 2020, 2:20:35 PM 8
domain customers-activities.site Feb 5, 2020, 2:20:35 PM 11
domain seisolarpros.org Feb 5, 2020, 2:20:35 PM 11
domain yah00.site Feb 5, 2020, 2:20:35 PM 4
domain skynevvs.com Feb 5, 2020, 2:20:35 PM 11
domain recovery-options.site Feb 5, 2020, 2:20:35 PM 4
domain malcolmrifkind.site Feb 5, 2020, 2:20:35 PM 8
domain instagram-com.site Feb 5, 2020, 2:20:35 PM 8
domain leslettrespersanes.net Feb 5, 2020, 2:20:35 PM 11
domain software-updating-managers.site Feb 5, 2020, 2:20:35 PM 8
domain cpanel-services.site Feb 5, 2020, 2:20:35 PM 8
domain service-activity-checkup.site Feb 5, 2020, 2:20:35 PM 7
domain inztaqram.ga Feb 5, 2020, 2:20:35 PM 8
domain unirsd.com Feb 5, 2020, 2:20:35 PM 8
domain phonechallenges-submit.site Feb 5, 2020, 2:20:35 PM 7
domain acconut-verify.com Feb 5, 2020, 2:20:35 PM 11
domain finance-usbnc.info Feb 5, 2020, 2:20:35 PM 8
FileHash-MD5 542128ab98bda5ea139b169200a50bce Feb 5, 2020, 2:20:35 PM 3
FileHash-MD5 3d67ce57aab4f7f917cf87c724ed7dab Feb 5, 2020, 2:20:35 PM 3
hostname x09live-ix3b.account-profile-users.info Feb 6, 2020, 2:56:07 PM 0
hostname www.phonechallenges-submit.site Feb 6, 2020, 2:56:07 PM
# Summarize captured types
print([(ioc, len(matches)) for ioc, matches in ioc_capture.items()])
%%ioc --ioc_types "ipv4, ipv6, linux_path, md5_hash"
netsh start capture=yes IPv4.Address=1.2.3.4 tracefile=C:\Users\user\AppData\Local\Temp\bzzzzzz.txt
tracefile2=/usr/localbzzzzzz.sh
hostname customers-service.ddns.net Feb 5, 2020, 2:20:35 PM 7
URL https://two-step-checkup.site/securemail/secureLogin/challenge/url?ucode=d50a3eb1-9a6b-45a8-8389-d5203bbddaa1&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;service=mailservice&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;type=password Feb 5, 2020, 2:20:35 PM 1
hostname mobile.phonechallenges-submit.site Feb 5, 2020, 2:20:35 PM 8
hostname youtube.service-activity-checkup.site Feb 5, 2020, 2:20:35 PM 8
hostname www.drive-accounts.com Feb 5, 2020, 2:20:35 PM 7
hostname google.drive-accounts.com Feb 5, 2020, 2:20:35 PM 7
domain niaconucil.org Feb 5, 2020, 2:20:35 PM 11
domain isis-online.net Feb 5, 2020, 2:20:35 PM 11
domain bahaius.info Feb 5, 2020, 2:20:35 PM 11
domain w3-schools.org Feb 5, 2020, 2:20:35 PM 12
domain system-services.site Feb 5, 2020, 2:20:35 PM 11
domain accounts-drive.com Feb 5, 2020, 2:20:35 PM 8
domain drive-accounts.com Feb 5, 2020, 2:20:35 PM 10
domain service-issues.site Feb 5, 2020, 2:20:35 PM 8
domain two-step-checkup.site Feb 5, 2020, 2:20:35 PM 8
domain customers-activities.site Feb 5, 2020, 2:20:35 PM 11
domain seisolarpros.org Feb 5, 2020, 2:20:35 PM 11
domain yah00.site Feb 5, 2020, 2:20:35 PM 4
domain skynevvs.com Feb 5, 2020, 2:20:35 PM 11
domain recovery-options.site Feb 5, 2020, 2:20:35 PM 4
domain malcolmrifkind.site Feb 5, 2020, 2:20:35 PM 8
domain instagram-com.site Feb 5, 2020, 2:20:35 PM 8
domain leslettrespersanes.net Feb 5, 2020, 2:20:35 PM 11
domain software-updating-managers.site Feb 5, 2020, 2:20:35 PM 8
domain cpanel-services.site Feb 5, 2020, 2:20:35 PM 8
domain service-activity-checkup.site Feb 5, 2020, 2:20:35 PM 7
domain inztaqram.ga Feb 5, 2020, 2:20:35 PM 8
domain unirsd.com Feb 5, 2020, 2:20:35 PM 8
domain phonechallenges-submit.site Feb 5, 2020, 2:20:35 PM 7
domain acconut-verify.com Feb 5, 2020, 2:20:35 PM 11
domain finance-usbnc.info Feb 5, 2020, 2:20:35 PM 8
FileHash-MD5 542128ab98bda5ea139b169200a50bce Feb 5, 2020, 2:20:35 PM 3
FileHash-MD5 3d67ce57aab4f7f917cf87c724ed7dab Feb 5, 2020, 2:20:35 PM 3
hostname x09live-ix3b.account-profile-users.info Feb 6, 2020, 2:56:07 PM 0
hostname www.phonechallenges-submit.site Feb 6, 2020, 2:56:07 PM
```
## Pandas Extension
The decoding functionality is also available in a pandas extension `mp_ioc`.
This supports a single method `extract()`.
This supports the same syntax
as `extract` (described earlier).
```
process_tree.mp_ioc.extract(columns=['CommandLine'])
```
| github_jupyter |
```
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
%matplotlib inline
# Constant seed for replicating training results
np.random.seed(2017)
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 267
nb_validation_samples = 84
epochs = 50
batch_size = 16
img_width= 28
img_height = 28
# used to rescale the pixel values from [0, 255] to [0, 1] interval
datagen = ImageDataGenerator(rescale=1./255)
# automagically retrieve images and their classes for train and validation sets
train_generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=16,
class_mode='binary')
validation_generator = datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=16,
class_mode='binary')
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit_generator(
train_generator,
steps_per_epoch=train_generator.samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size)
model.save_weights('first_try.h5')
# 0 = meme
# 1 = non meme
```
### Let us check with normal image
```
from PIL import Image
img = Image.open('./data/test/16-01910.500.jpg').convert('RGB')
img2 = Image.open('/home/rishikesh/Desktop/banner.png').convert('RGB')
imshow(img2)
input_img=np.asarray(img2.resize((28,28)))
input_img
input_img=np.asarray(img2.resize((28,28)))
input_img = input_img.astype('float32')
input_img /= 255
if K.image_data_format() == 'channels_first':
input_img=input_img.reshape((1,3,28, 28))
else:
input_img=input_img.reshape((1, 28, 28, 3))
dict_={0:'meme',1:'not meme'}
model.predict(input_img)
from pathlib import Path
if Path("model_weigts.h5").is_file():
print("yes")
y=z[0].clip(min=0, max=1)
import math
math.ceil(z[0][0])
imshow(img)
new_img = img.resize((28,28))
test=np.asarray(new_img)
y_w=np.asarray(new_img).reshape((1, 28, 28, 3))
y_w.shape
model.predict(y_w)
```
Not a meme
### Image with Text but not MEME
```
img1 = Image.open('./data/test/tuesday_quote.jpg')
imshow(img1)
y_w2=np.asarray(np.asarray(img1.resize((28,28)))).reshape((1, 28, 28, 3))
model.predict(y_w2)
# 1 = not meme
```
Oh good even with text which is not meme is successfully predicted
### With Actual Meme
```
img2 = Image.open('./data/test/maxresdefault.jpg')
imshow(img2)
model.predict(np.asarray(np.asarray(img2.resize((28,28)))).reshape((1, 28, 28, 3)))
```
Ok success it predicted as meme
| github_jupyter |
```
/from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/MyDrive/Neural_Tangent_Kernel/
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
from myrmsprop import MyRmsprop
from utils import plot_decision_boundary,attn_avg,plot_analysis
from synthetic_dataset import MosaicDataset1
from eval_model import calculate_attn_loss,analyse_data
%matplotlib inline
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
train_data = np.load("train_type4_data.npy",allow_pickle=True)
test_data = np.load("test_type4_data.npy",allow_pickle=True)
mosaic_list_of_images = train_data[0]["mosaic_list"]
mosaic_label = train_data[0]["mosaic_label"]
fore_idx = train_data[0]["fore_idx"]
test_mosaic_list_of_images = test_data[0]["mosaic_list"]
test_mosaic_label = test_data[0]["mosaic_label"]
test_fore_idx = test_data[0]["fore_idx"]
batch = 3000
train_dataset = MosaicDataset1(mosaic_list_of_images, mosaic_label, fore_idx)
train_loader = DataLoader( train_dataset,batch_size= batch ,shuffle=False)
#batch = 2000
#test_dataset = MosaicDataset1(test_mosaic_list_of_images, test_mosaic_label, test_fore_idx)
#test_loader = DataLoader(test_dataset,batch_size= batch ,shuffle=False)
```
# NTK
```
data = np.load("NTK_1.npy",allow_pickle=True)
# H = data[0]
print(data[0].keys())
H = torch.tensor(data[0]["NTK"])
lr_1 = 1/1470559.2
# p_vec = nn.utils.parameters_to_vector(where_func.parameters())
# p, = p_vec.shape
# n_m, n_obj,_ = inputs.shape # number of mosaic images x number of objects in each mosaic x d
# # this is the transpose jacobian (grad y(w))^T)
# features = torch.zeros(n_m*n_obj, p, requires_grad=False)
# k = 0
# for i in range(27000):
# out = where_func(inpp[i])
# where_func.zero_grad()
# out.backward(retain_graph=False)
# p_grad = torch.tensor([], requires_grad=False)
# for p in where_func.parameters():
# p_grad = torch.cat((p_grad, p.grad.reshape(-1)))
# features[k,:] = p_grad
# k = k+1
# tangent_kernel = features@features.T
# class Module1(nn.Module):
# def __init__(self):
# super(Module1, self).__init__()
# self.linear1 = nn.Linear(2,100)
# self.linear2 = nn.Linear(100,1)
# def forward(self,x):
# x = F.relu(self.linear1(x))
# x = self.linear2(x)
# return x
# from tqdm import tqdm as tqdm
# inputs,_,_ = iter(train_loader).next()
# inputs = torch.reshape(inputs,(27000,2))
# inputs = (inputs - torch.mean(inputs,dim=0,keepdims=True) )/torch.std(inputs,dim=0,keepdims=True)
# where_net = Module1()
# outputs = where_net(inputs)
# feature1 = torch.zeros((27000,200))
# feature2 = torch.zeros((27000,100))
# for i in tqdm(range(27000)):
# where_net.zero_grad()
# outputs[i].backward(retain_graph=True)
# par = []
# j = 0
# for p in where_net.parameters():
# if j%2 == 0:
# vec = torch.nn.utils.parameters_to_vector(p)
# p_grad = p.grad.reshape(-1)
# par.append(p_grad)
# j = j+1
# feature1[i,:] = par[0]
# feature2[i,:] = par[1]
# H = feature1@feature1.T + feature2@feature2.T
```
# Models
```
class Module2(nn.Module):
def __init__(self):
super(Module2, self).__init__()
self.linear1 = nn.Linear(2,100)
self.linear2 = nn.Linear(100,3)
def forward(self,x):
x = F.relu(self.linear1(x))
x = self.linear2(x)
return x
print(H)
torch.manual_seed(1234)
what_net = Module2().double()
what_net.load_state_dict(torch.load("type4_what_net.pt"))
what_net = what_net.to("cuda")
for param in what_net.parameters():
param.requires_grad = False
n_batches = 3000//batch
bg = []
for i in range(n_batches):
torch.manual_seed(i)
betag = torch.randn(3000,9)#torch.ones((250,9))/9
bg.append( betag.requires_grad_() )
```
# training
```
criterion = nn.CrossEntropyLoss()
optim1 = []
H= H.to("cpu")
for i in range(n_batches):
optim1.append(MyRmsprop([bg[i]],H=H,lr=1))
# instantiate what net optimizer
#optimizer_what = optim.RMSprop(what_net.parameters(), lr=0.0001)#, momentum=0.9)#,nesterov=True)
acti = []
analysis_data_tr = []
analysis_data_tst = []
loss_curi_tr = []
loss_curi_tst = []
epochs = 2500
# calculate zeroth epoch loss and FTPT values
running_loss,anlys_data,correct,total,accuracy = calculate_attn_loss(train_loader,bg,what_net,criterion)
print('training epoch: [%d ] loss: %.3f correct: %.3f, total: %.3f, accuracy: %.3f' %(0,running_loss,correct,total,accuracy))
loss_curi_tr.append(running_loss)
analysis_data_tr.append(anlys_data)
# training starts
for epoch in range(epochs): # loop over the dataset multiple times
ep_lossi = []
running_loss = 0.0
#what_net.train()
for i, data in enumerate(train_loader, 0):
# get the inputs
inputs, labels,_ = data
inputs = inputs.double()
beta = bg[i] # alpha for ith batch
#print(labels)
inputs, labels,beta = inputs.to("cuda"),labels.to("cuda"),beta.to("cuda")
# zero the parameter gradients
#optimizer_what.zero_grad()
optim1[i].zero_grad()
# forward + backward + optimize
avg,alpha = attn_avg(inputs,beta)
outputs = what_net(avg)
loss = criterion(outputs, labels)
# print statistics
running_loss += loss.item()
#alpha.retain_grad()
loss.backward(retain_graph=False)
#optimizer_what.step()
optim1[i].step()
running_loss_tr,anls_data,correct,total,accuracy = calculate_attn_loss(train_loader,bg,what_net,criterion)
analysis_data_tr.append(anls_data)
loss_curi_tr.append(running_loss_tr) #loss per epoch
print('training epoch: [%d ] loss: %.3f correct: %.3f, total: %.3f, accuracy: %.3f' %(epoch+1,running_loss_tr,correct,total,accuracy))
if running_loss_tr<=0.08:
break
print('Finished Training run ')
analysis_data_tr = np.array(analysis_data_tr)
columns = ["epochs", "argmax > 0.5" ,"argmax < 0.5", "focus_true_pred_true", "focus_false_pred_true", "focus_true_pred_false", "focus_false_pred_false" ]
df_train = pd.DataFrame()
df_test = pd.DataFrame()
df_train[columns[0]] = np.arange(0,epoch+2)
df_train[columns[1]] = analysis_data_tr[:,-2]/30
df_train[columns[2]] = analysis_data_tr[:,-1]/30
df_train[columns[3]] = analysis_data_tr[:,0]/30
df_train[columns[4]] = analysis_data_tr[:,1]/30
df_train[columns[5]] = analysis_data_tr[:,2]/30
df_train[columns[6]] = analysis_data_tr[:,3]/30
df_train
%cd /content/
plot_analysis(df_train,columns,[0,500,1000,1500,2000,2500])
aph = []
for i in bg:
aph.append(F.softmax(i,dim=1).detach().numpy())
aph = np.concatenate(aph,axis=0)
# torch.save({
# 'epoch': 500,
# 'model_state_dict': what_net.state_dict(),
# #'optimizer_state_dict': optimizer_what.state_dict(),
# "optimizer_alpha":optim1,
# "FTPT_analysis":analysis_data_tr,
# "alpha":aph
# }, "type4_what_net_500.pt")
aph[0]
avrg = []
avrg_lbls = []
with torch.no_grad():
for i, data1 in enumerate(train_loader):
inputs , labels , fore_idx = data1
inputs = inputs.double()
inputs = inputs.to("cuda")
beta = bg[i]
beta = beta.to("cuda")
avg,alpha = attn_avg(inputs,beta)
avrg.append(avg.detach().cpu().numpy())
avrg_lbls.append(labels.numpy())
avrg= np.concatenate(avrg,axis=0)
avrg_lbls = np.concatenate(avrg_lbls,axis=0)
%cd /content/drive/MyDrive/Neural_Tangent_Kernel/
data = np.load("type_4_data.npy",allow_pickle=True)
%cd /content/
plot_decision_boundary(what_net,[1,8,2,9],data,bg,avrg,avrg_lbls)
plt.plot(loss_curi_tr)
```
```
```
```
```
| github_jupyter |
# The python exercises
**Ex 0**: The Jupyter Notebooks are organized as a list of cells. There are two central kinds of cells, they are called **Code** and **Markdown**. The cell type can be set [using a keyboard shortcut](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/), or using the menus above.
The **Code** cells simply contain the Python code, no big deal.
The **Markdown** cells contain text (explanations, sections, etc). The text is written in Markdown. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML). You can read about it here:
http://daringfireball.net/projects/markdown/
In the cell below, write a short text that demonstrates that you can
* Create a section
* Write words in bold and italics
* Create lists
* Establish a [hyperlink](https://en.wikipedia.org/wiki/Hyperlink)
# Section
Some **bold** text.
Some *italic* text.
A [hyperlink](https://en.wikipedia.org/wiki/Hyperlink)
**Ex 1**: Create a list `a` that contains the numbers from $1$ to $1110$, incremented by one, using the `range` function.
```
lst = list(range(1, 1111))
```
**Ex 2**: Show that you understand [slicing](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) in Python by extracting a list `b` with the numbers from $543$ to $779$ from the list created above.
```
slc = lst[542:779]
```
**Ex 3**: Using `def`, define a function that takes as input a number $x$ and outputs the number multiplied by itself plus three $f(x) = x(x+3)$.
```
def function(x):
return x + 3
```
**Ex 4**: Apply this function to every element of the list `b` using a `for` loop.
```
for x in lst:
function(x)
```
**Ex 5**: Do the same thing using a list comprehension.
```
lst2 = [x for x in range(1, 1111)]
```
**Ex 6**: Write the output of your function to a text file with one number per line.
```
file = open("file.txt", "w")
for x in lst:
y = str(function(x)) + "\n"
file.write(y)
file.close()
```
**Ex 7**: Show that you know about strings using this example from http://learnpythonthehardway.org/book/ex6.html (code reproduced below).
1. Go through the code below and write a code comment above each line explaining it.
1. Find all the places where a string is put inside a string. There are four places.
1. Are you sure there are only four places? How do you know? Maybe I like lying.
1. Explain why adding the two strings w and e with + makes a longer string.
[**Hint**: If you feel this is too complex, try completing the prior learningthehardway exercises first. Start [here](http://learnpythonthehardway.org/book/ex1.html).
```
# Note from Sune: In Python, code comments follow the "#" character
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
```
*[Write the answer to **Ex 7**, 2-4 here]*
**Ex 8**: First, learn about JSON by reading the **[wikipedia page](https://en.wikipedia.org/wiki/JSON)**. Then answer the following two questions in the cell below.
* What is `json`? What do the letters stand for?
* Why is `json` superior to `xml`? (... or why not?)
### JavaScript Object Notation
It's just really good
**Ex 9a**: Use the `json` module (instructions on usage here: https://docs.python.org/2.7/library/json.html).
First use `urllib2` (https://docs.python.org/2.7/howto/urllib2.html), or another Python library, to download **[this file](https://raw.githubusercontent.com/suneman/socialgraphs2016/master/files/test.json)**.
The downloaded file is a string when you first download it, but you can use the `json` library to "load" the string and decode it to a Python object, using `json.loads()`. (The decoded string is a python object, a list with a single element, a dictionary (with nested dictionaries inside it)).
```
import json
import urllib2
url = "https://raw.githubusercontent.com/suneman/socialgraphs2016/master/files/test.json"
#url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
response = urllib2.urlopen(url)
listObj = json.load(response)
```
**Ex 9b**: Now, let's take a look at the file you downloaded. First, just write the name of the variable that contains the decoded file content and hit enter to take a look at it. It's the list of Twitter Trending topics, a few days ago.
**Ex 9c**: The thing you've just decoded is now a list of length 1. What are the names of the keys organizing the dictionary at position 0 in the list? (Just write the code to produce the answer.)
**Hint** use the `.keys()` method to easily get the keys of any dictionary.
```
obj = listObj[0]
obj.keys()
```
**Ex 9d**: Two small questions
* What time did I create the list of Trending Topics?
* Print the names of the trending topics (bonus for using a list comprehension)
(Just write the code to produce the answer.)
```
obj["created_at"]
```
**Ex 9e**: Two more small questions
* Go on-line and figure out why there's a `u` in front of every string. Write the answer in your own words. (Hint it has to do with strings in Python).
* What's going on with all of the `%22` and `%23`? Go on-line and figure it out. Write the answer in your own words. (Hint: It has to do with HTML URL encoding)
*[Write your answer to **Ex 9e** here]*
When a 'u' is in front of a string it means the string is a unicode string. Unicode can handle character id's between 0 and 255, and is a simple and old format for strings
```
str(obj["created_at"])
```
# Wikipedia
```
baseurl = "https://en.wikipedia.org/w/api.php?"
action = "action=query&"
titles = "titles=Wolverine_(character)&"
content = "prop=revisions&rvprop=content&"
dataformat = "format=json"
query = "%s%s%s%s%s" % (baseurl, action, titles, content, dataformat)
print query
import json
import urllib2
response = urllib2.urlopen(query)
obj = json.load(response)
obj.keys()
obj["query"].keys()
```
| github_jupyter |
*This notebook requires fenicstools to generate the DOFs plots*
```
import dolfin as df
import numpy as np
import finmag
```
Generate a 2D sqaure mesh:
```
mesh = df.RectangleMesh(-4, -4, 4, 4, 4, 4)
df.plot(mesh, interactive=True)
```
Mesh coordinates:
```
mesh.coordinates()
S1 = df.FunctionSpace(mesh, 'CG', 1)
S3 = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
v_fun = df.Function(S3)
```
Simulation with PBCs:
```
Ms = 1e5
sim = finmag.Simulation(mesh, Ms, unit_length=1e-9, pbc='2d')
```
The values in the boundaries are (0, 0, -1) while the rest of the mesh vertexes will have associated a value of (0, 0, 1)
```
def m_init(pos):
x, y = pos[0], pos[1]
if x > 3 or x < -3:
return (0, 0, -1)
elif y > 3 or y < -3:
return (0, 0, -1)
else:
return (0, 0, 1)
sim.set_m(m_init)
```
Now we will try to visualize the DOFs ordering and the mesh numbering:
```
%matplotlib qt4
import fenicstools
```
We can plot the DOFs (degrees of freedom) of the 3 components of the vector field (in the plot windows, press `D` to get the DOFs and `V` to get the vertex numbering). The values are the array indexes of the vector field, which goes into the mesh in the right order, following the **vertex to dof** mapping (see below):
```
dmp = fenicstools.DofMapPlotter(sim.S3)
dmp.plot([0, 1, 2])
dmp.show()
```
<img src='dofs_of_0_1_2.png' width=700>
Some values are repeated since they are the PBCs
The mesh indexes:
<img src='dofs_vertexes.png' width=500>
The dolfin vector function (reduced):
```
sim.m_field.f.vector().array()
```
The Vertex to DOF map give us the mapping for going from the dofin function towards the mesh ordering, which is a **full length** vector (the system including boundaries). It automatically copies the repeated values at the boundaries with PBC:
```
v2d = df.vertex_to_dof_map(sim.S3)
v2d
```
This gives us the dolfin function values in the same order than the mesh, in the *xyz* order
$$ [\underbrace{x_0, y_0, z_0}_\text{node 0}, \underbrace{x_1, y_1, z_1}_\text{node 1}, \underbrace{x_2, y_2, z_2}_\text{node 2}, \ldots ] $$
when calling a dolfin function with the mapping argument. The mapped function in array form looks like:
```
vfunction_to_mesh = sim.m_field.f.vector().array()[v2d]
vfunction_to_mesh
```
Since we know it is in the *xyz* order with respect to the mesh coordinates, we can print them according to their mesh node association:
```
for i in xrange(len(v2d) / 3):
print sim.mesh.coordinates()[i], ' --> ', vfunction_to_mesh.reshape(-1, 3)[i]
```
The DOF to vertex map, which is reduced, is:
```
d2v = df.dof_to_vertex_map(sim.S3)
d2v
```
This is the opposite mapping, for going from the ordered mesh towards the *original function* (which has a reduced number of elements, since it does not consider the repeated boundaries)
```
vfunction_mesh_to_original = vfunction_to_mesh[d2v]
vfunction_mesh_to_original
```
To compare this array, the original function was:
```
sim.m_field.f.vector().array()
```
| github_jupyter |
```
import torch
import re
from grid.clients.torch import TorchClient
client = TorchClient(verbose=False)
client.print_network_stats()
compute_nodes = [x for x in client if re.match('compute:', x)]
for x in compute_nodes:
print(x)
laptop = compute_nodes[0]
desktop = compute_nodes[1]
# Convenient way to send specific tensors to certain nodes
assign_tensors_to_nodes = {}
assign_tensors_to_nodes[desktop] = []
assign_tensors_to_nodes[laptop] = []
# Loop over available nodes
for node in compute_nodes:
for i in range(5):
# Just getting five randomly generated 2x2 matrices here
assign_tensors_to_nodes[node].append(torch.FloatTensor(2,2))
# Fill desktop tensors with 1s
for tensor in assign_tensors_to_nodes[desktop]:
tensor.fill_(1)
# Fill desktop tensors with 2s
for tensor in assign_tensors_to_nodes[laptop]:
tensor.fill_(2)
# List of tensors -- tensors are local
# Sanity check -- we want desktop to have 2x2 matrices filled with 1s
assign_tensors_to_nodes[desktop]
# List of tensors -- tensors are local
# Sanity check -- we want laptop to have 2x2 matrices filled with 2s
assign_tensors_to_nodes[laptop]
# Multiply all tensors we want to send to desktop.
# Computation is done on this machine
accumulate = assign_tensors_to_nodes[desktop][0]
for x in assign_tensors_to_nodes[desktop][1:]:
accumulate = accumulate.matmul(x)
print(accumulate)
# Multiply all tensors we want to send to laptop.
# Computation is done on this machine
accumulate = assign_tensors_to_nodes[laptop][0]
for x in assign_tensors_to_nodes[laptop][1:]:
accumulate = accumulate.matmul(x)
print(accumulate)
# Send tensors to desktop node
for send_this_to_desktop in assign_tensors_to_nodes[desktop]:
send_this_to_desktop.send_(desktop)
# Send tensors to laptop node
for send_this_to_laptop in assign_tensors_to_nodes[laptop]:
send_this_to_laptop.send_(laptop)
# List of desktop tensors, now on desktop node
assign_tensors_to_nodes[desktop]
# List of laptop tensors, now on laptop node
assign_tensors_to_nodes[laptop]
# Multiply all tensors on desktop.
# Computation is done on desktop.
accumulate_desk = assign_tensors_to_nodes[desktop][0]
for x in assign_tensors_to_nodes[desktop][1:]:
accumulate_desk = accumulate_desk.matmul(x)
print(accumulate_desk)
# Multiply all tensors on laptop.
# Computation is done on laptop.
accumulate_lap = assign_tensors_to_nodes[laptop][0]
for x in assign_tensors_to_nodes[laptop][1:]:
accumulate_lap = accumulate_lap.matmul(x)
print(accumulate_lap)
# Returns the data resulting from desktop computation
accumulate_desk.get_()
# Returns the data resulting from laptop computation
accumulate_lap.get_()
(2 * accumulate_desk ** 2 == accumulate_lap).all()
(accumulate_lap == accumulate).all()
```
| github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Simple-2d-gaussian-acquisition-function---update-using-MH" data-toc-modified-id="Simple-2d-gaussian-acquisition-function---update-using-MH-1"><span class="toc-item-num">1 </span>Simple 2d gaussian acquisition function - update using MH</a></span></li></ul></div>
```
# Generalised model set up that allows passing of arbitrary model for fitting,
# hyperparameters can specified as values = [_v1,_v2,...,_vn] for discrete and bounds = [_lower,_upper] for continuous
import matplotlib.pyplot as plt
import numpy as np
# --------------------------
# Bayesian Optimisation Code
# --------------------------
from scipy.stats import norm
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, Matern,RBF
from scipy.optimize import minimize
from pyDOE import *
# -----------------------------------------
# --- Class for a continuous hyperparameter
# -----------------------------------------
# --- Define a hyperparameter class that contains all the required specs of the hyperparameter
class hyperparam(object):
def __init__(self,list_in):
# Initiate with 2 types of variable. We either specify bounds
# for continuous variable or values for discrete. Note that for
# now the values must be integers and be a list of consecutive
# integers.
if len(list_in) == 2:
self.bounds = list_in
self.kind = 'continuous'
elif len(list_in) > 2:
self.bounds = [list_in[0],list_in[-1]]
self.kind = 'discrete'
self.vals = list_in
class iteration(object):
def __init__(self,pars):
# # --- Sample data
self.Xt = pars.Xt
self.Yt = pars.Yt
# Obtain next sampling point from the acquisition function (expected_improvement)
X_next = self.propose_location(pars)
# Convert to int where necessary
# We need to recreate a dictionary with the keys given by the hyperparameter name before pasing into our
# ML model
self.X_nextdict = {}
for i,hps1 in enumerate(sorted(pars.Xtdict.keys())):
if pars.hps[hps1].kind == 'discrete':
X_next[i] = int(X_next[i])
self.X_nextdict[hps1] = X_next[i]
else:
self.X_nextdict[hps1] = X_next[i]
#X_next = np.array(X_next,ndmin=(2)).reshape(1,-1)
Y_next = pars.objF(self.X_nextdict)
# Add the new sample point to the existing for the next iteration
self.Xt = np.vstack((self.Xt, X_next.reshape(1,-1)[0]))
self.Yt = np.concatenate((self.Yt, Y_next))
# Sampling function to find the next values for the hyperparameters
def propose_location(self,pars):
# Proposes the next sampling point by optimizing the acquisition function. Args: acquisition: Acquisition function. X_sample: Sample locations (n x d). Y_sample: Sample values (n x 1). gpr: A GaussianProcessRegressor fitted to samples. Returns: Location of the acquisition function maximum. '''
self.N_hps = pars.Xt.shape[1]
min_val = 1
min_x = None
self.gpr = pars.gpr
self.Xt = pars.Xt
# Find the best optimum by starting from n_restart different random points.
Xs = lhs(self.N_hps, samples=pars.n_restarts, criterion='centermaximin')
for i,hp in enumerate(sorted(pars.hps.keys())):
Xs[:,i] = Xs[:,i]*(pars.hps[hp].bounds[1]-pars.hps[hp].bounds[0])+pars.hps[hp].bounds[0]
# Convert int values to integers
if pars.hps[hp].kind == 'discrete':
Xs[:,i] = Xs[:,i].astype(int)
# Find the maximum in the acquisition function
if pars.optim_rout == 'minimize':
for x0 in Xs:
res = minimize(self.min_obj, x0=x0, bounds=pars.bounds, method=pars.method)
# Find the best optimum across all initiations
if res.fun < min_val:
min_val = res.fun[0]
min_x = res.x
elif pars.optim_rout == 'MCMC-MH':
for x0 in Xs:
res_x,res_f = self.MetroHastings(x0,[0.1]*self.N_hps,10000,tuple(pars.bounds))
if res_f < min_val:
min_val = res_f
min_x = res_x
elif pars.optim_rout == 'MCMC-discrete':
for x0 in Xs:
res_x,res_f = self.discrete_MCMC(x0,pars.x_dict,10000)
if res_f < min_val:
min_val = res_f
min_x = res_x
return min_x.reshape(-1, 1)
def min_obj(self,X):
# Minimization objective is the negative acquisition function
return -self.expected_improvement(X.reshape(-1, self.N_hps))
def max_obj(self,X):
# Minimization objective is the negative acquisition function
return self.expected_improvement(X.reshape(-1, self.N_hps))
# Acquisition function - here we use expected improvement
def expected_improvement(self,X):
# --- Computes the EI at points X based on existing samples X_sample and Y_sample using a Gaussian process
# surrogate model.
# X: Points at which EI shall be computed (m x d).
# X_sample: Sample locations (n x d).
# Y_sample: Sample values (n x 1).
# gpr: A GaussianProcessRegressor fitted to samples.
# xi: Exploitation-exploration trade-off parameter.
#. - xi ~ O(0) => exploitation
#. - xi ~ O(1) => exploration
# Returns: Expected improvements at points X.
# Evaluate the Gaussian Process at a test location X to get the mean and std
mu, sigma = self.gpr.predict(X, return_std=True)
# Evaluate the Gaussian Process at the sampled points - this gets the mean values without the noise
mu_sample = self.gpr.predict(self.Xt)
sigma = sigma.reshape(-1, 1)#self.Xt.shape[1])
# Needed for noise-based model,
# otherwise use np.max(Y_sample).
# See also section 2.4 in [...]
mu_sample_opt = np.max(mu_sample)
imp = mu - mu_sample_opt
Z = imp / sigma
Ei = (mu-mu_sample_opt) * norm.cdf(mu,loc=mu_sample_opt, scale=sigma) \
+ mu_sample_opt * norm.pdf(mu,loc=mu_sample_opt, scale=sigma)
return Ei
def MetroHastings(self,x0,sig,Niter,bounds):
"Function to perform metropolis Hastings sampling in an MCMC"
# --- Input ---
# x0: initial guess for random walk - list of continuous variables
# sig is the uncertainty in the MH sampling algorithm
# Niter is number of iterations to perform
# bounds: list of tuples of length x0, each one being the lower and upper bounds
# --- Output ---
# Modal solution from the MCMC
# Calculate initial guess
acq = np.zeros(Niter)
acq[0] = self.min_obj(x0.reshape(1,-1))
# proposition point
xp = np.zeros((len(x0),Niter))
xp[:,0] = x0
for iiter in range(1,Niter):
# Propose new data point to try using MH
for i in range(len(x0)):
# iterate until we get a point in the correct interval
if x0[i]<bounds[i][0]:
loc0 = bounds[i][0]
elif x0[i]>bounds[i][1]:
loc0 = bounds[i][1]
else:
loc0 = x0[i]
Pnext = np.random.normal(loc=loc0,scale=sig[i])
while (Pnext < bounds[i][0]) | (Pnext >= bounds[i][1]):
Pnext = np.random.normal(loc=loc0,scale=sig[i])
# Then choose the first point that is
xp[i,iiter] = Pnext
# Test value at this point
acq[iiter] = self.min_obj(xp[:,iiter].reshape(1,-1))
# Check if proposed point is better
if acq[iiter] > acq[iiter-1]:
x0 = xp[:,iiter].copy()
else:
p0 = [acq[iiter-1]/(acq[iiter]+acq[iiter-1]),acq[iiter]/(acq[iiter]+acq[iiter-1])]
nextP = np.random.choice([0,1],p=p0)
if nextP == 1:
x0 = xp[:,iiter].copy()
else:
x0 = xp[:,iiter-1].copy()
# Now get optimal solution by fitting a histogram to the data - ignore first 10% of samples
optim_x = np.zeros((1,len(x0)))
for i in range(optim_x.shape[1]):
optim_x[0,i] = kernel_density_estimation(xp[i,int(0.1*Niter):],Niter)
return optim_x,self.min_obj(optim_x.reshape(1,-1))
def kernel_density_estimation(self,xpi,Niter):
" Function to find peak in a kernel density "
# We initially fudge this to get it working!
# So we fit a histogram and then find the middle of the tallest bar
# Fit a histogram
data = xpi.copy()
data.sort()
hist, bin_edges = np.histogram(data, density=True,bins=max(10,30))
# Return the middle of the largest bin
n = np.argmax(hist)
return np.mean(bin_edges[n:n+2])
def discrete_MCMC(self,x0,x_dict,Niter):
"Function to perform fully discrete metropolis Hastings sampled MCMC"
# --- Input ---
# x0: starting guess
# Niter is number of iterations to perform
# bounds: dictionary of values for each variable with key equal to the position in the array
# --- Output ---
# Modal solution from the MCMC
# Calculate initial guess
acq = np.zeros(Niter)
acq[0] = acquisition_function(np.array(x0).reshape(1,-1))
# proposition point
xp = np.zeros((len(x0),Niter))
xp[:,0] = x0
# count frequency of each value appearing
N_dict = {}
for k1 in x_dict.keys():
N_dict[k1] = np.zeros(len(x_dict[k1]))
for iiter in range(1,Niter):
# Choose a location to swap
i_choice = np.random.choice(range(len(x0)))
# Set xp to be x0
xp[:,iiter] = x0.copy()
# choose a new value for the i_choice-th entry
xp[i_choice,iiter] = np.random.choice(x_dict[i_choice])
# Test value at this point
acq[iiter] = acquisition_function(xp[:,iiter].reshape(1,-1))
# Check if proposed point is better
if acq[iiter] > acq[iiter-1]:
x0 = xp[:,iiter].copy()
else:
p0 = [acq[iiter-1]/(acq[iiter]+acq[iiter-1]),acq[iiter]/(acq[iiter]+acq[iiter-1])]
nextP = np.random.choice([0,1],p=p0)
if nextP == 1:
x0 = xp[:,iiter].copy()
else:
x0 = xp[:,iiter-1].copy()
# accumulate the counts - when iiter excedes a 10th of Niter
if iiter > 0.1*Niter:
for aci in range(len(x0)):
N_dict[aci][x_dict[aci].index(x0[aci])] += 1
# Now get optimal solution by fitting a histogram to the data - already ignored first 10% of samples
optim_x = np.zeros((1,len(x0)))
for i in range(len(x0)):
optim_x[0,i] = x_dict[i][np.argmax(N_dict[i])]
return optim_x,acquisition_function(optim_x[0,:].reshape(1,-1))
class BayesianOptimisation(object):
def __init__(self,**kwargs):
# Get hyperparameter info and convert to hyperparameter class
self.hps = {}
for hp in kwargs['hps'].keys():
self.hps[hp] = hyperparam(kwargs['hps'][hp])
# Objective function to minimise
self.MLmodel = kwargs['MLmodel']
# Number of hyperparameters
N_hps = len(self.hps.keys())
# --- Initial sample data
if 'NpI' in kwargs.keys():
self.NpI = kwargs['NpI']
else:
self.NpI = 2**N_hps
# --- Optimisation routine for the acquisition function
if 'optim_rout' in kwargs.keys():
self.optim_rout = kwargs['optim_rout']
# Now define a new dictionary for use in discrete MCMC optimisation
if self.optim_rout == 'MCMC-discrete':
self.x_dict = {}
for i,hp in enumerate(self.hps.keys()):
self.x_dict[i] = list(self.hps[hp].vals)
else:
self.optim_rout = 'minimize'
# Establish a dictionary for our hyperparameter values that we sample
self.Xtdict = {}
# ...and then an array for the same thing but with each column being
# a different hyperparameter and ordered alphabetically
self.Xt = np.zeros((self.NpI,len(self.hps.keys())))
# We also need to collect together all of the bounds for the optimization routing into one array
self.bounds = np.zeros((2,len(self.hps.keys())))
# Get some initial samples on the unit interval
Xt = lhs(len(self.hps.keys()), samples=self.NpI, criterion='centermaximin')
# For each hyper parameter, rescale the unit inverval on the
# appropriate range for that hp and store in a dict
for i,hp in enumerate(sorted(self.hps.keys())):
self.Xtdict[hp] = self.hps[hp].bounds[0]+Xt[:,i]*(self.hps[hp].bounds[1]-self.hps[hp].bounds[0])
# convert these to an int if kind = 'discrete'
if self.hps[hp].kind == 'discrete':
self.Xtdict[hp] = self.Xtdict[hp].astype(int)
self.bounds[i,:] = self.hps[hp].bounds
self.Xt[:,i] = self.Xtdict[hp]
# Calculate objective function at the sampled points
self.Yt = self.objF(pars=self.Xtdict,n=self.NpI)
# --- Number of iterations
if 'Niter' in kwargs.keys():
self.Niter = kwargs['Niter']
else:
self.Niter = 10*N_hps
# --- Number of optimisations of the acquisition function
if 'n_restarts' in kwargs.keys():
self.n_restarts = kwargs['n_restarts']
else:
self.n_restarts = 25*N_hps
# --- Optimisation method used
if 'method' in kwargs.keys():
self.method = kwargs['method']
else:
self.method = 'L-BFGS-B'
# --- Define the Gaussian mixture model
if 'kernel' in kwargs.keys():
self.kernel = kwargs['kernel']
else:
self.kernel = RBF()
if 'noise' in kwargs.keys():
self.noise = kwargs['noise']
else:
self.noise = noise = 0.2
self.gpr = GaussianProcessRegressor(kernel=self.kernel, alpha=noise**2)
def optimise(self):
for i in range(self.Niter):
it1 = iteration(self)
self.Xt = it1.Xt
self.Yt = it1.Yt
if i == 0:
print self.Yt
print('current accuracy:',self.Yt[-1])
print('best accuracy:', max(self.Yt))
self.gpr.fit(self.Xt, self.Yt)
return self
def objF(self,pars,**kwargs):
# Number of hyperparameter values to try.
n = 1
if 'n' in kwargs.keys():
n = kwargs['n']
# Initiate array to accumate the accuracy of the model
sc = np.zeros(n)
# Establish the basic ML model
model = self.MLmodel
for i in range(n):
# Get dictionary of hyperparameter values to test at the ith iteration
hps_iter = {}
for hp in pars.keys():
if self.hps[hp].kind == 'discrete':
hps_iter[hp] = int(pars[hp][i])
else:
hps_iter[hp] = pars[hp][i]
# Create instance of MLmodel with the hps at this iteration
model.set_params(**hps_iter)
# Train
model.fit(self.X_train, self.y_train)
# Score
sc[i] = np.mean(cross_val_score(model, self.X_train, self.y_train, cv=5))
return sc
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
X_train = 15*np.random.uniform(size=(100,2))
y_train = np.zeros((100,1))
for i in range(X_train.shape[0]):
y_train[i] = 1-acquisition_function(X_train[i,:].reshape(1,-1))
y_train = y_train+0.1*np.random.uniform(size=(100,1))
y_train = y_train.ravel()
y_train
hps_rf = {
'n_estimators':range(1,10),
'max_depth':range(1,10)
}
BOout = BayesianOptimisation(
hps=hps_rf,
MLmodel = RandomForestRegressor(random_state= 42),
optim_rout = 'MCMC-discrete',
NpI = 2,
Niter = 5
).optimise()
best_params = BOout.Xt[np.argmax(BOout.Yt)]
RFr = RandomForestRegressor(
n_estimators=int(best_params[0]),
max_depth=int(best_params[1]),
random_state=42
).fit(X_train,y_train)
np.mean(cross_val_score(RFr, X_train,y_train, cv=5))
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.plot(BOout.Xt,'.')
plt.subplot(122)
plt.plot(BOout.Yt,'.')
```
# Simple 2d gaussian acquisition function - update using MH
```
def acquisition_function(z):
x=z[0,0]
y=z[0,1]
return np.exp(-((x-5)/10)**2)*np.exp(-((y-10)/10)**2)
plt.plot(np.linspace(0,1),acquisition_function(np.linspace(0,1)))
def MetroHastings(x0,optim_func,sig,Niter,bounds):
"Function to perform metropolis Hastings sampling in an MCMC"
# --- Input ---
# x0: initial guess for random walk - list of continuous variables
# sig is the uncertainty in the MH sampling algorithm
# Niter is number of iterations to perform
# bounds: list of tuples of length x0, each one being the lower and upper bounds
# --- Output ---
# Modal solution from the MCMC
# Calculate initial guess
acq = np.zeros(Niter)
acq[0] = acquisition_function(x0[0],x0[1])
# proposition point
xp = np.zeros((len(x0),Niter))
xp[:,0] = x0
for iiter in range(1,Niter):
# Propose new data point to try using MH
for i in range(len(x0)):
# iterate until we get a point in the correct interval
if x0[i]<bounds[i][0]:
loc0 = bounds[i][0]
elif x0[i]>bounds[i][1]:
loc0 = bounds[i][1]
else:
loc0 = x0[i]
Pnext = np.random.normal(loc=loc0,scale=sig[i])
while (Pnext < bounds[i][0]) | (Pnext >= bounds[i][1]):
Pnext = np.random.normal(loc=loc0,scale=sig[i])
# Then choose the first point that is
xp[i,iiter] = Pnext
# Test value at this point
acq[iiter] = acquisition_function(xp[0,iiter],xp[1,iiter])
# Check if proposed point is better
if acq[iiter] > acq[iiter-1]:
x0 = xp[:,iiter].copy()
else:
p0 = [acq[iiter-1]/(acq[iiter]+acq[iiter-1]),acq[iiter]/(acq[iiter]+acq[iiter-1])]
nextP = np.random.choice([0,1],p=p0)
if nextP == 1:
x0 = xp[:,iiter].copy()
else:
x0 = xp[:,iiter-1].copy()
# Now get optimal solution by fitting a histogram to the data
optim_x = np.zeros((1,len(x0)))
for i in range(optim_x.shape[1]):
optim_x[0,i] = kernel_density_estimation(xp[i,int(0.1*Niter):],Niter)
return optim_x,acquisition_function(optim_x[0,0],optim_x[0,1])
def kernel_density_estimation(xpi,Niter):
" Function to peak in a kernel density "
# We initially fudge this to get it working!
# Fit a histogram
data = xpi.copy()
data.sort()
hist, bin_edges = np.histogram(data, density=True,bins=max(10,30))
# Return the largest bin
n = np.argmax(hist)
return np.mean(bin_edges[n:n+2])
def discrete_MCMC(x0,x_dict,Niter):
"Function to perform fully discrete metropolis Hastings sampled MCMC"
# --- Input ---
# x0: starting guess
# Niter is number of iterations to perform
# bounds: dictionary of values for each variable with key equal to the position in the array
# --- Output ---
# Modal solution from the MCMC
# Calculate initial guess
acq = np.zeros(Niter)
acq[0] = acquisition_function(np.array(x0).reshape(1,-1))
# proposition point
xp = np.zeros((len(x0),Niter))
xp[:,0] = x0
# count frequency of each value appearing
N_dict = {}
for k1 in x_dict.keys():
N_dict[k1] = np.zeros(len(x_dict[k1]))
for iiter in range(1,Niter):
# Choose a location to swap
i_choice = np.random.choice(range(len(x0)))
# Set xp to be x0
xp[:,iiter] = x0.copy()
# choose a new value for the i_choice-th entry
xp[i_choice,iiter] = np.random.choice(x_dict[i_choice])
# Test value at this point
acq[iiter] = acquisition_function(xp[:,iiter].reshape(1,-1))
# Check if proposed point is better
if acq[iiter] > acq[iiter-1]:
x0 = xp[:,iiter].copy()
else:
p0 = [acq[iiter-1]/(acq[iiter]+acq[iiter-1]),acq[iiter]/(acq[iiter]+acq[iiter-1])]
nextP = np.random.choice([0,1],p=p0)
if nextP == 1:
x0 = xp[:,iiter].copy()
else:
x0 = xp[:,iiter-1].copy()
# accumulate the counts - when iiter excedes a 10th of Niter
if iiter > 0.1*Niter:
for aci in range(len(x0)):
N_dict[aci][x_dict[aci].index(x0[aci])] += 1
# Now get optimal solution by fitting a histogram to the data
optim_x = np.zeros((1,len(x0)))
for i in range(len(x0)):
optim_x[0,i] = x_dict[i][np.argmax(N_dict[i])]
return optim_x,acquisition_function(optim_x[0,:].reshape(1,-1))
x_dict = {}
x_dict[0] = range(1,11)
x_dict[1] = range(1,21)
Niter = 20000
guess = np.array([
np.random.choice(x_dict[0]),
np.random.choice(x_dict[1])
])
optim_x,optim_f = discrete_MCMC(guess,x_dict,Niter)
N_dict
optim_x
optim_f
Niter = 10000
optim_x,optim_f = MetroHastings([0.1,0.4],acquisition_function,[0.1,0.1],Niter,[(0,1),(0,1)])
optim_x,optim_f
from scipy.stats import norm
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.hist(xp[0],normed=True,bins=max(10,20))
mu, std = norm.fit(xp[0])
xlin = np.linspace(0,1)
plt.plot(xlin,norm.pdf(xlin, mu, std))
plt.subplot(122)
plt.hist(xp[1],normed=True,bins=max(10,20))
mu, std = norm.fit(xp[1])
xlin = np.linspace(0,1)
plt.plot(xlin,norm.pdf(xlin, mu, std))
plt.show()
optim_x
optim_x = np.zeros((1,len(x0)))
for i in range(len(optim_x)):
# Fit a normal
# Save the mean - ie highest density of points
optim_x[i] = kernel_density_estimation(xp[i,:])
xp[i]
data = xp[0].copy()
data.sort()
hist, bin_edges = np.histogram(data, density=True,bins=int(Niter/100))
#hist, bin_edges = np.histogram(data, density=True,bins=bin_edges)
len(bin_edges)
Niter = 10000
Niter/(100.)
len(np.zeros((1,4)))
import BayesianHyperparameter3
```
| github_jupyter |
```
import numpy as np
import scipy as sp
import scipy.stats
import itertools
import logging
import matplotlib.pyplot as plt
import pandas as pd
import torch.utils.data as utils
import math
import time
import tqdm
import torch
import torch.optim as optim
import torch.nn.functional as F
from argparse import ArgumentParser
from torch.distributions import MultivariateNormal
import torch.nn as nn
import torch.nn.init as init
from flows import RealNVP, Planar
from models import NormalizingFlowModel
```
## Load and process the data
```
mode = 'ROC'
f_rnd = pd.read_hdf("/data/t3home000/spark/LHCOlympics/data/MassRatio_RandD.h5")
f_PureBkg = pd.read_hdf("/data/t3home000/spark/LHCOlympics/data/MassRatio_pureBkg.h5")
f_rnd.head()
f_PureBkg.head()
if mode == 'ROC':
dt_PureBkg = f_rnd.values
else:
dt_PureBkg = dt_PureBkg = f_PureBkg.values
dt_PureBkg[:,1] = (dt_PureBkg[:,1]-np.mean(dt_PureBkg[:,1]))/np.std(dt_PureBkg[:,1])
dt_PureBkg[:,2] = (dt_PureBkg[:,2]-np.mean(dt_PureBkg[:,2]))/np.std(dt_PureBkg[:,2])
dt_PureBkg[:,3] = (dt_PureBkg[:,3]-np.mean(dt_PureBkg[:,3]))/np.std(dt_PureBkg[:,3])
dt_PureBkg[:,4] = (dt_PureBkg[:,4]-np.mean(dt_PureBkg[:,4]))/np.std(dt_PureBkg[:,4])
dt_PureBkg[:,5] = (dt_PureBkg[:,5]-np.mean(dt_PureBkg[:,5]))/np.std(dt_PureBkg[:,5])
dt_PureBkg[:,6] = (dt_PureBkg[:,6]-np.mean(dt_PureBkg[:,6]))/np.std(dt_PureBkg[:,6])
dt_PureBkg[:,8] = (dt_PureBkg[:,8]-np.mean(dt_PureBkg[:,8]))/np.std(dt_PureBkg[:,8])
dt_PureBkg[:,9] = (dt_PureBkg[:,9]-np.mean(dt_PureBkg[:,9]))/np.std(dt_PureBkg[:,9])
dt_PureBkg[:,10] = (dt_PureBkg[:,10]-np.mean(dt_PureBkg[:,10]))/np.std(dt_PureBkg[:,10])
dt_PureBkg[:,11] = (dt_PureBkg[:,11]-np.mean(dt_PureBkg[:,11]))/np.std(dt_PureBkg[:,11])
dt_PureBkg[:,12] = (dt_PureBkg[:,12]-np.mean(dt_PureBkg[:,12]))/np.std(dt_PureBkg[:,12])
dt_PureBkg[:,14] = (dt_PureBkg[:,14]-np.mean(dt_PureBkg[:,14]))/np.std(dt_PureBkg[:,14])
dt_PureBkg[:,15] = (dt_PureBkg[:,15]-np.mean(dt_PureBkg[:,15]))/np.std(dt_PureBkg[:,15])
dt_PureBkg[:,16] = (dt_PureBkg[:,16]-np.mean(dt_PureBkg[:,16]))/np.std(dt_PureBkg[:,16])
dt_PureBkg[:,17] = (dt_PureBkg[:,17]-np.mean(dt_PureBkg[:,17]))/np.std(dt_PureBkg[:,17])
dt_PureBkg[:,18] = (dt_PureBkg[:,18]-np.mean(dt_PureBkg[:,18]))/np.std(dt_PureBkg[:,18])
dt_PureBkg[:,19] = (dt_PureBkg[:,19]-np.mean(dt_PureBkg[:,19]))/np.std(dt_PureBkg[:,19])
dt_PureBkg[:,21] = (dt_PureBkg[:,21]-np.mean(dt_PureBkg[:,21]))/np.std(dt_PureBkg[:,21])
dt_PureBkg[:,22] = (dt_PureBkg[:,22]-np.mean(dt_PureBkg[:,22]))/np.std(dt_PureBkg[:,22])
dt_PureBkg[:,23] = (dt_PureBkg[:,23]-np.mean(dt_PureBkg[:,23]))/np.std(dt_PureBkg[:,23])
dt_PureBkg[:,24] = (dt_PureBkg[:,24]-np.mean(dt_PureBkg[:,24]))/np.std(dt_PureBkg[:,24])
dt_PureBkg[:,25] = (dt_PureBkg[:,25]-np.mean(dt_PureBkg[:,25]))/np.std(dt_PureBkg[:,25])
idx = dt_PureBkg[:,27]
bkg_idx = np.where(idx==0)[0]
signal_idx = np.where(idx==1)[0]
total_PureBkg = torch.tensor(dt_PureBkg[bkg_idx])
total_PureBkg_train_x_1 = total_PureBkg.t()[1:7].t()
total_PureBkg_train_x_2 = total_PureBkg.t()[8:13].t()
total_PureBkg_train_x_3 = total_PureBkg.t()[14:20].t()
total_PureBkg_train_x_4 = total_PureBkg.t()[21:26].t()
total_PureBkg_selection = torch.cat((total_PureBkg_train_x_1,total_PureBkg_train_x_2,total_PureBkg_train_x_3,total_PureBkg_train_x_4),dim=1)
#total_PureBkg_selection = torch.cat((total_PureBkg_train_x_1,total_PureBkg_train_x_3),dim=1)
total_PureBkg_selection.shape
bs = 1000
bkgAE_train_iterator = utils.DataLoader(total_PureBkg_selection, batch_size=bs, shuffle=True)
bkgAE_test_iterator = utils.DataLoader(total_PureBkg_selection, batch_size=bs)
```
## Build the model
```
class VAE_NF(nn.Module):
def __init__(self, K, D):
super().__init__()
self.dim = D
self.K = K
self.encoder = nn.Sequential(
nn.Linear(22, 96),
nn.LeakyReLU(True),
nn.Linear(96, 48),
nn.LeakyReLU(True),
nn.Linear(48, D * 2)
)
self.decoder = nn.Sequential(
nn.Linear(D, 48),
nn.LeakyReLU(True),
nn.Linear(48, 96),
nn.LeakyReLU(True),
nn.Linear(96, 22),
nn.Sigmoid()
)
flow_init = Planar(dim=D)
flows_init = [flow_init for _ in range(K)]
prior = MultivariateNormal(torch.zeros(D).cuda(), torch.eye(D).cuda())
self.flows = NormalizingFlowModel(prior, flows_init)
def forward(self, x):
# Run Encoder and get NF params
enc = self.encoder(x)
mu = enc[:, :self.dim]
log_var = enc[:, self.dim: self.dim * 2]
# Re-parametrize
sigma = (log_var * .5).exp()
z = mu + sigma * torch.randn_like(sigma)
kl_div = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
# Construct more expressive posterior with NF
z_k, _, sum_ladj = self.flows(z)
kl_div = kl_div / x.size(0) - sum_ladj.mean() # mean over batch
# Run Decoder
x_prime = self.decoder(z_k)
return x_prime, kl_div
```
## Creating Instance¶
```
N_EPOCHS = 50
PRINT_INTERVAL = 2000
NUM_WORKERS = 4
LR = 1e-4
N_FLOWS = 3
Z_DIM = 3
n_steps = 0
model = VAE_NF(N_FLOWS, Z_DIM).cuda()
optimizer = optim.Adam(model.parameters(), lr=LR)
def train():
global n_steps
train_loss = []
model.train()
for batch_idx, x in enumerate(bkgAE_train_iterator):
start_time = time.time()
x = x.float().cuda()
x_tilde, kl_div = model(x)
loss_recons = F.binary_cross_entropy(x_tilde, x, size_average=False) / x.size(0)
loss = loss_recons + kl_div
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss.append([loss_recons.item(), kl_div.item()])
if (batch_idx + 1) % PRINT_INTERVAL == 0:
print('\tIter [{}/{} ({:.0f}%)]\tLoss: {} Time: {:5.3f} ms/batch'.format(
batch_idx * len(x), 50000,
PRINT_INTERVAL * batch_idx / 50000,
np.asarray(train_loss)[-PRINT_INTERVAL:].mean(0),
1000 * (time.time() - start_time)
))
n_steps += 1
def evaluate(split='valid'):
global n_steps
start_time = time.time()
val_loss = []
model.eval()
with torch.no_grad():
for batch_idx, x in enumerate(bkgAE_test_iterator):
x = x.float().cuda()
x_tilde, kl_div = model(x)
loss_recons = F.binary_cross_entropy(x_tilde, x, size_average=False) / x.size(0)
loss = loss_recons + kl_div
val_loss.append(loss.item())
#writer.add_scalar('loss/{}/ELBO'.format(split), loss.item(), n_steps)
#writer.add_scalar('loss/{}/reconstruction'.format(split), loss_recons.item(), n_steps)
#writer.add_scalar('loss/{}/KL'.format(split), kl_div.item(), n_steps)
print('\nEvaluation Completed ({})!\tLoss: {:5.4f} Time: {:5.3f} s'.format(
split,
np.asarray(val_loss).mean(0),
time.time() - start_time
))
return np.asarray(val_loss).mean(0)
print(model)
BEST_LOSS = 99999
LAST_SAVED = -1
PATIENCE_COUNT = 0
PATIENCE_LIMIT = 5
for epoch in range(1, N_EPOCHS):
print("Epoch {}:".format(epoch))
train()
cur_loss = evaluate()
if cur_loss <= BEST_LOSS:
PATIENCE_COUNT = 0
BEST_LOSS = cur_loss
LAST_SAVED = epoch
print("Saving model!")
if mode == 'ROC':
torch.save(model.state_dict(),"/data/t3home000/spark/QUASAR/weights/bkg_vae_NF_planar_RND_22var.h5")
else:
torch.save(model.state_dict(), "/data/t3home000/spark/QUASAR/weights/bkg_vae_NF_planar_PureBkg_22var.h5")
else:
PATIENCE_COUNT += 1
print("Not saving model! Last saved: {}".format(LAST_SAVED))
if PATIENCE_COUNT > 5:
print("Patience Limit Reached")
break
model.load_state_dict(torch.load("/data/t3home000/spark/QUASAR/weights/bkg_vae_NF_planar_RND_22var.h5"))
```
## Testing with the trained model
```
def get_mass_and_loss(inputstring):
f_in = pd.read_hdf(inputstring)
dt_in = f_in.values
dt_in[:,1] = (dt_in[:,1]-np.mean(dt_in[:,1]))/np.std(dt_in[:,1])
dt_in[:,2] = (dt_in[:,2]-np.mean(dt_in[:,2]))/np.std(dt_in[:,2])
dt_in[:,3] = (dt_in[:,3]-np.mean(dt_in[:,3]))/np.std(dt_in[:,3])
dt_in[:,4] = (dt_in[:,4]-np.mean(dt_in[:,4]))/np.std(dt_in[:,4])
dt_in[:,5] = (dt_in[:,5]-np.mean(dt_in[:,5]))/np.std(dt_in[:,5])
dt_in[:,6] = (dt_in[:,6]-np.mean(dt_in[:,6]))/np.std(dt_in[:,6])
dt_in[:,8] = (dt_in[:,8]-np.mean(dt_in[:,8]))/np.std(dt_in[:,8])
dt_in[:,9] = (dt_in[:,9]-np.mean(dt_in[:,9]))/np.std(dt_in[:,9])
dt_in[:,10] = (dt_in[:,10]-np.mean(dt_in[:,10]))/np.std(dt_in[:,10])
dt_in[:,11] = (dt_in[:,11]-np.mean(dt_in[:,11]))/np.std(dt_in[:,11])
dt_in[:,12] = (dt_in[:,12]-np.mean(dt_in[:,12]))/np.std(dt_in[:,12])
dt_in[:,14] = (dt_in[:,14]-np.mean(dt_in[:,14]))/np.std(dt_in[:,14])
dt_in[:,15] = (dt_in[:,15]-np.mean(dt_in[:,15]))/np.std(dt_in[:,15])
dt_in[:,16] = (dt_in[:,16]-np.mean(dt_in[:,16]))/np.std(dt_in[:,16])
dt_in[:,17] = (dt_in[:,17]-np.mean(dt_in[:,17]))/np.std(dt_in[:,17])
dt_in[:,18] = (dt_in[:,18]-np.mean(dt_in[:,18]))/np.std(dt_in[:,18])
dt_in[:,19] = (dt_in[:,19]-np.mean(dt_in[:,19]))/np.std(dt_in[:,19])
dt_in[:,21] = (dt_in[:,21]-np.mean(dt_in[:,21]))/np.std(dt_in[:,21])
dt_in[:,22] = (dt_in[:,22]-np.mean(dt_in[:,22]))/np.std(dt_in[:,22])
dt_in[:,23] = (dt_in[:,23]-np.mean(dt_in[:,23]))/np.std(dt_in[:,23])
dt_in[:,24] = (dt_in[:,24]-np.mean(dt_in[:,24]))/np.std(dt_in[:,24])
dt_in[:,25] = (dt_in[:,25]-np.mean(dt_in[:,25]))/np.std(dt_in[:,25])
total_in = torch.tensor(dt_in)
total_in_train_x_1 = total_in.t()[1:7].t()
total_in_train_x_2 = total_in.t()[8:13].t()
total_in_train_x_3 = total_in.t()[14:20].t()
total_in_train_x_4 = total_in.t()[21:26].t()
#total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_2,total_in_train_x_3,total_in_train_x_4),dim=1)
total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_3),dim=1)
with torch.no_grad():
loss_total_in = torch.mean((model(total_in_selection.float().cuda())[0]-
total_in_selection.float().cuda())**2,dim=1).data.cpu().numpy()
f_in = pd.read_hdf(inputstring)
dt_in = f_in.values
return dt_in[:,0], dt_in[:,10], dt_in[:,23], dt_in[:,9], dt_in[:,22], loss_total_in
def get_mass(inputstring):
f_in = pd.read_hdf(inputstring)
dt_in = f_in.values
return dt_in[:,0]
bb2mass = get_mass("../../../2_lhc/LHC_Olympics2020/processing/test_dataset/MassRatio_BB1.h5")
purebkgmass = get_mass("../../../2_lhc/LHC_Olympics2020/processing/test_dataset/MassRatio_pureBkg.h5")
bb2mass, bb2mmdt1, bb2mmdt2, bb2prun1,bb2prun2, bb2loss = get_mass_and_loss("../../../2_lhc/LHC_Olympics2020/processing/test_dataset/MassRatio_BB1.h5")
purebkgmass, purebkgmmdt1, purebkgmmdt2, purebkgprun1,purebkgprun2, purebkgloss = get_mass_and_loss("../../../2_lhc/LHC_Olympics2020/processing/test_dataset/MassRatio_pureBkg.h5")
plt.rcParams["figure.figsize"] = (10,10)
bins = np.linspace(0,5,1100)
plt.hist(bb2loss,bins=bins,alpha=0.3,color='b',label='blackbox1')
plt.hist(purebkgloss,bins=bins,alpha=0.3,color='r',label='background')
plt.xlabel(r'Autoencoder Loss')
plt.ylabel('Count')
plt.legend(loc='upper right')
plt.show()
f = pd.read_hdf("Nsubjettiness_mjj.h5")
dt = f.values
idx = dt[:,15]
bkg_idx = np.where(idx==0)[0]
signal_idx = np.where(idx==1)[0]
data_bkg = torch.tensor(dt[bkg_idx])
data_signal = torch.tensor(dt[signal_idx])
data_train_x_1 = data_bkg.t()[0:6].t()
data_train_x_2 = data_bkg.t()[7:13].t()
data_test_bkg = torch.cat((data_train_x_1,data_train_x_2),dim=1)
data_train_x_1 = data_signal.t()[0:6].t()
data_train_x_2 = data_signal.t()[7:13].t()
data_test_signal = torch.cat((data_train_x_1,data_train_x_2),dim=1)
loss_bkg = torch.mean((model(data_test_bkg.float().cuda())[0]-data_test_bkg.float().cuda())**2,dim=1).data.cpu().numpy()
loss_sig = torch.mean((model(data_test_signal.float().cuda())[0]-data_test_signal.float().cuda())**2,dim=1).data.cpu().numpy()
def get_loss(dt_in):
#dt_in[:,1] = (dt_in[:,1]-np.mean(dt_in[:,1]))/np.std(dt_in[:,1])
#dt_in[:,2] = (dt_in[:,2]-np.mean(dt_in[:,2]))/np.std(dt_in[:,2])
#dt_in[:,3] = (dt_in[:,3]-np.mean(dt_in[:,3]))/np.std(dt_in[:,3])
#dt_in[:,4] = (dt_in[:,4]-np.mean(dt_in[:,4]))/np.std(dt_in[:,4])
#dt_in[:,5] = (dt_in[:,5]-np.mean(dt_in[:,5]))/np.std(dt_in[:,5])
#dt_in[:,6] = (dt_in[:,6]-np.mean(dt_in[:,6]))/np.std(dt_in[:,6])
#dt_in[:,8] = (dt_in[:,8]-np.mean(dt_in[:,8]))/np.std(dt_in[:,8])
#dt_in[:,9] = (dt_in[:,9]-np.mean(dt_in[:,9]))/np.std(dt_in[:,9])
#dt_in[:,10] = (dt_in[:,10]-np.mean(dt_in[:,10]))/np.std(dt_in[:,10])
#dt_in[:,11] = (dt_in[:,11]-np.mean(dt_in[:,11]))/np.std(dt_in[:,11])
#dt_in[:,12] = (dt_in[:,12]-np.mean(dt_in[:,12]))/np.std(dt_in[:,12])
#dt_in[:,14] = (dt_in[:,14]-np.mean(dt_in[:,14]))/np.std(dt_in[:,14])
#dt_in[:,15] = (dt_in[:,15]-np.mean(dt_in[:,15]))/np.std(dt_in[:,15])
#dt_in[:,16] = (dt_in[:,16]-np.mean(dt_in[:,16]))/np.std(dt_in[:,16])
#dt_in[:,17] = (dt_in[:,17]-np.mean(dt_in[:,17]))/np.std(dt_in[:,17])
#dt_in[:,18] = (dt_in[:,18]-np.mean(dt_in[:,18]))/np.std(dt_in[:,18])
#dt_in[:,19] = (dt_in[:,19]-np.mean(dt_in[:,19]))/np.std(dt_in[:,19])
#dt_in[:,21] = (dt_in[:,21]-np.mean(dt_in[:,21]))/np.std(dt_in[:,21])
#dt_in[:,22] = (dt_in[:,22]-np.mean(dt_in[:,22]))/np.std(dt_in[:,22])
#dt_in[:,23] = (dt_in[:,23]-np.mean(dt_in[:,23]))/np.std(dt_in[:,23])
#dt_in[:,24] = (dt_in[:,24]-np.mean(dt_in[:,24]))/np.std(dt_in[:,24])
#dt_in[:,25] = (dt_in[:,25]-np.mean(dt_in[:,25]))/np.std(dt_in[:,25])
total_in = torch.tensor(dt_in)
total_in_train_x_1 = total_in.t()[1:7].t()
total_in_train_x_2 = total_in.t()[8:13].t()
total_in_train_x_3 = total_in.t()[14:20].t()
total_in_train_x_4 = total_in.t()[21:26].t()
total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_2,total_in_train_x_3,total_in_train_x_4),dim=1)
#total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_3),dim=1)
with torch.no_grad():
loss_total_in = torch.mean((model(total_in_selection.float().cuda())[0]- total_in_selection.float().cuda())**2,dim=1).data.cpu().numpy()
return loss_total_in
def get_loss(dt):
#dt[:,0] = (dt[:,0]-np.mean(dt[:,0]))/np.std(dt[:,0])
#dt[:,1] = (dt[:,1]-np.mean(dt[:,1]))/np.std(dt[:,1])
#dt[:,2] = (dt[:,2]-np.mean(dt[:,2]))/np.std(dt[:,2])
#dt[:,3] = (dt[:,3]-np.mean(dt[:,3]))/np.std(dt[:,3])
#dt[:,4] = (dt[:,4]-np.mean(dt[:,4]))/np.std(dt[:,4])
#dt[:,5] = (dt[:,5]-np.mean(dt[:,5]))/np.std(dt[:,5])
#dt[:,7] = (dt[:,7]-np.mean(dt[:,7]))/np.std(dt[:,7])
#dt[:,8] = (dt[:,8]-np.mean(dt[:,8]))/np.std(dt[:,8])
#dt[:,9] = (dt[:,9]-np.mean(dt[:,9]))/np.std(dt[:,9])
#dt[:,10] = (dt[:,10]-np.mean(dt[:,10]))/np.std(dt[:,10])
#dt[:,11] = (dt[:,11]-np.mean(dt[:,11]))/np.std(dt[:,11])
#dt[:,12] = (dt[:,12]-np.mean(dt[:,12]))/np.std(dt[:,12])
total_in = torch.tensor(dt)
total_in_train_x_1 = total_in.t()[0:6].t()
#total_in_train_x_2 = total_in.t()[8:13].t()
total_in_train_x_3 = total_in.t()[7:13].t()
#total_in_train_x_4 = total_in.t()[21:26].t()
#total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_2,total_in_train_x_3,total_in_train_x_4),dim=1)
total_in_selection = torch.cat((total_in_train_x_1,total_in_train_x_3),dim=1)
with torch.no_grad():
loss_total_in = torch.mean((model(total_in_selection.float().cuda())[0]- total_in_selection.float().cuda())**2,dim=1).data.cpu().numpy()
return loss_total_in
loss_bkg = get_loss(dt_PureBkg[bkg_idx])
loss_sig = get_loss(dt_PureBkg[signal_idx])
plt.rcParams["figure.figsize"] = (10,10)
bins = np.linspace(0,5,1100)
plt.hist(loss_bkg,bins=bins,alpha=0.3,color='b',label='bkg')
plt.hist(loss_sig,bins=bins,alpha=0.3,color='r',label='sig')
plt.xlabel(r'Autoencoder Loss')
plt.ylabel('Count')
plt.legend(loc='upper right')
plt.show()
def get_tpr_fpr(sigloss,bkgloss,aetype='sig'):
bins = np.linspace(0,50,1001)
tpr = []
fpr = []
for cut in bins:
if aetype == 'sig':
tpr.append(np.where(sigloss<cut)[0].shape[0]/len(sigloss))
fpr.append(np.where(bkgloss<cut)[0].shape[0]/len(bkgloss))
if aetype == 'bkg':
tpr.append(np.where(sigloss>cut)[0].shape[0]/len(sigloss))
fpr.append(np.where(bkgloss>cut)[0].shape[0]/len(bkgloss))
return tpr,fpr
bkg_tpr, bkg_fpr = get_tpr_fpr(loss_sig,loss_bkg,aetype='bkg')
np.save('NFLOWVAE_PlanarNEW_bkgAE_fpr.npy',bkg_fpr)
np.save('NFLOWVAE_PlanarNEW_bkgAE_tpr.npy',bkg_tpr)
plt.plot(bkg_fpr,bkg_tpr,label='Bkg NFlowVAE-Planar')
def get_precision_recall(sigloss,bkgloss,aetype='bkg'):
bins = np.linspace(0,100,1001)
tpr = []
fpr = []
precision = []
for cut in bins:
if aetype == 'sig':
tpr.append(np.where(sigloss<cut)[0].shape[0]/len(sigloss))
precision.append((np.where(sigloss<cut)[0].shape[0])/(np.where(bkgloss<cut)[0].shape[0]+np.where(sigloss<cut)[0].shape[0]))
if aetype == 'bkg':
tpr.append(np.where(sigloss>cut)[0].shape[0]/len(sigloss))
precision.append((np.where(sigloss>cut)[0].shape[0])/(np.where(bkgloss>cut)[0].shape[0]+np.where(sigloss>cut)[0].shape[0]))
return precision,tpr
precision,recall = get_precision_recall(loss_sig,loss_bkg,aetype='bkg')
np.save('NFLOWVAE_PlanarNEW_22var_sigloss.npy',loss_sig)
np.save('NFLOWVAE_PlanarNEW_22var_bkgloss.npy',loss_bkg)
np.save('NFLOWVAE_PlanarNEW_precision.npy',precision)
np.save('NFLOWVAE_PlanarNEW_recall.npy',recall)
np.save('NFLOWVAE_PlanarNEW_bkgAE_fpr.npy',bkg_fpr)
np.save('NFLOWVAE_PlanarNEW_bkgAE_tpr.npy',bkg_tpr)
np.save('NFLOWVAE_PlanarNEW_sigloss.npy',loss_sig)
np.save('NFLOWVAE_PlanarNEW_bkgloss.npy',loss_bkg)
plt.plot(recall,precision)
flows = [1,2,3,4,5,6]
zdim = [1,2,3,4,5]
for N_flows in flows:
for Z_DIM in zdim:
model = VAE_NF(N_FLOWS, Z_DIM).cuda()
optimizer = optim.Adam(model.parameters(), lr=LR)
BEST_LOSS = 99999
LAST_SAVED = -1
PATIENCE_COUNT = 0
PATIENCE_LIMIT = 5
for epoch in range(1, N_EPOCHS):
print("Epoch {}:".format(epoch))
train()
cur_loss = evaluate()
if cur_loss <= BEST_LOSS:
PATIENCE_COUNT = 0
BEST_LOSS = cur_loss
LAST_SAVED = epoch
print("Saving model!")
if mode == 'ROC':
torch.save(model.state_dict(),f"/data/t3home000/spark/QUASAR/weights/bkg_vae_NF_planar_RND_22var_z{Z_DIM}_f{N_FLOWS}.h5")
else:
torch.save(model.state_dict(), f"/data/t3home000/spark/QUASAR/weights/bkg_vae_NF_planar_PureBkg_22var_z{Z_DIM}_f{N_FLOWS}.h5")
else:
PATIENCE_COUNT += 1
print("Not saving model! Last saved: {}".format(LAST_SAVED))
if PATIENCE_COUNT > 3:
print("Patience Limit Reached")
break
loss_bkg = get_loss(dt_PureBkg[bkg_idx])
loss_sig = get_loss(dt_PureBkg[signal_idx])
np.save(f'NFLOWVAE_PlanarNEW_22var_z{Z_DIM}_f{N_flows}_sigloss.npy',loss_sig)
np.save(f'NFLOWVAE_PlanarNEW_22var_z{Z_DIM}_f{N_flows}_bkgloss.npy',loss_bkg)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
from sklearn import model_selection, metrics
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
train_file='D:\\My Personal Documents\\Learnings\\Data Science\\Data Sets\\AmericanExpress\\train.csv'
test_file='D:\\My Personal Documents\\Learnings\\Data Science\\Data Sets\\AmericanExpress\\test.csv'
user_logs='D:\\My Personal Documents\\Learnings\\Data Science\\Data Sets\\AmericanExpress\\historical_user_logs.csv'
train=pd.read_csv(train_file)
test=pd.read_csv(test_file)
user_log=pd.read_csv(user_logs)
train.corr()
is_click_count= len(train[train.is_click==1])
non_click_indices = train[train.is_click==0].index
random_indices = np.random.choice(non_click_indices,is_click_count*10, replace=False)
click_indices = train[train.is_click==1].index
under_sample_indices = np.concatenate([click_indices,random_indices])
under_sample = train.loc[under_sample_indices]
train=under_sample
sb.countplot(under_sample.is_click)
user_log_view=user_log[user_log.action=='view']
user_log_interest=user_log[user_log.action=='interest']
user_log_interest=user_log_interest.groupby(['user_id','product']).action.count().reset_index()
user_log_interest.rename(columns={'action': 'interest'}, inplace=True)
user_log_interest.head()
user_log_view=user_log_view.groupby(['user_id','product']).action.count().reset_index()
user_log_view.rename(columns={'action': 'view'}, inplace=True)
user_log_view.head()
test.shape
train['source']='train'
test['source']='test'
train=train.append(test)
train.info()
train=pd.merge(train,user_log_interest,how='left', on=['user_id','product'])
train=pd.merge(train,user_log_view,how='left', on=['user_id','product'])
train.info()
#t_click1=train[train.is_click==1]
#train=train.append(t_click1)
#train=train.append(t_click1)
train.isnull().sum()
sb.countplot(train.is_click)
plt.figure(figsize=(12,6))
sb.countplot(x='is_click', hue='product', data=train)
plt.figure(figsize=(12,6))
sb.countplot(x='is_click', hue='gender', data=train)
plt.figure(figsize=(12,6))
sb.countplot(x='is_click', hue='var_1', data=train)
plt.figure(figsize=(12,6))
sb.countplot(x='var_1', hue='is_click', data=train)
```
```
train_label= train.is_click
train.gender=train.gender.fillna('Unknown')
train.city_development_index= train.city_development_index.fillna(method='pad')
train.age_level= train.age_level.fillna(method='pad')
train.user_depth= train.user_depth.fillna(method='pad')
train.user_group_id= train.user_group_id.fillna(method='pad')
train.view=train.view.fillna(0)
train.interest=train.interest.fillna(0)
train=pd.get_dummies(train,columns=['gender','product'])
train.head()
train= train.drop(['DateTime','user_id','product_category_2','session_id'],axis=1)
train.head()
test=train[train.source=='test']
train=train[train.source=='train']
train.drop('source',axis=1,inplace=True)
test.drop('source',axis=1,inplace=True)
train_label=train.is_click
train=train[~(train.city_development_index.isna())]
train.isna().sum()
x=train.drop("is_click",axis=1)
y=train["is_click"]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.3,random_state=22)
from sklearn.linear_model import LogisticRegression
logmod=LogisticRegression()
logmod.fit(x_train,y_train)
pred=logmod.predict(x_test)
from sklearn.metrics import classification_report
classification_report(y_test,pred)
from sklearn.metrics import confusion_matrix
confusion_matrix(y_test,pred)
from sklearn.metrics import accuracy_score
accuracy_score(y_test,pred)
x_test=test.drop("is_click",axis=1)
test_pred=logmod.predict(x_test)
prediction=pd.Series(test_pred.tolist()).astype(int)
prediction.to_csv('D:/My Personal Documents/Learnings/Data Science/Data Sets/AmericanExpress/predictionulgst.csv')
#test.shape
```
| github_jupyter |
# Project1 - Team 5, Studio 1
Annie Chu, SeungU Lyu
### Question: How would the age demographics change over the course of 15 years if the US implemented an one-child policy?
Currently, the US population is 325.7 million, projected to be around 360 million by 2030. Data provided by the US Census also shows the greatest change in population among the 65+ age group, followed by the 18-44 age group, followed by the 45-64 group, and finally the under 18 group. This change may be explained by the evident in the declining fertility, which has dropped to an all time low of 1.76 children/female.
We aimed to explore how the age group demographics would shift over 15 years if the US had implemented a one-child policy, essentially viewing how the US population would change if the fertility dropped to less than 1 child/female.
```
# 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 functions from the modsim.py module
from modsim import *
# importing "copy" for copy operations
import copy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
```
### Initial Data Pulls
#### Initial Population Data by Age Range and Gender (0-4, 5-9, etc)
```
pop_init_data = pd.read_csv('data/pop_2017_US.csv', index_col='age')
```
Source: https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=bkmk
#### Death Rate Data by Age Group and Gender (0, 1-4, 5-9, etc)
```
death_rate_data = pd.read_csv('data/age_death_rate.csv', index_col='age')
```
Source: https://www.statista.com/statistics/241488/population-of-the-us-by-sex-and-age/
#### Probability of Woman Ever Having a Child by Age Group (15-19, 20-24, etc)
```
child_ever_data = pd.read_csv('data/child_ever_born.csv', index_col='age')
```
Source: Fertility of Women in the United States: 2012, Lindsay M. Monte and Renee R. Ellis
#### Probability of Woman Having First Child by Age
```
first_birth_data = pd.read_csv('data/first_birth_rate.csv', index_col='age')
```
Source: https://www.cdc.gov/nchs/nvss/births.htm
#### Adapting Initial Population Data into Age Groups
```
male_pop = linspace(0,0,90)
female_pop = linspace(0,0,90)
ident = 4
for i in range(90):
if i>ident:
ident += 5
male_pop[i] = int(pop_init_data.male[ident]/5)
female_pop[i] = int(pop_init_data.female[ident]/5)
female_pop[0] #test
```
#### Setting Initial Population State by Gender
```
init_population = State(male = male_pop, female = female_pop)
```
#### Storing Model Parameters in a System Object
```
system = System(male_death = death_rate_data.male,
female_death = death_rate_data.female,
child_ever = child_ever_data.percentage,
first_rate = first_birth_data.percentage,
t_0 = 2018,
t_end = 2033,
init_pop = init_population)
```
#### Creating State object to initialize arrays for the 3 different groups: Males, Females who haven't had the chance to have a child, Females who have had the chance to have a child
```
population = State(male = copy.deepcopy(system.init_pop.male), female = copy.deepcopy(system.init_pop.female), female_w = linspace(0,0,90))
```
#### Assigning Population Value to 2 Female Groups Above
```
ident = 19
for i in range(15,49):
if i>ident:
ident += 5
population.female_w[i] = int(population.female[i]*system.child_ever[ident])
population.female[i] = int(population.female[i]*(1-system.child_ever[ident]))
```
#### Implementation of Relative Gender Death Rate to 3 Groups
```
def update_func_death(state,system):
ident = 4
state.male[0] = int(state.male[0] * (1-system.male_death[0]))
state.female[0] = int(state.female[0] * (1-system.female_death[0]))
for i in range(1,90):
if i>ident:
ident += 5
state.male[i] = int(state.male[i] * (1-system.male_death[ident]))
state.female[i] = int(state.female[i] * (1-system.female_death[ident]))
state.female_w[i] = int(state.female_w[i] * (1-system.female_death[ident]))
return state
```
#### Implementation of Birth Rate: Creating Newborns + Shifting Female Group (those who still have potential to give birth) to Female_W Group (those who no longer do)
```
def update_func_birth(state,system):
baby_total = 0
for i in range(15,50):
baby = int(state.female[i]*system.first_rate[i])
state.female[i] -= baby
state.female_w[i] += baby
baby_total += baby
return baby_total
```
#### Updating Population Age + New Births: Initializing New Births to Female/Male to 0 Age Group and Shifting All Ages Up by one
```
def update_func_pop(baby,state,system):
for i in range(89):
k = 89-i
state.male[k] = state.male[k-1]
state.female[k] = state.female[k-1]
state.female_w[k] = state.female_w[k-1]
state.male[0] = int(baby/2)
state.female[0] = int(baby/2)
return state
```
#### General adding function to find total population among 3 groups (male, female, female_w)
```
def addall(state):
total = 0
for i in range(90):
total = total + state.male[i] + state.female[i] + state.female_w[i]
return total
```
#### Function used to create TimeSeries with Total Population
```
def run_population(system, state, update_func_death, update_func_birth, update_func_pop, addall):
nstate = State(male = copy.deepcopy(state.male), female = copy.deepcopy(state.female), female_w = copy.deepcopy(state.female_w))
results = TimeSeries()
for t in linrange(system.t_0, system.t_end):
nstate = update_func_death(nstate,system)
baby = update_func_birth(nstate,system)
nstate = update_func_pop(baby,nstate,system)
totalpop = addall(nstate)
results[t+1] = totalpop
return results
```
#### Adding function used to define what the age groups are and their subsequent total population within that age group
Shown later, we split the population into 5 age groups: 0-14, 15-30, 31-49, 50-70, 71-89. The end age is 89 because the initial data pull age limit is 89.
```
def agedemos(num_s, num_e, state):
age_total = 0
for i in range(num_s, num_e+1):
age_total = age_total + state.male[i] + state.female[i] + state.female_w[i]
return age_total
```
#### Function used to create TimeSeries with Total Age Group Values
```
def age_group(system, state, update_func_death, update_func_birth, update_func_pop, agedemos):
nstate = State(male = copy.deepcopy(state.male), female = copy.deepcopy(state.female), female_w = copy.deepcopy(state.female_w))
demo_state = State(ag_one = TimeSeries(), ag_two = TimeSeries(), ag_three = TimeSeries(), ag_four = TimeSeries(), ag_five = TimeSeries())
for t in linrange(system.t_0, system.t_end):
nstate = update_func_death(nstate,system)
baby = update_func_birth(nstate,system)
nstate = update_func_pop(baby,nstate,system)
demo_state.ag_one[t+1] = agedemos(0,14,nstate)
demo_state.ag_two[t+1] = agedemos(15,30,nstate)
demo_state.ag_three[t+1] = agedemos(31,49,nstate)
demo_state.ag_four[t+1] = agedemos(50,70,nstate)
demo_state.ag_five[t+1] = agedemos(71,89,nstate)
return demo_state
```
#### Function used to create TimeSeries with Total Age Group Percentages (demographics)
```
def age_group_per(system, state, update_func_death, update_func_birth, update_func_pop, agedemos, addall):
nstate = State(male = copy.deepcopy(state.male), female = copy.deepcopy(state.female), female_w = copy.deepcopy(state.female_w))
demo_state = State(ag_one = TimeSeries(), ag_two = TimeSeries(), ag_three = TimeSeries(), ag_four = TimeSeries(), ag_five = TimeSeries())
for t in linrange(system.t_0, system.t_end):
nstate = update_func_death(nstate,system)
baby = update_func_birth(nstate,system)
nstate = update_func_pop(baby,nstate,system)
totalpop = addall(nstate)
demo_state.ag_one[t+1] = agedemos(0,14,nstate)*100/totalpop
demo_state.ag_two[t+1] = agedemos(15,30,nstate)*100/totalpop
demo_state.ag_three[t+1] = agedemos(31,50,nstate)*100/totalpop
demo_state.ag_four[t+1] = agedemos(51,70,nstate)*100/totalpop
demo_state.ag_five[t+1] = agedemos(71,89,nstate)*100/totalpop
return demo_state
```
Viewing Total Age Group Demographic (Values) by Year
```
demo = age_group(system, population, update_func_death, update_func_birth, update_func_pop, agedemos)
```
Viewing Total Age Group Demographic (Percentages) by Year
```
demo_per = age_group_per(system, population, update_func_death, update_func_birth, update_func_pop, agedemos, addall)
```
Viewing Total Population by Year
```
results = run_population(system, population, update_func_death, update_func_birth, update_func_pop, addall)
```
Creating a TimeSeries Adding All Age Group Values to Check Consistency with Total Population
```
check = TimeSeries()
for i in linrange(system.t_0, system.t_end):
check = demo.ag_one + demo.ag_two + demo.ag_three + demo.ag_four + demo.ag_five
check
```
#### Plotting Results
Plotting Total Population by Year -- Line Graph
```
plot(results, ':', label='Total World Population')
decorate(xlabel='Year',
ylabel='World population (billion)',
title='Total World Population Over 15 Years')
```
Plotting Age Group Demographics (Value) by Year -- Line Graph
```
plot(demo.ag_one, label = '0-14')
plot(demo.ag_two, label = '15-30')
plot(demo.ag_three, label = '31-50')
plot(demo.ag_four, label = '51-70')
plot(demo.ag_five, label = '71-89')
decorate(xlabel='Year',
ylabel='World population (billion)',
title='Total World Population Over 15 Years')
```
Plotting Age Group Demographics (Value) by Year -- Stacked Bar Graph
```
# Values of each group
bars1 = demo.ag_one
bars2 = demo.ag_two
bars3 = demo.ag_three
bars4 = demo.ag_four
bars5 = demo.ag_five
# The position of the bars on the x-axis-timerange
r = linrange(system.t_0+1, system.t_end+1)
#setting bar width
barWidth = 0.97
plt.figure(figsize=(15, 8))
# Create brown bars
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
# Create green bars (middle), on top of the firs ones
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
# Create green bars (top)
plt.bar(r, bars3, bottom=bars1+bars2, color='#2d7f5e', edgecolor='white', width=barWidth)
# Create Blue bars
plt.bar(r, bars4, bottom=bars1+bars2+bars3, color='#2E9BC8', edgecolor='white', width=barWidth)
#Create yellow bars
plt.bar(r, bars5, bottom=bars1+bars2+bars3+bars4, color='#AFA928', edgecolor='white', width=barWidth)
# Custom axis
plt.xticks(r)
plt.xlabel("Time")
plt.ylabel("Population")
plt.title('U.S Population Over 15 years', fontweight = 'bold')
group = ['0-14','15-30','31-49','50-70','71-89']
plt.legend(group,loc=4)
# Show graphic
plt.show()
```
Plotting Age Group Demographics (Percent) by Year -- Line Graph
```
plot(demo_per.ag_one, label = '0-14')
plot(demo_per.ag_two, label = '15-30')
plot(demo_per.ag_three, label = '31-50')
plot(demo_per.ag_four, label = '51-70')
plot(demo_per.ag_five, label = '71-89')
decorate(xlabel='Year',
ylabel='World population (billion)',
title='Total World Population Over 15 Years')
```
Plotting Age Group Demographics (Value) by Year -- Stacked Bar Graph
```
# Values of each group
bars1 = demo_per.ag_one
bars2 = demo_per.ag_two
bars3 = demo_per.ag_three
bars4 = demo_per.ag_four
bars5 = demo_per.ag_five
# The position of the bars on the x-axis-timerange
r = linrange(system.t_0+1, system.t_end+1)
#setting bar width
barWidth = 0.97
plt.figure(figsize=(15, 8))
# Create brown bars
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
# Create green bars (middle), on top of the firs ones
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
# Create green bars (top)
plt.bar(r, bars3, bottom=bars1+bars2, color='#2d7f5e', edgecolor='white', width=barWidth)
# Create Blue bars
plt.bar(r, bars4, bottom=bars1+bars2+bars3, color='#2E9BC8', edgecolor='white', width=barWidth)
#Create yellow bars
plt.bar(r, bars5, bottom=bars1+bars2+bars3+bars4, color='#AFA928', edgecolor='white', width=barWidth)
# Custom axis
plt.xticks(r)
plt.xlabel("Time")
plt.ylabel("Percentage")
plt.title('U.S Age Demographic over 15 years', fontweight = 'bold')
group = ['0-14','15-30','31-49','50-70','71-89']
plt.legend(group,loc=4)
# Show graphic
plt.show()
```
The graphs above show the change in age demographics within the US over the course of 15 years if a one-child policy was implemented.
Based on this model, total population seems to be dropping at a fairly linear rate. Within the total population, the
This model
Limitations:
1. Not accounting for twins
2. birth/death rate assuming constant for next 15 years
3. Assumption of gender birth ratio
4. No immigrants
5. Data not the most recent
| github_jupyter |
<h1>Weather on Mars - Training Notebook</h1>
<h2>Training for prediction of temperature based on empirical data collected by Curiosity Mars Rover</h2>
```
runLocallyOrOnDrive = 'Drive' # 'Drive' or 'Local', this variable only saves the prediction model to drive or local
#if 'Local' change the paths below to local paths e.g. r'C:/Users/..'
#@title Connect to Google Drive if runLocallyOrOnDrive=='Drive'
if runLocallyOrOnDrive == "Drive":
from google.colab import drive
drive.mount('/content/drive/')
#@title Change these file paths to your respective
#Google drive folder, but it can also be local e.g. on your C-disk
if runLocallyOrOnDrive == 'Local':
saveModelPath = r'/media/../model.json' # create Alphabet folder on disk
saveModelPathH5 = r'media/../model.h5'
elif runLocallyOrOnDrive == 'Drive':
saveModelPath = r'/content/../model.json' # create Alphabet folder on disk
saveModelPathH5 = r'/content/../model.h5'
#@title Import libraries
# # If you want to loads file, upload to drive and run the following
import urllib, json
# import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from keras.layers import Bidirectional,LSTM,Dense,Flatten,Conv1D,MaxPooling1D,Dropout,RepeatVector
from keras.models import Sequential
from keras.callbacks import EarlyStopping,ReduceLROnPlateau
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
loadHistoricalDataFrom = "API" # "Drive", "API" and "HBASE" work
#@title Import more libraries if HBASE if choosen
if loadHistoricalDataFrom == "HBASE":
#import hbase library
#pip install hbase-python
import hbase
#@title Functions: Load Data
def loadDataFromHBase():
zk = '127.0.0.1:2181'
hbaseData = []
#got connection issue but followed instruction herein: https://github.com/3601314/hbase-python/issues/4
#added "table = table.replace('default:','')" on lineno 195 in
# ~/anaconda2/lib/python3.5/site-packages/hbase/client/region.py
with hbase.ConnectionPool(zk).connect() as conn:
table = conn['default']['archive']
for row in table.scan():
hbaseData.append(row)
column_names = ["terrestrial_date", "min_temp", "max_temp"]
data = pd.DataFrame(columns = column_names)
for d in hbaseData:
terrestrial_date = d.get("cf:wind_speed").decode("utf-8")
min_temp = d.get("cf:season").decode("utf-8")
max_temp = d.get("cf:ls").decode("utf-8")
hbase_data = {'terrestrial_date': terrestrial_date, 'min_temp': min_temp, 'max_temp': max_temp}
data = data.append(hbase_data, ignore_index=True)
return data
def loadHistoricalData():
if loadHistoricalDataFrom == "API":
archiveUrl = 'https://pudding.cool/2017/12/mars-data/marsWeather.json'
data = pd.DataFrame(pd.DataFrame(json.loads(urllib.request.urlopen(archiveUrl).read().decode('utf-8'))))
return data
elif loadHistoricalDataFrom == "Drive":
data = pd.read_csv('/content/drive/My Drive/ID2221 Data Intensive Computing/Final Project/Data/mars-weather.csv')
return data
elif loadHistoricalDataFrom == "HBASE":
data = loadDataFromHBase()
return data
# returns the (average) weather data for a top level key [sol] from [sol_keys]
def findAtAndPre(dictionary, key):
value = dictionary.get(key)
return {'AT': value.get('AT')['av'], 'PRE': value.get('PRE')['av']}
def loadRecentNDaysOfData(NDays):
# returns the data of the latest 7 days
apiUrl = 'https://api.nasa.gov/insight_weather/?api_key=DEMO_KEY&feedtype=json&ver=1.0'
jsonApi = json.loads(urllib.request.urlopen(apiUrl).read())
dfApi = pd.DataFrame({key: findAtAndPre(jsonApi, key) for key in jsonApi.get('sol_keys')})
return dfApi
data = loadHistoricalData()
data['min_temp'] = pd.to_numeric(data['min_temp'], downcast="float")
data['max_temp'] = pd.to_numeric(data['max_temp'], downcast="float")
data['avg_temp'] = data[['min_temp', 'max_temp']].mean(axis=1)
data['terrestrial_date']=pd.to_datetime(data['terrestrial_date'])
df_avg_temp=pd.DataFrame(list(data['avg_temp']), index=data['terrestrial_date'], columns=['temp'])
df_avg_temp.fillna(data['avg_temp'].mean(),inplace=True)
scaler=MinMaxScaler(feature_range=(-1,1))
scData =scaler.fit_transform(df_avg_temp)
windowsDays=7
outputs=[]
inputs=[]
for i in range(len(scData)-windowsDays): #create the 7 day windows for training
inputs.append(scData[i:i+windowsDays])
outputs.append(scData[i+windowsDays])
outputs=np.asanyarray(outputs)
inputs=np.asanyarray(inputs)
trainingDays = int(np.round(len(inputs)*0.85,0)) #split the training data so that we have some test data below
# NOTE that we will also have validation data in the training
tr_x=inputs[:trainingDays,:,:]
tr_y=outputs[:trainingDays]
tst_x=inputs[trainingDays:,:,:]
tst_y=outputs[trainingDays:]
model=keras.Sequential([
LSTM(128,activation='relu',input_shape=(windowsDays,1), return_sequences=True),
Bidirectional(LSTM(64,activation='relu')), #train two instead of one LSTMs on the input sequence
Dense(1)
]
)
model.compile(optimizer='adam',loss='mse', metrics=['MeanAbsoluteError'])
# early_stop=EarlyStopping(monitor='val_loss',patience=5)
history = model.fit(tr_x,tr_y,epochs=10,verbose=1,validation_split=0.15)#,callbacks=[early_stop]) #validation data split at 15%
plt.plot(history.history['loss'], label='loss train')
plt.plot(history.history['val_loss'], label='loss val')
plt.legend();
trained = scaler.inverse_transform(tr_y)
predicted=scaler.inverse_transform(model.predict(tst_x))
actual=scaler.inverse_transform(tst_y)
plt.figure(figsize=(17,5))
plt.plot(np.arange(0, len(tr_y)), trained, 'g', label="history")
plt.plot(np.arange(len(tr_y), len(tr_y) + len(tst_y)), actual, marker='.', label="true")
plt.plot(np.arange(len(tr_y), len(tr_y) + len(tst_y)), predicted, 'r', label="prediction")
plt.ylabel('Temperature')
plt.xlabel('Time Step')
plt.legend()
plt.show();
#serialize mode to JSON
from keras.models import model_from_json
model_json = model.to_json()
with open(saveModelPath,"w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights(saveModelPathH5)
print("Saved model to disk")
#@title Load Model JSON for testing
#serialize mode to JSON
from tensorflow.keras.models import model_from_json
json_file = open(saveModelPath,"r")
model_json = json_file.read()
json_file.close()
model_fromDisk = model_from_json(model_json)
#load weights into the new model
model_fromDisk.load_weights(saveModelPathH5)
print("loaded from disk")
```
Here is how the model from disk predicts:
```
scaler.inverse_transform(model_fromDisk.predict(tst_x))[0]
```
In comparison to above i.e. the same. Thereby, loading from disk works fine:
```
predicted[0]
```
| github_jupyter |
```
!python -c "import monai" || pip install -q "monai-weekly[gdown, tqdm]"
import gdown
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import jit
from monai.apps.deepgrow.transforms import (
AddGuidanceFromPointsd,
AddGuidanceSignald,
ResizeGuidanced,
RestoreLabeld,
SpatialCropGuidanced,
)
from monai.transforms import (
AsChannelFirstd,
Spacingd,
LoadImaged,
AddChanneld,
NormalizeIntensityd,
EnsureTyped,
ToNumpyd,
Activationsd,
AsDiscreted,
Resized
)
max_epochs = 1
def draw_points(guidance, slice_idx):
if guidance is None:
return
colors = ['r+', 'b+']
for color, points in zip(colors, guidance):
for p in points:
if p[0] != slice_idx:
continue
p1 = p[-1]
p2 = p[-2]
plt.plot(p1, p2, color, 'MarkerSize', 30)
def show_image(image, label, guidance=None, slice_idx=None):
plt.figure("check", (12, 6))
plt.subplot(1, 2, 1)
plt.title("image")
plt.imshow(image, cmap="gray")
if label is not None:
masked = np.ma.masked_where(label == 0, label)
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
draw_points(guidance, slice_idx)
plt.colorbar()
if label is not None:
plt.subplot(1, 2, 2)
plt.title("label")
plt.imshow(label)
plt.colorbar()
# draw_points(guidance, slice_idx)
plt.show()
def print_data(data):
for k in data:
v = data[k]
d = type(v)
if type(v) in (int, float, bool, str, dict, tuple):
d = v
elif hasattr(v, 'shape'):
d = v.shape
if k in ('image_meta_dict', 'label_meta_dict'):
for m in data[k]:
print('{} Meta:: {} => {}'.format(k, m, data[k][m]))
else:
print('Data key: {} = {}'.format(k, d))
# Download data and model
resource = "https://drive.google.com/uc?id=1cIlDXWx4pEFpldoIXMEe-5JeaOxzB05Z"
dst = "_image.nii.gz"
if not os.path.exists(dst):
gdown.download(resource, dst, quiet=False)
resource = "https://drive.google.com/uc?id=1BcU4Z-wdkw7xjydDNd28iVBUVDJYKqCO"
dst = "deepgrow_3d.ts"
if not os.path.exists(dst):
gdown.download(resource, dst, quiet=False)
# Pre Processing
roi_size = [256, 256]
model_size = [128, 192, 192]
pixdim = (1.0, 1.0, 1.0)
dimensions = 3
data = {
'image': '_image.nii.gz',
'foreground': [[66, 180, 105], [66, 180, 145]],
'background': [],
}
slice_idx = original_slice_idx = data['foreground'][0][2]
pre_transforms = [
LoadImaged(keys='image'),
AsChannelFirstd(keys='image'),
Spacingd(keys='image', pixdim=pixdim, mode='bilinear'),
AddGuidanceFromPointsd(ref_image='image', guidance='guidance', foreground='foreground', background='background',
dimensions=dimensions),
AddChanneld(keys='image'),
SpatialCropGuidanced(keys='image', guidance='guidance', spatial_size=roi_size),
Resized(keys='image', spatial_size=model_size, mode='area'),
ResizeGuidanced(guidance='guidance', ref_image='image'),
NormalizeIntensityd(keys='image', subtrahend=208.0, divisor=388.0),
AddGuidanceSignald(image='image', guidance='guidance'),
EnsureTyped(keys='image')
]
original_image = None
for t in pre_transforms:
tname = type(t).__name__
data = t(data)
image = data['image']
label = data.get('label')
guidance = data.get('guidance')
print("{} => image shape: {}".format(tname, image.shape))
guidance = guidance if guidance else [np.roll(data['foreground'], 1).tolist(), []]
slice_idx = guidance[0][0][0] if guidance else slice_idx
print('Guidance: {}; Slice Idx: {}'.format(guidance, slice_idx))
if tname == 'Resized':
continue
image = image[:, :, slice_idx] if tname in ('LoadImaged') else image[slice_idx] if tname in (
'AsChannelFirstd', 'Spacingd', 'AddGuidanceFromPointsd') else image[0][slice_idx]
label = None
show_image(image, label, guidance, slice_idx)
if tname == 'LoadImaged':
original_image = data['image']
if tname == 'AddChanneld':
original_image_slice = data['image']
if tname == 'SpatialCropGuidanced':
spatial_image = data['image']
image = data['image']
label = data.get('label')
guidance = data.get('guidance')
for i in range(image.shape[1]):
print('Slice Idx: {}'.format(i))
# show_image(image[0][i], None, guidance, i)
# Evaluation
model_path = 'deepgrow_3d.ts'
model = jit.load(model_path)
model.cuda()
model.eval()
inputs = data['image'][None].cuda()
with torch.no_grad():
outputs = model(inputs)
outputs = outputs[0]
data['pred'] = outputs
post_transforms = [
Activationsd(keys='pred', sigmoid=True),
AsDiscreted(keys='pred', threshold_values=True, logit_thresh=0.5),
ToNumpyd(keys='pred'),
RestoreLabeld(keys='pred', ref_image='image', mode='nearest'),
]
pred = None
for t in post_transforms:
tname = type(t).__name__
data = t(data)
image = data['image']
label = data['pred']
print("{} => image shape: {}, pred shape: {}; slice_idx: {}".format(tname, image.shape, label.shape, slice_idx))
if tname in 'RestoreLabeld':
pred = label
image = original_image[:, :, original_slice_idx]
label = label[original_slice_idx]
print("PLOT:: {} => image shape: {}, pred shape: {}; min: {}, max: {}, sum: {}".format(
tname, image.shape, label.shape, np.min(label), np.max(label), np.sum(label)))
show_image(image, label)
elif tname == 'xToNumpyd':
for i in range(label.shape[1]):
img = image[0, i, :, :].detach().cpu().numpy() if torch.is_tensor(image) else image[0][i]
lab = label[0, i, :, :].detach().cpu().numpy() if torch.is_tensor(label) else label[0][i]
if np.sum(lab) > 0:
print("PLOT:: {} => image shape: {}, pred shape: {}; min: {}, max: {}, sum: {}".format(
i, img.shape, lab.shape, np.min(lab), np.max(lab), np.sum(lab)))
show_image(img, lab)
else:
image = image[0, slice_idx, :, :].detach().cpu().numpy() if torch.is_tensor(image) else image[0][slice_idx]
label = label[0, slice_idx, :, :].detach().cpu().numpy() if torch.is_tensor(label) else label[0][slice_idx]
print("PLOT:: {} => image shape: {}, pred shape: {}; min: {}, max: {}, sum: {}".format(
tname, image.shape, label.shape, np.min(label), np.max(label), np.sum(label)))
show_image(image, label)
for i in range(pred.shape[0]):
image = original_image[:, :, i]
label = pred[i, :, :]
if np.sum(label) == 0:
continue
print("Final PLOT:: {} => image shape: {}, pred shape: {}; min: {}, max: {}, sum: {}".format(
i, image.shape, label.shape, np.min(label), np.max(label), np.sum(label)))
show_image(image, label)
pred = data['pred']
meta_data = data['pred_meta_dict']
affine = meta_data.get("affine", None)
pred = np.moveaxis(pred, 0, -1)
print('Prediction NII shape: {}'.format(pred.shape))
# file_name = 'result_label.nii.gz'
# write_nifti(pred, file_name=file_name)
# print('Prediction saved at: {}'.format(file_name))
# remove downloaded files
os.remove('_image.nii.gz')
os.remove('deepgrow_3d.ts')
```
| github_jupyter |

# INTRODUCTION
In this data analysis report, I usually focus on feature visualization and selection as a different from other kernels. Feature selection with correlation, univariate feature selection, recursive feature elimination, recursive feature elimination with cross validation and tree based feature selection methods are used with random forest classification. Apart from these, principle component analysis are used to observe number of components.
**Enjoy your data analysis!!!**
# Data Analysis
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns # data visualization library
import matplotlib.pyplot as plt
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import time
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
# Any results you write to the current directory are saved as output.
data = pd.read_csv('../input/data.csv')
```
Before making anything like feature selection,feature extraction and classification, firstly we start with basic data analysis.
Lets look at features of data.
```
data.head() # head method show only first 5 rows
```
**There are 4 things that take my attention**
1) There is an **id** that cannot be used for classificaiton
2) **Diagnosis** is our class label
3) **Unnamed: 32** feature includes NaN so we do not need it.
4) I do not have any idea about other feature names actually I do not need because machine learning is awesome **:)**
Therefore, drop these unnecessary features. However do not forget this is not a feature selection. This is like a browse a pub, we do not choose our drink yet !!!
```
# feature names as a list
col = data.columns # .columns gives columns names in data
print(col)
# y includes our labels and x includes our features
y = data.diagnosis # M or B
list = ['Unnamed: 32','id','diagnosis']
x = data.drop(list,axis = 1 )
x.head()
ax = sns.countplot(y,label="Count") # M = 212, B = 357
B, M = y.value_counts()
print('Number of Benign: ',B)
print('Number of Malignant : ',M)
```
Okey, now we have features but **what does they mean** or actually **how much do we need to know about these features**
The answer is that we do not need to know meaning of these features however in order to imagine in our mind we should know something like variance, standart deviation, number of sample (count) or max min values.
These type of information helps to understand about what is going on data. For example , the question is appeared in my mind the **area_mean** feature's max value is 2500 and **smoothness_mean** features' max 0.16340. Therefore **do we need standirdization or normalization before visualization, feature selection, feature extraction or classificaiton?** The answer is yes and no not surprising ha :) Anyway lets go step by step and start with visualization.
```
x.describe()
```
# Visualization
In order to visualizate data we are going to use seaborn plots that is not used in other kernels to inform you and for diversity of plots. What I use in real life is mostly violin plot and swarm plot. Do not forget we are not selecting feature, we are trying to know data like looking at the drink list at the pub door.
Before violin and swarm plot we need to normalization or standirdization. Because differences between values of features are very high to observe on plot. I plot features in 3 group and each group includes 10 features to observe better.
```
# first ten features
data_dia = y
data = x
data_n_2 = (data - data.mean()) / (data.std()) # standardization
data = pd.concat([y,data_n_2.iloc[:,0:10]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
sns.violinplot(x="features", y="value", hue="diagnosis", data=data,split=True, inner="quart")
plt.xticks(rotation=90)
```
Lets interpret the plot above together. For example, in **texture_mean** feature, median of the *Malignant* and *Benign* looks like separated so it can be good for classification. However, in **fractal_dimension_mean** feature, median of the *Malignant* and *Benign* does not looks like separated so it does not gives good information for classification.
```
# Second ten features
data = pd.concat([y,data_n_2.iloc[:,10:20]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
sns.violinplot(x="features", y="value", hue="diagnosis", data=data,split=True, inner="quart")
plt.xticks(rotation=90)
# Second ten features
data = pd.concat([y,data_n_2.iloc[:,20:31]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
sns.violinplot(x="features", y="value", hue="diagnosis", data=data,split=True, inner="quart")
plt.xticks(rotation=90)
# As an alternative of violin plot, box plot can be used
# box plots are also useful in terms of seeing outliers
# I do not visualize all features with box plot
# In order to show you lets have an example of box plot
# If you want, you can visualize other features as well.
plt.figure(figsize=(10,10))
sns.boxplot(x="features", y="value", hue="diagnosis", data=data)
plt.xticks(rotation=90)
```
Lets interpret one more thing about plot above, variable of **concavity_worst** and **concave point_worst** looks like similar but how can we decide whether they are correlated with each other or not.
(Not always true but, basically if the features are correlated with each other we can drop one of them)
In order to compare two features deeper, lets use joint plot. Look at this in joint plot below, it is really correlated.
Pearsonr value is correlation value and 1 is the highest. Therefore, 0.86 is looks enough to say that they are correlated.
Do not forget, we are not choosing features yet, we are just looking to have an idea about them.
```
sns.jointplot(x.loc[:,'concavity_worst'], x.loc[:,'concave points_worst'], kind="regg", color="#ce1414")
```
What about three or more feauture comparision ? For this purpose we can use pair grid plot. Also it seems very cool :)
And we discover one more thing **radius_worst**, **perimeter_worst** and **area_worst** are correlated as it can be seen pair grid plot. We definetely use these discoveries for feature selection.
```
sns.set(style="white")
df = x.loc[:,['radius_worst','perimeter_worst','area_worst']]
g = sns.PairGrid(df, diag_sharey=False)
g.map_lower(sns.kdeplot, cmap="Blues_d")
g.map_upper(plt.scatter)
g.map_diag(sns.kdeplot, lw=3)
```
Up to this point, we make some comments and discoveries on data already. If you like what we did, I am sure swarm plot will open the pub's door :)
In swarm plot, I will do three part like violin plot not to make plot very complex appearance
```
sns.set(style="whitegrid", palette="muted")
data_dia = y
data = x
data_n_2 = (data - data.mean()) / (data.std()) # standardization
data = pd.concat([y,data_n_2.iloc[:,0:10]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
tic = time.time()
sns.swarmplot(x="features", y="value", hue="diagnosis", data=data)
plt.xticks(rotation=90)
data = pd.concat([y,data_n_2.iloc[:,10:20]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
sns.swarmplot(x="features", y="value", hue="diagnosis", data=data)
plt.xticks(rotation=90)
data = pd.concat([y,data_n_2.iloc[:,20:31]],axis=1)
data = pd.melt(data,id_vars="diagnosis",
var_name="features",
value_name='value')
plt.figure(figsize=(10,10))
sns.swarmplot(x="features", y="value", hue="diagnosis", data=data)
toc = time.time()
plt.xticks(rotation=90)
print("swarm plot time: ", toc-tic ," s")
```
They looks cool right. And you can see variance more clear. Let me ask you a question, **in these three plots which feature looks like more clear in terms of classification.** In my opinion **area_worst** in last swarm plot looks like malignant and benign are seprated not totaly but mostly. Hovewer, **smoothness_se** in swarm plot 2 looks like malignant and benign are mixed so it is hard to classfy while using this feature.
**What if we want to observe all correlation between features?** Yes, you are right. The answer is heatmap that is old but powerful plot method.
```
#correlation map
f,ax = plt.subplots(figsize=(18, 18))
sns.heatmap(x.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)
```
Well, finaly we are in the pub and lets choose our drinks at feature selection part while using heatmap(correlation matrix).
# Feature Selection and Random Forest Classification
Today our purpuse is to try new cocktails. For example, we are finaly in the pub and we want to drink different tastes. Therefore, we need to compare ingredients of drinks. If one of them includes lemon, after drinking it we need to eliminate other drinks which includes lemon so as to experience very different tastes.
In this part we will select feature with different methods that are feature selection with correlation, univariate feature selection, recursive feature elimination (RFE), recursive feature elimination with cross validation (RFECV) and tree based feature selection. We will use random forest classification in order to train our model and predict.
## 1) Feature selection with correlation and random forest classification
As it can be seen in map heat figure **radius_mean, perimeter_mean and area_mean** are correlated with each other so we will use only **area_mean**. If you ask how i choose **area_mean** as a feature to use, well actually there is no correct answer, I just look at swarm plots and **area_mean** looks like clear for me but we cannot make exact separation among other correlated features without trying. So lets find other correlated features and look accuracy with random forest classifier.
**Compactness_mean, concavity_mean and concave points_mean** are correlated with each other.Therefore I only choose **concavity_mean**. Apart from these, **radius_se, perimeter_se and area_se** are correlated and I only use **area_se**. **radius_worst, perimeter_worst and area_worst** are correlated so I use **area_worst**. **Compactness_worst, concavity_worst and concave points_worst** so I use **concavity_worst**. **Compactness_se, concavity_se and concave points_se** so I use **concavity_se**. **texture_mean and texture_worst are correlated** and I use **texture_mean**. **area_worst and area_mean** are correlated, I use **area_mean**.
```
drop_list1 = ['perimeter_mean','radius_mean','compactness_mean','concave points_mean','radius_se','perimeter_se','radius_worst','perimeter_worst','compactness_worst','concave points_worst','compactness_se','concave points_se','texture_worst','area_worst']
x_1 = x.drop(drop_list1,axis = 1 ) # do not modify x, we will use it later
x_1.head()
```
After drop correlated features, as it can be seen in below correlation matrix, there are no more correlated features. Actually, I know and you see there is correlation value 0.9 but lets see together what happen if we do not drop it.
```
#correlation map
f,ax = plt.subplots(figsize=(14, 14))
sns.heatmap(x_1.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)
```
Well, we choose our features but **did we choose correctly ?** Lets use random forest and find accuracy according to chosen features.
```
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score,confusion_matrix
from sklearn.metrics import accuracy_score
# split data train 70 % and test 30 %
x_train, x_test, y_train, y_test = train_test_split(x_1, y, test_size=0.3, random_state=42)
#random forest classifier with n_estimators=10 (default)
clf_rf = RandomForestClassifier(random_state=43)
clr_rf = clf_rf.fit(x_train,y_train)
ac = accuracy_score(y_test,clf_rf.predict(x_test))
print('Accuracy is: ',ac)
cm = confusion_matrix(y_test,clf_rf.predict(x_test))
sns.heatmap(cm,annot=True,fmt="d")
```
Accuracy is almost 95% and as it can be seen in confusion matrix, we make few wrong prediction.
Now lets see other feature selection methods to find better results.
## 2) Univariate feature selection and random forest classification
In univariate feature selection, we will use SelectKBest that removes all but the k highest scoring features.
<http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html#sklearn.feature_selection.SelectKBest>
In this method we need to choose how many features we will use. For example, will k (number of features) be 5 or 10 or 15? The answer is only trying or intuitively. I do not try all combinations but I only choose k = 5 and find best 5 features.
```
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
# find best scored 5 features
select_feature = SelectKBest(chi2, k=5).fit(x_train, y_train)
print('Score list:', select_feature.scores_)
print('Feature list:', x_train.columns)
```
Best 5 feature to classify is that **area_mean, area_se, texture_mean, concavity_worst and concavity_mean**. So lets se what happens if we use only these best scored 5 feature.
```
x_train_2 = select_feature.transform(x_train)
x_test_2 = select_feature.transform(x_test)
#random forest classifier with n_estimators=10 (default)
clf_rf_2 = RandomForestClassifier()
clr_rf_2 = clf_rf_2.fit(x_train_2,y_train)
ac_2 = accuracy_score(y_test,clf_rf_2.predict(x_test_2))
print('Accuracy is: ',ac_2)
cm_2 = confusion_matrix(y_test,clf_rf_2.predict(x_test_2))
sns.heatmap(cm_2,annot=True,fmt="d")
```
Accuracy is almost 96% and as it can be seen in confusion matrix, we make few wrong prediction. What we did up to now is that we choose features according to correlation matrix and according to selectkBest method. Although we use 5 features in selectkBest method accuracies look similar.
Now lets see other feature selection methods to find better results.
## 3) Recursive feature elimination (RFE) with random forest
<http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html>
Basically, it uses one of the classification methods (random forest in our example), assign weights to each of features. Whose absolute weights are the smallest are pruned from the current set features. That procedure is recursively repeated on the pruned set until the desired number of features
Like previous method, we will use 5 features. However, which 5 features will we use ? We will choose them with RFE method.
```
from sklearn.feature_selection import RFE
# Create the RFE object and rank each pixel
clf_rf_3 = RandomForestClassifier()
rfe = RFE(estimator=clf_rf_3, n_features_to_select=5, step=1)
rfe = rfe.fit(x_train, y_train)
print('Chosen best 5 feature by rfe:',x_train.columns[rfe.support_])
```
Chosen 5 best features by rfe is **texture_mean, area_mean, concavity_mean, area_se, concavity_worst**. They are exactly similar with previous (selectkBest) method. Therefore we do not need to calculate accuracy again. Shortly, we can say that we make good feature selection with rfe and selectkBest methods. However as you can see there is a problem, okey I except we find best 5 feature with two different method and these features are same but why it is **5**. Maybe if we use best 2 or best 15 feature we will have better accuracy. Therefore lets see how many feature we need to use with rfecv method.
## 4) Recursive feature elimination with cross validation and random forest classification
<http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFECV.html>
Now we will not only **find best features** but we also find **how many features do we need** for best accuracy.
```
from sklearn.feature_selection import RFECV
# The "accuracy" scoring is proportional to the number of correct classifications
clf_rf_4 = RandomForestClassifier()
rfecv = RFECV(estimator=clf_rf_4, step=1, cv=5,scoring='accuracy') #5-fold cross-validation
rfecv = rfecv.fit(x_train, y_train)
print('Optimal number of features :', rfecv.n_features_)
print('Best features :', x_train.columns[rfecv.support_])
```
Finally, we find best 11 features that are **texture_mean, area_mean, concavity_mean, texture_se, area_se, concavity_se, symmetry_se, smoothness_worst, concavity_worst, symmetry_worst and fractal_dimension_worst** for best classification. Lets look at best accuracy with plot.
```
# Plot number of features VS. cross-validation scores
import matplotlib.pyplot as plt
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score of number of selected features")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()
```
Lets look at what we did up to this point. Lets accept that guys this data is very easy to classification. However, our first purpose is actually not finding good accuracy. Our purpose is learning how to make **feature selection and understanding data.** Then last make our last feature selection method.
## 5) Tree based feature selection and random forest classification
<http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html>
In random forest classification method there is a **feature_importances_** attributes that is the feature importances (the higher, the more important the feature). **!!! To use feature_importance method, in training data there should not be correlated features. Random forest choose randomly at each iteration, therefore sequence of feature importance list can change.**
```
clf_rf_5 = RandomForestClassifier()
clr_rf_5 = clf_rf_5.fit(x_train,y_train)
importances = clr_rf_5.feature_importances_
std = np.std([tree.feature_importances_ for tree in clf_rf.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(x_train.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure(1, figsize=(14, 13))
plt.title("Feature importances")
plt.bar(range(x_train.shape[1]), importances[indices],
color="g", yerr=std[indices], align="center")
plt.xticks(range(x_train.shape[1]), x_train.columns[indices],rotation=90)
plt.xlim([-1, x_train.shape[1]])
plt.show()
```
As you can seen in plot above, after 5 best features importance of features decrease. Therefore we can focus these 5 features. As I sad before, I give importance to understand features and find best of them.
# Feature Extraction
<http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html>
We will use principle component analysis (PCA) for feature extraction. Before PCA, we need to normalize data for better performance of PCA.
```
# split data train 70 % and test 30 %
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)
#normalization
x_train_N = (x_train-x_train.mean())/(x_train.max()-x_train.min())
x_test_N = (x_test-x_test.mean())/(x_test.max()-x_test.min())
from sklearn.decomposition import PCA
pca = PCA()
pca.fit(x_train_N)
plt.figure(1, figsize=(14, 13))
plt.clf()
plt.axes([.2, .2, .7, .7])
plt.plot(pca.explained_variance_ratio_, linewidth=2)
plt.axis('tight')
plt.xlabel('n_components')
plt.ylabel('explained_variance_ratio_')
```
According to variance ration, 3 component can be chosen.
# Conclusion
Shortly, I tried to show importance of feature selection and data visualization.
Default data includes 33 feature but after feature selection we drop this number from 33 to 5 with accuracy 95%. In this kernel we just tried basic things, I am sure with these data visualization and feature selection methods, you can easily ecxeed the % 95 accuracy. Maybe you can use other classification methods.
### I hope you enjoy in this kernel
## If you have any question or advise, I will be apreciate to listen them ...
| github_jupyter |
<a href="https://colab.research.google.com/github/Stable-Baselines-Team/rl-colab-notebooks/blob/sb3/rl-baselines-zoo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# RL Baselines3 Zoo: Training in Colab
Github Repo: [https://github.com/DLR-RM/rl-baselines3-zoo](https://github.com/DLR-RM/rl-baselines3-zoo)
Stable-Baselines3 Repo: [https://github.com/DLR-RM/rl-baselines3-zoo](https://github.com/DLR-RM/stable-baselines3)
# Install Dependencies
```
!apt-get install swig cmake ffmpeg freeglut3-dev xvfb
```
## Clone RL Baselines3 Zoo Repo
```
!git clone --recursive https://github.com/DLR-RM/rl-baselines3-zoo
%cd /content/rl-baselines3-zoo/
```
### Install pip dependencies
```
!pip install -r requirements.txt
```
## Train an RL Agent
The train agent can be found in the `logs/` folder.
Here we will train A2C on CartPole-v1 environment for 100 000 steps.
To train it on Pong (Atari), you just have to pass `--env PongNoFrameskip-v4`
Note: You need to update `hyperparams/algo.yml` to support new environments. You can access it in the side panel of Google Colab. (see https://stackoverflow.com/questions/46986398/import-data-into-google-colaboratory)
```
!python train.py --algo a2c --env CartPole-v1 --n-timesteps 100000
```
#### Evaluate trained agent
You can remove the `--folder logs/` to evaluate pretrained agent.
```
!python enjoy.py --algo a2c --env CartPole-v1 --no-render --n-timesteps 5000 --folder logs/
```
#### Tune Hyperparameters
We use [Optuna](https://optuna.org/) for optimizing the hyperparameters.
Tune the hyperparameters for PPO, using a tpe sampler and median pruner, 2 parallels jobs,
with a budget of 1000 trials and a maximum of 50000 steps
```
!python train.py --algo ppo --env MountainCar-v0 -n 50000 -optimize --n-trials 1000 --n-jobs 2 --sampler tpe --pruner median
```
### Record a Video
```
# Set up display; otherwise rendering will fail
import os
os.system("Xvfb :1 -screen 0 1024x768x24 &")
os.environ['DISPLAY'] = ':1'
!python -m utils.record_video --algo a2c --env CartPole-v1 --exp-id 0 -f logs/ -n 1000
```
### Display the video
```
import base64
from pathlib import Path
from IPython import display as ipythondisplay
def show_videos(video_path='', prefix=''):
"""
Taken from https://github.com/eleurent/highway-env
:param video_path: (str) Path to the folder containing videos
:param prefix: (str) Filter the video, showing only the only starting with this prefix
"""
html = []
for mp4 in Path(video_path).glob("{}*.mp4".format(prefix)):
video_b64 = base64.b64encode(mp4.read_bytes())
html.append('''<video alt="{}" autoplay
loop controls style="height: 400px;">
<source src="data:video/mp4;base64,{}" type="video/mp4" />
</video>'''.format(mp4, video_b64.decode('ascii')))
ipythondisplay.display(ipythondisplay.HTML(data="<br>".join(html)))
show_videos(video_path='logs/videos/', prefix='a2c')
```
### Continue Training
Here, we will continue training of the previous model
```
!python train.py --algo a2c --env CartPole-v1 --n-timesteps 50000 -i logs/a2c/CartPole-v1_1/CartPole-v1.zip
!python enjoy.py --algo a2c --env CartPole-v1 --no-render --n-timesteps 1000 --folder logs/
```
| github_jupyter |
# A.1 Working with data in R
### A.1.1 What are the other advantages of using R?
- We can be lazy and use the thousands of free libraries to easily:
- Easily manipulate data (Today's topic)
- Download data directly from the internet
- Viusualize our data (graphing etc.)
- Build models (Regression, Machine learning, Neural Networks)
- You have all used libraries before, perhaps without knowing it!
- This is done in R in two steps:
1. install.packages("Package name") Downloads package
2. library(Package name) Imports package
### A.1.2 What is a Data Frame?
- Think of it as an excel sheet with data
- In many cases:
- Rows are observations (e.g. people, households, countries, time)
- Columns are variables (e.g. GDP, life expectancy)
### A.1.3 What applications can I use to run R?
R is not a software, it is a coding language! So there are multiple applications which can run R in
### A.1.3.1 R-studio cloud!
- Many students get frustrated because there are sometimes bugs which prevent the software from running smoothly
- R-studio cloud takes the hassle out of the setup of r-studio and allows for us to focus on learning R!
### A.1.3.2 R-studio software for your machine [link]((https://rstudio.com/products/rstudio/download/))
#### For those who want to use r in Jupyter notebook (what this tutorial is written in).
- [Computer download: Anaconda software](https://www.anaconda.com/)
- Cloud services
- [R-studio cloud](https://rstudio.cloud/)
- [Azure cloud](https://notebooks.azure.com/)
## A.2 R-studio basics
### - Tutorial can be found at this [link](https://nbviewer.jupyter.org/github/corybaird/PLCY_610_public/blob/master/Discussion_sections/Disc1_Intro/Disc1_intro.ipynb)
## A.3 Import data and libraries
### A.3.1 Import libraries
```
# Step 1
#install.packages('dplyr')
#install.packages('gapminder')
#Step 2
library('dplyr')
library('gapminder')
```
### A.3.2 Import data
```
gapminder %>% head(2)
```
# 1. DPLYR review
- This is meant to be a brief review
- If you want to see longer DPLYR notes please check out this other [notebook](https://nbviewer.jupyter.org/github/corybaird/PLCY_610_public/blob/master/Reference_materials/Tutorials_R_Stata_Python/R/W1_DPLYR/W1_DPLYR_code.ipynb) I created
## 1.1 Select
```
gapminder %>%
select(country, year, gdpPercap) %>%
head(3)
```
## 1.2 Filter
### 1.2.1 Filter by 1 condition
```
gapminder %>%
filter(year==2007) %>%
head(2)
```
### 1.2.2 Filter by 2 conditions
```
gapminder %>%
filter(year>1990 & year<2007) %>%
head(2)
```
## 1.3 Mutate
```
gapminder %>%
mutate(gdp_log = log(gdpPercap)) %>%
head(3)
```
## 1.4 Summarise
- See list of functions under the "useful functions" header [here]
```
gapminder %>%
summarise(mean_pop = mean(pop),
median_pop = median(pop))
```
### 1.4.1 Summarise & Filter
- Chain two functions
```
gapminder %>%
filter(year==2007) %>%
summarise(mean_pop = mean(pop))
```
## 1.5 Groupby
```
gapminder %>%
group_by(continent) %>%
summarise(mean_gdp = mean(gdpPercap))
```
# 2. Data check
## 2.1 Data types: str(DF_NAME)
```
str(gapminder)
```
## 2.2 Summary stats: summary(DF_NAME)
```
summary(gapminder)
```
## 2.3 Check for NA: is.na()
```
gapminder %>%
is.na() %>%
any()
```
## 2.4 Drop na: na.omit()
- Add na then drop
### 2.4.1 Add na observations in the last row
```
# Adds NA row at the bottom of dataset
gapminder = gapminder %>% rbind(c(NA,NA, NA, NA, NA, NA))
gapminder %>% tail(2)
```
### 2.4.2 Re-check for na
```
gapminder %>%
is.na() %>%
any()
```
### 2.4.3 na.omit()
```
gapminder %>%
na.omit() %>% tail(2)
```
# 3. Data manipulation
## 3.1 Dummy variable
```
gapminder_2007 = gapminder %>% filter(year==2007)
gapminder_2007 %>% head(5)
```
### 3.1.1 Add dummy for high-income countries
```
gapminder_2007 = gapminder_2007 %>%
mutate(highinc_dummy = as.numeric(gdpPercap>10000))
gapminder_2007 %>% head(2)
```
### 3.1.2 Dummies are useful for summary stats
```
gapminder_2007 %>%
group_by(highinc_dummy) %>%
summarise(gdp_mean = mean(gdpPercap),
pop_mean = mean(pop))
```
## 3.2 Mapping values
```
gapminder_2007 %>%
mutate(highinc_dummy_factor = recode(highinc_dummy, '0'='Low', '1'='High')) %>%
tail(2)
```
## 3.3 Cut-off dummies
```
cutoffs = c(seq(40, 100, by = 10))
cutoffs
gapminder_2007 = gapminder_2007 %>%
mutate(cut_variable = cut(gapminder_2007$lifeExp, cutoffs, include.lowest=TRUE))
gapminder_2007 %>% head(3)
gapminder_2007 %>%
group_by(cut_variable) %>%
summarise(mean_gdp = mean(gdpPercap))
```
# 4. Misc
## 4.1 Rename column
```
gapminder_2007 %>% rename('gdp'='gdpPercap') %>% head(2)
```
## 4.2 Unique
```
gapminder_2007 %>%
select(continent) %>%
unique()
```
## 4.3 Table(row, column)
```
df_polity = read.csv('https://raw.githubusercontent.com/corybaird/PLCY_610_public/master/Discussion_sections/Disc4_PS2/demo.csv')
df_polity %>% head(2)
```
### 4.3.1 Freq table
```
freq_table = df_polity %>% select(wealth, regime) %>% table()
freq_table
rownames(freq_table) = c('Wealth 1', 'Wealth 2', 'Wealth 3')
colnames(freq_table) = c('Regime 1', 'Regime 2', 'Regime 3')
freq_table
```
### 4.3.2 Prop.table
```
prop.table(freq_table)
```
## 4.4 Filter list
```
country_list = c('Albania', 'Italy', 'France', 'Belgium')
gapminder_2007 %>% filter(country %in% country_list)
```
## 4.5 Case when
```
spanish_country_list = c('Spain', 'Argentina', 'Mexico','Chile')
gapminder_2007 %>%
mutate(language = case_when(country=='Spain'~'Spanish',
country=='Italy' ~ 'Italian',
country=='United Kingdom'~'English')) %>% na.omit()
```
## 4.6 Count
```
gapminder_2007 %>% count(highinc_dummy)
```
## 4.7 Export data
```
#gapminder_2007 %>% write.csv('FILENAME.csv')
#gapminder_2007 %>% write.xlsx('FILENAME.xlsx')
```
# 5. Merge
## 5.1 Merge rows
```
df_1 = gapminder_2007[1:3, ]
df_1
df_2 = gapminder_2007[5:7, ]
df_2
```
### 5.1.1 rbind
```
rbind(df_1, df_2)
```
## 5.2 Merge columns
```
df_1 = gapminder_2007[1:3, c('year','lifeExp')]
df_1
df_2 = gapminder_2007[5:7, c('continent','country')]
df_2
cbind(df_1, df_2)
```
## 5.3 Merge rows and columns
### 5.3.1 Case data
```
url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'
nyt_cases_df = read.csv(url)
nyt_cases_df %>% head(3)
```
### 5.3.2 Mask data
```
url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/mask-use/mask-use-by-county.csv'
nyt_mask_df = read.csv(url)
nyt_mask_df %>% head(3)
```
### 5.3.3 Merge
#### 5.3.3.1 For the column merge on make sure the name is the same in both data sets
```
nyt_mask_df = nyt_mask_df %>% rename('fips'='COUNTYFP')
nyt_mask_df %>% names()
merge(nyt_cases_df, nyt_mask_df, by='fips') %>% head(10)
```
| github_jupyter |
## `ipywidgets`
Using the `ipywidgets` module, an add-on to Jupyter, you can create interactive Python functions.
```
import ipywidgets
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
```
### Widget Basics
The simplest interface is the function `ipywidgets.interact`, which, in its simplest form, takes a function and makes a widget that lets you change the values of its arguments. Each time an argument is changed, the function is called again.
```
lst = ["hello", "it's me", "i was wondering", "if after all these years you'd like to meet"]
def my_function(the_box_is_checked=False, integer=(0, 2), string=lst):
pass
ipywidgets.interact(my_function);
```
The type of widget is inferred from the type of the argument. So, because `this_box_is_checked` is a boolean (`True`/`False`), the widget is a checkbox, because `integer` is a tuple, the widget is a slider, and because `string` is a list, the widget is a dropdown menu.
The above example is obviously useless -- `my_function` does nothing with its arguments. Generally, if we want the interaction to do something that the user can see, we need to either `print` or `plot` something.
The example below is a reasonably minimal example of such an interaction.
```
def my_function(this_box_is_checked=False, integer=(0, 2), string=lst):
if this_box_is_checked:
print(integer*string)
ipywidgets.interact(my_function);
```
### Widgets for Interactive Plotting
One of the most common uses is for interactive plotting. In that case, we need to use, instead of the typical `%matplotlib inline` magic, the `%matplotlib notebook` magic to get interactive plots.
```
%matplotlib notebook
```
The examples below show how to create a variety of interactive plots.
In general, you set up the plot, then draw something on it that you want the user to interact with. Then you create a function that, when it is called, changes the values of the thing you drew.
#### A Line with Interactive Slope
In the example below, we draw a `line` on an `ax`is using `ax.plot`. The function that modifies it is `f` and it changes the slope of the line using `line.set_data`.
```
def setup_plot_cartesian(mn, mx):
"""create a figure and axes with the origin in the center
and the Cartesian x- and y-axes (y=0 and x=0) drawn in.
"""
fig, ax = plt.subplots()
ax.set_xlim([mn, mx]); ax.set_ylim([mn, mx])
plt.hlines(0, 2*mn, 2*mx)
plt.vlines(0, 2*mn, 2*mx)
return fig, ax
def make_line_plotter():
"""create a function that plots a line with variable slope parameter,
suitable for use with ipywidgets.interact.
"""
fig, ax = setup_plot_cartesian(-1, 1)
xs = np.arange(-2, 2, 1)
line, = ax.plot(xs, xs)
plt.axis("off")
def f(m=0.):
line.set_data(xs, m*xs)
return f
f = make_line_plotter()
ipywidgets.interact(f, m=ipywidgets.FloatSlider(0, min=-10, max=10));
```
#### A Line with Interactive Slope and Color
We're not stuck just modifying the data of a plot. There are a variety of `.set_foo` methods that let us set a property `foo` of a plot.
The example below also sets the color. Notice that we just had to add a line calling the `.set_color` method to our previous example.
As an added bonus, we pull our colors from the [XKCD color survey](https://blog.xkcd.com/2010/05/03/color-survey-results/), which has been added to matplotlib. These colors are often more visually appealing than the base matplotlib colors, and they have very memorable names!
```
def make_colorful_line_plotter():
"""create a function that plots a line with variable slope parameter,
and a variable color, suitable for use with ipywidgets.interact.
"""
fig, ax = setup_plot_cartesian(-1, 1)
xs = np.arange(-2, 2, 1)
line, = ax.plot(xs, xs, lw=2)
plt.axis("off")
def f(m=0., color="cloudy blue"):
line.set_data(xs, m*xs)
line.set_color("xkcd:"+color)
return f
color_options = [color_key.split(":")[1] for color_key in matplotlib.colors.XKCD_COLORS.keys()]
f = make_colorful_line_plotter()
ipywidgets.interact(f, m=ipywidgets.FloatSlider(0, min=-10, max=10),
color=ipywidgets.Dropdown(options=color_options));
```
#### Bespoke Data Analysis
Now on to a moderately more useful and data-science-y example.
Normally, we fit our data using maximum likelihood. If we're fitting a Gaussian to our data, that means calculating the mean and standard deviation/variance of the data (or, from another perspective, every time we report our data as a mean ± standard deviation, we're fitting a Gaussian to our data).
Alternatively, we could fit our data by hand! The cell below generates an interactive plot with a histogram of the data and a freely modifiable Gaussian probability curve. You can use the sliders to adjust the center and spread of the curve until it seems to fit the data nicely, and then compare it with the `true` mean `mu` and variance `Sigma`.
```
def make_gauss_fitter(data, true_mu, true_Sigma):
"""given a dataset with a given mean mu and variance Sigma,
construct a function that plots a gaussian pdf with variable
mean and variance over a normed histogram of the data.
intended for use with ipywidgets.interact.
"""
xs = np.arange(-5*np.sqrt(true_Sigma)+true_mu,
5*np.sqrt(true_Sigma)+true_mu,
0.01)
gauss_pdf = lambda xs, mu, sigma: (1/np.sqrt(2*np.pi*sigma))*np.exp((-0.5*(xs-mu)**2)/sigma)
fig, ax = plt.subplots()
hist = ax.hist(data, density=True, bins=max(10, N//50))
fit, = plt.plot(xs, gauss_pdf(xs, 0, 1), lw=4)
def f(mu=0., sigma=1.):
fit.set_data(xs, gauss_pdf(xs, mu, sigma))
return f
true_mu = 2.; true_Sigma = 0.5; N = 20;
data = np.sqrt(true_Sigma)*np.random.standard_normal(size=N) + true_mu
f = make_gauss_fitter(data, true_mu, true_Sigma)
ipywidgets.interact(f, mu=ipywidgets.FloatSlider(0, min=-10, max=10),
sigma=ipywidgets.FloatSlider(1., min=1e-1, max=10, step=1e-1));
```
| github_jupyter |
<a href="https://colab.research.google.com/github/maiormarso/DS-Unit-2-Linear-Models/blob/master/module2-regression-2/LS_DS_213_assignment_ridge_regression_classification_3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Lambda School Data Science
*Unit 2, Sprint 1, Module 3*
---
# Ridge Regression
## Assignment
We're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.
But not just for condos in Tribeca...
Instead, predict property sales prices for **One Family Dwellings** (`BUILDING_CLASS_CATEGORY` == `'01 ONE FAMILY DWELLINGS'`).
Use a subset of the data where the **sale price was more than \\$100 thousand and less than $2 million.**
The [NYC Department of Finance](https://www1.nyc.gov/site/finance/taxes/property-rolling-sales-data.page) has a glossary of property sales terms and NYC Building Class Code Descriptions. The data comes from the [NYC OpenData](https://data.cityofnewyork.us/browse?q=NYC%20calendar%20sales) portal.
- [ ] Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.
- [ ] Do one-hot encoding of categorical features.
- [ ] Do feature selection with `SelectKBest`.
- [ ] Do [feature scaling](https://scikit-learn.org/stable/modules/preprocessing.html).
- [ ] Fit a ridge regression model with multiple features.
- [ ] Get mean absolute error for the test set.
- [ ] As always, commit your notebook to your fork of the GitHub repo.
## Stretch Goals
- [ ] Add your own stretch goal(s) !
- [ ] Instead of `Ridge`, try `LinearRegression`. Depending on how many features you select, your errors will probably blow up! 💥
- [ ] Instead of `Ridge`, try [`RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html).
- [ ] Learn more about feature selection:
- ["Permutation importance"](https://www.kaggle.com/dansbecker/permutation-importance)
- [scikit-learn's User Guide for Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html)
- [mlxtend](http://rasbt.github.io/mlxtend/) library
- scikit-learn-contrib libraries: [boruta_py](https://github.com/scikit-learn-contrib/boruta_py) & [stability-selection](https://github.com/scikit-learn-contrib/stability-selection)
- [_Feature Engineering and Selection_](http://www.feat.engineering/) by Kuhn & Johnson.
- [ ] Try [statsmodels](https://www.statsmodels.org/stable/index.html) if you’re interested in more inferential statistical approach to linear regression and feature selection, looking at p values and 95% confidence intervals for the coefficients.
- [ ] Read [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapters 1-3, for more math & theory, but in an accessible, readable way.
- [ ] Try [scikit-learn pipelines](https://scikit-learn.org/stable/modules/compose.html).
```
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
# Ignore this Numpy warning when using Plotly Express:
# FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy')
import pandas as pd
import pandas_profiling
# Read New York City property sales data
df = pd.read_csv(DATA_PATH+'condos/NYC_Citywide_Rolling_Calendar_Sales.csv')
# Change column names: replace spaces with underscores
df.columns = [col.replace(' ', '_') for col in df]
# SALE_PRICE was read as strings.
# Remove symbols, convert to integer
df['SALE_PRICE'] = (
df['SALE_PRICE']
.str.replace('$','')
.str.replace('-','')
.str.replace(',','')
.astype(int)
)
# BOROUGH is a numeric column, but arguably should be a categorical feature,
# so convert it from a number to a string
df['BOROUGH'] = df['BOROUGH'].astype(str)
# Reduce cardinality for NEIGHBORHOOD feature
# Get a list of the top 10 neighborhoods
top10 = df['NEIGHBORHOOD'].value_counts()[:10].index
# At locations where the neighborhood is NOT in the top 10,
# replace the neighborhood with 'OTHER'
df.loc[~df['NEIGHBORHOOD'].isin(top10), 'NEIGHBORHOOD'] = 'OTHER'
df.head(1)
df.shape
# Do train/test split
# Use data from April & May 2016 to train
# Use data from June 2016 to test
df['SALE_DATE'] = pd.to_datetime(df['SALE_DATE'], infer_datetime_format=True)
cutoff = pd.to_datetime('2016-04-01')
train = df[df.SALE_DATE < cutoff]
test = df[df.SALE_DATE >= cutoff]
df.loc[(df['SALE_PRICE'] >=100000) & (df['SALE_PRICE'] <= 2000000)]
df1=df.loc[(df['BUILDING_CLASS_CATEGORY'] == '01 ONE FAMILY DWELLINGS')]
df1.head(8)
```
# Ridge Regression
## Assignment
We're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.
But not just for condos in Tribeca...
Instead, predict property sales prices for **One Family Dwellings** (`BUILDING_CLASS_CATEGORY` == `'01 ONE FAMILY DWELLINGS'`).
Use a subset of the data where the **sale price was more than \\$100 thousand and less than $2 million.**
The [NYC Department of Finance](https://www1.nyc.gov/site/finance/taxes/property-rolling-sales-data.page) has a glossary of property sales terms and NYC Building Class Code Descriptions. The data comes from the [NYC OpenData](https://data.cityofnewyork.us/browse?q=NYC%20calendar%20sales) portal.
- [ ] Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test.
- [ ] Do one-hot encoding of categorical features.
- [ ] Do feature selection with `SelectKBest`.
- [ ] Do [feature scaling](https://scikit-learn.org/stable/modules/preprocessing.html).
- [ ] Fit a ridge regression model with multiple features.
- [ ] Get mean absolute error for the test set.
- [ ] As always, commit your notebook to your fork of the GitHub repo.
## Stretch Goals
- [ ] Add your own stretch goal(s) !
- [ ] Instead of `Ridge`, try `LinearRegression`. Depending on how many features you select, your errors will probably blow up! 💥
- [ ] Instead of `Ridge`, try [`RidgeCV`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html).
- [ ] Learn more about feature selection:
- ["Permutation importance"](https://www.kaggle.com/dansbecker/permutation-importance)
- [scikit-learn's User Guide for Feature Selection](https://scikit-learn.org/stable/modules/feature_selection.html)
- [mlxtend](http://rasbt.github.io/mlxtend/) library
- scikit-learn-contrib libraries: [boruta_py](https://github.com/scikit-learn-contrib/boruta_py) & [stability-selection](https://github.com/scikit-learn-contrib/stability-selection)
- [_Feature Engineering and Selection_](http://www.feat.engineering/) by Kuhn & Johnson.
- [ ] Try [statsmodels](https://www.statsmodels.org/stable/index.html) if you’re interested in more inferential statistical approach to linear regression and feature selection, looking at p values and 95% confidence intervals for the coefficients.
- [ ] Read [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapters 1-3, for more math & theory, but in an accessible, readable way.
- [ ] Try [scikit-learn pipelines](https://scikit-learn.org/stable/modules/compose.html).
| github_jupyter |
```
import pandas as pd
from pathlib import Path
from sklearn.svm import LinearSVR,SVR
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import learning_curve,RepeatedKFold
from sklearn.decomposition import PCA
from yellowbrick.model_selection import LearningCurve
from yellowbrick.regressor import ResidualsPlot
from yellowbrick.regressor import PredictionError
from sklearn.preprocessing import StandardScaler,scale,RobustScaler,MinMaxScaler
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
from sklearn import metrics
from sklearn.externals import joblib
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.compose import TransformedTargetRegressor
from sklearn.preprocessing import QuantileTransformer,quantile_transform,PowerTransformer
%matplotlib inline
sns.set_context(context="paper")
def learn_curves(estimator, features, target, cv):
train_sizes, train_scores, validation_scores = learning_curve(
estimator, features, target,train_sizes = np.linspace(.1, 1.0, 10),
cv = cv, scoring = 'neg_mean_squared_error',n_jobs=-1)
train_scores_mean = -train_scores.mean(axis = 1)
validation_scores_mean = -validation_scores.mean(axis = 1)
plt.plot(train_sizes, np.sqrt(train_scores_mean), label = 'Training error')
plt.plot(train_sizes, np.sqrt(validation_scores_mean), label = 'Validation error')
plt.ylabel('RMSE', fontsize = 14)
plt.xlabel('Training set size', fontsize = 14)
title = 'Learning curve'
plt.title(title, fontsize = 18, y = 1.03)
plt.legend()
plt.ylim(0,3)
#dataframe final
df_final = pd.read_csv("../data/DF_contact400_energy_sasa.FcorrZero.csv",index_col=0)
index_ddg8 = (df_final['ddG_exp']>6.3)
df_final = df_final.loc[-index_ddg8]
#testiar eliminando estructuras con ddg menor o igual a -4 kcal/mol , outliers
index_ddg_4 = (df_final['ddG_exp'] <= -4)
df_final = df_final.loc[-index_ddg_4]
pdb_names = df_final.index
features_names = df_final.drop('ddG_exp',axis=1).columns
df_final.shape
#X = df_final_f1 # con filtrado de varianza
X = df_final.drop('ddG_exp',axis=1).astype(float)
y = df_final['ddG_exp']
# binned split
bins = np.linspace(0, len(X), 50)
y_binned = np.digitize(y, bins)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y_binned,random_state=1)
sns.distplot( y_test , color="red", label="ddG_exp_test")
sns.distplot( y_train , color="skyblue", label="ddG_exp_train")
import numpy as np
from yellowbrick.model_selection import ValidationCurve
# Load a regression dataset
selector = VarianceThreshold()
scaler = MinMaxScaler()
trf = PowerTransformer()
#2)
lr_model = LinearSVR(max_iter=8000)
#3) Crear pipeline
pipeline1 = make_pipeline(scaler,selector,lr_model)
regr_trans = TransformedTargetRegressor(
regressor=pipeline1, transformer=PowerTransformer())
# Extract the instances and target
viz = ValidationCurve(
pipeline1, njobs=-1,param_name="linearsvr__C",
param_range=np.arange(0.05,0.3,0.05), cv=10, scoring="r2"
)
#plt.ylim(0,0.6)
# Fit and poof the visualizer
viz.fit(X_train, y_train)
viz.poof()
```
# LinearSVR gridsearch
```
Rep
selector = VarianceThreshold()
scaler = MinMaxScaler()
#scaler = RobustScaler()
#2)
lr_model = LinearSVR(max_iter=8000)
#3) Crear pipeline
pipeline1 = make_pipeline(scaler,selector,lr_model)
regr_trans = TransformedTargetRegressor(
regressor=pipeline1, transformer=PowerTransformer())
# 5) hiperparametros a ajustar
param_grid = { 'regressor__linearsvr__C': [0.05,0.1,0.15,0.2] , 'regressor__linearsvr__epsilon':[1.2,1.3,1.4,1.5],
'regressor__linearsvr__random_state': [1313],'regressor__linearsvr__fit_intercept':[False,True],
'regressor__variancethreshold__threshold':[0.001,0.0015,0.0]}
cv = RepeatedKFold(n_splits=5,n_repeats=10,random_state=13,)
grid1 = GridSearchCV(regr_trans, param_grid, verbose=5, n_jobs=-1,cv=cv,scoring=['neg_mean_squared_error','r2'],
refit='r2',return_train_score=True)
grid1.fit(X_train, y_train)
# index of best scores
rmse_bestCV_test_index = grid1.cv_results_['mean_test_neg_mean_squared_error'].argmax()
rmse_bestCV_train_index = grid1.cv_results_['mean_train_neg_mean_squared_error'].argmax()
r2_bestCV_test_index = grid1.cv_results_['mean_test_r2'].argmax()
r2_bestCV_train_index = grid1.cv_results_['mean_train_r2'].argmax()
# scores
rmse_bestCV_test_score = grid1.cv_results_['mean_test_neg_mean_squared_error'][rmse_bestCV_test_index]
rmse_bestCV_test_std = grid1.cv_results_['std_test_neg_mean_squared_error'][rmse_bestCV_test_index]
rmse_bestCV_train_score = grid1.cv_results_['mean_train_neg_mean_squared_error'][rmse_bestCV_train_index]
rmse_bestCV_train_std = grid1.cv_results_['std_train_neg_mean_squared_error'][rmse_bestCV_train_index]
r2_bestCV_test_score = grid1.cv_results_['mean_test_r2'][r2_bestCV_test_index]
r2_bestCV_test_std = grid1.cv_results_['std_test_r2'][r2_bestCV_test_index]
r2_bestCV_train_score = grid1.cv_results_['mean_train_r2'][r2_bestCV_train_index]
r2_bestCV_train_std = grid1.cv_results_['std_train_r2'][r2_bestCV_train_index]
print('CV test RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_test_score),np.sqrt(rmse_bestCV_test_std)))
print('CV train RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_train_score),np.sqrt(rmse_bestCV_train_std)))
print('CV test r2 {:f} +/- {:f}'.format(r2_bestCV_test_score,r2_bestCV_test_std))
print('CV train r2 {:f} +/- {:f}'.format(r2_bestCV_train_score,r2_bestCV_train_std))
print(r2_bestCV_train_score-r2_bestCV_test_score)
print("",grid1.best_params_)
y_test_pred = grid1.best_estimator_.predict(X_test)
y_train_pred = grid1.best_estimator_.predict(X_train)
print("\nRMSE for test dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_test, y_test_pred)), 2)))
print("RMSE for train dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_train, y_train_pred)), 2)))
print("pearson corr {:f}".format(np.corrcoef(y_test_pred,y_test)[0][1]))
print('R2 test',grid1.score(X_test,y_test))
print('R2 train',grid1.score(X_train,y_train))
visualizer = ResidualsPlot(grid1.best_estimator_,hist=False)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof() # Draw/show/poof the data
perror = PredictionError(grid1.best_estimator_)
perror.fit(X_train, y_train) # Fit the training data to the visualizer
perror.score(X_test, y_test) # Evaluate the model on the test data
g = perror.poof()
learn_curves(grid1.best_estimator_,X,y,10)
viz = LearningCurve(grid1.best_estimator_, cv=cv, n_jobs=-1,scoring='r2',train_sizes=np.linspace(0.4, 1.0, 10))
viz.fit(X, y)
plt.ylim(0,0.4)
viz.poof()
final_svr1 = grid1.best_estimator_.fit(X,y)
# save final model
joblib.dump(final_svr1, 'SVRmodel_contact400energy_sasa_linear.pkl')
```
# SVR poly, rbf kernel gridsearch
```
SVR?
import numpy as np
from yellowbrick.model_selection import ValidationCurve
# Load a regression dataset
selector = VarianceThreshold()
scaler = MinMaxScaler()
#scaler = StandardScaler()
#2)
lr_model = SVR(max_iter=8000,kernel="rbf")
#3) Crear pipeline
pipeline2 = make_pipeline(scaler,selector,lr_model)
regr_trans = TransformedTargetRegressor(
regressor=pipeline2, transformer=PowerTransformer())
# Extract the instances and target
viz = ValidationCurve(
regr_trans, njobs=-1,param_name="regressor__svr__gamma",
param_range=np.arange(0.01,0.1,0.01), cv=cv, scoring="r2"
)
#plt.ylim(0,0.6)
# Fit and poof the visualizer
viz.fit(X_train, y_train)
viz.poof()
selector = VarianceThreshold()
scaler = MinMaxScaler()
#scaler = RobustScaler()
#2)
lr_model = SVR(max_iter=8000)
#3) Crear pipeline
pipeline2 = make_pipeline(scaler,selector,lr_model)
# 5) hiperparametros a ajustar
param_grid = { 'regressor__svr__kernel': ['rbf'],'regressor__svr__C': [1.5],'regressor__svr__gamma': [0.025],
'regressor__svr__epsilon':[0.9],'regressor__variancethreshold__threshold':[0.001] }
cv = RepeatedKFold(n_splits=5,n_repeats=10,random_state=13)
regr_trans = TransformedTargetRegressor(
regressor=pipeline2, transformer=PowerTransformer())
grid2 = GridSearchCV(regr_trans, param_grid, verbose=5, n_jobs=-1,cv=cv,scoring=['neg_mean_squared_error','r2'],
refit='r2',return_train_score=True)
# fit
grid2.fit(X_train, y_train)
# index of best scores
rmse_bestCV_test_index = grid2.cv_results_['mean_test_neg_mean_squared_error'].argmax()
rmse_bestCV_train_index = grid2.cv_results_['mean_train_neg_mean_squared_error'].argmax()
r2_bestCV_test_index = grid2.cv_results_['mean_test_r2'].argmax()
r2_bestCV_train_index = grid2.cv_results_['mean_train_r2'].argmax()
# scores
rmse_bestCV_test_score = grid2.cv_results_['mean_test_neg_mean_squared_error'][rmse_bestCV_test_index]
rmse_bestCV_test_std = grid2.cv_results_['std_test_neg_mean_squared_error'][rmse_bestCV_test_index]
rmse_bestCV_train_score = grid2.cv_results_['mean_train_neg_mean_squared_error'][rmse_bestCV_train_index]
rmse_bestCV_train_std = grid2.cv_results_['std_train_neg_mean_squared_error'][rmse_bestCV_train_index]
r2_bestCV_test_score = grid2.cv_results_['mean_test_r2'][r2_bestCV_test_index]
r2_bestCV_test_std = grid2.cv_results_['std_test_r2'][r2_bestCV_test_index]
r2_bestCV_train_score = grid2.cv_results_['mean_train_r2'][r2_bestCV_train_index]
r2_bestCV_train_std = grid2.cv_results_['std_train_r2'][r2_bestCV_train_index]
print('CV test RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_test_score),np.sqrt(rmse_bestCV_test_std)))
print('CV train RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_train_score),np.sqrt(rmse_bestCV_train_std)))
print('CV test r2 {:f} +/- {:f}'.format(r2_bestCV_test_score,r2_bestCV_test_std))
print('CV train r2 {:f} +/- {:f}'.format(r2_bestCV_train_score,r2_bestCV_train_std))
print(r2_bestCV_train_score-r2_bestCV_test_score)
print("",grid2.best_params_)
y_test_pred = grid2.best_estimator_.predict(X_test)
y_train_pred = grid2.best_estimator_.predict(X_train)
print("\nRMSE for test dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_test, y_test_pred)), 2)))
print("RMSE for train dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_train, y_train_pred)), 2)))
print("pearson corr {:f}".format(np.corrcoef(y_test_pred,y_test)[0][1]))
print('R2 test',grid2.score(X_test,y_test))
print('R2 train',grid2.score(X_train,y_train))
CV test RMSE 1.136342 +/- 0.483132
CV train RMSE 1.038431 +/- 0.220192
CV test r2 0.255360 +/- 0.058354
CV train r2 0.385056 +/- 0.018497
0.12969578040681795
{'regressor__svr__C': 2, 'regressor__svr__epsilon': 0.6, 'regressor__svr__gamma': 0.03, 'regressor__svr__kernel': 'rbf'}
RMSE for test dataset: 1.07
RMSE for train dataset: 1.04
pearson corr 0.555573
R2 test 0.30467618432470744
R2 train 0.38296278782456605
visualizer = ResidualsPlot(grid2.best_estimator_,hist=False)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof() # Draw/show/poof the data
perror = PredictionError(grid2.best_estimator_)
perror.fit(X_train, y_train) # Fit the training data to the visualizer
perror.score(X_test, y_test) # Evaluate the model on the test data
g = perror.poof()
viz = LearningCurve(grid2.best_estimator_, cv=cv, n_jobs=-1,scoring='r2',train_sizes=np.linspace(0.3, 1.0, 10))
viz.fit(X, y)
#plt.ylim(5,-5)
viz.poof()
final_svr2 = grid2.best_estimator_.fit(X,y)
# save final model
joblib.dump(final_svr2, 'SVRmodel_contact400energy_sasa_rbf.pkl')
```
# Poly kernel
```
selector = VarianceThreshold()
scaler = MinMaxScaler()
#scaler = RobustScaler()
#2)
lr_model = SVR(max_iter=8000)
#3) Crear pipeline
pipeline3 = make_pipeline(scaler,selector,lr_model)
# 5) hiperparametros a ajustar
param_grid = { 'regressor__svr__kernel': ['poly'],'regressor__svr__C': [3,4,5,6],'regressor__svr__gamma': [0.02,0.03,0.04,0.05],
'regressor__svr__epsilon':[0.6,0.7],'regressor__svr__degree':[4,5,6] }
cv = RepeatedKFold(n_splits=5,n_repeats=10,random_state=13)
regr_trans = TransformedTargetRegressor(
regressor=pipeline3, transformer=PowerTransformer())
grid3 = GridSearchCV(regr_trans, param_grid, verbose=5, n_jobs=-1,cv=cv,scoring=['neg_mean_squared_error','r2'],
refit='r2',return_train_score=True)
# fit
grid3.fit(X_train, y_train)
grid3.best_score_
```
# Best estimators with smote
```
from imblearn import over_sampling as ovs
# forma 1
df_final['class'] = np.where((df_final['ddG_exp'] <= -0.5) | (df_final['ddG_exp'] >= 2),0,1)
# forma 2
#df_final['class'] = np.where((df_final['ddG_exp'] < 0),1,0)
df_final['ddG_exp'].hist(bins=np.arange(-3,7,0.5))
print("Before OverSampling, counts of label '1': {}".format(sum(df_final['class'] == 1)))
print("Before OverSampling, counts of label '0': {}".format(sum(df_final['class'] == 0)))
df_final.loc[df_final['class'] == 0]['ddG_exp'].hist(bins=50)
X = df_final.drop('class',axis=1)
y = df_final['class']
# binned split
bins = np.linspace(0, len(X), 50)
y_binned = np.digitize(y, bins)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y_binned,random_state=1)
smote = ovs.SMOTE(random_state=12,m_neighbors=3)
#smote = ovs.BorderlineSMOTE(random_state=12,m_neighbors=3,kind='borderline-2')
#adasyn = ovs.ADASYN(random_state=10,n_neighbors=5)
#X_train_re , y_train_re = adasyn.fit_sample(X_train,y_train)
X_train_re , y_train_re = smote.fit_sample(X_train,y_train)
# back to originalk shape and target
X_train_normal = X_train_re[:,:-1]
y_train_normal = X_train_re[:,-1]
X_test_normal = X_test.iloc[:,:-1]
y_test_normal = X_test.iloc[:,-1]
model = grid2.best_estimator_.fit(X_train_normal,y_train_normal)
#print('CV test RMSE',np.sqrt(-grid.best_score_))
#print('CV train RMSE',np.sqrt(-grid.cv_results_['mean_train_score'].max()))
y_test_pred = model.predict(X_test_normal.values)
y_train_pred = model.predict(X_train_normal)
print('Training score (r2): {}'.format(r2_score(y_train_normal, y_train_pred)))
print('Test score (r2): {}'.format(r2_score(y_test_normal.values, y_test_pred)))
print("\nRoot mean square error for test dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_test_normal.values, y_test_pred)), 2)))
print("Root mean square error for train dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_train_normal, y_train_pred)), 2)))
print("pearson corr: ",np.corrcoef(y_test_pred,y_test_normal.values)[0][1])
perror = PredictionError(model)
perror.fit(X_train_normal, y_train_normal) # Fit the training data to the visualizer
perror.score(X_test_normal.values, y_test_normal.values) # Evaluate the model on the test data
g = perror.poof()
```
## Salvar modelo final, entrenado con el total de lso datos
```
ABPRED_DIR = Path().cwd().parent
DATA = ABPRED_DIR / "data"
#dataframe final
df_final = pd.read_csv(DATA/"../data/DF_features_400_2019.csv",index_col=0)
# Quitar modelos por homologia deltraining set
#df_final_onlyHM = df_final.loc[df_final.index.str.startswith("HM")]
#df_final= df_final.loc[~df_final.index.str.startswith("HM")]
index_ddg8 = (df_final['ddG(kcal/mol)']==8)
df_final = df_final.loc[-index_ddg8]
#testiar eliminando estructuras con ddg menor o igual a -4 kcal/mol , outliers
index_ddg_4 = (df_final['ddG(kcal/mol)'] <= -4)
df_final = df_final.loc[-index_ddg_4]
pdb_names = df_final.index
features_names = df_final.drop('ddG(kcal/mol)',axis=1).columns
# forma 1
df_final['class'] = np.where((df_final['ddG(kcal/mol)'] < -0.4) | (df_final['ddG(kcal/mol)'] > 2.4),0,1)
# forma 2
#df_final['class'] = np.where((df_final['ddG(kcal/mol)'] < 0),1,0)
print("Before OverSampling, counts of label '1': {}".format(sum(df_final['class'] == 1)))
print("Before OverSampling, counts of label '0': {}".format(sum(df_final['class'] == 0)))
X = df_final.drop('class',axis=1)
y = df_final['class']
smote = ovs.SMOTE(random_state=12,m_neighbors=25)
X_re , y__re = smote.fit_sample(X,y)
# back to originalk shape and target
X_normal = X_re[:,:-1]
y_normal = X_re[:,-1]
final_svr = grid1.best_estimator_.fit(X_normal,y_normal)
# save final model
joblib.dump(final_svr, 'SVRmodel_400.linear.v1.pkl')
rmse_test = np.round(np.sqrt(mean_squared_error(y_test, y_test_pred)), 3)
df_pred = pd.DataFrame({"Predicted ddG(kcal/mol)": y_test_pred, "Actual ddG(kcal/mol)": y_test.values})
pearsonr_test = round(df_pred.corr().iloc[0,1],3)
g = sns.regplot(x="Actual ddG(kcal/mol)", y="Predicted ddG(kcal/mol)",data=df_pred)
plt.title("Predicted vs Experimental ddG (Independent set: 123 complexes)")
plt.text(-2,3,"pearsonr = %s" %pearsonr_test)
plt.text(4.5,-0.5,"RMSE = %s" %rmse_test)
#plt.savefig("RFmodel_300_testfit.png",dpi=600)
df_train_pred = pd.DataFrame({"Predicted ddG(kcal/mol)": y_train, "Actual ddG(kcal/mol)": y_train_pred})
pearsonr_train = round(df_train_pred.corr().iloc[0,1],3)
rmse_train = np.round(np.sqrt(mean_squared_error(y_train, y_train_pred)), 3)
g = sns.regplot(x="Actual ddG(kcal/mol)", y="Predicted ddG(kcal/mol)",data=df_train_pred)
plt.text(-0.4,6.5,"pearsonr = %s" %pearsonr_train)
plt.text(3.5,-2.5,"RMSE = %s" %rmse_train)
plt.title("Predicted vs Experimental ddG (Train set: 492 complexes)")
#plt.savefig("RFmodel_300_trainfit.png",dpi=600)
```
| github_jupyter |
```
import numpy as np
import tools as t
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from collections import defaultdict
import re
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (10.0, 8.0)
%matplotlib inline
%load_ext autoreload
%autoreload 2
import gensim
data = pd.read_csv("news.csv")
paragraph = np.array(data["paragraph"] )
headline = np.array(data["title"] )
print paragraph.shape
print headline.shape
index = ['paragraph']
dataframe = pd.DataFrame()
dataframe['paragraph']=paragraph
dataframe.to_csv("test.csv")
def values():
return 0
unique = defaultdict(values)
N = headline.shape[0]
for i in range (N):
line = str(headline[i])
line=re.sub('[\n]',' ',line)
line=re.sub('[:]',' ',line)
line=re.sub('[-?",()\']',' ',line)
lines = line.split(".")
for sent in lines:
#print word
#word = word.lower().strip()
words = sent.split()
for word in words:
word = word.lower().strip()
word = word.decode('utf-8')
#word = word.replace('\u','')
#word = str(word)
#word = word.replace('\u','')
unique[word] += 1
for i in range (N):
line = paragraph[i]
lines = str(line).split(".")
for sent in lines:
#word = word.lower().strip()
sent=re.sub('[\n]',' ',sent)
sent=re.sub('[:]',' ',sent)
sent=re.sub('[-?",()\']',' ',sent)
words = sent.split()
for word in words:
word = word.lower().strip()
word = word.decode('utf8')
#word = word.replace('\u','')
#word = word.replace('\xa0','')
#word = word.replace('\xc2','')
#word = word.replace('\u','')
#word = word.decode("utf-8").encode("ascii", "ignore")
#word = re.sub(r'[^\x00-\x7f]',' ', word)
unique[word] += 1
words = unique.keys()
#print len(words)
print words[0:100]
#print type(words[2])
# Load Google's pre-trained Word2Vec model.
model = gensim.models.KeyedVectors.load_word2vec_format('./data/GoogleNews-vectors-negative300.bin', binary=True)
#vectorizer_word2Vec = CountVectorizer()
#vectorizer_word2Vec.fit(X)
word2vec = defaultdict()
for w in words:
#w = unicode(w).replace("\r", " ").replace("\n", " ").replace("\t", '').replace("\"", "")
#w = w.encode('utf-8')
#w = w.replace('\u','')
#word = word
if w in model:
word2vec[w] = model[w]
with open("reduced_worc2vec", "wb") as output_file:
pickle.dump(word2vec, output_file)
with open("reduced_worc2vec", "r") as input_file:
word2vec=pickle.load(input_file)
print len(word2vec.keys())
print word2vec["pakistan"]
#embeddings =np.zeros((paragraph.shape[0],300))
for i in range (0,paragraph.shape[0]):
wembedding = np.zeros((300,))
comment = paragraph[i]
words = comment.split()
length=0
for word in words:
try:
wembedding+=word2vec[word.lower().strip()]
length+=1
except:
continue
wembedding/=length
embeddings[i]=wembedding
text_test = np.array(text_test)
test_embeddings =np.zeros((text_test.shape[0],300))
# Parameters
learning_rate = 0.01
num_steps = 500
batch_size = 128
display_step = 100
# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 300 # MNIST data input (img shape: 28*28)
num_classes = 2 # MNIST total classes (0-9 digits)
# tf Graph input
X = tf.placeholder("float", [None, num_input])
Y = tf.placeholder("float", [None, num_classes])
print embeddings.shape
print test_embeddings.shape
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([num_classes]))
}
# Create model
def neural_net(x):
# Hidden fully connected layer with 256 neurons
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
# Hidden fully connected layer with 256 neurons
layer_1=tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
# Output fully connected layer with a neuron for each class
layer_2=tf.nn.relu(layer_2);
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# Construct model
logits = neural_net(X)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
# reg=tf.reduce_sum(tf.square(weights))
# cost=tf.add(loss_op,reg)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(logits,axis=1), tf.argmax(Y,axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
y_train = np.array(y_train)
y_test = np.array(y_test)
#print
from sklearn.preprocessing import MultiLabelBinarizer
encoder = MultiLabelBinarizer()
one_train = encoder.fit_transform(y_train[:,np.newaxis])
one_test = encoder.fit_transform(y_test[:,np.newaxis])
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
#start_size=0
#end_size=batch_size
for step in range(1, num_steps+1):
#batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop)
#indices=np.arange(X_train.shape[0])
indices=np.random.randint(0,embeddings.shape[0],size=batch_size)
#np.random.shuffle(indices)
batch_x=embeddings[indices]
batch_y=one_train[indices]
#batch_y=batch_y.reshape(batch_y.shape[0],1)
#Loss=0
#Acc=0
#print batch_x.shape
#print batch_y.shape
#print batch_x
#print batch_y
sess.run(train_op,feed_dict={X:batch_x,Y:batch_y})
if step %display_step == 0 or step==1:
#for j in range (X_train.shape[0]/batch_size):
#batch_x=X_train[indices[j*batch_size:(j+1)*batch_size]]
#batch_y=y_train[indices[j*batch_size:(j+1)*batch_size]]
#sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
#if step % display_step == 0 or step == 1:
# Calculate batch loss and accuracy
loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
#Loss+=loss
#Acc+=acc
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
#print "Loss ",Loss/(X_train.shape[0]/batch_size)," Accuracy", Acc/(X_train.shape[0]/batch_size)
print("Optimization Finished!")
# Calculate accuracy for MNIST test images
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={X: test_embeddings,
Y: one_test}))
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@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.
```
# pandas.DataFrame 로드
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tutorials/load_data/pandas_dataframe"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/load_data/pandas_dataframe.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab에서 실행하기</a></td>
<td><a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/load_data/pandas_dataframe.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub에서소스 보기</a></td>
<td><a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/load_data/pandas_dataframe.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">노트북 다운로드하기</a></td>
</table>
이 튜토리얼은 pandas 데이터 프레임을 `tf.data.Dataset`에 로드하는 방법의 예제를 제공합니다.
이 튜토리얼에서는 Cleveland Clinic Foundation for Heart Disease에서 제공하는 작은 [데이터세트를](https://archive.ics.uci.edu/ml/datasets/heart+Disease) 사용합니다. CSV에는 수백 개의 행이 있습니다. 각 행은 환자를 설명하고 각 열은 속성을 설명합니다. 이 정보를 사용하여 이 데이터세트에서 환자가 심장 질환이 있는지 여부를 예측하는 이진 분류 작업입니다.
## pandas를 사용하여 데이터 읽기
```
import pandas as pd
import tensorflow as tf
```
심장 데이터세트가 포함된 csv 파일을 다운로드합니다.
```
csv_file = tf.keras.utils.get_file('heart.csv', 'https://storage.googleapis.com/applied-dl/heart.csv')
```
pandas를 사용하여 csv 파일을 읽습니다.
```
df = pd.read_csv(csv_file)
df.head()
df.dtypes
```
데이터 프레임의 `object` `thal` 열을 이산 숫자 값으로 변환합니다.
```
df['thal'] = pd.Categorical(df['thal'])
df['thal'] = df.thal.cat.codes
df.head()
```
## `tf.data.Dataset`를 사용하여 데이터 로드하기
`tf.data.Dataset.from_tensor_slices`를 사용하여 pandas 데이터 프레임에서 값을 읽습니다.
`tf.data.Dataset`를 사용할 때의 이점 중 하나는 간단하고 효율적인 데이터 파이프라인을 작성할 수 있다는 것입니다. 자세한 내용은 [데이터 로드 가이드](https://www.tensorflow.org/guide/data)를 참조하세요.
```
target = df.pop('target')
dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))
for feat, targ in dataset.take(5):
print ('Features: {}, Target: {}'.format(feat, targ))
```
`pd.Series`는 `__array__` 프로토콜을 구현하므로 `np.array` 또는 `tf.Tensor`를 사용하는 거의 모든 곳에서 투명하게 사용할 수 있습니다.
```
tf.constant(df['thal'])
```
데이터세트를 섞고 배치 처리합니다.
```
train_dataset = dataset.shuffle(len(df)).batch(1)
```
## 모델 생성 및 훈련
```
def get_compiled_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
return model
model = get_compiled_model()
model.fit(train_dataset, epochs=15)
```
## 특성 열의 대안
사전을 모델에 대한 입력으로 전달하는 것은 `tf.keras.layers.Input` 레이어의 일치하는 사전을 작성하는 것만큼 간편하며, [함수형 API](../../guide/keras/functional.ipynb)를 사용하여 필요한 사전 처리를 적용하고 레이어를 쌓습니다. [특성 열](../keras/feature_columns.ipynb)의 대안으로 사용할 수 있습니다.
```
inputs = {key: tf.keras.layers.Input(shape=(), name=key) for key in df.keys()}
x = tf.stack(list(inputs.values()), axis=-1)
x = tf.keras.layers.Dense(10, activation='relu')(x)
output = tf.keras.layers.Dense(1)(x)
model_func = tf.keras.Model(inputs=inputs, outputs=output)
model_func.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
`tf.data`와 함께 사용했을 때 `pd.DataFrame`의 열 구조를 유지하는 가장 쉬운 방법은 `pd.DataFrame`을 `dict`로 변환하고 해당 사전을 조각화하는 것입니다.
```
dict_slices = tf.data.Dataset.from_tensor_slices((df.to_dict('list'), target.values)).batch(16)
for dict_slice in dict_slices.take(1):
print (dict_slice)
model_func.fit(dict_slices, epochs=15)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/jzinnegger/differential-ml/blob/main/Illustrations.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## Illustration of pathwise learning with differentials
The notebook illustrates the pathwise learning of the fair value and delta (as a function of the underlying stock price) in the Black Scholes setup. The example is based on the work of Brian Huge and Antoine Savine (see Working paper: https://arxiv.org/abs/2005.02347 and GitHub: https://github.com/differential-machine-learning).
The samples of the initial stock price $S_1$ at $T_1$ are drawn from a uniform distribution. In the original example the initial state space at $T_1$ can be seen as a time slice of the (simulated) process starting at $T_0$. The time slice approach is convenient to the derive a consitent state space for a higher dimensional market model where all paths follow the same underlying model and calibration.
The twin neural network is indepedently implemented in Keras/Tensorflow2.
The implementation of the model is provided in [Github: jzinnegger/differential-ml](https://github.com/jzinnegger/differential-ml/)
```
import numpy as np
import matplotlib.pyplot as plt
import time
import datetime
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tqdm.keras import TqdmCallback
from scipy.stats import norm
import pathlib
import shutil
import tempfile
tf.keras.backend.set_floatx('float32') # default
real_type = tf.float32
# clone git
import os
os.chdir("/content")
!rm -rf differential-ml
!git clone --depth=1 https://github.com/jzinnegger/differential-ml.git
os.chdir("./differential-ml")
from my_python.models import *
```
### Generate training data of pathwise values and deltas
```
import numpy as np
from scipy.stats import norm
# helper analytics
def bsPrice(spot, strike, vol, T):
d1 = (np.log(spot/strike) + vol * vol * T) / vol / np.sqrt(T)
d2 = d1 - vol * np.sqrt(T)
return spot * norm.cdf(d1) - strike * norm.cdf(d2)
def bsDelta(spot, strike, vol, T):
d1 = (np.log(spot/strike) + vol * vol * T) / vol / np.sqrt(T)
return norm.cdf(d1)
def bsVega(spot, strike, vol, T):
d1 = (np.log(spot/strike) + vol * vol * T) / vol / np.sqrt(T)
return spot * np.sqrt(T) * norm.pdf(d1)
#
# main class
class BlackScholes:
def __init__(self,
vol=0.2,
T1=1,
T2=2,
K=1.10,
volMult=1.5,
lower=0.35,
upper=1.65):
self.spot = 1
self.vol = vol
self.T1 = T1
self.T2 = T2
self.K = K
self.volMult = volMult
# training set: returns S1 (mx1), C2 (mx1) and dC2/dS1 (mx1)
def trainingSet(self, m, anti=True, seed=None):
np.random.seed(seed)
# 2 sets of normal returns
returns = np.random.normal(size=[m, 2])
# SDE
vol0 = self.vol * self.volMult
R1 = np.exp(-0.5*vol0*vol0*self.T1 + vol0*np.sqrt(self.T1)*returns[:,0])
R2 = np.exp(-0.5*self.vol*self.vol*(self.T2-self.T1) \
+ self.vol*np.sqrt(self.T2-self.T1)*returns[:,1])
S1 = self.spot * R1
S2 = S1 * R2
# payoff
pay = np.maximum(0, S2 - self.K)
# two antithetic paths
if anti:
R2a = np.exp(-0.5*self.vol*self.vol*(self.T2-self.T1) \
- self.vol*np.sqrt(self.T2-self.T1)*returns[:,1])
S2a = S1 * R2a
paya = np.maximum(0, S2a - self.K)
X = S1
Y = 0.5 * (pay + paya)
# differentials
Z1 = np.where(S2 > self.K, R2, 0.0).reshape((-1,1))
Z2 = np.where(S2a > self.K, R2a, 0.0).reshape((-1,1))
Z = 0.5 * (Z1 + Z2)
# standard
else:
X = S1
Y = pay
# differentials
Z = np.where(S2 > self.K, R2, 0.0).reshape((-1,1))
return X.reshape([-1,1]), Y.reshape([-1,1]), Z.reshape([-1,1])
def trainingSetUniformS1(self, m, lower=0.2, upper=2.0, anti=True, seed=None):
np.random.seed(seed)
# 1 set of uniform samples in the one-dim parameter space for S1=S1(R1)
S1 = np.random.uniform(lower,upper,m) * self.spot
# 2 sets of normal returns, only R2 required
returns = np.random.normal(size=[m, 1])
# SDE
R2 = np.exp(-0.5*self.vol*self.vol*(self.T2-self.T1) \
+ self.vol*np.sqrt(self.T2-self.T1)*returns[:,0])
# S1 = self.spot * R1
S2 = S1 * R2
# payoff
pay = np.maximum(0, S2 - self.K)
# two antithetic paths
if anti:
R2a = np.exp(-0.5*self.vol*self.vol*(self.T2-self.T1) \
- self.vol*np.sqrt(self.T2-self.T1)*returns[:,0])
S2a = S1 * R2a
paya = np.maximum(0, S2a - self.K)
X = S1
Y = 0.5 * (pay + paya)
# differentials
Z1 = np.where(S2 > self.K, R2, 0.0).reshape((-1,1))
Z2 = np.where(S2a > self.K, R2a, 0.0).reshape((-1,1))
Z = 0.5 * (Z1 + Z2)
# standard
else:
X = S1
Y = pay
# differentials
Z = np.where(S2 > self.K, R2, 0.0).reshape((-1,1))
return X.reshape([-1,1]), Y.reshape([-1,1]), Z.reshape([-1,1])
# test set: returns a grid of uniform spots
# with corresponding ground true prices, deltas and vegas
def testSet(self, lower=0.35, upper=1.65, num=100, seed=None):
spots = np.linspace(lower, upper, num).reshape((-1, 1))
# compute prices, deltas and vegas
prices = bsPrice(spots, self.K, self.vol, self.T2 - self.T1).reshape((-1, 1))
deltas = bsDelta(spots, self.K, self.vol, self.T2 - self.T1).reshape((-1, 1))
vegas = bsVega(spots, self.K, self.vol, self.T2 - self.T1).reshape((-1, 1))
return spots, spots, prices, deltas, vegas
```
### Training values and deltas jointly with the twin network
Equal weighting of values and differentials in the training (alpha = 0.5)
```
weightSeed = np.random.randint(0, 10000)
log_dir = "tensorboard_logs/"
#!mkdir {log_dir}f"illu_bs"
nTest = 4096
sizes = [4096, 4096*2, 4096*4]
generator = BlackScholes()
x_train, y_train, dydx_train = generator.trainingSetUniformS1(max(sizes), seed=None, anti=False)
x_true, x_axis, y_true, dydx_true, vegas = generator.testSet(num=nTest, lower = 0.2, upper=2.0, seed=None)
size=sizes[2]
prep_layer, scaled_MSE = preprocess_data(x_train, y_train, dydx_train, prep_type='Normalisation')
model = build_and_compile_model(prep_layer.output_n(),
get_model_autodiff,
scaled_MSE,
lr_schedule = lr_inv_time_decay, # lr_warmup, lr_inv_time_decay
alpha = 0.5
)
history = train_model(model,
prep_layer,
f"illu_bs",
x_train[0:size,:],
y_train[0:size,:],
dydx_train[0:size,:],
epochs=EPOCHS,
x_true = x_true,
y_true = y_true,
dydx_true = dydx_true)
y_pred, dydx_pred = predict_unscaled(model, prep_layer, x_true)
```
### Illustration
```
fig, ax = plt.subplots(1, 2, sharex='row', figsize=(18,7), squeeze=False)
sample_path = 300
# Fair value
ax[0,0].plot(x_train * 100, y_train, 'c.', markersize=1.5, markerfacecolor='white', label='Training data: Pathwise values')
ax[0,0].plot(x_axis*100, y_pred, 'b.', markersize=0.5, markerfacecolor='white', label='Prediction: Expected values')
ax[0,0].plot(x_train[sample_path] * 100, y_train[sample_path], 'ro', markersize=7, markerfacecolor='r', label=f"Training data: Path {sample_path:d}")
# ax[0,0].plot(x_axis*100, y_true, 'r.', markersize=0.5, markerfacecolor='white', label='True values')
#ax[0,0].set_xlim(0.60*100, 1.65*100)
ax[0,0].set_ylim(-0.01, 0.6)
ax[0,0].set_title("Fair value")
ax[0,0].legend(loc='upper left')
ax[0,0].set_xlabel('Initial stock price at $T_1$')
# Deltas
deltidx=0
ax[0,1].plot(x_train * 100, dydx_train[:,deltidx], 'c.', markersize=1.5, markerfacecolor='white', label='Training data: Pathwise deltas')
ax[0,1].plot(x_axis*100, dydx_pred[:,deltidx], 'b.', markersize=0.5, markerfacecolor='white', label='Prediction: Expected deltas')
ax[0,1].plot(x_train[sample_path] * 100, dydx_train[sample_path,deltidx], 'ro', markersize=7, markerfacecolor='r', label=f"Training data: Path {sample_path:d}")
# ax[0,1].plot(x_axis*100, dydx_true[:,deltidx], 'r.', markersize=0.5, markerfacecolor='white', label='True deltas')
ax[0,1].set_ylim(-0.05, 2)
ax[0,1].set_title("Delta")
ax[0,1].legend(loc='upper left')
ax[0,1].set_xlabel('Initial stock price at $T_1$')
plt.xlim(0.6*100, 1.65*100)
plt.savefig('illustration_1.png')
plt.show()
```
### Train net on values only.
Alpha = 1
```
prep_layer, scaled_MSE = preprocess_data(x_train, y_train, dydx_train, prep_type='NoNormalisation')
model = build_and_compile_model(prep_layer.output_n(),
get_model_autodiff,
scaled_MSE,
lr_schedule = lr_inv_time_decay, # lr_warmup, lr_inv_time_decay
alpha = 1)
history = train_model(model,
prep_layer,
f"illu_bs",
x_train[0:size,:],
y_train[0:size,:],
dydx_train[0:size,:],
epochs=EPOCHS,
x_true = x_true,
y_true = y_true,
dydx_true = dydx_true)
y_pred, dydx_pred = predict_unscaled(model, prep_layer, x_true)
fig, ax = plt.subplots(1, 2, sharex='row', figsize=(18,7), squeeze=False)
# Fair value
ax[0,0].plot(x_train * 100, y_train, 'c.', markersize=1.5, markerfacecolor='white', label='Training data: Pathwise values')
ax[0,0].plot(x_axis*100, y_pred, 'b.', markersize=0.5, markerfacecolor='white', label='Prediction: Expected values')
ax[0,0].plot(x_train[sample_path] * 100, y_train[sample_path], 'ro', markersize=7, markerfacecolor='r', label=f"Training data: Path {sample_path:d}")
# ax[0,0].plot(x_axis*100, y_true, 'r.', markersize=0.5, markerfacecolor='white', label='True values')
#ax[0,0].set_xlim(0.60*100, 1.65*100)
ax[0,0].set_ylim(-0.01, 0.6)
ax[0,0].set_title("Fair value")
ax[0,0].legend(loc='upper left')
ax[0,0].set_xlabel('Initial stock price at $T_1$')
# Deltas
deltidx=0
# ax[0,1].plot(x_train * 100, dydx_train[:,deltidx], 'c.', markersize=1.5, markerfacecolor='white', label='Training data: Pathwise deltas')
ax[0,1].plot(x_axis*100, dydx_pred[:,deltidx], 'b.', markersize=0.5, markerfacecolor='white', label='Prediction: Expected deltas')
# ax[0,1].plot(x_axis*100, dydx_true[:,deltidx], 'r.', markersize=0.5, markerfacecolor='white', label='True deltas')
ax[0,1].set_ylim(-0.05, 2)
ax[0,1].set_title("Delta")
ax[0,1].legend(loc='upper left')
ax[0,1].set_xlabel('Initial stock price at $T_1$')
plt.xlim(0.6*100, 1.65*100)
plt.savefig('illustration_2.png')
plt.show()
```
| github_jupyter |
# Python Loop Performance
> Andrew Kubera
Q: You have a collection, or some iterator/generator, and you want to apply some function to each item. How do you do it?
If you don't want to create a new collection, just do for loop
```python
for x in things:
func(x)
```
If you DO want to create a new collection, do NOT
```python
>>> result = []
>>> for x in things:
>>> result.append(func(x))
```
do
```python
>>> result = [func(x) for x in things]
```
But there *may* be a better way!
`map(function, *iterables)`
```python
result = map(func, things) # WRONG
```
result is now a 'map' object (iterable) - not a collection.
Wrap in a collection (list, tuple, set, etc...) to get your result
```python
result = list(map(func, things))
result == [func(x) for x in things] # True!
```
But which is better?
```
import this
```
I care about performance, so let's do some timeit examples
```
import sys, platform
print(sys.version)
print("---")
print(*platform.uname()[3:])
```
---
Transform a list of numbers into hex strings
```
hex(61)
%timeit [hex(x) for x in range(500)]
%timeit [hex(x) for x in range(5000)]
%timeit [hex(x) for x in range(50000)]
%timeit list(map(hex, range(500)))
%timeit list(map(hex, range(5000)))
%timeit list(map(hex, range(50000)))
"%.3f, %0.3f, %0.3f" % ((79.5 - 70.8) / 0.795, (897 - 815) / 8.97, (10.2 - 9.19) / .102)
```
There should be no reason why tuples or lists should be more efficient
```
%timeit tuple(map(hex, range(500)))
%timeit tuple(map(hex, range(5000)))
%timeit tuple(map(hex, range(50000)))
```
Let's try again with a `lambda` calling hex instead of just hex.
There is no reason why this should be faster, and I don't expect it to be
```
%timeit list(map(lambda i: hex(i), range(500)))
%timeit list(map(lambda i: hex(i), range(5000)))
%timeit list(map(lambda i: hex(i), range(50000)))
```
Hmm, looks like map is winning if the method is right there, but using the lambda slows it down by A LOT.
Give a little math to the library - hex the square of each number
```
%timeit -n 1000 [hex(x ** 2) for x in range(500)]
%timeit -n 500 [hex(x ** 2) for x in range(5000)]
%timeit -n 200 [hex(x ** 2) for x in range(50000)]
%timeit -n 1000 list(map(lambda i: hex(i ** 2), range(500)))
%timeit -n 500 list(map(lambda i: hex(i ** 2), range(5000)))
%timeit -n 200 list(map(lambda i: hex(i ** 2), range(50000)))
"%.3f, %0.3f, %0.3f" % ((274 - 346) / 2.74, (2.89 - 3.50) / .0289, (32.7 - 37.5) / 0.327)
```
hmm, decrease in efficiency by ~20%!!
```
%timeit -n 1000 list((hex(i ** 2) for i in range(500)))
%timeit -n 1000 list((hex(i ** 2) for i in range(5000)))
%timeit -n 1000 list((hex(i ** 2) for i in range(50000)))
```
Huh, that's actually worse than the list comprehension from before, too bad.
```
%timeit -n 1000 list(map(hex, (i ** 2 for i in range(500))))
%timeit -n 400 list(map(hex, (i ** 2 for i in range(5000))))
%timeit -n 100 list(map(hex, (i ** 2 for i in range(50000))))
%timeit -n 1000 [hex(i) for i in (i ** 2 for i in range(500))]
%timeit -n 400 [hex(i) for i in (i ** 2 for i in range(5000))]
%timeit -n 100 [hex(i) for i in (i ** 2 for i in range(50000))]
def hexsquare(x):
return hex(x ** 2)
%timeit -n 1000 list(map(hexsquare, range(500)))
%timeit -n 500 list(map(hexsquare, range(5000)))
%timeit -n 100 list(map(hexsquare, range(50000)))
```
The lambda performs better than the function by a marginal amount ~2%
| github_jupyter |
# CNTK 103 Part A: MNIST Data Loader
This tutorial is targeted to individuals who are new to CNTK and to machine learning. We assume you have completed or are familiar with CNTK 101 and 102. In this tutorial, we will download and pre-process the MNIST digit images to be used for building different models to recognize handwritten digits. We will extend CNTK 101 and 102 to be applied to this data set. Additionally we will introduce a convolutional network to achieve superior performance. This is the first example, where we will train and evaluate a neural network based model on read real world data.
CNTK 103 tutorial is divided into multiple parts:
- Part A: Familiarize with the [MNIST][] database that will be used later in the tutorial
- Subsequent parts in this 103 series would be using the MNIST data with different types of networks.
[MNIST]: http://yann.lecun.com/exdb/mnist/
```
# Import the relevant modules to be used later
from __future__ import print_function
import gzip
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
import struct
import sys
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
# Config matplotlib for inline plotting
%matplotlib inline
```
## Data download
We will download the data into local machine. The MNIST database is a standard handwritten digits that has been widely used for training and testing of machine learning algorithms. It has a training set of 60,000 images and a test set of 10,000 images with each image being 28 x 28 pixels. This set is easy to use visualize and train on any computer.
```
# Functions to load MNIST images and unpack into train and test set.
# - loadData reads image data and formats into a 28x28 long array
# - loadLabels reads the corresponding labels data, 1 for each image
# - load packs the downloaded image and labels data into a combined format to be read later by
# CNTK text reader
def loadData(src, cimg):
print ('Downloading ' + src)
gzfname, h = urlretrieve(src, './delete.me')
print ('Done.')
try:
with gzip.open(gzfname) as gz:
n = struct.unpack('I', gz.read(4))
# Read magic number.
if n[0] != 0x3080000:
raise Exception('Invalid file: unexpected magic number.')
# Read number of entries.
n = struct.unpack('>I', gz.read(4))[0]
if n != cimg:
raise Exception('Invalid file: expected {0} entries.'.format(cimg))
crow = struct.unpack('>I', gz.read(4))[0]
ccol = struct.unpack('>I', gz.read(4))[0]
if crow != 28 or ccol != 28:
raise Exception('Invalid file: expected 28 rows/cols per image.')
# Read data.
res = np.fromstring(gz.read(cimg * crow * ccol), dtype = np.uint8)
finally:
os.remove(gzfname)
return res.reshape((cimg, crow * ccol))
def loadLabels(src, cimg):
print ('Downloading ' + src)
gzfname, h = urlretrieve(src, './delete.me')
print ('Done.')
try:
with gzip.open(gzfname) as gz:
n = struct.unpack('I', gz.read(4))
# Read magic number.
if n[0] != 0x1080000:
raise Exception('Invalid file: unexpected magic number.')
# Read number of entries.
n = struct.unpack('>I', gz.read(4))
if n[0] != cimg:
raise Exception('Invalid file: expected {0} rows.'.format(cimg))
# Read labels.
res = np.fromstring(gz.read(cimg), dtype = np.uint8)
finally:
os.remove(gzfname)
return res.reshape((cimg, 1))
def try_download(dataSrc, labelsSrc, cimg):
data = loadData(dataSrc, cimg)
labels = loadLabels(labelsSrc, cimg)
return np.hstack((data, labels))
```
# Download the data
The MNIST data is provided as train and test set. Training set has 60000 images while the test set has 10000 images. Let us download the data.
```
# URLs for the train image and labels data
url_train_image = 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz'
url_train_labels = 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz'
num_train_samples = 60000
print("Downloading train data")
train = try_download(url_train_image, url_train_labels, num_train_samples)
url_test_image = 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz'
url_test_labels = 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz'
num_test_samples = 10000
print("Downloading test data")
test = try_download(url_test_image, url_test_labels, num_test_samples)
```
# Visualize the data
```
# Plot a random image
sample_number = 5001
plt.imshow(train[sample_number,:-1].reshape(28,28), cmap="gray_r")
plt.axis('off')
print("Image Label: ", train[sample_number,-1])
```
# Save the images
Save the images in a local directory. While saving the data we flatten the images to a vector (28x28 image pixels becomes an array of length 784 data points).

The labels are encoded as [1-hot][] encoding (label of 3 with 10 digits becomes `0001000000`, where the first index corresponds to digit `0` and the last one corresponds to digit `9`.

[1-hot]: https://en.wikipedia.org/wiki/One-hot
```
# Save the data files into a format compatible with CNTK text reader
def savetxt(filename, ndarray):
dir = os.path.dirname(filename)
if not os.path.exists(dir):
os.makedirs(dir)
if not os.path.isfile(filename):
print("Saving", filename )
with open(filename, 'w') as f:
labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str)))
for row in ndarray:
row_str = row.astype(str)
label_str = labels[row[-1]]
feature_str = ' '.join(row_str[:-1])
f.write('|labels {} |features {}\n'.format(label_str, feature_str))
else:
print("File already exists", filename)
# Save the train and test files (prefer our default path for the data)
data_dir = os.path.join("..", "Examples", "Image", "DataSets", "MNIST")
if not os.path.exists(data_dir):
data_dir = os.path.join("data", "MNIST")
print ('Writing train text file...')
savetxt(os.path.join(data_dir, "Train-28x28_cntk_text.txt"), train)
print ('Writing test text file...')
savetxt(os.path.join(data_dir, "Test-28x28_cntk_text.txt"), test)
print('Done')
```
**Suggested Explorations**
One can do data manipulations to improve the performance of a machine learning system. I suggest you first use the data generated so far and run the classifier in subsequent parts of the CNTK 103 tutorial series. Once you have a baseline with classifying the data in its original form, now use the different data manipulation techniques to further improve the model.
There are several ways data alterations can be performed. CNTK readers automate a lot of these actions for you. However, to get a feel for how these transforms can impact training and test accuracies, I strongly encourage individuals to try one or more of data perturbation.
- Shuffle the training data (rows to create a different). Hint: Use `permute_indices = np.random.permutation(train.shape[0])`. Then run Part B of the tutorial with this newly permuted data.
- Adding noise to the data can often improves [generalization error][]. You can augment the training set by adding noise (generated with numpy, hint: use `numpy.random`) to the training images.
- Distort the images with [affine transformation][] (translations or rotations)
[generalization error]: https://en.wikipedia.org/wiki/Generalization_error
[affine transformation]: https://en.wikipedia.org/wiki/Affine_transformation
| github_jupyter |
<a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/9gegpsmnsoo25ikkbl4qzlvlyjbgxs5x.png" width = 400> </a>
<h1 align=center><font size = 5>From Understanding to Preparation</font></h1>
## Introduction
In this lab, we will continue learning about the data science methodology, and focus on the **Data Understanding** and the **Data Preparation** stages.
## Table of Contents
<div class="alert alert-block alert-info" style="margin-top: 20px">
1. [Recap](#0)<br>
2. [Data Understanding](#2)<br>
3. [Data Preparation](#4)<br>
</div>
<hr>
# Recap <a id="0"></a>
In Lab **From Requirements to Collection**, we learned that the data we need to answer the question developed in the business understanding stage, namely *can we automate the process of determining the cuisine of a given recipe?*, is readily available. A researcher named Yong-Yeol Ahn scraped tens of thousands of food recipes (cuisines and ingredients) from three different websites, namely:
<img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab3_fig1_allrecipes.png" width=500>
www.allrecipes.com
<img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab3_fig2_epicurious.png" width=500>
www.epicurious.com
<img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab3_fig3_menupan.png" width=500>
www.menupan.com
For more information on Yong-Yeol Ahn and his research, you can read his paper on [Flavor Network and the Principles of Food Pairing](http://yongyeol.com/papers/ahn-flavornet-2011.pdf).
We also collected the data and placed it on an IBM server for your convenience.
------------
# Data Understanding <a id="2"></a>
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab3_fig4_flowchart_data_understanding.png" width=500>
<strong> Important note:</strong> Please note that you are not expected to know how to program in Python. The following code is meant to illustrate the stages of data understanding and data preparation, so it is totally fine if you do not understand the individual lines of code. We have a full course on programming in Python, <a href="http://cocl.us/PY0101EN_DS0103EN_LAB3_PYTHON_Coursera"><strong>Python for Data Science</strong></a>, which is also offered on Coursera. So make sure to complete the Python course if you are interested in learning how to program in Python.
### Using this notebook:
To run any of the following cells of code, you can type **Shift + Enter** to excute the code in a cell.
Get the version of Python installed.
```
# check Python version
!python -V
```
Download the library and dependencies that we will need to run this lab.
```
import pandas as pd # import library to read data into dataframe
pd.set_option('display.max_columns', None)
import numpy as np # import numpy library
import re # import library for regular expression
```
Download the data from the IBM server and read it into a *pandas* dataframe.
```
recipes = pd.read_csv("https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/data/recipes.csv")
print("Data read into dataframe!") # takes about 30 seconds
```
Show the first few rows.
```
recipes.head()
```
Get the dimensions of the dataframe.
```
recipes.shape
```
So our dataset consists of 57,691 recipes. Each row represents a recipe, and for each recipe, the corresponding cuisine is documented as well as whether 384 ingredients exist in the recipe or not, beginning with almond and ending with zucchini.
We know that a basic sushi recipe includes the ingredients:
* rice
* soy sauce
* wasabi
* some fish/vegetables
Let's check that these ingredients exist in our dataframe:
```
ingredients = list(recipes.columns.values)
print([match.group(0) for ingredient in ingredients for match in [(re.compile(".*(rice).*")).search(ingredient)] if match])
print([match.group(0) for ingredient in ingredients for match in [(re.compile(".*(wasabi).*")).search(ingredient)] if match])
print([match.group(0) for ingredient in ingredients for match in [(re.compile(".*(soy).*")).search(ingredient)] if match])
```
Yes, they do!
* rice exists as rice.
* wasabi exists as wasabi.
* soy exists as soy_sauce.
So maybe if a recipe contains all three ingredients: rice, wasabi, and soy_sauce, then we can confidently say that the recipe is a **Japanese** cuisine! Let's keep this in mind!
----------------
# Data Preparation <a id="4"></a>
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab3_fig5_flowchart_data_preparation.png" width=500>
In this section, we will prepare data for the next stage in the data science methodology, which is modeling. This stage involves exploring the data further and making sure that it is in the right format for the machine learning algorithm that we selected in the analytic approach stage, which is decision trees.
First, look at the data to see if it needs cleaning.
```
recipes["country"].value_counts() # frequency table
```
By looking at the above table, we can make the following observations:
1. Cuisine column is labeled as Country, which is inaccurate.
2. Cuisine names are not consistent as not all of them start with an uppercase first letter.
3. Some cuisines are duplicated as variation of the country name, such as Vietnam and Vietnamese.
4. Some cuisines have very few recipes.
#### Let's fixes these problems.
Fix the name of the column showing the cuisine.
```
column_names = recipes.columns.values
column_names[0] = "cuisine"
recipes.columns = column_names
recipes
```
Make all the cuisine names lowercase.
```
recipes["cuisine"] = recipes["cuisine"].str.lower()
```
Make the cuisine names consistent.
```
recipes.loc[recipes["cuisine"] == "austria", "cuisine"] = "austrian"
recipes.loc[recipes["cuisine"] == "belgium", "cuisine"] = "belgian"
recipes.loc[recipes["cuisine"] == "china", "cuisine"] = "chinese"
recipes.loc[recipes["cuisine"] == "canada", "cuisine"] = "canadian"
recipes.loc[recipes["cuisine"] == "netherlands", "cuisine"] = "dutch"
recipes.loc[recipes["cuisine"] == "france", "cuisine"] = "french"
recipes.loc[recipes["cuisine"] == "germany", "cuisine"] = "german"
recipes.loc[recipes["cuisine"] == "india", "cuisine"] = "indian"
recipes.loc[recipes["cuisine"] == "indonesia", "cuisine"] = "indonesian"
recipes.loc[recipes["cuisine"] == "iran", "cuisine"] = "iranian"
recipes.loc[recipes["cuisine"] == "italy", "cuisine"] = "italian"
recipes.loc[recipes["cuisine"] == "japan", "cuisine"] = "japanese"
recipes.loc[recipes["cuisine"] == "israel", "cuisine"] = "jewish"
recipes.loc[recipes["cuisine"] == "korea", "cuisine"] = "korean"
recipes.loc[recipes["cuisine"] == "lebanon", "cuisine"] = "lebanese"
recipes.loc[recipes["cuisine"] == "malaysia", "cuisine"] = "malaysian"
recipes.loc[recipes["cuisine"] == "mexico", "cuisine"] = "mexican"
recipes.loc[recipes["cuisine"] == "pakistan", "cuisine"] = "pakistani"
recipes.loc[recipes["cuisine"] == "philippines", "cuisine"] = "philippine"
recipes.loc[recipes["cuisine"] == "scandinavia", "cuisine"] = "scandinavian"
recipes.loc[recipes["cuisine"] == "spain", "cuisine"] = "spanish_portuguese"
recipes.loc[recipes["cuisine"] == "portugal", "cuisine"] = "spanish_portuguese"
recipes.loc[recipes["cuisine"] == "switzerland", "cuisine"] = "swiss"
recipes.loc[recipes["cuisine"] == "thailand", "cuisine"] = "thai"
recipes.loc[recipes["cuisine"] == "turkey", "cuisine"] = "turkish"
recipes.loc[recipes["cuisine"] == "vietnam", "cuisine"] = "vietnamese"
recipes.loc[recipes["cuisine"] == "uk-and-ireland", "cuisine"] = "uk-and-irish"
recipes.loc[recipes["cuisine"] == "irish", "cuisine"] = "uk-and-irish"
recipes
```
Remove cuisines with < 50 recipes.
```
# get list of cuisines to keep
recipes_counts = recipes["cuisine"].value_counts()
cuisines_indices = recipes_counts > 50
cuisines_to_keep = list(np.array(recipes_counts.index.values)[np.array(cuisines_indices)])
rows_before = recipes.shape[0] # number of rows of original dataframe
print("Number of rows of original dataframe is {}.".format(rows_before))
recipes = recipes.loc[recipes['cuisine'].isin(cuisines_to_keep)]
rows_after = recipes.shape[0] # number of rows of processed dataframe
print("Number of rows of processed dataframe is {}.".format(rows_after))
print("{} rows removed!".format(rows_before - rows_after))
```
Convert all Yes's to 1's and the No's to 0's
```
recipes = recipes.replace(to_replace="Yes", value=1)
recipes = recipes.replace(to_replace="No", value=0)
```
#### Let's analyze the data a little more in order to learn the data better and note any interesting preliminary observations.
Run the following cell to get the recipes that contain **rice** *and* **soy** *and* **wasabi** *and* **seaweed**.
```
recipes.head()
check_recipes = recipes.loc[
(recipes["rice"] == 1) &
(recipes["soy_sauce"] == 1) &
(recipes["wasabi"] == 1) &
(recipes["seaweed"] == 1)
]
check_recipes
```
Based on the results of the above code, can we classify all recipes that contain **rice** *and* **soy** *and* **wasabi** *and* **seaweed** as **Japanese** recipes? Why?
Double-click __here__ for the solution.
<!-- The correct answer is:
-->
Let's count the ingredients across all recipes.
```
# sum each column
ing = recipes.iloc[:, 1:].sum(axis=0)
# define each column as a pandas series
ingredient = pd.Series(ing.index.values, index = np.arange(len(ing)))
count = pd.Series(list(ing), index = np.arange(len(ing)))
# create the dataframe
ing_df = pd.DataFrame(dict(ingredient = ingredient, count = count))
ing_df = ing_df[["ingredient", "count"]]
#print(ing_df.to_string())
```
Now we have a dataframe of ingredients and their total counts across all recipes. Let's sort this dataframe in descending order.
```
ing_df.sort_values(["count"], ascending=False, inplace=True)
ing_df.reset_index(inplace=True, drop=True)
print(ing_df)
```
#### What are the 3 most popular ingredients?
Double-click __here__ for the solution.
<!-- The correct answer is:
// 1. Egg with 21,025 occurrences.
// 2. Wheat with 20,781 occurrences.
// 3. Butter with 20,719 occurrences.
-->
However, note that there is a problem with the above table. There are ~40,000 American recipes in our dataset, which means that the data is biased towards American ingredients.
**Therefore**, let's compute a more objective summary of the ingredients by looking at the ingredients per cuisine.
#### Let's create a *profile* for each cuisine.
In other words, let's try to find out what ingredients Chinese people typically use, and what is **Canadian** food for example.
```
cuisines = recipes.groupby("cuisine").mean()
cuisines.head()
```
As shown above, we have just created a dataframe where each row is a cuisine and each column (except for the first column) is an ingredient, and the row values represent the percentage of each ingredient in the corresponding cuisine.
**For example**:
* *almond* is present across 15.65% of all of the **African** recipes.
* *butter* is present across 38.11% of all of the **Canadian** recipes.
Let's print out the profile for each cuisine by displaying the top four ingredients in each cuisine.
```
num_ingredients = 4 # define number of top ingredients to print
# define a function that prints the top ingredients for each cuisine
def print_top_ingredients(row):
print(row.name.upper())
row_sorted = row.sort_values(ascending=False)*100
top_ingredients = list(row_sorted.index.values)[0:num_ingredients]
row_sorted = list(row_sorted)[0:num_ingredients]
for ind, ingredient in enumerate(top_ingredients):
print("%s (%d%%)" % (ingredient, row_sorted[ind]), end=' ')
print("\n")
# apply function to cuisines dataframe
create_cuisines_profiles = cuisines.apply(print_top_ingredients, axis=1)
```
At this point, we feel that we have understood the data well and the data is ready and is in the right format for modeling!
-----------
### Thank you for completing this lab!
This notebook was created by [Alex Aklson](https://www.linkedin.com/in/aklson/). We hope you found this lab session interesting. Feel free to contact us if you have any questions!
This notebook is part of a course on **Coursera** called *Data Science Methodology*. If you accessed this notebook outside the course, you can take this course, online by clicking [here](https://cocl.us/DS0103EN_Coursera_LAB3).
<hr>
Copyright © 2019 [Cognitive Class](https://cognitiveclass.ai/?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/).
| github_jupyter |
CI strings can be converted to the following formats via the `output_format` parameter:
* `compact`: only number strings without any seperators or whitespace, like "1714307103"
* `standard`: CI strings with proper whitespace in the proper places. Note that in the case of CI, the compact format is the same as the standard one.
Invalid parsing is handled with the `errors` parameter:
* `coerce` (default): invalid parsing will be set to NaN
* `ignore`: invalid parsing will return the input
* `raise`: invalid parsing will raise an exception
The following sections demonstrate the functionality of `clean_ec_ci()` and `validate_ec_ci()`.
### An example dataset containing CI strings
```
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"ci": [
'171430710-3',
'BE431150351',
'BE 428759497',
'BE431150351',
"002 724 334",
"hello",
np.nan,
"NULL",
],
"address": [
"123 Pine Ave.",
"main st",
"1234 west main heights 57033",
"apt 1 789 s maple rd manhattan",
"robie house, 789 north main street",
"1111 S Figueroa St, Los Angeles, CA 90015",
"(staples center) 1111 S Figueroa St, Los Angeles",
"hello",
]
}
)
df
```
## 1. Default `clean_ec_ci`
By default, `clean_ec_ci` will clean ci strings and output them in the standard format with proper separators.
```
from dataprep.clean import clean_ec_ci
clean_ec_ci(df, column = "ci")
```
## 2. Output formats
This section demonstrates the output parameter.
### `standard` (default)
```
clean_ec_ci(df, column = "ci", output_format="standard")
```
### `compact`
```
clean_ec_ci(df, column = "ci", output_format="compact")
```
## 3. `inplace` parameter
This deletes the given column from the returned DataFrame.
A new column containing cleaned CI strings is added with a title in the format `"{original title}_clean"`.
```
clean_ec_ci(df, column="ci", inplace=True)
```
## 4. `errors` parameter
### `coerce` (default)
```
clean_ec_ci(df, "ci", errors="coerce")
```
### `ignore`
```
clean_ec_ci(df, "ci", errors="ignore")
```
## 4. `validate_ec_ci()`
`validate_ec_ci()` returns `True` when the input is a valid CI. Otherwise it returns `False`.
The input of `validate_ec_ci()` can be a string, a Pandas DataSeries, a Dask DataSeries, a Pandas DataFrame and a dask DataFrame.
When the input is a string, a Pandas DataSeries or a Dask DataSeries, user doesn't need to specify a column name to be validated.
When the input is a Pandas DataFrame or a dask DataFrame, user can both specify or not specify a column name to be validated. If user specify the column name, `validate_ec_ci()` only returns the validation result for the specified column. If user doesn't specify the column name, `validate_ec_ci()` returns the validation result for the whole DataFrame.
```
from dataprep.clean import validate_ec_ci
print(validate_ec_ci("171430710-3"))
print(validate_ec_ci("BE431150351"))
print(validate_ec_ci('BE 428759497'))
print(validate_ec_ci('BE431150351'))
print(validate_ec_ci("004085616"))
print(validate_ec_ci("hello"))
print(validate_ec_ci(np.nan))
print(validate_ec_ci("NULL"))
```
### Series
```
validate_ec_ci(df["ci"])
```
### DataFrame + Specify Column
```
validate_ec_ci(df, column="ci")
```
### Only DataFrame
```
validate_ec_ci(df)
```
| github_jupyter |
## Transfer learning - Application à la classification d'images
Dans ce TP, nous allons utiliser la technique du transfer learning pour réaliser un classificateur d'images capable de distinguer différents types de nuages :
* cirrus
* cumulus
* cumulonimbus
Ce TP est basé sur la leçon n°1 du cours en ligne http://www.fast.ai/.
__Attention !__ La version de la librairie fastai utilisée est la 0.7. Ce TP n'est pas compatible avec fastai v1.0 et supérieures.
```
# A mettre en haut de chaque notebook afin d'activer certaines fonctionnalités de jupyter notebook
# Autoreload
%reload_ext autoreload
%autoreload 2
# Permet d'afficher les graphiques dans le notebook
%matplotlib inline
```
## Import des librairies
Nous allons utiliser la librairie de haut niveau fastai.
Cette librairie permet de réaliser en très peu de lignes de code certaines tâches classiques de Deep Learning, telles que la classification d'image.
```
# This file contains all the main external libs we'll use
from fastai.imports import *
from fastai.transforms import *
from fastai.conv_learner import *
from fastai.model import *
from fastai.dataset import *
from fastai.sgdr import *
from fastai.plots import *
```
`PATH` est le chemin d'accès à vos données.
`sz` est la taille à laquelle vos images seront redimensionnées, afin d'obtenir un entraînement rapide.
```
PATH = "data/nuages/"
sz=224
```
Vérifie si le GPU est disponible sur votre machine.
```
torch.cuda.is_available()
```
## Jetons un oeil à nos images
Pour utiliser les fonctions de classification d'image de la librairie fastai, il faut classer les images dans des répertoires *train* et *valid*. Dans chacun de ces répertoires, il faut un sous-répertoire par classe (dans notre exemple, *cirrus*, *cumulus* et *cumulonimbus*).
```
os.listdir(PATH)
os.listdir(f'{PATH}valid')
# A quoi ressemblent nos noms de fichiers ?
files = os.listdir(f'{PATH}valid/cirrus')[:5]
files
# A quoi ressemble une image de cirrus ?
img = plt.imread(f'{PATH}valid/cirrus/{files[0]}')
plt.imshow(img);
```
Voici à quoi ressemble la donnée brute pour une image :
```
img.shape
img[:4,:4]
```
## C'est parti pour notre premier modèle !
Nous allons utiliser un modèle <b>pré-entraîné</b>, c'est-à-dire un modèle créé par quelqu'un d'autre pour classifier d'autres types d'images. Ici nous allons utiliser un modèle entraîné sur le jeu de données ImageNet (1,2 millions d'images et 1000 classes). Ce modèle est un réseau de neurones convolutionnel.
Nous allons utiliser le modèle <b>resnet34</b>. Il s'agit du réseau de neurones qui a remporté le challenge ImageNet en 2015.
Plus d'infos sur ce modèle : [resnet models](https://github.com/KaimingHe/deep-residual-networks)
Et hop, voici comment entraîner notre classificateur de nuages en quatre lignes de code !
```
# Décommenter cette ligne si vous souhaitez recalculer les activations
# (en cas de modification du jeu de données images)
#shutil.rmtree(f'{PATH}tmp', ignore_errors=True)
arch=resnet34
data = ImageClassifierData.from_paths(PATH, tfms=tfms_from_model(arch, sz))
learn = ConvLearner.pretrained(arch, data, precompute=True)
learn.fit(0.01, 20)
```
Que vaut notre modèle ? Il a une précision d'environ 80%, ce qui n'est pas si mal vu le peu d'efforts consentis... Nous verrons plus tard comment faire mieux.
## Analyse des résultats : regardons quelques images
En plus des métriques telles que le coût et la précision, il est utile de regarder qualitativement le fonctionnement du modèle :
1. Quelques images correctement classifiées, prises au hasard
2. Quelques images mal classifiées, prises au hasard
3. Les images les plus correctes de chaque classe (celles pour lesquelles le modèle attribue une probabilité élevée d'appartenance à la classe)
4. Les images les plus incorrectes de chaque classe (celles pour lesquelles le modèle attribue une probabilité élevée d'appartenance à une autre classe)
5. Les images les plus incertaines
```
# Labels du jeu de validation
data.val_y
# Permet de savoir à quelle classe correspond le label 0, 1 et 2
data.classes
# Calcul des prédictions pour le jeu de validation. Predictions en échelle logarithmique
log_preds = learn.predict()
log_preds.shape
log_preds[:10]
preds = np.argmax(log_preds, axis=1) # convertit les log probabilities en classe 0, 1 et 2
probs = np.exp(log_preds) # probabilités en échelle [0,1]
def rand_by_mask(mask): return np.random.choice(np.where(mask)[0], 4, replace=False)
def rand_by_correct(is_correct): return rand_by_mask((preds == data.val_y)==is_correct)
def plot_val_with_title(idxs, title):
imgs = np.stack([data.val_ds[x][0] for x in idxs])
title_probs = [probs[x] for x in idxs]
print(title)
return plots(data.val_ds.denorm(imgs), rows=1, titles=title_probs)
def plots(ims, figsize=(12,6), rows=1, titles=None):
f = plt.figure(figsize=figsize)
for i in range(len(ims)):
sp = f.add_subplot(rows, len(ims)//rows, i+1)
sp.axis('Off')
if titles is not None: sp.set_title(titles[i], fontsize=16)
plt.imshow(ims[i])
def load_img_id(ds, idx): return np.array(PIL.Image.open(PATH+ds.fnames[idx]))
def plot_val_with_title(idxs, title):
imgs = [load_img_id(data.val_ds,x) for x in idxs]
title_probs = [probs[x] for x in idxs]
print(title)
return plots(imgs, rows=1, titles=title_probs, figsize=(16,8))
# 1. A few correct labels at random
plot_val_with_title(rand_by_correct(True), "Correctly classified")
# 2. A few incorrect labels at random
plot_val_with_title(rand_by_correct(False), "Incorrectly classified")
def most_by_mask(mask, y):
idxs = np.where(mask)[0]
return idxs[np.argsort(-probs[idxs, y])[:4]]
def most_by_correct(y, is_correct):
return most_by_mask(((preds == data.val_y)==is_correct) & (data.val_y == y), y)
plot_val_with_title(most_by_correct(0, True), "Cirrus les plus corrects")
plot_val_with_title(most_by_correct(1, True), "Cumulonimbus les plus corrects")
plot_val_with_title(most_by_correct(2, True), "Cumulus les plus corrects")
plot_val_with_title(most_by_correct(0, False), "Cirrus les plus incorrects")
plot_val_with_title(most_by_correct(1, False), "Cumulonimbus les plus incorrects")
plot_val_with_title(most_by_correct(2, False), "Cumulus les plus incorrects")
most_uncertain = np.argsort(np.abs(probs[:,0] - 0.5))[:4]
plot_val_with_title(most_uncertain, "Probabilité de cirrus les plus proches de 0.5 (incertain)")
most_uncertain = np.argsort(np.abs(probs[:,1] - 0.5))[:4]
plot_val_with_title(most_uncertain, "Probabilité de cumulonimbus les plus proches de 0.5 (incertain)")
most_uncertain = np.argsort(np.abs(probs[:,2] - 0.5))[:4]
plot_val_with_title(most_uncertain, "Probabilité de cumulus les plus proches de 0.5 (incertain)")
```
## Améliorons notre modèle
### Data augmentation
Si vous continuez d'entraîner votre modèle en augmentant le nombre d'épochs, vous vous apercevrez que le modèle va *overfitter*. D'une certaine manière, il va apprendre par coeur les images du jeu d'entraînement, mais deviendra moins performant losqu'il s'agira de généraliser sur le jeu de validation.
Une solution pour éviter ce phénomène est d'ajouter des données d'entraînement. Pour cela, deux solutions :
* Aller chercher d'autres images. C'est évidemment une solution performante, mais potentiellement longue et coûteuse.
* Faire de la *data augmentation*.
Nous allons mettre en oeuvre cette seconde solution. La data augmentation va consister à modifier les images lors de l'entraînement, en leur appliquant différentes transformations : miroir, zoom, rotation...
Pour cela, nous allons utiliser la fonctionnalité de data augmentation de la librairie fastai. La librairie dispose de fonctions de data augmentation prédéfinies. Nous allons utiliser :
* `transforms_side_on` : rotations et symétrie gauche/droite (pas de symétrie haut/bas, afin de garder les objets "la tête en haut")
* `max_zoom` : zoome dans l'image
```
tfms = tfms_from_model(resnet34, sz, aug_tfms=transforms_side_on, max_zoom=1.1)
def get_augs():
data = ImageClassifierData.from_paths(PATH, bs=2, tfms=tfms, num_workers=1)
x,_ = next(iter(data.aug_dl))
return data.trn_ds.denorm(x)[1]
ims = np.stack([get_augs() for i in range(6)])
plots(ims, rows=2)
```
Let's create a new `data` object that includes this augmentation in the transforms.
```
data = ImageClassifierData.from_paths(PATH, tfms=tfms)
learn = ConvLearner.pretrained(arch, data, precompute=False)
learn.fit(1e-2, 20)
```
Maintenant que nous avons un bon modèle, nous pouvons le sauvegarder.
```
learn.save('224_lastlayer')
learn.load('224_lastlayer')
```
### Fine-tuning
Maintenant que nous avons entraîné la dernière couche, nous pouvons essayer de faire un fine-tuning des autres couches. Pour dire à la librairie que nous voulons *dégeler* les poids de l'ensemble des couches, nous allons utiliser `unfreeze()`.
```
learn.unfreeze()
```
Notez que les autres couches ont déjà été entraînées pour reconnaître les photos imagenet (alors que nos couches finales étaient initialisées aléatoirement). Il faut donc veiller à ne pas détruire les poids qui ont déjà été soigneusement entraînés.
D'une manière générale, les couches précédentes ont des caractéristiques plus générales. Par conséquent, nous nous attendons à ce qu'ils aient besoin de moins de réglages pour les nouveaux jeux de données. Pour cette raison, nous utiliserons différents learning rates pour différentes couches: les premières couches seront à 1e-4, les couches intermédiaires à 1e-3, et pour nos couches FC nous partirons à 1e-2 comme auparavant. FastAI appelle cela le *differential learning rate*, bien qu'il n'y ait pas de nom officiel dans la littérature.
```
lr=np.array([1e-4,1e-3,1e-2])
learn.fit(lr, 6)
```
Est-ce que le modèle est meilleur ?
A votre avis, que s'est-il passé ?
```
learn.save('224_all')
learn.load('224_all')
```
Une dernière chose que nous pouvons faire avec l'augmentation des données est de l'utiliser lors de l'inférence. C'est une technique appellée *Test Time Augmentation* (TTA).
TTA effectue simplement des prédictions non seulement sur les images du jeu de validation, mais également avec un certain nombre de versions augmentées de manière aléatoire (par défaut, l'image originale et 4 versions augmentées de façon aléatoire). Il prend alors la prédiction moyenne de ces images.
C'est le même principe qu'en prévision d'ensemble météo.
```
log_preds,y = learn.TTA()
probs = np.mean(np.exp(log_preds),0)
accuracy_np(probs, y)
```
On peut en général espérer autour de 10 à 20% de réduction de l'erreur grâce au TTA.
## Analyse des résultats
### Confusion matrix
```
preds = np.argmax(probs, axis=1)
#probs = probs[:,1]
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y, preds)
```
Nous pouvons afficher la matrice de contingence sous une forme graphique (ce qui est pratique lorsqu'on a un nombre important de classes).
```
plot_confusion_matrix(cm, data.classes)
```
### Revoyons nos images
```
plot_val_with_title(most_by_correct(0, False), "Cirrus les plus incorrects")
plot_val_with_title(most_by_correct(1, False), "Cumulonimbus les plus incorrects")
plot_val_with_title(most_by_correct(2, False), "Cumulus les plus incorrects")
```
## Résumé :
<b>Comment entraîner un classificateur d'image au top niveau international grâce au transfer learning !</b>
1. Récupérer un modèle pré-entraîné
1. Entraîner la dernière couche pour quelques epochs, en veillant à ne pas overfitter
1. Entraîner la dernière couche avec data augmentation
1. Dégeler les autres couches et entraîner pour le fine-tuning
| github_jupyter |
### Dependencies
```
from utillity_script_cloud_segmentation import *
seed = 0
seed_everything(seed)
warnings.filterwarnings("ignore")
```
### Load data
```
train = pd.read_csv('../input/understanding_cloud_organization/train.csv')
hold_out_set = pd.read_csv('../input/clouds-data-split/hold-out.csv')
X_train = hold_out_set[hold_out_set['set'] == 'train']
X_val = hold_out_set[hold_out_set['set'] == 'validation']
print('Compete set samples:', len(train))
print('Train samples: ', len(X_train))
print('Validation samples: ', len(X_val))
# Preprocecss data
train['image'] = train['Image_Label'].apply(lambda x: x.split('_')[0])
display(X_train.head())
```
# Model parameters
```
BACKBONE = 'densenet169'
BATCH_SIZE = 16
EPOCHS = 30
LEARNING_RATE = 3e-4
HEIGHT = 256
WIDTH = 384
CHANNELS = 3
N_CLASSES = 4
ES_PATIENCE = 5
RLROP_PATIENCE = 3
DECAY_DROP = 0.3
ADJUST_FN = exposure.adjust_log
ADJUST_PARAM = 1
model_path = '47-uNet_%s_%sx%s.h5' % (BACKBONE, HEIGHT, WIDTH)
train_images_path = '../input/cloud-images-resized-256x384/train_images256x384/train_images/'
preprocessing = sm.backbones.get_preprocessing(BACKBONE)
augmentation = albu.Compose([albu.HorizontalFlip(p=0.5),
albu.VerticalFlip(p=0.5),
albu.GridDistortion(p=0.5),
albu.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0,
shift_limit=0.1, border_mode=0, p=0.5),
])
```
### Data generator
```
train_generator = DataGenerator(
directory=train_images_path,
dataframe=X_train,
target_df=train,
batch_size=BATCH_SIZE,
target_size=(HEIGHT, WIDTH),
n_channels=CHANNELS,
n_classes=N_CLASSES,
preprocessing=preprocessing,
augmentation=augmentation,
adjust_fn = ADJUST_FN,
adjust_param = ADJUST_PARAM,
seed=seed)
valid_generator = DataGenerator(
directory=train_images_path,
dataframe=X_val,
target_df=train,
batch_size=BATCH_SIZE,
target_size=(HEIGHT, WIDTH),
n_channels=CHANNELS,
n_classes=N_CLASSES,
preprocessing=preprocessing,
adjust_fn = ADJUST_FN,
adjust_param = ADJUST_PARAM,
seed=seed)
```
# Model
```
model = sm.Unet(backbone_name=BACKBONE,
encoder_weights='imagenet',
classes=N_CLASSES,
activation='sigmoid',
input_shape=(HEIGHT, WIDTH, CHANNELS))
checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)
es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)
rlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience=RLROP_PATIENCE, factor=DECAY_DROP, verbose=1)
metric_list = [dice_coef, sm.metrics.iou_score, sm.metrics.f1_score]
callback_list = [checkpoint, es, rlrop]
optimizer = RAdam(learning_rate=LEARNING_RATE, warmup_proportion=0.1)
model.compile(optimizer=optimizer, loss=sm.losses.bce_dice_loss, metrics=metric_list)
model.summary()
STEP_SIZE_TRAIN = len(X_train)//BATCH_SIZE
STEP_SIZE_VALID = len(X_val)//BATCH_SIZE
history = model.fit_generator(generator=train_generator,
steps_per_epoch=STEP_SIZE_TRAIN,
validation_data=valid_generator,
validation_steps=STEP_SIZE_VALID,
callbacks=callback_list,
epochs=EPOCHS,
verbose=2).history
```
## Model loss graph
```
plot_metrics(history, metric_list=['loss', 'dice_coef', 'iou_score', 'score'])
```
| github_jupyter |
# DFI Tutorial
## Description
The Dynamic Flexiblity index (DFI) is a measure of each residue's contribution to a protein's dynamics. A low %DFI score indicates a rigid portion of the protein while a high %DFI score indicates a flexible portion of the protein. The %DFI score has been used as a predictive feature in genetic disease prediction. Mutations in genomes can lead to proteins which can misfunction, manifesting in genetic disease. Our proteome-wide analysis using DFI indicates that certain sites play a critical role in the functinally reated dynamics (i.e, those with low dfi values); therefore, mutations at those sites are more likely to be associated with disease. DFI has been used to study docking, protein evolution, and disease evolution
## Table of Contents
1. Basic DFI
2. Saving Results
3. Outputing a PDB with the b-factors replaced with the %DFI Profile
4. Calling from the commandline
5. Running f-DFI
6. Using a covariance matrix
```
%pylab inline
import pandas as pd
import seaborn as sns
import dfi.dfi_calc
```
# 1. Basic DFI
grab a pdb from the protein data bank
```
dfi.fetch_pdb('1l2y')
```
let's run DFI on a single protein
```
df_dfi = dfi.calc_dfi('1l2y.pdb')
```
when we run the command dfi.calc_dfi it will run DFI and return the DataFrame of the results
```
df_dfi.head()
```
the fields of the DataFrame are:
- ResI: The residue index found in the PDB
- dfi: The raw dfi score
- pctdfi: The pct ranking of the DFI score
- ChainID: The Chain of the PDB
- Res: The three-letter residue code
- R: The one letter-residue code
let's to some basic plotting
```
sns.set_style("whitegrid")
plt.figure(figsize=(32, 12))
sns.set_context("poster", font_scale=2.25, rc={"lines.linewidth": 1.25,"lines.markersize":8})
ResI = df_dfi.ResI.values
pctdfi = df_dfi.pctdfi.values
plt.plot(ResI, pctdfi, label='%DFI',
marker='o', linestyle='--', markersize=20)
plt.xlabel('ResI')
plt.ylabel('%DFI')
plt.legend(bbox_to_anchor=(0., 1.005, 1., .102), loc=7,ncol=2, borderaxespad=0.)
```
this is a plot of the DFI profile
# 2.Saving Results
```
dfi.calc_dfi('1l2y.pdb',writetofile=True)
```
## Saving results with a custom name
```
dfi.calc_dfi('1l2y.pdb',writetofile=True, dfianalfile='test.csv')
```
# 3.Output a pdb with the b-factors column replaced with the pctdfi values
```
dfi.calc_dfi('1l2y.pdb',writetofile=True,colorpdb=True)
```
# 4.Calling from the command line
## Example
### Run just bare DFI on a protein
```
./dfi_calc.py --pdb 1l2y.pdb --fdfi A10
```
This will run dfi on 1l2y.pdb and write out to 1l2y-dfianalysis.csv,
1l2y-fdficolor.pdb, and 1l2y-dficolor.pdb.
### Run based on UniprotID
```
./dfi.py P42771
```
This will take the UniprotID and blast it on the NCBI server, find the
highest PDB hit and then run dfi analysis on that PDB. The output is
P42771-1DC2-dfianalysis.csv.
*Note: If you query the NCBI server too often it will push your query
down the queue*
# 5. Running f-DFI
```
df_dfi = dfi.calc_dfi('1l2y.pdb',ls_reschain=['A18'])
```
We can run f-DFI by passing a list of the relevant residues using the keyword `ls_reschain`. The format is chainIDResidueIndex. For instance A18 is the 18th residue on Chain A. The Residue Index and ChainID must match what is found in the PDB file.
Five new fields will appear:
- fdfi: Raw f-dfi value
- pctfdfi: Percent ranking of f-dfi
- ravg: Average distance away from the functionally relevant sites
- rmin: Minimum distance away from the functionally relevant sites
- A: A classification of whether a site is a alloseric site or not
```
sns.set_style("whitegrid")
plt.figure(figsize=(32, 12))
sns.set_context("poster", font_scale=2.25, rc={"lines.linewidth": 1.25,"lines.markersize":8})
ResI = df_dfi.ResI.values
pctdfi = df_dfi.pctdfi.values
pctfdfi = df_dfi.pctfdfi.values
plt.plot(ResI, pctdfi, label='%DFI',
marker='o', linestyle='--', markersize=20)
plt.plot(ResI, pctfdfi, label='%fDFI',
marker='o', linestyle='--', markersize=20)
plt.xlabel('ResI')
plt.ylabel('%DFI/%fDFI')
plt.legend(bbox_to_anchor=(0., 1.005, 1., .102), loc=7,ncol=2, borderaxespad=0.)
```
# 6. Finally we can also pass in a covariance matrix
```
df_dfi = dfi.calc_dfi('1l2y.pdb',ls_reschain=['A18'], covar='./../dfi/data/1l2y_covar.dat')
sns.set_style("whitegrid")
plt.figure(figsize=(32, 12))
sns.set_context("poster", font_scale=2.25, rc={"lines.linewidth": 1.25,"lines.markersize":8})
ResI = df_dfi.ResI.values
pctdfi = df_dfi.pctdfi.values
pctfdfi = df_dfi.pctfdfi.values
plt.plot(ResI, pctdfi, label='%DFI',
marker='o', linestyle='--', markersize=20)
plt.plot(ResI, pctfdfi, label='%fDFI',
marker='o', linestyle='--', markersize=20)
plt.xlabel('ResI')
plt.ylabel('%DFI/%fDFI')
plt.legend(bbox_to_anchor=(0., 1.005, 1., .102), loc=7,ncol=2, borderaxespad=0.)
```
| github_jupyter |
# Linked List
### 1. Array
Fixed size, contain elements of same data type.
When array is full, we need to create a new array with double the size and free the memory for former array.
Insertion and deletion make almost all element moved/shifted
1. Access: read/write element at any position: O(1) - best thing about array
2. Insert, worst case is insert at the first position so all elements are shifted: O(n), insert at last position costs O(1)
3. Remove, remove first element cost O(n) and remove last element costs O(1)
4. Add, when array reaches max size, we need to copy all elements into new array: O(n), when not max size, it costs O(1)
### 2. Linked list
Linked list is non-consecutive nodes in memory, each node stores the actual data and the link to the next node (the address of the next node).
Good thing is that each node cost small memory and all nodes doesnt take a long chunk in memory.
Althought the total memory is a bit larger (carry a pointer every element), if data is big, carrying a pointer is not a big deal
First node: Head node, this gives access of completed list
Last node: Does not point to any node. So if we want to access an element in between, we need to start to ask the first node.
1. Access: O(n)
2. Insert O(1), indexing (finding the node) is O(n)
Implementation:
These implementations are done individually and independent to each other
1. size() - returns number of data elements in list - O(n)
2. is_empty() - bool returns true if empty - O(1)
3. value_at(index) - returns the value of the nth item (starting at 0 for first) O(n)
4. push_front(value) - adds an item to the front of the list O(1)
5. pop_front() - remove front item and return its value O(1)
6. push_back(value) - adds an item at the end O(1)
7. pop_back() - removes end item and returns its value O(n)
8. front() - get value of front item O(1)
9. back() - get value of end item O(1)
10. insert(index, value) - insert value at index, so current item at that index is pointed to by new item at index O(n)
11. erase(index) - removes node at given index O(n)
12. search(value) - return an a list containing the indexes of every items that match the value O(n)
13. reverse() - reverses the list, reverse_recursion() - reverse the list using recursion O(n)
14. clear() - empty the list O(1)
15. search() - search list and return the array that containt the position of the value that matched, index start at 0 O(n)
## Implementation
```
class ListNode:
"ListNode class, each node has data and the reference to the next node"
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
"class for single linked list: each node contain reference to next node"
def __init__(self):
"A LinkedList only has first node and last node "
self.head = None
self.tail = None
def size(self):
"count the number of list items"
count = 0
current_node = self.head
while current_node is not None:
count += 1
current_node = current_node.next
return count
def is_empty(self):
"check if the list is empty or not"
if self.head is None:
return True
else:
return False
def value_at(self, index):
"return the value of the nth element, index start at 0"
current_index = 0
current_node = self.head
while current_node is not None:
if current_index == index:
return current_node.data
current_index += 1
current_node = current_node.next
return "Error: Index out of range"
def push_front(self, value):
"push an item to the front of the list"
# convert data type of item to ListNode data type
if not isinstance(value, ListNode):
value = ListNode(value)
# when list is empty
if self.head is None:
self.head = value
return
# when list has one element, has to fix tail when add new element
if self.tail is None:
self.tail = self.head
self.tail.next = None
self.head = value
value.next = self.tail
return
# when list has at least 2 element
value.next = self.head
self.head = value
return
def pop_front(self):
"remove front item and return its value"
# when list is empty, return None, list remains unchanged
if self.head is None:
return None
# when list has 1 item, return head value and remove head of list
if self.tail is None:
head_value = self.head.data
self.head = None
return head_value
# when list has 2 items, return head value and remove head from list
if self.head.next is self.tail:
head_value = self.head.data
self.head = self.tail
self.head.next = None
self.tail = None
return head_value
# when list has 3 items
head_value = self.head.data
# change head position of linked list
self.head = self.head.next
return head_value
def push_back(self, item):
"add item to end of list"
# convert data type of item to ListNode data type
if not isinstance(item, ListNode):
item = ListNode(item)
# when list is empty then the value being added becomes head, otherwise it becomes
if self.head is None:
self.head = item
return
# when list has 1 item
elif self.tail is None:
self.tail = item
self.head.next = item
return
else:
self.tail.next = item
self.tail = item
return
def pop_back(self):
"removes end item and returns its value"
# edge case
# when list is empty
if self.head is None:
self.head = None
return None
# when list has 1 item, head is the last element
if self.tail is None:
head_value = self.head.data
self.head = None
return head_value
# when list has 2 items, remove tail and return it
if self.head.next is self.tail:
tail_value = self.tail.data
self.tail = None
self.head.next = None
return tail_value
# when list has at least 3 items
previous_node = None
current_node = self.head
# traverse the whole list to get the last node
while current_node.next is not None:
previous_node = current_node
current_node = current_node.next
tail_value = self.tail.data
# current_node.next is none when current_node is the last node
self.tail = previous_node
previous_node.next = None
return tail_value
def front(self):
"get value of front item"
if self.head is None:
return None
else:
return self.head.data
def back(self):
"get value of end item"
if self.tail is None:
return None
else:
return self.tail.data
def insert(self, index, value):
"insert value at index, put value at position index so current item at that index is pointed to the new item at index, index starts at 0"
success_msg = "Node inserted succesfully at index %s" % index
fail_msg = "Error: index %s out of range, unable to insert" % index
# convert value to ListNode type if not already
if not isinstance(value, ListNode):
value = ListNode(value)
# edge case: list is empty, there will be no next node
if self.head is None:
if index == 0:
self.head = value
return success_msg
else:
return fail_msg
# when list has 1 item, we have to fix tail
if self.tail is None:
# insert to head
if index == 0:
self.tail = self.head
self.head = value
value.next = self.tail
return success_msg
# insert to tail
if index == 1:
self.tail = value
self.head.next = value
return success_msg
# when list has at least 2 items, put value in the position index
current_index = 0
previous_node = None
current_node = self.head
while current_node.next is not None:
# insert to head
if index == 0:
value.next = self.head
self.head = value
return success_msg
# insert to the middle of the list
if current_index == index:
# insert new node
previous_node.next = value
value.next = current_node
return success_msg
# increment index
current_index += 1
previous_node = current_node
current_node = current_node.next
# when current_node.next is none, it mean we have traversed the whole list insert to tail
if current_node.next is None and current_index == index:
current_node.next = value
self.tail = value
return success_msg
return fail_msg
def print(self):
"outputs all value of list"
current_node = self.head
while current_node is not None:
print(current_node.data, end=' ')
current_node = current_node.next
print()
def erase(self, index):
"remove a node from the list by its position, change the referece of the node that point to them to the reference of next node from the deleted node, unrefereced data will be taken by python garbage collector"
success_msg = "Node deleted successfully at index %s" % index
fail_msg = "Error: index %s out of range, unable to delete" %index
# When list is empty
if self.head is None:
return fail_msg
# When list has 1 item
if self.tail is None:
if index == 0:
self.head = None
return success_msg
# When list has 2 items, has to remove tail
if self.head.next is self.tail:
# when erase head
if index == 0:
self.head = self.tail
self.head.next = None
self.tail = None
return success_msg
# when erase tail
if index == 1:
self.tail = None
self.head.next = None
return success_msg
return fail_msg
# when list has at least 3 items
current_index = 0
previous_node = None
current_node = self.head
while current_node is not None:
if current_index == index:
# when erase the first node
if previous_node is None: # if current_node is head
# when erase first node, the second node become the head
self.head = current_node.next
# remove the current node to free memory
current_node = None
return success_msg
# when erase last node
if current_node.next is None: # if current_node is tail
previous_node.next = None # current_node will be collected by python garbage collector
self.tail = previous_node
return success_msg
# when erase a node in the middle of the list, change reference of the node before the one being deleted
previous_node.next = current_node.next
return success_msg
current_index +=1
previous_node = current_node
current_node = current_node.next
return fail_msg
def search(self, value):
"search list and return the array that containt the position of the value that matched, index start at 0"
results = []
index = 0
current_node = self.head
while current_node is not None:
if current_node.data == value:
results.append(index)
index += 1
current_node = current_node.next
return results
def reverse(self):
"reverse the referencing order of linked list using iterative method"
previous_node = None
current_node = self.head
self.tail = self.head
while current_node is not None:
# store next node because the pointer to the next node will be change after that
next_node = current_node.next
# change pointer of each node to the previous node
current_node.next = previous_node
# shift the position of current and previous node
previous_node = current_node
current_node = next_node
# previous node is the last node, make it the head of single linked list
self.head = previous_node
def reverse_recursion(self, head):
"reverse a linked list using recursion method given the head node"
# cannot use self.head instead of head because head is updated in recursion while self.head is a fixed value, self doesn't change
self.tail = self.head
current_node = head
rest = current_node.next
if rest is None:
# rest is null when current_node is the last node of the list
self.tail = self.head
self.head = current_node
return
self.reverse_recursion(rest)
# create a reverse the link between current_node and the next node of it
current_node.next.next = current_node
# remove the the original link
current_node.next = None
def clear(self):
"empty the list, python garbage collector will clear unreferenced memory"
self.head = None
self.tail = None
```
## Testing
```
# function for testing
def print_list_infor(list):
"print head,tail and the actual list"
print("Front: %s, Back: %s" % (list.front(), list.back()))
print("Actual list: ", end="")
list.print()
print()
```
### Test size(), push_front(), is_empty()
```
list = SingleLinkedList()
print("Size of empty list: %s" % list.size(), end = "\n")
print("Is empty value: %s" % list.is_empty())
print()
list.push_front(2)
print_list_infor(list)
list.push_front(1)
print_list_infor(list)
print("List size: %s, actual list: " % list.size(), end = "")
list.print()
```
### Test value_at()
```
print_list_infor(list)
print("Value at index -1: %s" % list.value_at(-1))
print("Value at index 0: %s" % list.value_at(0))
print("Value at index 1: %s" % list.value_at(1))
print("Value at index 2: %s" % list.value_at(2))
```
### Test pop_front()
```
list.push_front(3)
print_list_infor(list)
print("Value return by pop front: %s" % list.pop_front())
print_list_infor(list)
print("Value return by pop front: %s" % list.pop_front())
print_list_infor(list)
print("Value return by pop front: %s" % list.pop_front())
print_list_infor(list)
print("Value return by pop front: %s" % list.pop_front())
print_list_infor(list)
```
### Test push_back()
```
print("Actual list: ", end="")
print_list_infor(list)
list.push_back(1)
print_list_infor(list)
list.push_back(2)
print_list_infor(list)
```
### Test pop_back()
```
list.push_back(3)
print_list_infor(list)
print("Value return by pop back: %s" % list.pop_back())
print_list_infor(list)
print("Value return by pop back: %s" % list.pop_back())
print_list_infor(list)
print("Value return by pop back: %s" % list.pop_back())
print_list_infor(list)
print("Value return by pop back: %s" % list.pop_back())
print_list_infor(list)
```
### Test front() back()
```
print("Front: %s, Back: %s" % (list.front(), list.back()))
print("Actual list: ", end="")
list.print()
print()
list.push_back(3)
print("Actual list: ", end="")
list.print()
print("Front: %s, Back: %s" % (list.front(), list.back()))
print()
list.push_back(2)
print("Actual list: ", end="")
list.print()
print("Front: %s, Back: %s" % (list.front(), list.back()))
print()
list.push_back(1)
print("Actual list: ", end="")
list.print()
print("Front: %s, Back: %s" % (list.front(), list.back()))
print()
```
## Test insert(index,value)
```
list.clear()
print_list_infor(list)
print(list.insert(-1,1))
print_list_infor(list)
print(list.insert(1,1))
print_list_infor(list)
print(list.insert(0,1))
print_list_infor(list)
print(list.insert(1,2))
print_list_infor(list)
print(list.insert(0,2))
print_list_infor(list)
print(list.insert(0,3))
print_list_infor(list)
print(list.insert(2,4))
print_list_infor(list)
```
### Test erase(index)
```
print("Actual list: ", end="")
print_list_infor(list)
print(list.erase(1))
print_list_infor(list)
print(list.erase(0))
print_list_infor(list)
print(list.erase(3))
print_list_infor(list)
print(list.erase(2))
print_list_infor(list)
print(list.erase(0))
print_list_infor(list)
print(list.erase(0))
print_list_infor(list)
```
### Test reverse(), reverse_recursion()
```
list.push_front(1)
list.push_front(3)
list.push_front(4)
list.push_front(5)
print_list_infor(list)
list.reverse()
print("List reversing...")
print_list_infor(list)
list.reverse_recursion(list.head)
print("List reversing...")
print_list_infor(list)
```
| github_jupyter |
# PyTorch에서의 이미지와 로지스틱 회귀
### "Deep Learning with Pytorch: Zero to GANs"의 3번째 파트
이 튜토리얼은 [PyTorch](https://pytorch.org)를 이용한 초보자용 딥러닝 학습 튜토리얼 입니다.
학습하기 위한 최고의 방법은 본인이 코드를 실행하고, 실험해 보는 것이기 때문에 이 튜토리얼은 실용성과 코딩 중심으로 진행됩니다.
이번 튜토리얼에선 다음과 같은 주제를 다룹니다:
>* PyTorch에서의 __이미지 작업 (MNIST 데이터셋을 사용)__
>* __학습, 검증 및 테스트 세트__ 로 데이터셋 분할
>* `nn.Module` 클래스를 확장하여 커스텀 로직으로 PyTorch 모델을 생성합니다.
>* __Softmax__ 를 사용하여 모델 출력을 __확률로 해석__ 하고 예측된 레이블 선택
>* 분류 문제를 위한 유용한 __평가 지표(정확도)__ 와 __손실 함수(교차 엔트로피)__ 를 선정
>* 검증 세트를 사용하여 모델을 평가하는 교육 루프 설정
>* 무작위로 선택한 예제에 대해 수동으로 모델 테스트
>* 모델 체크포인트 저장 및 로딩으로 처음부터 재교육 하는 것을 방지
---
## 이미지 작업
>이 튜토리얼에서, 저희는 PyTorch에 대한 기본 지식과 선형 회귀를 사용해 __이미지 분류__ 라는 색다른 종류의 문제를 풀어볼 것입니다.<br>
저희는 [MNIST 손글씨 숫자 데이터베이스](http://yann.lecun.com/exdb/mnist/)를 사용할 것입니다. <br>
__<font color=blue>MNIST 데이터 셋</font>__ 은 28×28(pixel) 흑백 손글씨 숫자 이미지와 각 이미지가 나타내는 숫자의 레이블로 구성되어 있습니다.<br>
아래 그림은 MNIST 데이터 셋의 샘플 이미지들 입니다:

`torch`와 `torchvision`을 설치하고 import 하는것으로 시작합니다. <br>
`torchvision`은 이미지 작업을 위한 몇 가지 유틸리티가 포함되어 있고, MNIST와 같은 유명한 데이터 셋을 자동으로 다운로드하고 가져올수 있는 클래스 또한 제공합니다.
```
# 필요한 경우 주석 처리를 제거하고 여러분의 운영 체제에 적합한 명령을 실행하시면 됩니다.
# Linux / Binder
# !pip install numpy matplotlib torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# Windows
# !pip install numpy matplotlib torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# MacOS
# !pip install numpy matplotlib torch torchvision torchaudio
# Imports
import torch
import torchvision
from torchvision.datasets import MNIST
# 학습 데이터 셋 다운로드
dataset = MNIST(root='./data/', download=True)
```
위 코드가 처음 실행되면 노트북과 같은 폴더 내에 있는 `data/` 디렉토리에 데이터를 다운로드하고 PyTorch `Dataset`을 생성합니다.<br>
이후 실행에서는 데이터가 이미 다운로드 되었기 때문에 다운로드를 건너뛰게 됩니다.<br>
이제 데이터셋의 크기를 확인해 보겠습니다.
```
len(dataset)
```
__MNIST__ <br>
>받은 데이터 셋에는 모델을 교육하는데 사용할 60000개의 이미지가 있고,<br>
아래 셀에서 확인할 것이지만 모델 평가에 사용될 10000개의 테스트 데이터가 있습니다.<br>
`train=False`를 생성자에게 전달해 __MNIST__ 데이터의 테스트 데이터 셋을 생성할 수 있습니다.
```
test_dataset = MNIST(root='data/', train=False)
len(test_dataset)
```
학습 데이터 셋으로부터 샘플 요소를 보겠습니다.
```
dataset[0]
```
위에서 보이듯이 데이터는 28×28px 이미지와 레이블로 구성되어 있습니다.<br>
이미지는 클래스 `PIL.Image.Image`의 객체로 이 객체는 Python 이미지 라이브러리 [Pillow](https://pillow.readthedocs.io/en/stable/)의 요소입니다.<br>
저희는 [`matplotlib`](https://matplotlib.org/)을 이용해 이미지를 주피터 노트북에서 시각화 할 수 있습니다.
```
import matplotlib.pyplot as plt
%matplotlib inline
```
`%matplotlib inline`이라는 코드는 주피터에게 그래프를 노트북 내에서 그리고 싶다는 것을 알려주는 코드입니다.<br>
`%`로 시작하는 코드는 _magic commands_ 라 부르며 주피터의 동작을 제어하는데 사용됩니다.<br>
_magic commands_ 에 대한 전체 내용은 다음 링크에서 찾을 수 있습니다: https://ipython.readthedocs.io/en/stable/interactive/magics.html <br>
데이터셋의 몇가지 이미지를 확인해 보겠습니다.
```
image, label = dataset[0]
plt.imshow(image, cmap='gray')
print('Label:', label)
image, label = dataset[10]
plt.imshow(image, cmap='gray')
print('Label:', label)
```
이미지들은 상대적으로 작으며, 숫자를 인식하는 것이 때로는 사람의 눈으로도 어려울 수 있습니다. <br>
이러한 이미지를 보는 것은 쓸모가 있지만, _PyTorch_ 는 이미지를 어떻게 처리할지를 모른다는 문제점이 존재합니다. <br>
그래서 저희는 __이미지를 텐서로 변환__ 할 필요가 있습니다.<br>
저희는 `transforms`를 사용해 데이터셋을 텐서로 변환이 가능합니다. <br>
```
import torchvision.transforms as transforms
```
PyTorch의 데이터 셋을 사용하면 로드될때 이미지에 적용할 변환 기능을 한 가지 이상 지정 가능합니다.<br>
`torchvision.transforms` 모듈은 많은 미리 정의된 함수들을 포함하고 있습니다.<br>
저희는 `ToTensor` 변환으로 이미지를 PyTorch 텐서로 바꿀 수 있습니다.
```
# MNIST 데이터 셋 (이미지와 레이블)
dataset = MNIST(root='data/',
train=True,
transform=transforms.ToTensor())
img_tensor, label = dataset[0]
print(img_tensor.shape, label)
```
이제 이미지는 1×28×28 텐서로 변환됩니다. <br>
첫번째 차원은 __색상의 채널__ 을 의미하고, 두번째와 세번째 차원은 __이미지의 height와 width의 픽셀__ 을 의미합니다. <br>
MNIST 데이터셋은 흑백 이미지이기 때문에 1개의 색상 채널을 가지게 됩니다.<br>
다른 데이터셋들은 컬러 이미지로 되어있고, 이 경우 <font color=red>빨강</font>, <font color=green>초록</font>, <font color=blue>파랑</font>(RGB)로 3가지의 채널을 갖게 됩니다.
몇몇 샘플 값을 확인해 보겠습니다.
```
print(img_tensor[0,10:15,10:15])
print(torch.max(img_tensor), torch.min(img_tensor))
```
값의 범위는 0~1이고 `0`은 검정, `1` 흰색, 그리고 사잇 값은 회색을 가집니다. <br>
또한 `plt.imshow`를 사용해 텐서를 이미지로 표시할 수 있습니다.
```
# 28x28 행렬을 전달하여 이미지를 플로팅
plt.imshow(img_tensor[0,10:15,10:15], cmap='gray');
```
채널 차원 없이 28×28 행렬을 `plt.imshow`로 전달하면 됩니다. <br>
이때 회색조 이미지를 표시하기 위해 `cmap=gray`으로 설정합니다.
## 학습과 검증 데이터셋
실제 기계 학습 모델을 구축하는 동안 데이터 세트를 세 부분으로 분할하는 것이 매우 일반적입니다.
>1. **Training set** - 모델을 훈련시키는 데 사용되는 데이터 셋<br>
= 즉, 손실 계산과 경사 하강을 사용해 모델의 가중치를 조정합니다.
>2. **Validation set** - 학습 도중 모델을 평가하는데 사용되는 데이터 셋<br>
= 하이퍼 파라미터를 조정하고, 최적의 모델을 선택하게 합니다.
>3. **Test set** - 다른 모델이나 접근법들과 비교하기 위해 사용되는 데이터 셋<br>
= 모델의 최종 정확도를 나타냅니다.
MNIST 데이터 셋에는 60000개의 학습 이미지와 10000개의 테스트 이미지들이 있습니다. <br>
테스트 셋은 서로 다른 연구자들이 동일한 이미지 셋에 대해 모델 결과(성능)를 보고할 수 있도록 표준화되었습니다.
미리 정의된 검증 셋이 없으므로 60000개의 이미지를 훈련 및 검증 데이터 셋으로 수동으로 분할해야 합니다.<br>
PyTorch의 `random_split` 메서드를 사용해 10000개를 무작위로 뽑아 검증 셋으로 만듭니다.
```
from torch.utils.data import random_split
train_ds, val_ds = random_split(dataset, [50000, 10000])
len(train_ds), len(val_ds)
```
검증 세트를 생성하기 위해 무작위 샘플을 선택하는 것이 중요합니다. <br>
학습 데이터는 종종 타겟 레이블에 의해 정렬됩니다. (0 이미지 뒤에 1 이미지, 그 뒤에 2 이미지...)<br>
만약 마지막 20%의 이미지를 사용해 검증 셋을 생성하는 경우 검증 셋은 8과 9로만 구성됩니다.<br>
반면 훈련 데이터에는 8과 9가 포함되지 않습니다. <br>
그러한 훈련 검증은 유용한 모델을 훈련시키는 것이 거의 불가능합니다. <br>
그러므로 검증 세트는 무작위 샘플을 선택하는 것이 중요합니다.
이제 데이터를 배치 단위로 로드하기 위해 데이터 로더를 생성합니다. 배치 사이즈를 여기서는 128로 정의하겠습니다.
```
from torch.utils.data import DataLoader
batch_size = 128
train_loader = DataLoader(train_ds, batch_size, shuffle=True)
val_loader = DataLoader(val_ds, batch_size)
```
`shuffle=True`로 설정해 학습 데이터 로더가 매 epoch마다 배치가 다르게 생성되게 됩니다. <br>
이러한 무작위화는 __학습 과정을 일반화__ 하고 __학습 속도를 높이는데 도움__ 이 됩니다. <br>
반면, 검증 데이터 로더는 모델을 평가하는데만 사용되기 때문에, 이미지를 __섞을 필요가 없습니다__.
## Model
이제 데이터 로더가 준비되었으므로 모델을 정의할 차례입니다.
* __로지스틱 회귀__ 는 선형 회귀 모델과 거의 동일합니다. 로지스틱 회귀는 가중치와 편향 행렬을 가지고, 출력은 `pred = x @ w.t() + b`라는 간단한 행렬 연산으로 얻어질 수 있습니다.
* 선형 회귀에서 했던 것처럼, 직접 클래스를 정의하고 행렬을 초기화 하는것 대신 `nn.Linear`를 사용해 모델을 정의 할 수 있습니다.
* `nn.Linear`는 __입력 데이터가 벡터__ 이어야 합니다. 각 1×28×28 이미지 텐서는 784크기(28×28) 벡터로 _평탄화_ 되어 모델에 입력으로 들어갑니다. (_평탄화_ 란 다차원 행렬을 1차원으로 바꾸는 것을 의미합니다.)
* 각 이미지의 출력 벡터는 10의 사이즈를 가지고, 각 요소는 벡터의 인덱스에 따라 레이블의 확률이 됩니다.(즉, 0~9)
* 결과적으로 이미지의 예측된 레이블은 전체 레이블중 <font color=red>가장 확률이 높은 것</font>으로 선택됩니다.
```
import torch.nn as nn
input_size = 28*28
num_classes = 10
# Logistic regression model
model = nn.Linear(input_size, num_classes)
```
이 모델은 파라미터 수 측면에서 이전 모델보다 훨씬 큽니다.<br>
모델의 가중치와 편향에대해 살펴보도록 하겠습니다.
```
print(model.weight.shape)
model.weight
print(model.bias.shape)
model.bias
```
비록 전체 파라미터 수가 7850(10×784+10)으로 많이 이전보다 훨씬 커졌지만, __개념적으로 달라진것은 없습니다__. <br>
이제 이 모델로 출력을 생성해 보도록 하겠습니다.<br>
데이터 셋으로부터 128개의 첫 이미지 배치를 가져와 모델에 넣어 학습시킬 것입니다.
```
for images, labels in train_loader:
print(labels)
print(images.shape)
outputs = model(images.reshape(-1,784))
print(outputs)
break
images.shape
images.reshape(128, 784).shape
```
저희의 입력 데이터가 __적절한 형태(shape)__ 가 아니기 때문에 위의 코드는 오류를 일으킵니다.<br>
MNIST 이미지의 형태(shape)는 1×28×28이지만, 모델은 784 사이즈의 벡터를 입력으로 받을 수 있습니다.<br>
즉, 이 이미지를 벡터로 _평탄화_ 시켜야만 합니다.<br>
텐서의 `.reshape` 메서드를 사용해 텐서의 shape를 변환 할 수 있습니다.<br>
이 방법으로 각 이미지를 복사하지 않고도 벡터로 만들 수 있습니다.<br>
모델에 이러한 추가 기능을 모델에 포함시키기 위해, PyTorch의 `nn.Module`을 사용해 커스텀 모델을 만들 수 있습니다.
Python의 클래스는 객체를 생성하기 위한 __"청사진"(설계도)__ 를 제공합니다.<br>
Python의 새로운 클래스를 정의하는 한가지 예시를 보도록 하겠습니다.
```
class Person:
# 클래스 생성자
def __init__(self, name, age):
# 객체 속성
self.name = name
self.age = age
# 메서드
def say_hello(self):
print("Hello my name is " + self.name + "!")
```
아래 코드는 `Person`클래스의 인스턴스를 생성하는 방법입니다.
```
bob = Person("Bob", 32)
```
객체 `bob`은 `Person`클래스의 인스턴스입니다.
저희는 객체의 속성이라 불리는 요소들에 접근이 가능하고, `.`을 이용해 객체 내 함수를 호출 가능합니다.
```
bob.name, bob.age
bob.say_hello()
```
Python 클래스에 대해 더 알고싶다면 다음 링크를 참조하시길 바랍니다:
https://www.w3schools.com/python/python_classes.asp .
클래스들은 이미 존재하는 클래스를 상속받아 해당 클래스의 함수들을 사용 및 수정 할 수 있습니다.<br>
PyTorch의 `nn.Module`클래스를 상속한 커스텀 모델을 정의해 보겠습니다.
```
class MnistModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, xb):
xb = xb.reshape(-1, 784)
out = self.linear(xb)
return out
model = MnistModel()
```
`__init__` 생성자 메서드안에 `nn.Linear`를 사용해 가중치와 편향을 인스턴스화 하였고, `forward` 메서드 안에서 입력 텐서를 _평탄화_ 하여 `self.linear`에 넣어주게 정의 하였습니다.<br>
이때 `forward`함수는 모델에 __입력 배치를 넘겨줄때 호출__되는 함수입니다.
`xb.reshape(-1, 28×28)`은 `xb` 텐서를 2개의 차원으로 *볼 것*이라는 것을 나타냅니다.<br>
2번째 차원의 길이는 28×28 (즉, 784)입니다.<br>
`.reshape`에 `-1`이라는 값을 파라미터로 넣어줄 수 있습니다.(위의 경우 첫번째 차원에 넣어줌) <br>
이것은 원본 텐서의 형태를 기반으로 나머지 차원의 길이를 전부 계산하고 <font color=blue>남은 값</font>을 PyTorch가 자동적으로 계산에 넣는 것을 의미합니다. (위의 경우 본래 입력의 형태가 128×28×28이었으므로 -1에 들어갈 값은 128이 됩니다.)
모델은 더이상 `.weight`와 `.bias`라는 속성을 __가지지 않는다__ 는 것에 유의하시길 바랍니다. <br>
하지만 `.parameters` 메서드를 가지고 있어 가중치와 편향을 포함한 리스트를 반환 할 수 있습니다.
```
model.linear
print(model.linear.weight.shape, model.linear.bias.shape)
list(model.parameters())
```
이렇게 새로 만들어진 모델은 이전과 같은 방식으로 사용이 가능합니다.<br>
어떻게 작동하는지 보도록 하겠습니다.<br>
```
for images, labels in train_loader:
print(images.shape)
outputs = model(images)
break
print('outputs.shape : ', outputs.shape)
print('Sample outputs :\n', outputs[:2].data)
```
100개의 입력 이미지 각각에 대해 타겟 클래스당 하나씩 10개의 출력을 제공합니다.<br>
앞서 설명한 바와 같이, 이러한 결과물이 <font color=blue>확률</font>을 나타내기를 원합니다. <br>
각 출력 행의 요소는 __[0,1]__ 의 범위를 만족해야 합니다.
출력 행을 확률로 변환하기 위해 아래 그림에서 설명하는 소프트맥스 함수를 사용합니다.

첫째로, 출력행의 각 요소 `yi`를 `e^y`로 대체해 모든 요소를 <font color=red>양수</font>로 만듭니다.

그 후 각 요소를 모든 요소의 합계로 나누어 __전체 요소의 합이 1__ 이 되도록 합니다.<br>
그 결과 각 요소는 __확률로 해석__ 될 수 있습니다.
소프트맥스 함수의 구현은 쉽지만(실제로 한번쯤은 구현해 보셔야 합니다!) 구현하는것 대신 PyTorch에서 제공하는 소프트맥스 함수를 사용할 것입니다.
```
import torch.nn.functional as F
```
소프트맥스 함수는 `torch.nn.functional` 패키지에 포함되어 있고, 이때 소프트맥스를 적용할 차원을 지정해야 합니다.
```
outputs[:2]
# Apply softmax for each output row
probs = F.softmax(outputs, dim=1)
# Look at sample probabilities
print("Sample probabilities:\n", probs[:2].data)
# Add up the probabilities of an output row
print("Sum: ", torch.sum(probs[0]).item())
```
마지막으로 각 출력 행에서 확률이 가장 높은 요소의 인덱스를 선택하는 것으로 각 이미지에 대한 예측 레이블을 결정할 수 있습니다.<br>
각 행의 가장 큰 요소와 해당 인덱스를 반환하는 `torch.max`를 사용해 이 작업을 수행 가능합니다.
```
max_probs, preds = torch.max(probs, dim=1)
print(preds)
print(max_probs)
```
위 숫자는 학습 이미지의 첫 배치에 대한 예측 레이블입니다. <br>
실제 레이블과 비교해 보겠습니다.
```
labels
```
예측된 라벨의 대부분은 실제 라벨과 다릅니다. <br>
그것은 우리가 __무작위로 초기화__ 된 가중치와 편향으로 예측을 했기 때문입니다.<br>
더 나은 예측을 얻기 위해선 _경사 하강법_ 을 사용해 가중치를 조정해 모델을 훈련 시켜야 합니다.
## 평가 메트릭과 손실 함수
선형 회귀때와 마찬가지로 모델이 얼마나 잘 작동하는지 __평가__ 할 수 있는 방법이 필요합니다. <br>
이를 위한 적절한 방법은 예측의 __정확도__ 입니다.
```
outputs[:2]
torch.sum(preds == labels)
def accuracy(outputs, labels):
_, preds = torch.max(outputs, dim=1)
return torch.tensor(torch.sum(preds == labels).item() / len(preds))
```
`==` 연산자는 같은 형태(shape)의 두 텐서를 원소별로 비교한 후 동일한 원소의 경우 `True`, 동일하지 않은 원소의 경우 `False`를 값으로 갖는 동일한 형태의 텐서를 반환합니다. <br>
결과를 `torch.sum`에 전달하면 올바르게 예측된 레이블 수가 반환되고, 마지막으로 정확성을 얻기 위해 총 데이터 수로 나눕니다.
첫 번째 데이터 배치에서 현재 모델의 정확도를 계산해 봅시다.
```
accuracy(outputs, labels)
probs
```
정확도는 모델을 평가하는데 좋은 방법입니다.<br>
하지만 다음과 같은 이유로 경사 하강법을 사용하여 모델을 최적화하기 위한 손실 함수로는 사용할 수 없습니다:
1. 차별화 가능한 함수가 아닙니다. `torch.max`와 `==`은 둘다 불연속이자 미분 불가능이므로 가중치와 편향에 대한 경사를 계산하는데 정확도를 사용할 수 없습니다.
2. 모델에 의해 예측된 실제 확률을 고려하지 않기 때문에 점진적 개선을 위한 충분한 피드백을 제공하지 못합니다.
이러한 이유로 정확도는 분류에서 __평가 지표__ 로는 자주 활용되지만, 손실 함수로는 활용되지 않습니다.<br>
흔히 분류 문제에서 사용되는 손실 함수로는 아래 그림의 공식을 갖는 __교차 엔트로피__ 가 있습니다.

보기에는 복잡해 보이지만, 실제로는 꽤 간단합니다:
* 각 출력 행에 대해 올바른 레이블에 대한 예측 확률을 뽑습니다. <br> 즉, 만약 한 이미지에서 예측된 확률이 `[0.1, 0.3, 0.2,...]`이고, 실제 레이블이 1인 경우, `0.3`을 뽑고 나머지는 무시해 버립니다.
<br><br>
* 그 후 선택된 확률에 [로그](https://en.wikipedia.org/wiki/Logarithm)를 취합니다.<br> 만약 _확률이 높다면(1에 가깝다면)_ 로그 값은 <font color=blue>매우 작은 음의 값</font>을 가지게 되고, 반대로 _확률이 작다면(0에 가깝다면)_ <font color=red>매우 큰 음수의 값</font>을 가지게 됩니다.<br> 이 결과에 -1을 곱해 결과를 __양수__ 로 만들어 손실을 계산하게 됩니다.

* 마지막으로, 각 행의(데이터의) 교차 엔트로피의 __평균__ 을 취해 데이터 전체의 손실을 계산합니다.
정확도와 달리 교차 엔트로피는 __연속적이고 미분 가능한 함수__ 입니다.<br>
또한 모델의 점진적 개선에 대한 피드백을 제공합니다.(올바른 레이블에 대한 확률이 약간 높을수록 손실은 낮아짐).<br>
이러한 두 가지 요소는 교차 엔트로피를 좋은 손실 함수로 만듭니다.
PyTorch는 `torch.nn.functional` 패키지의 일부로 교차 엔트로피를 효율적이고 텐서 친화적으로 이미 구현해 놓았습니다.<br>
또한 __내부적으로도 소프트맥스를 수행__ 하므로, 모델의 출력을 확률로 변환하지 않아도 됩니다.
```
outputs
loss_fn = F.cross_entropy
# Loss for current batch of data
loss = loss_fn(outputs, labels)
print(loss)
```
우리는 위에서 교차 엔트로피가 모든 학습 샘플에 대해 평균화된 올바른(correct) 레이블의 예측 확률의 로그에 -1을 곱한 값이라는 것을 배웠습니다. <br>
그러므로, `2.23`과 같은 결과를 해석하는 한가지 방법은 `e^-2.23`으로 보는것입니다. <br>
_손실이 적을수록 더 좋은 모델입니다._
## 모델 학습
이제 데이터 로더, 모델, 손실 함수, optimizer가 정의 되었으므로 모델을 학습할 준비가 끝났습니다.<br>
학습과정은 선형 회귀때와 동일하며, 각 epoch마다 모델을 평가하기 위한 검증 단계가 추가되었습니다.<br>
아래는 의사 코드입니다.
```
for epoch in range(num_epochs):
# Training phase
for batch in train_loader:
# Generate predictions
# Calculate loss
# Compute gradients
# Update weights
# Reset gradients
# Validation phase
for batch in val_loader:
# Generate predictions
# Calculate loss
# Calculate metrics (accuracy etc.)
# Calculate average validation loss & metrics
# Log epoch, loss & metrics for inspection
```
학습 루프의 일부는 우리가 해결 중인 _특정 문제_ (예: 손실 함수, 행렬 등)에 특정한 반면, 다른 부분은 일반적이며 __모든 딥러닝 문제에 적용__ 될 수 있습니다.
위와 모든 딥러닝 문제에 적용될 수 있는 부분의 일부를 `fit`이라는 메서드 내에 포함시켜 모델을 학습하는 데 사용할 것입니다. <br>
특정 문제를 다루는 부분은 `nn.Module` 클래스에 새로운 메서드를 추가하는 것으로 구현됩니다.
```
def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
optimizer = opt_func(model.parameters(), lr)
history = [] # for recording epoch-wise results
for epoch in range(epochs):
# Training Phase
for batch in train_loader:
loss = model.training_step(batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
# Validation phase
result = evaluate(model, val_loader)
model.epoch_end(epoch, result)
history.append(result)
return history
```
`fit` 함수는 각 epoch의 검증 손실과 정확도를 기록합니다.<br>
이는 디버깅 및 시각화에 유용한 학습 기록을 반환합니다.
_배치 크기, 학습률_ 등의 구성(<font color=red>하이퍼 파라미터</font>라고 함)은 기계 학습 모델을 학습하는 동안 __미리__ 선택해야 합니다. <br>
적절한 하이퍼 파라미터를 선택하는 것은 적절한 시간 내에 정확한 모델을 학습하는 데 매우 중요하고 이는 기계 학습에 대한 연구와 실험의 활동적인 분야입니다.<br>
다양한 학습률을 자유롭게 시도해 보고 학습 프로세스에 어떤 영향을 미치는지 알아보볼 것입니다.<br>
이제 `fit`에서 사용할 `evaluate` 함수를 정의합시다.
```
l1 = [1, 2, 3, 4, 5]
l2 = [x*2 for x in l1]
l2
def evaluate(model, val_loader):
outputs = [model.validation_step(batch) for batch in val_loader]
return model.validation_epoch_end(outputs)
```
마지막으로 `MnistModel` 클래스를 재정의해 'training_step', 'validation_step', 'validation_epoch_end', 'epoch_end' 등의 메서드들을 추가로 포함하도록 하겠습니다.
```
class MnistModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, xb):
xb = xb.reshape(-1, 784)
out = self.linear(xb)
return out
def training_step(self, batch):
images, labels = batch
out = self(images) # Generate predictions
loss = F.cross_entropy(out, labels) # Calculate loss
return loss
def validation_step(self, batch):
images, labels = batch
out = self(images) # Generate predictions
loss = F.cross_entropy(out, labels) # Calculate loss
acc = accuracy(out, labels) # Calculate accuracy
return {'val_loss': loss, 'val_acc': acc}
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result):
print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))
model = MnistModel()
```
모델을 학습하기 전 _무작위로 초기화_ 된 가중치화 편향을 사용해 검증 세트에서 모델이 어떻게 수행되는지 확인해 보겠습니다.
```
result0 = evaluate(model, val_loader)
result0
```
초기 정확도는 무작위로 초기화된 모델이므로 10% 근처가 나왔습니다.(10개의 레이블중 임의로 선택하여 정답이 나올 확률이 10%이기 때문)<br>
이제 모델을 학습한 준비가 끝났습니다.<br>
모델을 5 epoch 동안 학습후 결과를 살펴보도록 하겠습니다.
```
history1 = fit(5, 0.001, model, train_loader, val_loader)
```
상당히 괜찮은 결과가 나왔습니다! <br>
단 5 epoch의 학습으로 검증 셋의 정확도가 80%가 넘었습니다.<br>
좀 더 훈련을 길게 함으로써 모델을 개선할 수 있는지 알아보도록 하겠습니다.<br>
아래의 각 셀에서 학습률과 epoch의 수를 변경해가며 실험해 보십시오.
```
history2 = fit(5, 0.001, model, train_loader, val_loader)
history3 = fit(5, 0.001, model, train_loader, val_loader)
history4 = fit(5, 0.001, model, train_loader, val_loader)
```
epoch를 거듭할수록 정확성은 높아지지만, 높아지는 폭은 매 epoch마다 작아집니다. <br>
선 그래프를 사용해 이것을 시각화 해보겠습니다.
```
history = [result0] + history1 + history2 + history3 + history4
accuracies = [result['val_acc'] for result in history]
plt.plot(accuracies, '-x')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.title('Accuracy vs. No. of epochs');
```
위의 그림에서 보듯이 이 모델은 오랜 시간 학습을 진행한 후에도 정확도가 90%를 넘지 못할 것입니다.<br>
이것에 대한 한 가지 이유는 학습률(learning rate)가 너무 높아서일수 있습니다. <br>
모델의 파라미터는 가장 낮은 손실에 대한 최적의 파라미터를 중심으로 _진동_ 할 수 있습니다.<br>
학습률을 낮추고 몇 epoch 더 학습하여 이것이 개선 될 수 있는지 알아볼 수 있습니다.
더 가능성 있는 이유로는 __모델이 충분히 강력하지 않기 때문__ 일수도 있습니다.<br>
초기 가설을 생각해보면, 출력(위의 경우 클래스별 확률)이 입력(픽셀 강도)의 __선형 함수__ 라고 가정했는데, 가중치 행렬을 사용한 행렬곱을 수행하고 편향을 더함으로써 얻어진 것입니다.<br>
이는 이미지의 픽셀 강도와 픽셀이 나타내는 숫자 사이의 선형 관계가 사실 존재하지 않을 수 있기에 상당히 __약한__ 가정입니다.<br>
MNIST와 같은 단순 데이터셋에는 적합한 가정일 수 있지만, 일상적 물체, 동물 인식과 같은 복잡한 작업을 위해서는 이미지 픽셀과 레이블 사이의 <font color=red>_비선형 관계_</font> 를 파악할 수 있는 __보다 복잡하고 정교한 모델__이 필요합니다.
## 개별 이미지 테스트
지금까지 모델의 전체적인 정확도를 주로 보았지만, _일부 샘플 이미지_ 에서의 모델의 결과를 살펴보는 것도 좋습니다. <br>
사전 정의된 테스트 데이터 세트인 10000개의 영상으로 모델을 테스트해 보겠습니다.<br>
먼저 테스트 데이터 셋을 `ToTensor`변환으로 적용하도록 재생성 합니다.
```
# Define test dataset
test_dataset = MNIST(root='data/',
train=False,
transform=transforms.ToTensor())
```
아래는 데이터 셋의 샘플 이미지 입니다.
```
img, label = test_dataset[0]
plt.imshow(img[0], cmap='gray')
print('Shape:', img.shape)
print('Label:', label)
```
단일 이미지 텐서에 대한 예측 레이블을 반환하는 `predict_image`함수를 정의하겠습니다.
```
def predict_image(img, model):
xb = img.unsqueeze(0)
yb = model(xb)
_, preds = torch.max(yb, dim=1)
return preds[0].item()
```
`img.unsqueeze`는 단순히 텐서에 1차원을 더해주는 메서드입니다.<br>
1×28×28인 텐서가 이 메서드를 호출한다면 1×1×28×28 텐서가 되는데, 이 텐서는 모델이 하나의 이미지를 포함한 배치로 간주하게 됩니다.
몇가지 이미지로 실험해 보겠습니다.
```
img, label = test_dataset[0]
plt.imshow(img[0], cmap='gray')
print('Label:', label, ', Predicted:', predict_image(img, model))
img, label = test_dataset[10]
plt.imshow(img[0], cmap='gray')
print('Label:', label, ', Predicted:', predict_image(img, model))
img, label = test_dataset[193]
plt.imshow(img[0], cmap='gray')
print('Label:', label, ', Predicted:', predict_image(img, model))
img, label = test_dataset[1839]
plt.imshow(img[0], cmap='gray')
print('Label:', label, ', Predicted:', predict_image(img, model))
```
모델이 성능이 떨어지는 부분을 파악한다면, 더 많은 학습 데이터를 수집하고, 모델의 복잡성을 조절하고, 하이퍼 파라미터를 변경하여 모델의 성능을 개선할 수 있습니다.
마지막으로 테스트 셋에서의 모델의 전체 손실과 정확도를 살펴보겠습니다.
```
test_loader = DataLoader(test_dataset, batch_size=256)
result = evaluate(model, test_loader)
result
```
일반적으로 테스트 셋의 정확도와 손실은 검증 셋에서와 비슷할 것으로 예상됩니다.<br>
그렇지 않다면, 테스트 세트와 유사한 데이터와 분포를 가진 더 나은 검증 셋이 필요할 수 있습니다.
## 모델을 저장하고 불러오기
오랜 시간 모델을 학습하여 이상적인 정확도를 달성하였습니다.<br>
이 모델의 가중치와 편향 행렬을 <font color=blue>저장</font>하면 나중에 모델이 필요할때 모델을 처음부터 재학습 하지 않고 기존에 학습한 모델을 불러와 __재사용__ 할 수 있으므로 좋습니다.<br>
모델을 저장 할 수 있는 방법은 아래 코드와 같습니다.
```
torch.save(model.state_dict(), 'mnist-logistic.pth')
```
`.state_dict` 메서드는 모델의 모든 가중치와 편향 행렬이 포함된 `OrderedDict`를 반환합니다.
```
model.state_dict()
```
`MnistModel`클래스의 새로운 객체를 만들고, `.load_state_dict` 메서드를 사용해 __모델의 가중치__ 를 불러올 수 있습니다.
```
model2 = MnistModel()
model2.state_dict()
evaluate(model2, test_loader)
model2.load_state_dict(torch.load('mnist-logistic.pth'))
model2.state_dict()
```
안전성 검사때와 마찬가지로, 모델이 테스트 셋에 이전과 같은 손실과 정확성을 갖는지 확인해 보겠습니다.
```
test_loader = DataLoader(test_dataset, batch_size=256)
result = evaluate(model2, test_loader)
result
```
## 연습 과제
짧은 시간 내에 훌륭한 기계 학습 모델을 교육하려면 여러번의 연습과 많은 경험이 필요합니다. <br>
다양한 데이터셋, 모델 및 하이퍼 파라미터로 실험해 보는것이 이 기술을 습득하는 가장 좋은 방법입니다.
## 요약과 더 읽을 거리
이번 튜토리얼에서는 상당히 정교한 교육 및 평가 파이프라인을 만들었습니다. <br>
다음은 이번 튜토리얼에서 다룬 주제 목록입니다:
* PyTorch에서의 이미지 작업(MNIST 데이터셋을 사용)
* 교육, 검증 및 테스트 세트로 데이터셋 분할
* `nn.Module`을 상속해 커스텀 로직 PyTorch 모델 클래스
* Softmax를 사용하여 모델 출력을 확률로 해석 및 예측 레이블 선택
* 분류문제의 평가지표(정확도) 및 손실함수(크로스 엔트로피) 선정
* 검증 셋을 사용하여 모델을 평가하는 학습 루프 설정
* 무작위로 선택한 예제에 대해 수동으로 모델 테스트
* 모델 체크포인트 저장 및 로딩으로 처음부터 재교육 방지
이 튜토리얼에는 아직 하지 않은 많은 실험들이 있습니다. <br>
따라서 주피터의 상호작용 특성을 활용하여 다양한 매개 변수를 활용할 것을 권장합니다. 다음은 몇 가지 아이디어입니다:
* 검증 셋을 더 작거나 크게 만든 후 모델에 어떤 영향을 미치는지 확인하기
* 학습률을 변경하여 더 적은 시간에 동일한 정확도를 달성할 수 있는지 확인하기
* 배치 크기를 변경 후 배치 크기가 너무 크거나 너무 작으면 어떻게 되는지 알아보기.
* `fit` 기능을 수정하여 학습 셋의 전체적인 손실과 정확성을 기록하고, 검증 손실/정확도와 비교. 낮은/높은 이유를 설명해보기.
* 데이터의 작은 서브셋으로 교육하여 비슷한 수준의 정확도를 얻을 수 있는지 확인해보기.
* [CIFAR10 또는 CIFAR100 데이터셋](https://www.cs.toronto.edu/~kriz/cifar.complete)과 같은 다른 데이터셋에 대한 모델을 구축해 보기.
| github_jupyter |
# SOLVING THE TRANSVERSE ISING MODEL WITH VQE
In this tutorial we show how to solve for the ground state of the __Transverse Ising Model__, arguably one of the most prominent, canonical quantum spin systems, using the __variational quantum eigenvalue solver (VQE)__.
The VQE algorithm belongs to the class of __hybrid quantum algorithms__ (leveraging both classical as well as quantum compute), that are widely believed to be the working horse for the current __NISQ (noisy intermediate-scale quantum) era__.
To validate our approach we benchmark our results with exact results as obtained from a Jordan-Wigner transformation.
We provide a step-by-step walkthrough explaining the VQE quantum algorithm and show how to build the corresponding parametrized quantum circuit ansatz using the Braket SDK, with simple modular building blocks (that can be re-used for other purposes).
While we demonstrate our proof-of-concept approach using classical simulators for circuit execution, our code could in principle be run on actual quantum hardware by simply changing the definition of the ```device``` object.
## BACKGROUND: THE VARIATIONAL QUANTUM EIGENSOLVER (VQE)
Quantum computers hold the promise to outperform even the most-powerful classical computers on a range of computational problems in (for example) optimization, chemistry, material science and cryptography.
The canonical set of quantum algorithms (such as Shor's or Grover's quantum algorithms), however, comes with hardware requirements (such as a large number of quantum gates) that are currently not available with state-of-the-art technology.
Specifically, these algorithms are typically believed to be feasible only with fault-tolerance as provided by quantum error correction.
In the current __noisy intermediate-sclae (NISQ) era__, near-term quantum computers do not have a large enough number of physical qubits for the implementation of error correction protocols, making this canonical set of quantum algorithms unsuitable for near-term devices. Against this background, the near-term focus has widely shifted to the class of __hybrid quantum algorithms__ that do not require quantum error correction.
In these hybrid quantum algorithms are the noisy __near-term quantum computers are used as co-processors__ only, within a larger classical optimization loop, as sketched in the schematic figure below.
Here, the undesired effects of noise are suppressed by deliberately limiting the quantum circuits on the quantum processing unit (QPU) to short bursts of the calculation, and the need for long coherence times (as required for the standard set of quantum algorithms) is traded for a classical overhead due to (possibly many) measurement repetitions and (essentially error-free) classical processing.

__Variational Quantum Algorithms__: Specifically, variational quantum algorithms such as the Variational Quantum Eigensolver (VQE) [1, 2] or the Quantum Approximate Optimization Algorithm (QAOA) [3] belong to this emerging class of hybrid quantum algorithms.
These are widely believed to be promising candidates for the demonstration of a __quantum advantage__, already with near-term (NISQ) devices in areas such as quantum chemistry [4], condensed matter simulations [5], and discrete optimization tasks [6].
__Variational Quantum Computing vs. Deep Learning__: The working principle of variational quantum computing is very much reminiscent of training deep neural networks:
When you train a neural network, you have an objective function that you want to minimize, typically characterized by the error on your training set.
To minimize that error, typically you start out with an initial guess for the weights in your network.
The coprocessor, in that case a GPU, takes these weights which define the exact operation to execute and the output of the neural network is computed.
This output is then used to calculate the value of your objective function, which in turn is used by the CPU to make an educated guess to update the weights and the cycle continues.
Variational quantum algorithms, a specific form of hybrid algorithms, work in the very same way, using parametrized quantum circuits rather than parametrized neural networks and replacing the GPU with a QPU.
Here, you start with an initial guess for the parameters that define your circuit, have the QPU execute that circuit, perform measurements to calculate an objective function, pass this value (together with the current values of the parameters) back to the CPU and have this *classical* CPU update the parameters based on that information.
Of course, coordinating that workflow for quantum computers is much more challenging than in the previous case. Quantum computers are located in specialized laboratory facilities, are typically single threaded, and have special latency requirements.
This is exactly the undifferentiated heavy-lifting that Amazon Braket takes away for you such that we can focus on our scientific problem.
For the sake of this introductory tutorial, we simply use a classical circuit simulator (that mimic the behaviour of a quantum machine) as device to execute our quantum circuits.
Within Amazon Braket, the workflow, however, is exactly the same.
## BACKGROUND: THE TRANSVERSE ISING MODEL
While VQE is a very general approach, for concreteness we will focus on applying VQE to the one-dimensional Transverse Ising Model (TIM). The TIM belongs to a the broader class of many-body spin systems that are inherently hard to study on classical computers as the dimension of the Hilbert space grows exponentially with the number of particles in the system. With the help of a quantum computer, however, we can study these many-body systems with less overhead as the number of qubits required only grows polynomially. Even more so, the specific TIM is an integrable system and can be solved exactly, as shown in [7]. We will use these exact results as a benchmark for our approximate VQE results.
The transverse field Ising model is a quantum version of the classical Ising model that describes a lattice of spins with nearest neighbour interactions of strength $J$ (as set by the alignment or anti-alignment of spin projections along the $z$ axis), as well as an external magnetic field along the $x$ axis with strength $B$, creating an energetic bias for one x-axis spin direction over the other.
In one dimension, the Hamiltonian describing the TIM for $N$ spin-$1/2$ particles reads:
$$H = -J\sum_{i}S_{i}^{z}S_{i+1}^{z} - B\sum_{i}S_{i}^{x}.$$
Transforming the spin variables to qubits, we obtain:
$$H = -\frac{1}{4}\sum_{i}\sigma_{i}^{z}\sigma_{i+1}^{z} - \frac{B}{2}\sum_{i}\sigma_{i}^{x}.$$
Here, $B$ denotes the strength of the transverse magnetic field (in units of the hopping matrix element $J$ that we have set to unity).
__Symmetries and Phases__: The Hamiltonian $H$ possesses a $\mathbb{Z}_{2}$ symmetry, as it is invariant under the unitary transformation of flipping all qubits along the $z$-direction by an angle of $\pi$. Formally, this property can be expressed as $R_{x}HR_{x}^{\dagger}=H$, since $R_{x}\sigma_{i}^{z}R_{x}^{\dagger}=-\sigma_{i}^{z}$ and $R_{x}\sigma_{i}^{x}R_{x}^{\dagger}=\sigma_{i}^{x}$, with $R_{x}=\exp(-i \pi/2 \sum_{i}\sigma_{i}^{x})= (-i)^{N}\prod _{i}\sigma_{i}^{x}$ being a global rotation around the $x$-axis by angle $\pi$.
The 1D model then allows for two phases, depending on whether the ground state $\left|\Psi_{\mathrm{gs}}\right>$ breaks or preserves this global spin-flip symmetry [8]:
* *Ordered Phase*: When the transverse field $B$ is small, the system is in the ordered phase. In this phase the ground state breaks the spin-flip symmetry. Thus, the ground state is in fact two-fold degenerate.
Mathematically, if ${\displaystyle |\psi _{1}\rangle }$ is a ground state of the Hamiltonian, then ${\displaystyle |\psi _{2}\rangle \equiv \prod \sigma^{x}_{j}|\psi _{1}\rangle \neq |\psi _{1}\rangle }$ is a ground state as well. Taken together, these two distinct states span the degenerate ground state space.
Consider the following example for $B=0$: In this case, the ground state space is spanned by the states ${\displaystyle |\ldots 1,1,1, \ldots \rangle }$ and ${\displaystyle |\ldots 0,0,0, \ldots \rangle }$, that is, with all the qubits aligned along the $z$ axis.
* *Disordered Phase*: In contrast, when $B>1$, the system is in the disordered phase. Here, the ground state *does* preserve the spin-flip symmetry, and is nondegenerate (as opposed to the ordered phase discussed above).
Consider the following example when $B \rightarrow \infty$: Here, the ground state is simply the state aligned with the external magnetic field, ${\displaystyle |\ldots +,+,+, \ldots \rangle}$, with every qubit (spin) pointing in the $x$ direction.
There is a quantum phase transition at $B=1$ separating these two phases.
## IMPORTS and SETUP
```
# general imports
import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import time
from datetime import datetime
# magic word for producing visualizations in notebook
%matplotlib inline
# Ensure consistent results
np.random.seed(0)
# Flag to trigger writing results plot to file
SAVE_FIG = False
# AWS imports: Import Braket SDK modules
from braket.circuits import Circuit, Gate, AngledGate, QubitSet
from braket.devices import LocalSimulator
from braket.aws import AwsDevice, AwsSession
```
__NOTE__: Enter your desired device and S3 location (bucket and key) below. If you are working with the local simulator ```LocalSimulator()``` you do not need to specify any S3 location. However, if you are using a managed device or any QPU devices you need to specify the S3 location where your results will be stored. In this case, you need to replace the API call ```device.run(circuit, ...)``` below with ```device.run(circuit, s3_folder, ...)```.
```
# Set up device: Local Simulator
device = LocalSimulator()
# Enter the S3 bucket you created during onboarding in the code below
my_bucket = "amazon-braket-Your-Bucket-Name" # the name of the bucket
my_prefix = "Your-Folder-Name" # the name of the folder in the bucket
s3_folder = (my_bucket, my_prefix)
## example code for other backends
## choose the cloud-based managed simulator to run your circuit
# device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1")
## choose the Rigetti device to run your circuit
# device = AwsDevice("arn:aws:braket:::device/qpu/rigetti/Aspen-8")
## choose the Ionq device to run your circuit
# device = AwsDevice("arn:aws:braket:::device/qpu/ionq/ionQdevice")
```
## PROBLEM SETUP
In this section we develop a set of useful helper functions that we will explain in detail below.
Specifically we provide simple building blocks for the core modules of our VQE algorithm, that is (i) a function called ```circuit``` that defines the parametrized ansatz, (ii) a function called ```objective_function``` that takes a list of variational parameters as input, and returns the cost associated with those parameters and finally (iii) a function ```train``` to run the entire VQE algorithm for given ansatz.
This way we can solve the problem in a clean and modular approach.
```
# helper function to set up interaction term
def get_ising_interactions(n_qubits):
"""
function to setup Ising interaction term
"""
# set number of qubits
ising = np.zeros((n_qubits, n_qubits))
# set nearest-neighbour interactions to nonzero values only
for ii in range(0, n_qubits-1):
ising[ii][ii+1] = -1
# add periodic boundary conditions
ising[0][n_qubits-1] = -1
print('Ising matrix:\n', ising)
return ising
# function to build the VQE ansatz
def circuit(params, n_qubits):
"""
function to return full VQE circuit ansatz
input: parameter list with three parameters
"""
# instantiate circuit object
circuit = Circuit()
# add Hadamard gate on first qubit
circuit.rz(0, params[0]).ry(0, params[1])
# apply series of CNOT gates
for ii in range(1, n_qubits):
circuit.cnot(control=0, target=ii)
# add parametrized single-qubit rotations around y
for qubit in range(n_qubits):
gate = Circuit().ry(qubit, params[2])
circuit.add(gate)
return circuit
# function that computes cost function for given params
def objective_function(params, b_field, n_qubits, n_shots, s3_folder, verbose=False):
"""
objective function takes a list of variational parameters as input,
and returns the cost associated with those parameters
"""
global CYCLE
CYCLE += 1
if verbose:
print('==================================' * 2)
print('Calling the quantum circuit. Cycle:', CYCLE)
# obtain a quantum circuit instance from the parameters
vqe_circuit = circuit(params, n_qubits)
# Computations are independent of one another, so can be triggered in parallel
# run the circuit on appropriate device
if isinstance(device, LocalSimulator):
task_zz = device.run(vqe_circuit, shots=n_shots)
else:
task_zz = device.run(vqe_circuit, shots=n_shots, s3_destination_folder=s3_folder)
# Hb term: construct the circuit for measuring in the X-basis
H_on_all = Circuit().h(range(0, n_qubits))
vqe_circuit.add(H_on_all)
# run the circuit (with H rotation at end)
if isinstance(device, LocalSimulator):
task_b = device.run(vqe_circuit, shots=n_shots)
else:
task_b = device.run(vqe_circuit, shots=n_shots, s3_destination_folder=s3_folder)
# Collect results from devices (wait for results, if necessary)
result_zz = task_zz.result()
result_b = task_b.result()
# Compute Hzz term
# convert results (0 and 1) to ising (1 and -1)
meas_ising = result_zz.measurements
meas_ising[meas_ising == 1] = -1
meas_ising[meas_ising == 0] = 1
# Hzz term: get all energies (for every shot): (n_shots, 1) vector
all_energies_zz = np.diag(np.dot(meas_ising, np.dot(J, np.transpose(meas_ising))))
# Hzz term: get approx energy expectation value (factor 1/4 for Pauli vs spin 1/2)
energy_expect_zz = 0.25*np.sum(all_energies_zz)/n_shots
# Compute Hb term
# convert results (0 and 1) to ising (1 and -1)
meas_ising = result_b.measurements
meas_ising[meas_ising == 1] = -1
meas_ising[meas_ising == 0] = 1
# Hb term: get all energies (for every shot): (n_shots, 1) vector
# factor 1/2 for Pauli vs spin 1/2
energy_expect_b = -1*b_field/2*meas_ising.sum()/n_shots
# get total energy expectation value
energy_expect = energy_expect_zz + energy_expect_b
# per site
energy_expect_ind = energy_expect/n_qubits
# print energy expectation value
if verbose:
print('Energy expectation value:', energy_expect)
print('Energy expectation value (per particle):', energy_expect_ind)
return energy_expect
# The function to execute the training: run classical minimization.
def train(b_field, options, n_qubits, n_shots, n_initial=10, s3_folder=None, verbose=False):
"""
function to run VQE algorithm with several random seeds for initialization
"""
print('Starting the training.')
if verbose:
print('==================================' * 3)
print('Running VQE OPTIMIZATION.')
# initialize vectors for results per random seed
cost_energy = []
angles = []
# optimize for different random initializations: avoid local optima
for ii in range(n_initial):
#print counter
if verbose:
run_init = ii+1
print('Running VQE OPTIMIZATION for random seed NUMBER', run_init)
# randomly initialize variational parameters within appropriate bounds
params0 = np.random.uniform(0, 2 * np.pi, 3).tolist()
# set bounds for search space
bnds = [(0, 2 * np.pi) for _ in range(int(len(params0)))]
# run classical optimization
result = minimize(objective_function, params0, args=(b_field, n_qubits, n_shots, s3_folder, verbose),
options=options, method='SLSQP', bounds=bnds)
# store result of classical optimization
result_energy = result.fun
cost_energy.append(result_energy)
result_angle = result.x
angles.append(result_angle)
if verbose:
print('Optimal avg energy:', result_energy)
print('Optimal angles:', result_angle)
# reset cycle count
global CYCLE
CYCLE = 0
# store energy minimum (over different initial configurations)
energy_min = np.min(cost_energy)
optim_angles = angles[np.argmin(cost_energy)]
if verbose:
print('Energy per initial seeds:', cost_energy)
print('Minimal energy:', energy_min)
print('Optimal variational angles:', optim_angles)
return energy_min
```
## Illustration of the VQE ansatz
__VQE ansatz__: VQE tries to find the lowest energy configuration of a given Hamiltonian, such as that of a chemical system or some many-body spin system (as studied here). Being a variational quantum-classical algorithm, VQE uses the QPU for state preparation and measurement subroutines, and the classical computer to post-process the measurement results and update the parametrized VQE ansatz according to an update rule such as gradient descent.
VQE, however, does not come without limitations.
Akin to what happens in deep learning, the quality of our results will depend very much on the trial architecture of our circuit (i.e., the trial wave function) and its the expressive power.
In other words, to *approximate* the ground state we are looking for, VQE can only operate within the bounds of the general ansatz we are using (the so-called ansatz space), by having a quantum computer prepare this very ansatz state with a parameterized gate sequence, and then have a classical optimizer iteratively update the optimal parameters.
Here, we will be guided by physical intuition and symmetry arguments to make an educated guess for our variational ansatz.
In general, VQE makes us of the variational principle, by preparing a parametrized trial wavefunction $\left|\Psi(\vec{\theta})\right>$, and trying to find the optimal set of parameters $\vec{\theta}^{*}$, according to the following objective
$$\mathrm{min} \left<\Psi(\vec{\theta})|H|\Psi(\vec{\theta})\right> \geq E_{0}.$$
Here, $E_{0}$ denotes the (true) lowest energy eigenvalue of the Hamiltonian $H$.
Since (for sufficiently large systems with more than $\sim 50$ qubits) classical computers are unable to efficiently prepare, store and measure the wavefunction, we use the quantum computer for this subroutine.
We then use the classical computer to iteratively update the parameters using some optimization algorithm [9].
__VQE ansatz for TIM__: Next, we need to choose an ansatz appropriate for the system under study, the Transverse Ising Model (TIM).
We use an ansatz that can account for quantum entanglement.
Because of the $\mathbb{Z}_{2}$ symmetry discussed above, for any given state $\left|\Psi(\theta)\right>$ the rotated state $R_{x}\left|\Psi(\theta)\right>$ is a degenerate state with the same energy.
Therefore, we take our ansatz as a linear superposition of these two degenerate states, $\left|\psi(\theta)\right> = \alpha \left|\Psi(\theta)\right> + \beta R_{x}\left|\Psi(\theta)\right>$. How can we prepare such a state on a quantum computer? We use the following sequence of parametrized gates [10]:
First, starting from $\left|0000\right>$ we apply a general single qubit rotation to the first qubit to obtain the state
$$\left|000\dots\right> \rightarrow \alpha \left|000\dots\right> + \beta \left|100\dots\right>,$$
where the parameters $\alpha, \beta$ can be learned in the training process.
Then, we apply a sequence of CNOT gates as is done for the preparation of GHZ states.
The first CNOT between the first and second qubits prepares the state
$$\alpha \left|000\dots\right> + \beta \left|110\dots\right>.$$
We continue with CNOT gates till we arrive at the parametrized ansatz
$$\alpha \left|000\dots\right> + \beta \left|111\dots\right>.$$
Finally, to account for different polarization directions we apply parametrized single qubit rotations around the $y$ axis to arrive at our VQE trial ansatz state
$$\left|\Psi(\theta)\right> = \alpha U_{y}(\theta_{y})\left|000\dots\right> + \beta U_{y}(\theta_{y})\left|111\dots\right>,$$
with $U_{y}(\theta_{y})=\prod \exp(-i \theta_{y}/2 \sigma_{i}^{y})$.
__Illustration__: Below, we illustrate our ansatz (as prepared by our method ```circuit```) with a circuit diagram for a small number of qubits $N$ and a fixed set of classical parameters. We print both our VQE ansatz as well as the modified circuit with a layer of single-qubit Hadamard gates ```H``` attached at the end, as needed to measure the $x$ projection with $\sigma_{i}^{x}$ for all qubits. The latter is needed to compute the expectation value for the transverse field term $H_{B}=(B/2)\sum_{i}\sigma_{i}^{x}$. With this simple visualization we can convince ourselves that we have implemented the circuit ansatz as desired.
```
# visualize VQE circuit example
N = 4
params = [0.1, 0.2, 0.3]
vqe_circuit = circuit(params, N)
print('1. Printing VQE test circuit:')
print(vqe_circuit)
# Hb term: construct the circuit for measuring in the X-basis
print('')
print('2. Apply Hadamard to measure in x-basis:')
H_on_all = Circuit().h(range(0, N))
vqe_circuit.add(H_on_all)
print(vqe_circuit)
```
## VQE SIMULATION ON LOCAL SIMULATOR
We are now ready to run some VQE simulation experiments. First of all, you can play and experiment yourself with the number of qubits $N$. Secondly, you may also experiment with the classical optimizer. Since we are using an off-the-shelf ```scipy``` minimizer (as described in more detail [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html)), you can simply swap between different optimizers by setting the ```method``` parameter accordingly, as done above in the line ```result = minimize(..., method='SLSQP')```. Some popular options readily available within this library include *Nelder-Mead*, *BFGS* and *COBYLA*.
As a precautionary warning, note that the classical optimization step may get stuck in a local optimum, rather than finding the global minimum for our parametrized VQE ansatz wavefunction.
To address this issue, we run several optimization loops, starting from different random parameter seeds.
You can set the number of these optimization loops using the ```n_initial``` parameter, as shown below.
While this brute-force approach does not provide any guarantee to find the global optimum, from a pragmatic point of view at least it does increase the odds of finding an acceptable solution, at the expense of potentially having to run many more circuits on the QPU.
For a more detailed and sophisticated discussion of classical optimization of VQE we refer to Ref.[11].
```
# set up the problem
SHOTS = 1000
N = 10 # number of qubits
n_initial = 30 # number of random seeds to explore optimization landscape
verbose = False # control amount of print output
# set counters
CYCLE = 0
# set up Ising matrix with nearest neighbour interactions and PBC
J = get_ising_interactions(N)
# set options for classical optimization
if verbose:
options = {'disp': True}
else:
options = {}
# kick off training
start = time.time()
# parameter scan
stepsize = 0.5
xvalues = np.arange(0, 2+stepsize, stepsize)
results = []
results_site = []
for bb in xvalues:
b_field = bb
print('Strength of magnetic field:', b_field)
energy_min = train(b_field, options=options, n_qubits=N, n_shots=SHOTS, n_initial=n_initial,
s3_folder=s3_folder, verbose=verbose)
results.append(energy_min)
results_site.append(energy_min/N)
# reset counters
CYCLE = 0
end = time.time()
# print execution time
print('Code execution time [sec]:', end - start)
# print optimized results
print('Optimal energies:', results)
print('Optimal energies (per site):', results_site)
# plot the VQE results for the energy per site
plt.plot(xvalues, results_site, 'm--o')
plt.xlabel('transverse field $B [J]$')
plt.ylabel('groundstate energy per site $E_{0}/N [J]$')
plt.show()
```
## BENCHMARKING OUR VQE ANSATZ WITH EXACT RESULTS
As detailed in the seminal paper by [7], the paradigmatic TIM can be solved with the help of a (highly non-local) Jordan-Wigner transformation that expresses the spin (qubit) variables as fermionic variables, and leading to a sum of local quadratic terms containing fermionic creation and annihilation operators.
The resulting Hamiltonian is mathematically identical to that of a superconductor in the mean field Bogoliubov deGennes formalism and can be completely understood in the same standard way.
Specifically, the exact excitation spectrum and eigenvalues can be determined by Fourier transforming into momentum space and diagonalizing the Hamiltonian.
Here, we just use the known results from Ref.[7] to recover the exact ground-state energy with the helper function defined below, and refer the interested reader to the broad set of literature on the TIM for further details. The original paper is available [online here](https://www.math.ucdavis.edu/~bxn/pfeuty1970.pdf).
```
# helper function to numerically solve for gs energy of TIM
def num_integrate_gs(B):
"""
numerically integrate exact band to get gs energy of TIM
this should give -E_0/(N*J) by Pfeufy
Here set J=1 (units of energy)
"""
# lamba_ratio (setting J=1): compare thesis
ll = 1/(2*B)
# set energy
gs_energy = 0
# numerical integration
step_size = 0.0001
k_values = np.arange(0, np.pi, step_size)
integration_values = [step_size*np.sqrt(1 + ll**2 + 2*ll*np.cos(kk)) for kk in k_values]
integral = np.sum(integration_values)
gs_energy = 1*integral/(4*np.pi*ll)
return gs_energy
# plot exact gs energy of TIM vs VQE results
x = np.arange(0.01, 2.2, 0.2)
y = [-1*num_integrate_gs(xx) for xx in x]
# plot exact results
plt.plot(x, y, 'b--s')
# plot vqe results
plt.plot(xvalues, results_site, 'm--o')
plt.xlabel('magnetic field $B [J]$')
plt.ylabel('groundstate energy $E_{0}/N [J]$')
plt.tight_layout();
# save figure
if SAVE_FIG:
time_now = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
filename = 'vqe_tim_gs-energy_'+time_now+'.png'
plt.savefig(filename, dpi=700);
```
As shown above, for sufficiently large number of seeds (```n_initial```) we approximate the exact results reasonably well with our relatively simple three-parameter VQE ansatz, in the whole magnetic field region under consideration.
---
## REFERENCES
[1] A. Peruzzo, J. McClean, P. Shadbolt, M.-H. Yung, X.-Q. Zhou, P. J. Love, A. Aspuru-Guzik, and J. L. Obrien, Nature communications 5, 56 (2014).
[2] J. R. McClean, J. Romero, R. Babbush, and A. Aspuru-Guzik, *The theory of variational hybrid quantum-classical algorithms*, New Journal of Physics 18, 023023 (2016).
[3] E. Farhi, J. Goldstone, and S. Gutmann, arXiv 1411.4028 (2014).
[4] Y. Cao, J. Romero, J. P. Olson, M. Degroote, P. D. Johnson, M. Kieferov´a, I. D. Kivlichan, T. Menke, B. Peropadre, N. P. Sawaya, et al., Chemical reviews 119,
10856 (2019).
[5] A. Smith, M. Kim, F. Pollmann, and J. Knolle, npj
Quantum Information 5, 1 (2019).
[6] L. Zhou, S.-T. Wang, S. Choi, H. Pichler, and M. D.
Lukin, arXiv 1812.01041 (2018).
[7] P. Pfeuty, *The One-Dimensional Ising Model with a Transverse Field*, Annals of Physics __57__, 79-90 (1970).
[8] https://en.wikipedia.org/wiki/Transverse-field_Ising_model
[9] S. McArdle, S. Endo, A. Aspuru-Guzik, S. Benjamin, X. Yuan, *Quantum computational chemistry*, Rev. Mod. Phys. 92, 15003 (2020).
[10] Abhijith J. *et al.*, *Quantum Algorithm Implementations for Beginners*, arXiv:1804.03719 (2018).
[11] D. Wierichs, C. Gogolin, M. Kastoryano, *Avoiding local minima in variational quantum eigensolvers with the natural gradient optimizer*, arXiv:2004.14666 (2020).
---
## APPENDIX
```
# Check SDK version
!pip show amazon-braket-sdk | grep Version
```
| github_jupyter |
```
import checklist
from checklist.test_suite import TestSuite
import logging
logging.basicConfig(level=logging.ERROR)
from transformers import pipeline
```
## Sentiment analysis
```
model = pipeline("sentiment-analysis", device=0)
```
Add some batching, I run out of memory otherwise:
```
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
def batch_predict(model, data, batch_size=128):
ret = []
for d in chunks(data, batch_size):
ret.extend(model(d))
return ret
```
The tests in the paper are for 3-label sentiment analysis (negative, positive, neutral). We adapt this binary model by making everything in the [0.33, 0.66] range be predicted as neutral:
```
import numpy as np
def pred_and_conf(data):
# change format to softmax, make everything in [0.33, 0.66] range be predicted as neutral
preds = batch_predict(model, data)
pr = np.array([x['score'] if x['label'] == 'POSITIVE' else 1 - x['score'] for x in preds])
pp = np.zeros((pr.shape[0], 3))
margin_neutral = 1/3.
mn = margin_neutral / 2.
neg = pr < 0.5 - mn
pp[neg, 0] = 1 - pr[neg]
pp[neg, 2] = pr[neg]
pos = pr > 0.5 + mn
pp[pos, 0] = 1 - pr[pos]
pp[pos, 2] = pr[pos]
neutral_pos = (pr >= 0.5) * (pr < 0.5 + mn)
pp[neutral_pos, 1] = 1 - (1 / margin_neutral) * np.abs(pr[neutral_pos] - 0.5)
pp[neutral_pos, 2] = 1 - pp[neutral_pos, 1]
neutral_neg = (pr < 0.5) * (pr > 0.5 - mn)
pp[neutral_neg, 1] = 1 - (1 / margin_neutral) * np.abs(pr[neutral_neg] - 0.5)
pp[neutral_neg, 0] = 1 - pp[neutral_neg, 1]
preds = np.argmax(pp, axis=1)
return preds, pp
suite_path = '../release_data/sentiment/sentiment_suite.pkl'
suite = TestSuite.from_file(suite_path)
suite.run(pred_and_conf, n=500)
# suite.visual_summary_table()
suite.summary()
```
## QQP
Transformers doesn't have a model pretrained on QQP, so we'll use one trained on MRPC for this demo
```
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
model.to('cuda');
model.eval();
def batch_qqp(data, batch_size=128):
ret = []
for d in chunks(data, batch_size):
t = tokenizer([a[0] for a in d], [a[1] for a in d], return_tensors='pt', padding=True).to('cuda')
with torch.no_grad():
logits = torch.softmax(model(**t)[0], dim=1).cpu().numpy()
ret.append(logits)
return np.vstack(ret)
from checklist.pred_wrapper import PredictorWrapper
# wrapped_pp returns a tuple with (predictions, softmax confidences)
wrapped_pp = PredictorWrapper.wrap_softmax(batch_qqp)
s0 = "The company HuggingFace is based in New York City"
s1 = "Apples are especially bad for your health"
s2 = "HuggingFace's headquarters are situated in Manhattan"
batch_qqp([(s0, s1), (s0, s2)])
suite_path = '../release_data/qqp/qqp_suite.pkl'
suite = TestSuite.from_file(suite_path)
suite.run(wrapped_pp, n=500)
suite.summary()
```
## SQuAD
```
model = pipeline("question-answering", device=0)
suite_path = '../release_data/squad/squad_suite.pkl'
suite = TestSuite.from_file(suite_path)
```
Our suite has data as lists of (context, question) tuples. We'll adapt to this prediction format below:
```
def predconfs(context_question_pairs):
preds = []
confs = []
for c, q in context_question_pairs:
try:
p = model(question=q, context=c, truncation=True, )
except:
print('Failed', q)
preds.append(' ')
confs.append(1)
preds.append(p['answer'])
confs.append(p['score'])
return preds, np.array(confs)
# suite.tests['Question typo'].run(predconfs,n=100, overwrite=True)
suite.run(predconfs, n=100, overwrite=True)
def format_squad_with_context(x, pred, conf, label=None, *args, **kwargs):
c, q = x
ret = 'C: %s\nQ: %s\n' % (c, q)
if label is not None:
ret += 'A: %s\n' % label
ret += 'P: %s\n' % pred
return ret
suite.summary(format_example_fn=format_squad_with_context)
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
# Auto ML : Remote Execution with Text data from Blobstorage
In this example we use the [Burning Man 2016 dataset](https://innovate.burningman.org/datasets-page/) to showcase how you can use AutoML to handle text data from a Azure blobstorage.
Make sure you have executed the [00.configuration](00.configuration.ipynb) before running this notebook.
In this notebook you would see
1. Creating an Experiment using an existing Workspace
2. Attaching an existing DSVM to a workspace
3. Instantiating AutoMLConfig
4. Training the Model using the DSVM
5. Exploring the results
6. Testing the fitted model
In addition this notebook showcases the following features
- **Parallel** Executions for iterations
- Asyncronous tracking of progress
- **Cancelling** individual iterations or the entire run
- Retrieving models for any iteration or logged metric
- specify automl settings as **kwargs**
- handling **text** data with **preprocess** flag
## Create Experiment
As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments.
```
import logging
import os
import random
from matplotlib import pyplot as plt
from matplotlib.pyplot import imshow
import numpy as np
import pandas as pd
from sklearn import datasets
import azureml.core
from azureml.core.experiment import Experiment
from azureml.core.workspace import Workspace
from azureml.train.automl import AutoMLConfig
from azureml.train.automl.run import AutoMLRun
ws = Workspace.from_config()
# choose a name for the run history container in the workspace
experiment_name = 'automl-remote-dsvm-blobstore'
# project folder
project_folder = './sample_projects/automl-remote-dsvm-blobstore'
experiment = Experiment(ws, experiment_name)
output = {}
output['SDK version'] = azureml.core.VERSION
output['Subscription ID'] = ws.subscription_id
output['Workspace'] = ws.name
output['Resource Group'] = ws.resource_group
output['Location'] = ws.location
output['Project Directory'] = project_folder
output['Experiment Name'] = experiment.name
pd.set_option('display.max_colwidth', -1)
pd.DataFrame(data=output, index=['']).T
```
## Diagnostics
Opt-in diagnostics for better experience, quality, and security of future releases
```
from azureml.telemetry import set_diagnostics_collection
set_diagnostics_collection(send_diagnostics=True)
```
## Attach a Remote Linux DSVM
To use remote docker commpute target:
1. Create a Linux DSVM in Azure. Here is some [quick instructions](https://docs.microsoft.com/en-us/azure/machine-learning/desktop-workbench/how-to-create-dsvm-hdi). Make sure you use the Ubuntu flavor, NOT CentOS. Make sure that disk space is available under /tmp because AutoML creates files under /tmp/azureml_runs. The DSVM should have more cores than the number of parallel runs that you plan to enable. It should also have at least 4Gb per core.
2. Enter the IP address, username and password below
**Note**: By default SSH runs on port 22 and you don't need to specify it. But if for security reasons you can switch to a different port (such as 5022), you can append the port number to the address. [Read more](https://render.githubusercontent.com/documentation/sdk/ssh-issue.md) on this.
```
from azureml.core.compute import RemoteCompute
# Add your VM information below
dsvm_name = 'mydsvm1'
dsvm_ip_addr = '<<ip_addr>>'
dsvm_username = '<<username>>'
dsvm_password = '<<password>>'
dsvm_compute = RemoteCompute.attach(workspace=ws, name=dsvm_name, address=dsvm_ip_addr, username=dsvm_username, password=dsvm_password, ssh_port=22)
```
## Create Get Data File
For remote executions you should author a get_data.py file containing a get_data() function. This file should be in the root directory of the project. You can encapsulate code to read data either from a blob storage or local disk in this file.
The *get_data()* function returns a [dictionary](README.md#getdata).
```
if not os.path.exists(project_folder):
os.makedirs(project_folder)
%%writefile $project_folder/get_data.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
def get_data():
# Burning man 2016 data
df = pd.read_csv("https://automldemods.blob.core.windows.net/datasets/PlayaEvents2016,_1.6MB,_3.4k-rows.cleaned.2.tsv",
delimiter="\t", quotechar='"')
# get integer labels
le = LabelEncoder()
le.fit(df["Label"].values)
y = le.transform(df["Label"].values)
df = df.drop(["Label"], axis=1)
df_train, _, y_train, _ = train_test_split(df, y, test_size=0.1, random_state=42)
return { "X" : df, "y" : y }
```
### View data
You can execute the *get_data()* function locally to view the *train* data
```
%run $project_folder/get_data.py
data_dict = get_data()
df = data_dict["X"]
y = data_dict["y"]
pd.set_option('display.max_colwidth', 15)
df['Label'] = pd.Series(y, index=df.index)
df.head()
```
## Instantiate AutoML <a class="anchor" id="Instatiate-AutoML-Remote-DSVM"></a>
You can specify automl_settings as **kwargs** as well. Also note that you can use the get_data() symantic for local excutions too.
<i>Note: For Remote DSVM and Batch AI you cannot pass Numpy arrays directly to the fit method.</i>
|Property|Description|
|-|-|
|**primary_metric**|This is the metric that you want to optimize.<br> Classification supports the following primary metrics <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>balanced_accuracy</i><br><i>average_precision_score_weighted</i><br><i>precision_score_weighted</i>|
|**max_time_sec**|Time limit in seconds for each iteration|
|**iterations**|Number of iterations. In each iteration Auto ML trains a specific pipeline with the data|
|**n_cross_validations**|Number of cross validation splits|
|**concurrent_iterations**|Max number of iterations that would be executed in parallel. This should be less than the number of cores on the DSVM
|**preprocess**| *True/False* <br>Setting this to *True* enables AutoML to perform preprocessing <br>on the input to handle *missing data*, and perform some common *feature extraction*|
|**max_cores_per_iteration**| Indicates how many cores on the compute target would be used to train a single pipeline.<br> Default is *1*, you can set it to *-1* to use all cores|
```
automl_settings = {
"max_time_sec": 3600,
"iterations": 10,
"n_cross_validations": 5,
"primary_metric": 'AUC_weighted',
"preprocess": True,
"max_cores_per_iteration": 2
}
automl_config = AutoMLConfig(task = 'classification',
path=project_folder,
compute_target = dsvm_compute,
data_script = project_folder + "/get_data.py",
**automl_settings
)
```
## Training the Model <a class="anchor" id="Training-the-model-Remote-DSVM"></a>
For remote runs the execution is asynchronous, so you will see the iterations get populated as they complete. You can interact with the widgets/models even when the experiment is running to retreive the best model up to that point. Once you are satisfied with the model you can cancel a particular iteration or the whole run.
```
remote_run = experiment.submit(automl_config)
```
## Exploring the Results <a class="anchor" id="Exploring-the-Results-Remote-DSVM"></a>
#### Widget for monitoring runs
The widget will sit on "loading" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete.
You can click on a pipeline to see run properties and output logs. Logs are also available on the DSVM under /tmp/azureml_run/{iterationid}/azureml-logs
NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details.
```
from azureml.train.widgets import RunDetails
RunDetails(remote_run).show()
```
#### Retrieve All Child Runs
You can also use sdk methods to fetch all the child runs and see individual metrics that we log.
```
children = list(remote_run.get_children())
metricslist = {}
for run in children:
properties = run.get_properties()
metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}
metricslist[int(properties['iteration'])] = metrics
rundata = pd.DataFrame(metricslist).sort_index(1)
rundata
```
## Canceling runs
You can cancel ongoing remote runs using the *cancel()* and *cancel_iteration()* functions
```
# Cancel the ongoing experiment and stop scheduling new iterations
remote_run.cancel()
# Cancel iteration 1 and move onto iteration 2
# remote_run.cancel_iteration(1)
```
### Retrieve the Best Model
Below we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*.
```
best_run, fitted_model = remote_run.get_output()
print(best_run)
print(fitted_model)
```
#### Best Model based on any other metric
```
# lookup_metric = "accuracy"
# best_run, fitted_model = remote_run.get_output(metric=lookup_metric)
```
#### Model from a specific iteration
```
iteration = 0
zero_run, zero_model = remote_run.get_output(iteration=iteration)
```
### Register fitted model for deployment
```
description = 'AutoML Model'
tags = None
remote_run.register_model(description=description, tags=tags)
remote_run.model_id # Use this id to deploy the model as a web service in Azure
```
### Testing the Fitted Model <a class="anchor" id="Testing-the-Fitted-Model-Remote-DSVM"></a>
```
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from pandas_ml import ConfusionMatrix
df = pd.read_csv("https://automldemods.blob.core.windows.net/datasets/PlayaEvents2016,_1.6MB,_3.4k-rows.cleaned.2.tsv",
delimiter="\t", quotechar='"')
# get integer labels
le = LabelEncoder()
le.fit(df["Label"].values)
y = le.transform(df["Label"].values)
df = df.drop(["Label"], axis=1)
_, df_test, _, y_test = train_test_split(df, y, test_size=0.1, random_state=42)
ypred = fitted_model.predict(df_test.values)
ypred_strings = le.inverse_transform(ypred)
ytest_strings = le.inverse_transform(y_test)
cm = ConfusionMatrix(ytest_strings, ypred_strings)
print(cm)
cm.plot()
```
| github_jupyter |
```
import numpy as np
arr = np.arange(0,11)
arr
# Simplest way to pick an element or some of the elements from an array is similar to indexing in a python list.
arr[8] # Gives value at the index 8
# Slice Notations [start:stop]
arr[1:5] # 1 inclusive and 5 exclusive
# Another Example of Slicing
arr[0:5]
# To have everything from beginning to the index 6 we use the following syntax on a numpy array :
print(arr[:6]) # No need to define the starting point and this basically means arr[0:6]
# To have everything from a 5th index to the last we use the following syntax on a numpy array :
print(arr[5:])
```
# Broadcasting the Value
**Numpy arrays differ from normal python list due to their ability to broadcast.**
```
arr[0:5] = 100 # Broacasts the value 100 to first 5 digits.
arr
# Reset the array
arr = np.arange(0,11)
arr
slice_of_arr = arr[0:6]
slice_of_arr
# To grab everything in the slice
slice_of_arr[:]
# Broadcasting after grabbing everything in the array
slice_of_arr[:] = 99
slice_of_arr
arr
# Notice above how not only slice_of_arr got changed due to the broadcast but the array arr was also changed.
# Slice and the original array both got changed in terms of values.
# Data is not copied but rather just copied or pointed from original array.
# Reason behind such behaviour is that to prevent memory issues while dealing with large arrays.
# It basically means numpy prefers not setting copies of arrays and would rather point slices to their original parent arrays.
# Use copy() method which is array_name.copy()
arr_copy = arr.copy()
arr_copy
arr_copy[0:5] = 23
arr
arr_copy #Since we have copied now we can see that arr and arr_copy would be different even after broadcasting.
# Original array remains unaffected despite changes on the copied array.
# Main idea here is that if you grab the actual slice of the array and set it as variable without calling the method copy
# on the array then you are just seeing the link to original array and changes on slice would reflect on original/parent array.
```
# 2D Array/Matrix
```
arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]])
arr_2d # REMEMBER If having confusion regarding dimensions of the matrix just call shape.
arr_2d.shape # 3 rows, 3 columns
# Two general formats for grabbing elements from a 2D array or matrix format :
# (i) Double Bracket Format (ii) Single Bracket Format with comma (Recommended)
# (i) Double Bracket Format
arr_2d[0][:] # Gives all the elements inside the 0th index of array arr.
# arr_2d[0][:] Also works
arr_2d[1][2] # Gives the element at index 2 of the 1st index of arr_2d i.e. 30
# (ii) Single Bracket Format with comma (Recommended) : Removes [][] 2 square brackets with a tuple kind (x,y) format
# To print 30 we do the following 1st row and 2nd index
arr_2d[1,2]
# Say we want sub matrices from the matrix arr_2d
arr_2d[:3,1:] # Everything upto the third row, and anything from column 1 onwards.
arr_2d[1:,:]
```
# Conditional Selection
```
arr = np.arange(1,11)
arr
# Taking the array arr and comapring it using comparison operators to get a full boolean array out of this.
bool_arr = arr > 5
'''
1. Getting the array and using a comparison operator on it will actually return a boolean array.
2. An array with boolean values in response to our condition.
3. Now we can use the boolean array to actually index or conditionally select elements from the original array where boolean
array is true.
'''
bool_arr
arr[bool_arr] # Gives us only the results which are only true.
# Doing what's described above in one line will be
arr[arr<3] # arr[comaprison condition] Get used to this notation we use this a lot especially in Pandas!
```
# Exercise
1. Create a new 2d array np.arange(50).reshape(5,10).
2. Grab any 2sub matrices from the 5x10 chunk.
```
arr_2d = np.arange(50).reshape(5,10)
arr_2d
# Selecting 11 to 35
arr_2d[1:4,1:6]# Keep in mind it is exclusive for the end value in the start:end format of indexing.
# Selecting 5-49
arr_2d[0:,5:]
```
| github_jupyter |
```
%matplotlib widget
import os
import sys
sys.path.insert(0, os.getenv('HOME')+'/pycode/MscThesis/')
import pandas as pd
from amftrack.util import get_dates_datetime, get_dirname, get_plate_number, get_postion_number,get_begin_index
import ast
from amftrack.plotutil import plot_t_tp1
from scipy import sparse
from datetime import datetime
from amftrack.pipeline.functions.node_id import orient
import pickle
import scipy.io as sio
from pymatreader import read_mat
from matplotlib import colors
import cv2
import imageio
import matplotlib.pyplot as plt
import numpy as np
from skimage.filters import frangi
from skimage import filters
from random import choice
import scipy.sparse
import os
from amftrack.pipeline.functions.extract_graph import from_sparse_to_graph, generate_nx_graph, sparse_to_doc
from skimage.feature import hessian_matrix_det
from amftrack.pipeline.functions.experiment_class_surf import Experiment, Edge, Node, Hyphae, plot_raw_plus
from amftrack.pipeline.paths.directory import run_parallel, find_state, directory_scratch, directory_project
from amftrack.notebooks.analysis.util import *
from scipy import stats
from scipy.ndimage.filters import uniform_filter1d
from statsmodels.stats import weightstats as stests
from amftrack.pipeline.functions.hyphae_id_surf import get_pixel_growth_and_new_children
from collections import Counter
from IPython.display import clear_output
from amftrack.notebooks.analysis.data_info import *
inst = (19,0,25)
exp = get_exp(inst,directory_project)
def criter(max_growth,length):
return(a*length+b*max_growth>=2.5 and max_growth>=50)
RH, BAS, max_speeds, total_growths, widths, lengths, branch_frequ,select_hyph = get_rh_bas(exp,criter)
hyph_anas_tip_hyph = [hyphat for hyphat in exp.hyphaes if len(hyphat.ts)>=2 and hyphat.end.degree(hyphat.ts[-1])>=3 and hyphat.end.degree(hyphat.ts[-2])>=3]
branches = {}
lengths = {}
bd = []
ts = []
rh_ends = [rh.end for rh in RH]
daughters = {}
begins = {}
for rh in RH:
tp1 = rh.ts[-1]
t = rh.ts[0]
pixels, nodes = get_pixel_growth_and_new_children(rh, t, tp1)
curv_length = np.sum([get_length_um(seg) for seg in pixels])
branch = []
daughter_list=[]
begins[rh] = nodes[1]
for node in nodes[1:-1]:
if node not in [hyph.end for hyph in hyph_anas_tip_hyph]:
node_obj = node
# t0 = node_obj.ts()[0]
# neighbours = node_obj.neighbours(t0)
# if t0 in rh.ts:
# nodes_hyph,edge = rh.get_nodes_within(t0)
# for neighbour in neighbours:
# if neighbour.label not in nodes_hyph:
# daughter_list.append(neighbour)
# if neighbour in rh_ends and neighbour!=rh.end:
branch.append(node)
bd.append(len(branch)/curv_length)
ts.append(get_time(exp,0,t))
branches[rh] = branch
daughters[rh] = daughter_list
lengths[rh] = curv_length
data = pd.DataFrame(list(zip(ts,bd)),columns = ['time','branchin_dist'])
corrected = data.loc[(data['branchin_dist']>0)]
corrected['real_branchin_dist'] = 1/corrected['branchin_dist']
plt.close('all')
abcisse = 'time'
ordinate = 'real_branchin_dist'
tab = corrected
baits_sort = tab.sort_values(abcisse)
N=100
moving_av = baits_sort.rolling(N,min_periods=N//2).mean()
moving_std = baits_sort.rolling(N,min_periods=N//2).std()
fig=plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax.set_xlabel('time (h)')
ax.set_ylabel('Branching distance (BAS and RH undistinguished) ($\mu m$)',color='red')
# ax.set_xlim(0,70)
ax.set_ylim(0,1500)
# ax.set_xlim(-190,190)
# slope, intercept, r_value, p_value, std_err = stats.linregress(densities_sort,np.abs(curvatures_sort))
ax.scatter(tab[abcisse],tab[ordinate],alpha=0.3,color='red')
ax.plot(moving_av[abcisse],moving_av[ordinate],color='red',label = 'moving average')
ax.plot(moving_av[abcisse],(moving_av[ordinate]+moving_std[ordinate]/np.sqrt(N)),color='red',label = 'std',linestyle = 'dotted')
ax.plot(moving_av[abcisse],(moving_av[ordinate]-moving_std[ordinate]/np.sqrt(N)),color='red',label = 'std',linestyle = 'dotted')
ax.spines['right'].set_color('red')
ax.set_title((inst,np.mean(corrected['real_branchin_dist'])))
ax.tick_params(axis='y', colors='red') #setting up Y-axis tick color to black
np.mean(corrected['real_branchin_dist'])
exp.plot_raw(-1)
# bd = [790,983,1078,664,1593,860,1132,809,607,573,1455,672,754]
# nconnection = [11,4,3,8,2,14,3,6,10,4,3,5,5]
# total_network = [3589,1668,1301,1187,348,2776,528,2413,2920,1034,1557,1795]
bd = [790,983,1078,664,860,1132,809,607,573,1455,672,754,1136]
nconnection = [11,4,3,8,14,3,6,10,4,3,5,5,2]
total_network = [3589,1668,1301,1187,2776,528,2413,2920,1034,1557,1180,1795,1497]
data = pd.DataFrame(list(zip(nconnection,bd,total_network)),columns = ['n_connect','branchin_dist','total_network'])
corrected = data.loc[(data['branchin_dist']>0)]
corrected['length_connection_rat'] = corrected['total_network']/corrected['n_connect']
#### from scipy.optimize import curve_fit
plt.rcParams.update({
"font.family": "verdana",
'font.weight' : 'normal',
'font.size': 20})
plt.close('all')
abcisse = 'length_connection_rat'
ordinate = 'branchin_dist'
tab = corrected
baits_sort = tab.sort_values(abcisse)
N=3
moving_av = baits_sort.rolling(N,min_periods=N//4).mean()
moving_std = baits_sort.rolling(N,min_periods=N//4).std()
fig=plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
# ax.set_xlabel('number of trunk hyphae')
ax.set_xlabel('network length/number of trunk hyphae ($\mu m$)')
ax.set_ylabel('Branching distance (BAS and RH undistinguished) ($\mu m$)',color='red')
# ax.set_xlim(0,70)
# ax.set_ylim(0,1500)
# ax.set_xlim(-190,190)
# slope, intercept, r_value, p_value, std_err = stats.linregress(densities_sort,np.abs(curvatures_sort))
ns = list(set(corrected['n_connect'].values))
ns.sort()
averages = [np.mean(corrected.loc[corrected["n_connect"]==n][ordinate]) for n in ns]
sts = [np.std(corrected.loc[corrected["n_connect"]==n][ordinate])/np.sqrt(len(corrected.loc[corrected["n_connect"]==n][ordinate])) for n in ns]
# plt.errorbar(ns,averages,yerr=sts, linestyle="None",capthick = 1)
def func2(t,alpha,beta):
return((beta*np.exp(-alpha*(t))))
popt1, pcov = curve_fit(func2,tab[abcisse],tab[ordinate],bounds = ([0,0],2*[np.inf]),p0=[1,1])
# popt2, pcov = curve_fit(func2, times, total_anastomosis_theory,bounds = ([0,0,-np.inf],3*[np.inf]),p0=[1,1,0])
# ax.plot(ns,func2(np.array(ns),*popt1),label = f'exponential fit : alpha= {"{:.2f}".format(popt1[0]*24)}.day-1',color='blue')
ax.scatter(tab[abcisse],tab[ordinate],alpha=0.3,color='red')
# ax.plot(moving_av[abcisse],moving_av[ordinate],color='red',label = 'moving average')
# ax.plot(moving_av[abcisse],(moving_av[ordinate]+moving_std[ordinate]/np.sqrt(N)),color='red',label = 'std',linestyle = 'dotted')
# ax.plot(moving_av[abcisse],(moving_av[ordinate]-moving_std[ordinate]/np.sqrt(N)),color='red',label = 'std',linestyle = 'dotted')
ax.spines['right'].set_color('red')
ax.tick_params(axis='y', colors='red') #setting up Y-axis tick color to black
fig=plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax.scatter(nconnection,bd)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/deerow22/EscapeEarth/blob/main/interns/Activities/Data/Activity_3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Mount google drive to access/write data
```
from google.colab import drive
drive.mount('/content/gdrive')
```
# Import/Install needed packages
```
import pandas as pd
!pip install lightkurve
import lightkurve as lk
```
# Functions to open data
```
import lightkurve as lk
import glob
import os
import pandas as pd
def locate_files(tic,path=None):
'''
~ Locates TESS lightcurve files with filenames formatted from a mast bulk download.~
REQUIRES: glob
Args:
tic -(int or str)TESS TIC ID
path -(str) path on computer to file(s) location
Returns:
list of path strings for all files found with specified tic
'''
if path == None: #if only need filename
fullpath = glob.glob('*{}-*-s_lc.fits'.format(tic)) #to use wildcard*
else: #user defined path to datafile on their computer
pathstart = path
pathstart = str(pathstart) #make a string in case user forgets to but think that gives an err anyway
pathend = pathstart +'*{}-*-s_lc.fits'.format(tic) #stitches path & filename
fullpath= glob.glob(pathend) #to use wildcard*
return fullpath
def open_rawdata(fullpath,sector):
'''
~ Opens raw data light curve file objects downloaded to our shared google drive folder~
REQUIRES: lightkurve as lk
Args:
fullpath -(str) list of path strings for all files found with specified tic
sector -(int) sector number for desired data
Returns:
lcfs -(list) list of lightkurve 'lightcurvefile' class objects
'''
lcfs = []
for file in fullpath:
if len(file)==0:
print('no files')
else:
try:
lcfile = lk.open(file)
mystring = str(type(lcfile))
if mystring[34:-2] == 'TessLightCurveFile':
hdr = lcfile.get_header()
mysector = hdr['SECTOR']
if sector == mysector:
lcfs.append(lcfile)
else:
pass
else:
pass
except FileNotFoundError:
pass
return lcfs
```
# Load in starting data
```
# tic ids for subsample
subsample_tics = [7582594, 7582633, 7620704, 7618785, 7584049]
# path to raw data
raw_data_path = '/content/gdrive/MyDrive/EscapeEarthData/Sector_14_rawdata/'
# open data
paths2files = locate_files(subsample_tics[1],raw_data_path) #locate filename given tic id
subsample_data = open_rawdata(paths2files,sector=14) #open the lightcurvefile
print('Initial function output data type:',type(subsample_data))
```
# Test on a single target
```
# examine input data
print('Initial data type:',type(subsample_data[0])) #check inital class object type to see allowed methods
subsample_data[0].scatter() #visualize original data
```
# Apply class method to clean single target
```
# change/select data type to necessary class object in order to use class method
pdcsap_data = subsample_data[0].PDCSAP_FLUX #change class object type
print('original data type:',type(subsample_data[0])) #print to see change in class object type
print('new data type:',type(pdcsap_data)) #verify class object change
# apply class method
bin_data = pdcsap_data.bin() #apply method
bin_data.plot() #visualize the effect of method
print('type:',type(bin_data)) #check for output data type
# show how to use any helpful args
bin_data2 = pdcsap_data.bin(bins=27) #see how args change output data
bin_data2.plot() #visualize effect of arg change
# examine output data
print('Output data type:',type(bin_data2)) #NOTE: your output data type should be 'TessLightCurve' or 'LightCurve'
```
# Apply method iteratively to all targets
```
for target in subsample_tics:
#open data
paths = locate_files(target,raw_data_path)
original_data = open_rawdata(paths,sector=14)
#saveguard against missing files
if len(original_data)==0: #if no files exist go to next target in for loop
pass
else: #if files exist proceed
#format data (class object type)
new_data = original_data[0].PDCSAP_FLUX #index into orignal_data b/c its a list
#verify class object change
print('class object change:',type(original_data[0]),'changed to',type(new_data))
#apply method
cleaned_data = new_data.bin(bins=27)
#verify cleaned data looks different (or save it)
cleaned_data.plot()
# BONUS work: write this new data to a file so we can open cleaned data directly
# instead of opening raw data, cleaning it, then running analysis code on it
# Tip: Similar to above, test your code on one target first, then edit code to
# work in a for loop
```
| github_jupyter |
### The purpose of this notebook is to complete a data cleaning workflow from start to finish in order to validate the core functionality our package
#### TO DO:
- Add in complete PubChem data
- Write PubChem function
- Organize code modules & tests
- Clean up/finish writing tests
- Write main script wrapper function
```
# imports
#rdkit imports
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.EState import Fingerprinter
from rdkit.Chem import Descriptors
from rdkit.Chem import rdFMCS
from rdkit.Chem.rdmolops import RDKFingerprint
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit import DataStructs
from rdkit.Avalon.pyAvalonTools import GetAvalonFP
#housekeeping imports
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import gzip
```
all enzymes df with all known reactions
promiscuous enzymes df with all promiscuous reactions (pos and neg)
should we combine the kegg data and the metacyc data and see if that gives us more reactions? (future problem!)
1) filter and select all promiscuous pos and neg reactions into one dataframe (CHECK)
2) binarize that dataframe (CHECK)
3) write code to check whether a transformation exists
4) take binarized info and test out different models on it
make model with promiscuous enzymes
write code to check whether a transformation exists first, then puts the molecule through the model if necessary
check model_query_metacyc ntoebook for example of how to query this thing
## Step 8
#### Pre-process negative and positive datasets to remove rows with only 1 enzyme
Positive and negative data must be processed separately, as the average molecular distances will be calculated separately for each dataset
```
all_pos = pd.read_csv('../../../big-datasets/pos-with-dist-promlabel.csv')
neg = pd.read_csv('../../../big-datasets/neg-with-dist-promlabel.csv')
prom_pos = all_pos[all_pos['Promiscuous'] == 1]
prom_neg = neg[neg['Promiscuous'] == 1]
print(all_pos.shape, neg.shape, prom_pos.shape, prom_neg.shape)
prom = pd.concat((prom_pos,prom_neg), axis=0)
prom = prom.drop(columns='Unnamed: 0')
prom.shape
prom.head()
```
## Step 10
#### Get dummy variables to represent enzyme class
We expect that many enzyme properties could be predictive features for this model. Enzyme class should encapsulate many of these features at a high level.
```
def binarize_enzyme_class(dataframe, column):
"""
binarize_enzyme_class() converts the enzyme class into binary dummy variables
that are appended onto the input dataframe
Args:
dataframe (pandas.DataFrame): input dataset
column (str): column name containing kegg enzyme id
Returns:
pandas.DataFrame: with seven columns appended for the seven enzyme classes
"""
dataframe['enzyme_class'] = [row[column][0] for _, row in dataframe.iterrows()]
dataframe = pd.get_dummies(dataframe, columns=['enzyme_class'])
return dataframe
import re
def strip_ec(df, ec_colname):
stripped = []
non_decimal = re.compile(r'[^\d.]+')
for index, row in df.iterrows():
target = row[ec_colname]
fixed = non_decimal.sub('', target)
stripped.append(fixed)
df = df.drop(columns=ec_colname)
df.insert(0,'Enzyme',stripped)
return df
small = prom.iloc[:10,:].copy()
small.head(10)
attempted = strip_ec(small, 'enzyme')
attempted.head(10)
prom_stripped = strip_ec(prom, 'enzyme')
prom_stripped.head(10)
# binarize_enzyme_class()
master_df = binarize_enzyme_class(prom_stripped, 'Enzyme')
#master_df_df = master_df.reset_index(drop=True)
#print(master_df.shape)
master_df.head(20)
master_df.shape
master_df = pd.read_csv('../../../big-datasets/master_dataframe_metacyc.csv')
master_df.to_csv('../../../big-datasets/master_dataframe_metacyc.csv.gz', index=None, compression='gzip')
```
## Out of curiosity:
#### Examine average molecular distance distributions for negative and positive data
On first glance, it appears that our hypothesis is correct in that the distributions of average molecular distances are qualitatively different between the positive and negative datasets
```
# look at distributions of distances for positive and negative data
#fig, axes = plt(1, 1, figsize=(9, 5))
fig, axes = plt.plot(1, 1, figsize=(9, 5))
pos = sns.distplot(pos_dist_df['dist'], bins=90, kde=True, norm_hist=True, ax=axes[0], color= 'red')
axes[0].set_title('Avg. Tanimoto Similarity to Positive Prediction Products')
neg = sns.distplot(neg_dist_df['dist'], bins=30, kde=True, norm_hist=False, ax=axes[0])
axes[0].set_title('Avg. Tanimoto Similarity to Negative Prediction Products')
for axis in axes:
axis.set_xlim([0.0, 1.0])
fig.savefig('output')
pos_dist_df = prom_pos
# look at distributions of distances for positive and negative data
pos_dist = pd.Series(prom_pos['Dist'], name="Avg. Tanimoto Similarity")
neg_dist = pd.Series(prom_neg['Dist'], name="Avg. Tanimoto Similarity")
fig = sns.distplot(pos_dist, bins=75, kde=True,
kde_kws={"color": "b", "lw": 2, "label": "Positive Prediction Products"},
hist_kws={"histtype": "bar", "linewidth": 3, "alpha": 0.5, "color": "b"})
fig.set_xlim([0.0, 1.0])
sns.distplot(neg_dist, bins=25, kde=True,
kde_kws={"color": "r", "lw": 2, "label": "Negative Prediction Products"},
hist_kws={"histtype": "bar", "linewidth": 3, "alpha": 0.5, "color": "r"})
fig.set_title('Normed Distribution of Avg. Similarity to Products ')
plt.savefig('output')
fig.savefig
fig, ax = plt.subplots(figsize=(16,10), facecolor='white', dpi= 100)
sns.distplot(pos_dist, ax=ax, bins=75, kde=True,
kde_kws={"color": "r", "lw": 2, "label": "Positive Prediction Products"},
hist_kws={"histtype": "bar", "linewidth": 3, "alpha": 0.5, "color": "r"})
ax.set_xlim([0.0, 1.0])
sns.distplot(neg_dist, ax=ax, bins=23, kde=True,
kde_kws={"color": "b", "lw": 2, "label": "Negative Prediction Products"},
hist_kws={"histtype": "bar", "linewidth": 3, "alpha": 0.5, "color": "b"})
ax.set_title('Normed Density Distribution of Average Similarity to Products', fontsize=26)
ax.set_xlabel('Average Tanimoto Similarity', fontsize=22)
ax.set_ylabel('Normalized Density', fontsize=22)
fig.savefig('output')
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
```
# Transformer Position Encoding
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/position_encoding.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/examples/blob/master/community/en/position_encoding.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
</table>
See [this notebook](https://github.com/site/en/r2/tutorials/sequences/transformer.ipynb) for a walk-through of full transformer implementation.
The transformer architecture uses stacked attention layers in place of CNNs or RNNs. This makes it easy to learn long-range dependencise but it contains no built in information about the relative positions of items in a sequence.
To give the model access to this information the transformer architecture uses adda a position encoding to the input.
This endocing is a vector of sines and cosines at each position, where each sine-cosine pair rotates at a different frequency.
Nearby locations will have similar position-encoding vectors.
## Imports
```
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import matplotlib.pyplot as plt
```
The angle rates range from `1 [rads/step]` to `min_rate [rads/step]` over the vector depth.
Formula for angle rate:
$$angle\_rate_d = (min\_rate)^{d / d_{max}} $$
```
num_positions = 50
depth = 512
min_rate = 1/10000
assert depth%2 == 0, "Depth must be even."
angle_rate_exponents = np.linspace(0,1,depth//2)
angle_rates = min_rate**(angle_rate_exponents)
```
The resulting exponent goes from `0` to `1`, causing the `angle_rates` to drop exponentially from `1` to `min_rate`.
```
plt.semilogy(angle_rates)
plt.xlabel('Depth')
plt.ylabel('Angle rate [rads/step]')
```
Broadcasting a multiply over angle rates and positions gives a map of the position encoding angles as a function of depth.
```
positions = np.arange(num_positions)
angle_rads = (positions[:, np.newaxis])*angle_rates[np.newaxis, :]
plt.figure(figsize = (14,8))
plt.pcolormesh(
# Convert to degrees, and wrap around at 360
angle_rads*180/(2*np.pi) % 360,
# Use a cyclical colormap so that color(0) == color(360)
cmap='hsv', vmin=0, vmax=360)
plt.xlim([0,len(angle_rates)])
plt.ylabel('Position')
plt.xlabel('Depth')
bar = plt.colorbar(label='Angle [deg]')
bar.set_ticks(np.linspace(0,360,6+1))
```
Raw angles are not a good model input (they're either unbounded, or discontinuous). So take the sine and cosine:
```
sines = np.sin(angle_rads)
cosines = np.cos(angle_rads)
pos_encoding = np.concatenate([sines, cosines], axis=-1)
plt.figure(figsize=(14,8))
plt.pcolormesh(pos_encoding,
# Use a diverging colormap so it's clear where zero is.
cmap='RdBu', vmin=-1, vmax=1)
plt.xlim([0,depth])
plt.ylabel('Position')
plt.xlabel('Depth')
plt.colorbar()
```
## Nearby positions
Nearby locations will have similar position-encoding vectors.
To demonstrate compare one position's encoding (here position 20) with each of the others:
```
pos_encoding_at_20 = pos_encoding[20]
dots = np.dot(pos_encoding,pos_encoding_at_20)
SSE = np.sum((pos_encoding - pos_encoding_at_20)**2, axis=1)
```
Regardless of how you compare the vecors, they are most similar 20, and clearly diverge as you move away:
```
plt.figure(figsize=(10,8))
plt.subplot(2,1,1)
plt.plot(dots)
plt.ylabel('Dot product')
plt.subplot(2,1,2)
plt.plot(SSE)
plt.ylabel('SSE')
plt.xlabel('Position')
```
## Relative positions
The [paper](https://arxiv.org/pdf/1706.03762.pdf) explains, at the end of section 3.5, that any relative position encoding can be written as a linear function of the current position.
To demonstrate, this section builds a matrix that calculates these relative position encodings.
```
def transition_matrix(position_delta, angle_rates = angle_rates):
# Implement as a matrix multiply:
# sin(a+b) = sin(a)*cos(b)+cos(a)*sin(b)
# cos(a+b) = cos(a)*cos(b)-sin(a)*sin(b)
# b
angle_delta = position_delta*angle_rates
# sin(b), cos(b)
sin_delta = np.sin(angle_delta)
cos_delta = np.cos(angle_delta)
I = np.eye(len(angle_rates))
# sin(a+b) = sin(a)*cos(b)+cos(a)*sin(b)
update_sin = np.concatenate([I*cos_delta, I*sin_delta], axis=0)
# cos(a+b) = cos(a)*cos(b)-sin(a)*sin(b)
update_cos = np.concatenate([-I*sin_delta, I*cos_delta], axis=0)
return np.concatenate([update_sin, update_cos], axis=-1)
```
For example, create the matrix that calculates the position encoding 10 steps back, from the current position encoding:
```
position_delta = -10
update = transition_matrix(position_delta)
```
Applying this matrix to each position encoding vector gives position encoding vector from -10 steps away, resulting in a shifted position-encoding map:
```
plt.figure(figsize=(14,8))
plt.pcolormesh(np.dot(pos_encoding,update), cmap='RdBu', vmin=-1, vmax=1)
plt.xlim([0,depth])
plt.ylabel('Position')
plt.xlabel('Depth')
```
This is accurate to numerical precision.
```
errors = np.dot(pos_encoding,update)[10:] - pos_encoding[:-10]
abs(errors).max()
```
| github_jupyter |
# Speech to Text using a Raspberry Pi
This lab shows how to use the [Azure Cognitive Services speech service](https://azure.microsoft.com/services/cognitive-services/speech-services/?WT.mc_id=academic-7372-jabenn) on a Raspberry Pi. You will need a Cognitive Services speech resource to use this lab, and you can find all the instructions to get set up in the [README file](https://github.com/microsoft/iot-curriculum/tree/main/labs/ai-edge/speech).
This lab records 10 seconds of speech, then sends it to the Speech service to convert to text.
There is currently no SDK support for this speech service on ARM32 Linux, so this lab uses the REST APIs.
To use this Notebook, read each documentation cell, then select Run to run each code cell. The output of the code cells will be shown below. You can read more on running Jupyter Notebooks in the [Jupyter Notebooks documentation](https://jupyter-notebook.readthedocs.io/en/stable/notebook.html#notebook-user-interface).
First the options for the Speech cognitive service need to be configured.
* Set the `KEY` variable to be the key of your speech resource.
* Set the `ENDPOINT` variable to be the endpoint of your speech resource.
* Set the `LANGUAGE` variable to the language you will be speaking in. You can find details on the supported langauges in the [Language and voice support for the Speech service documentation](https://docs.microsoft.com/azure/cognitive-services/speech-service/language-support?WT.mc_id=academic-7372-jabenn).
```
KEY = "YOUR_SPEECH_KEY"
ENDPOINT = "YOUR_SPEECH_ENDPOINT"
LANGUAGE = "en-US"
```
Import some Python packages to hande the microphone, audio files and REST requests to make them available to the Python code
```
import sounddevice as sd
import requests
import json
import os
from scipy.io.wavfile import write
```
Before audio can be captured, some configuration needs to be set up. The sample rate needs to be set to 16khz, and the sample length needs to be set to 10 seconds.
> If you want to record for longer, change the value of `sample_len` to the time in seconds that you want to record for.
```
# The Speech to Text Cognitive Service API currently only supports a 16000hz samplerate
sample_rate = 16000
# Length of the audio sample in seconds
sample_len = 10
```
Now capture the audio. Once you start running this cell, speak into the microphone for 10 seconds.
```
# Record the speech sample
speech_sample = sd.rec(int(sample_len * sample_rate), samplerate=sample_rate, channels=1)
print("Start speaking now!")
# Wait for the recording to stop after the specified number of seconds
sd.wait()
# Let the user know the recording is done
print("Recorded!")
```
The speech sample now needs to be saved to disk.
```
# Name of audio file to save sample
filename = "speech_to_text_rec.wav"
# Save speech sample as a .wav file
write(filename, sample_rate, speech_sample)
```
To verify everything was recorded correctly, playback the audio by using the `aplay` command line utility
```
os.system("aplay " + filename)
```
The endpoint that comes from the Cognitive Service is designed to issue access tokens so you can then make the relevant API call.
The REST API is documented in the [Speech-to-text REST API documentation](https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/rest-speech-to-text?WT.mc_id=academic-7372-jabenn#authentication).
The header passes the following:
* The API Key of the speech resource
The return value is an access token that lasts for 10 minutes and is used when calling the rest of the API.
```
# Create the request headers with the API key
headers = {
"Ocp-Apim-Subscription-Key": KEY
}
# Make a POST request to the endpoint to get the token
response = requests.post(ENDPOINT, headers=headers)
access_token = str(response.text)
```
Next step is to make the REST API call, uploading the file with the speech data to a URL. The URL is built by extracting the location from the API endpoint and using that to build a new URL pointing to the speech service itself.
The REST API is documented in the [Speech-to-text REST API documentation](https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-speech-to-text?WT.mc_id=academic-7372-jabenn#sample-request).
The header passes the following:
* The bearer token that was retrieved earlier
* The content type as a WAV file with a sample rate of 16KHz
The body of the request is the audio file that was just written.
The return value is a JSON document with details on the detected speech, including the text from the speech.
```
# Get the location from the endpoint by removing the http protocol and getting the section before the first .
location = ENDPOINT.split("//")[-1].split(".")[0]
# Build the URL from the location
url = "https://" + location + ".stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1"
# Set the headers to include the Cognitive Services resource key
headers = {
"Authorization": "Bearer " + access_token,
"Content-Type": "audio/wav; codecs=audio/pcm; samplerate=16000",
"Accept": "application/json;text/xml"
}
# Configure the language parameter for the call
params = {
"language": LANGUAGE
}
# Make the request passing the file as the body
response = requests.post(url, headers=headers, params=params, data=open(filename, "rb"))
```
The `response` contains the result of the speech to text call as JSON. If the call was successful, it will return an object with a `RecognitionStatus` of `Success`, and a `DisplayText` with the speech converted to text.
```
# Convert the response to JSON
response_json = json.loads(response.text)
if response_json["RecognitionStatus"] == "Success":
print('Results from Speech to Text API:')
print(response_json['DisplayText'])
else:
print("No speech detected")
print("The raw response is:")
print(response.text)
```
| github_jupyter |
In this notebook, we go through feature importance analysis. Feature importance analysis is useful tool to find and validate statistical edges. Although p-value has been widely used to validate statistical patterns, it has some caveats:
1. Relying on the strong assumption
2. In the existence of highly multi collinear model, p-value cannot be robust
3. Estimating parameter value probability rather than probability of the null hypothesis in general
4. Significance at in-sample
The first caveat implies that the model assumes linear model with Gaussian noise, which is not always the case in real world problems. The second caveat states that traditional regression model cannot discriminate among redundant variables, leading to substitution effects between related p-values. Third caveat comes from the fact that p-value estimate probability of empirically estimated parameter being generated subjected to null hypothesis. Thus, they do not provide the probability of null hypothesis being true. The fourth caveat is that p-value estimates significance at in-sample. Multiple testing inflates estimated p-values and leads to p-hacking.
Feature importance is alternative way and solve these caveats.
```
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
```
We use an artificially generated classification problem. Data has some informative, redundant, and noise features.
```
from finance_ml.experiments import get_classification_data
X,y = get_classification_data(40, 5, 30, 10000, sigma=0.1)
print(X.shape)
print(X.head())
print(f"columns={X.columns.tolist()}")
```
Each feature is named as the following name convention:
1. I_\*: informative feature
2. R_\*: redundant feature. The information is shared with some I_\*
3. N_\*: noise feature. No predictive power is contained
# Mean-Decrease Impurity (MDI)
MDI is feature importance is sub-products of decision tree learning process.
At each node t splitting with feature f, a tree maximize impurity gain
$$ \Delta g[t, f] = i[t] - (\frac{N^0}{N} i[t^0] +\frac{N^1}{N} i[t^1])$$
where $N^0$ and $N^1$ are the number of samples of left and right node. $i[t^0]$ and $i[t^1]$ are impurity of left and right node.
This impurities are aggregated across nodes with weighted average. The value is bounded at [0, 1] and all added up to 1. The non-important value is expected to be around 1/F where F features exist.
```
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
import multiprocessing as mp
from finance_ml.importance import feat_imp_MDI
clf = DecisionTreeClassifier(criterion="entropy", max_features=1, class_weight="balanced", min_weight_fraction_leaf=0)
clf = BaggingClassifier(base_estimator=clf, n_estimators=1000, max_features=1.,
max_samples=1., oob_score=False, n_jobs=mp.cpu_count())
clf.fit(X, y);
imp = feat_imp_MDI(clf, X.columns)
print(imp.head())
imp.sort_values('mean', inplace=True)
plt.figure(figsize=(10, imp.shape[0] / 5));
F = X.shape[1]
print(f"1/F = {1./F}")
plt.axvline(x=1./F, linestyle='dashed', color='r');
imp['mean'].plot(kind='barh', color='b', alpha=0.25, xerr=imp['std'], error_kw={'ecolor': 'r'});
```
MDI does a good job. Non-noisy features are ranked higher than noise ones. Due to substitution effects, some non-noisy features appear to be much more important than the others. This comes from the fact that some features share the information of other features and they are not necessary to be used for prediction.
MDI solves three out of four caveats, 1-3. First, trees do not assume any specific algebraic formula. Second, ensemble of tress reduce variance of the model. Lastly, MDI estimates usefulness of the feature in general. MDI is , however, still estimated at in-sample.
# Mean-Decrease Accuracy (MDA)
To combat caveat 4, we introduce MDA, which estimates importance using cross validation. For each round, one of the features are shuffled one by one and see the difference from the original performance. This importance is not bounded.
```
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
import multiprocessing as mp
from finance_ml.importance import feat_imp_MDA
clf = DecisionTreeClassifier(criterion="entropy", max_features=1, class_weight="balanced", min_weight_fraction_leaf=0)
clf = BaggingClassifier(base_estimator=clf, n_estimators=1000, max_features=1.,
max_samples=1., oob_score=False, n_jobs=mp.cpu_count())
imp = feat_imp_MDA(clf, X, y, n_splits=5)
print(imp.head())
imp.sort_values('mean', inplace=True)
plt.figure(figsize=(10, imp.shape[0] / 5))
imp['mean'].plot(kind='barh', color='b', alpha=0.25, xerr=imp['std'], error_kw={'ecolor': 'r'});
```
This method can use any scores in general. One thing you have to care about is substitution effects. In the extreme case, you have two identical features. One of them is shuffled, the accuracy may not change. Thus, feature importance would be close to zero.
# Substitution Effects
When more than one features share the same predictive information, substitution effects can bias the results of features importance. In the case of MDI, the importance would be halved.
In order to deal with this, we have two methods:
1. Orthogonalization: Generate PCA components features and estimate importances on them
2. Clustering Features: Cluster features and estimate importance of clusters
The method 1, may reduce the substitution effects, but it has three caveats:
1. non linear relation redundant features still cause substitution effects
2. May not have intuitive explanation
3. Defined by eigen vectors, which may not necessary maximize the output
Let's look at clustering feature importance.
For clustering method, it involves the two steps:
1. Features Clustering
2. Clustered Importance
For step1, you can utilize ONC algorithm(`finance_ml/clustering.py`). In this step, you can check the quality of clustering based on silhouette scores. If the scores is not good, one feature may contain information across multiple clusters. you can use the following algorithms:
$$X_{n, i} = \alpha_i + \sum_{j \in \cup_{l < k} D_l} \beta_{i, j} X_{n, j} + \epsilon_{n, i} \forall i \in D_k$$
For each cluster, you regress on the the other cluster. Then you can use residual instead.
In the step2, we estimate importance of each cluster rather than individual features.
```
from finance_ml.clustering import cluster_kmeans_base
import warnings
warnings.simplefilter('ignore')
corr0, clstrs, silh = cluster_kmeans_base(X.corr(), max_num_clusters=10, n_init=20)
print(clstrs)
sns.heatmap(corr0);
```
In this clustering, one of the cluster contains noise features.
```
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
import multiprocessing as mp
from finance_ml.importance import feat_imp_MDI_clustered
clf = DecisionTreeClassifier(criterion="entropy", max_features=1, class_weight="balanced", min_weight_fraction_leaf=0)
clf = BaggingClassifier(base_estimator=clf, n_estimators=1000, max_features=1.,
max_samples=1., oob_score=False, n_jobs=mp.cpu_count())
clf = clf.fit(X, y)
imp = feat_imp_MDI_clustered(clf, X.columns, clstrs)
print(imp.head())
imp.sort_values('mean', inplace=True)
plt.figure(figsize=(10, imp.shape[0] / 5))
imp['mean'].plot(kind='barh', color='b', alpha=0.25, xerr=imp['std'], error_kw={'ecolor': 'r'})
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
import multiprocessing as mp
from finance_ml.importance import feat_imp_MDA_clustered
clf = DecisionTreeClassifier(criterion="entropy", max_features=1, class_weight="balanced", min_weight_fraction_leaf=0)
clf = BaggingClassifier(base_estimator=clf, n_estimators=1000, max_features=1.,
max_samples=1., oob_score=False, n_jobs=mp.cpu_count())
imp = feat_imp_MDA_clustered(clf, X, y, clstrs, n_splits=10)
print(imp.head())
imp.sort_values('mean', inplace=True)
plt.figure(figsize=(10, imp.shape[0] / 5))
imp['mean'].plot(kind='barh', color='b', alpha=0.25, xerr=imp['std'], error_kw={'ecolor': 'r'})
```
As you see in the result above, the cluster containing noise gains low importance.
| github_jupyter |
```
import numpy as np
import pandas as pd
from tools import seq_to_num, acc_score, prep_submit
df_train = pd.read_csv("../data/train.csv", index_col=0)
df_test = pd.read_csv('../data/test.csv', index_col=0)
X_train, y_train = seq_to_num(df_train.Sequence, pad=False)
def good_len(data):
"""
filter out seqences which have good length increase
"""
for seq in data:
lengths = [len(f"{_:.0f}") for _ in seq]
if lengths.count(1) == len(lengths):
print("Sequence of single-digit numbers")
continue
seq_good = True
for cur, next in zip(lengths, lengths[1:]):
pred_length = cur * 2
if abs(next - pred_length) > 1:
seq_good = False
break
if seq_good:
print(f"Good seq: {seq[:5]}")
good_len(X_train[:100])
import sys
sys.path.append('..')
from models.diff_table import DiffTable
def quad_good(data, verbose=False, stoplen=2):
"""
a_n = a_{n-1} ** 2 + c
Note:
- Works only for monotonically increasing sequences.
- Encapsulates all sequences solved by DiffTable
"""
sequences = []
indices = []
predictions = []
ind_iter = data.index if isinstance(data, (np.ndarray, pd.Series)) else range(len(data))
for seq, ind in zip(data, ind_iter):
if len(seq) < stoplen:
continue
divisor = seq[0] - 1
if divisor == 0 and len(seq) > 1:
divisor = seq[1] - 1
if divisor == 0:
continue
diffs = [(next - cur) / divisor for cur, next in zip(seq, seq[1:])]
if len(diffs) < stoplen:
continue
if np.all([np.isclose(prev, diff) for prev, diff in zip(seq, diffs)]):
if verbose:
print(f"Good seq: {seq[:5]}")
sequences.append(seq)
indices.append(ind)
predictions.append(seq[-1] * (divisor + 1))
continue
quad_diffs = [(next - cur ** 2) for cur, next in zip(seq, seq[1:])]
_, _, pred = DiffTable().predict([quad_diffs], maxstep=10, stoplen=stoplen)
if len(pred) > 0:
if verbose:
print(f"a_n = a_n-1^2 + {pred[0]}, {ind}: {seq[:5]}")
sequences.append(seq)
indices.append(ind)
predictions.append(seq[-1] ** 2 + pred[0])
return sequences, indices, predictions
X_train[X_train.map(is_increasing)].shape
X_increase = X_train[X_train.map(is_increasing)]
X_increase.shape
seq_diff, ind_diff, pred_diff = DiffTable().predict(X_increase, maxstep=10, stoplen=10)
X_unsolved = X_increase[~X_increase.index.isin(ind_diff)]
X_unsolved.shape
seq, ind, pred = quad_good(X_unsolved, stoplen=10, verbose=False)
len(ind)
cnt = 0
y_ind, pred_int = [], []
for pred_i, i in enumerate(ind):
if i in ind_diff:
cnt += 1
else:
pred_int.append(pred_i)
y_ind.append(i)
print(f"{cnt}/{len(ind)} are already predicted by common differences")
len(ind)
acc_score(y_train[ind], pred)
DiffTable().predict([[0, 3, 8, 15, 24]])
is_increasing = lambda seq: np.all([cur < next for cur, next in zip(seq, seq[1:])])
quad_good([[0, 3, 8, 15]])
```
| github_jupyter |

# R for Data Professionals
## 02 Programming Basics
<p style="border-bottom: 1px solid lightgrey;"></p>
<dl>
<dt>Course Outline</dt>
<dt>1 - Overview and Course Setup</dt>
<dt>2 - Programming Basics <i>(This section)</i></dt>
<dd>2.1 - Getting help</dd>
<dd>2.2 Code Syntax and Structure</dd>
<dd>2.3 Variables<dd>
<dd>2.4 Operations and Functions<dd>
<dt>3 Working with Data</dt>
<dt>4 Deployment and Environments</dt>
<dl>
<p style="border-bottom: 1px solid lightgrey;"></p>
From here on out, you'll focus on using R in programming mode. You can open your R IDE or R Command prompt and copy and paste the code you see here, and later you'll have a set of exercises to do on your own.
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/cortanalogo.png"><b>2.1 - Getting help and the Workspace</b></p>
The very first thing you should learn in any language is how to get help. You can [find the help documents on-line](https://mran.microsoft.com/documents/getting-started), or simply type
`help()`
or
`?`
For help on a specific topic, put the topic in the parenthesis:
`help(str)`
To see a list of topics in an HTML viewer, type:
`help.start()`
Need help on help()? Just type:
`?help`
As you work, your commands, the libraries (packages) that you have loaded, and other environment settings are saved in a file called the *Workspace*. You'll be prompted when you leave an R session to save the session as the current Workspace, you can save the Workspace manually, and you can load a Workspace. The Workspace is stored in a file in your current directory. To work with your directory, check out these commands (again, use help() for more info):
`# Print the current working directory`
`getwd()`
`# List objects in the current workspace`
`ls()`
`# Change to NewDirectory`
`setwd("c:/NewDirectory")`
There's more than just the Workspace - you'll cover the environment in the last module of this course.
```
# Try it:
```
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/cortanalogo.png"><b>2.2 Code Syntax and Structure</b></p>
Let's cover a few basics about how R code is written. First, R is a *Functional* programming language. That means you'll take objects and perform functions on them, working from right to left. You can pass operations like you do in PowerShell, but in the opposite direction.
Here are few "style guide" concepts to keep in mind (For a full discussion, check out the [Style Guide for R blog from R-Bloggers](https://www.r-bloggers.com/r-style-guide/) ):
File Names: end in .R
Identifiers: variable.name (or variableName), FunctionName, kConstantName
Line Length: try to keep a maximum of 80 characters
Indentation: two spaces, no tabs
Curly Braces: first on same line, last on own line
else: Surround else with braces
Assignment: use <-, not =
Semicolons: don't
Commenting Guidelines: all comments begin with # followed by a space;
inline comments need two spaces before the #
In general, use standard coding practices - don't use keywords for variables, be consistent in your naming (camel-case, lower-case, etc.), comment your code clearly, and understand the general syntax of your language, and follow the principles above. But the most important tip is to at least read R code examples on the web and decide for yourself how well that fits into your organization's standards.
Comments in R start with the hash-tag: `#`. There are no block comments (and this makes us all sad) so each line you want to comment must have a tag in front of that line. Keep the lines short (80 characters or so) so that they don't fall off a single-line display like at the command line.
R is case-sensitive, for both variables and commands.
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/checkbox.png"><b>2.3 Variables</b></p>
Variables (more properly, *objects*) stand in for replaceable values. R is not strongly-typed, meaning you can just declare a variable name and set it to a value at the same time, and R will try and guess what data type you want. You use an `<-` sign to assign values, and `==` to compare things. The `<-` below is read as "x gets 10" or x takes 10". It's part of the functional programming model R uses:
`x <- 10`
Quotes \" or ticks \' are fine for character values, just be consistent.
`# There are some keywords to be aware of, but x and y are always good choices.`
`x <- "Buck" # I'm a string.`
`typeof(x)`
`y <- 10 # I'm an integer.`
`typeof(y)`
`# What's in memory now?`
`objects()`
To change the type of a value, just re-enter something else:
`x <- "Buck" # I'm a string.`
`type(x)`
`x <- 10 # Now I'm an integer.`
`typeof(x)`
Or cast it By implicitly declaring the conversion:
`x <- "10"`
`typeof(x)`
`# Or use a test:`
`is.character(x)`
`# Cast it to another type, use as not is:`
`y <- as.numeric(x)`
`typeof(y)`
To concatenate numeric values, use the `c()` (combine) function:
`x <- 10`
`y <- 20`
`c(x, y)`
To concatenate string values, use the `paste()` function - which can automatically add a space for you:
`x <- "Buck"`
`y <- "Woody"`
`paste(x, y)`
<pre>
Buck Woody
</pre>
```
# Try it:
```
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/checkbox.png"><b>2.4 Operations and Functions</b></p>
R training normally starts with data types (called *Data Structures* in R) - and you'll do that in a moment. For now, know that the primary data object in R is something called a *vector*, which is similar to a row of data, each with an individual address.
R has the following main operators:
<pre>
+ Addition
- Subtraction
* Multiplication
/ Division
^ or ** Exponentiation
x %% y Modulus
x %/% y Integer Division
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Exactly equal to
!= Not equal to
!x Not x
x | y x OR y
x & y x AND y
isTRUE(x) Test x
</pre>
Wait...that's it? That's all you're going to tell me? *(Hint: use what you've learned):*
`help("%%")`
Walk through each of these operators carefully - you'll use them when you work with data in the next module.
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/aml-logo.png"><b>Activity - Programming basics</b></p>
Open the **02_ProgrammingBasics.R** file and run the code you see there. The exercises will be marked out using comments:
`# <TODO> - 2`
```
# 02_ProgrammingBasics.py
# Purpose: General Programming exercises for R
# Author: Buck Woody
# Credits and Sources: Inline
# Last Updated: 27 June 2018
# <TODO> - 2.1 Getting Help
### Start the HTML interface to on-line help (using a web browser available at your machine). OPen help this way and briefly explore the features of this facility with the mouse:
### Show one example of the help function. Is there more than one way to do that?
### Show the R version:
### Show all system environment settings:
# Code Syntax and Structure
## Programming and Flow
x <- 1
if (x > 1) "Higher than 1" else "Not higher than 1"
0xFFFF
### loop types
i <- 5
repeat { if (i > 25) break else { print(i); i <- i + 5; }}
i <- 5
while (i <= 25) { print(i); i <- i + 5; }
for (i in seq(from = 5, to = 25, by = 5))
print(i)
# Variables (Objects)
# <TODO> - Add a line below x<-3 that changes the object x from int to a string
x <- 3
typeof(x)
# <TODO> - Write code that prints the string "This class is awesome" using variables:
x <- "is awesome"
y <- "This Class"
# Operations and Functions
# <TODO> - Use some basic operators to write the following code:
# Assign two variables
# Add them
# Subtract 20 from each, add those values together, save that to a new variable
# Create a new string variable with the text "The result of my operations are: "
# Print out a single string on the screen with the result of the variables
# showing that result.
# EOF: 02_ProgrammingBasics.R
```
<p><img style="float: left; margin: 0px 15px 15px 0px;" src="../graphics/thinking.jpg"><b>For Further Study</b></p>
- Introduction to the R Coding Style - http://stackabuse.com/introduction-to-the-python-coding-style/
- The Microsoft Tutorial and samples for R - https://code.visualstudio.com/docs/languages/R
Next, Continue to *03 Working with Data*
| github_jupyter |
# Handling Networking Data
This notebook shows how to use IntelligentElement to handle nested networking data.
The example uses captures obtained using CISCO Joy - https://github.com/cisco/joy
You can either use Joy to capture network traffic directly or extract information from PCAPS files using Joy.
## Obtain data from file
The first step is to read Joy file, a gzip compresses list of dictionaries.
```
import json
import gzip
import struct
def GzipFileSize(filename):
'''
Auxiliary function that returns the size of a Gzip file.
filename - Path to the Gzip file
returns - Uncompressed size of Gzip file in bytes
'''
fo = open(filename, 'rb')
fo.seek(-4, 2)
r = fo.read()
fo.close()
return struct.unpack('<I', r)[0]
def LoadJoyJson(filename):
'''
Loads a .gzip file extracted from PCAP using CISCO's Joy tool.
filename - Path to the Gzip file
returns - List of dictionaries. Each entry corresponds to a flow capture in Joy file.
'''
fileData = []
totalsize = GzipFileSize(filename)
i=0
#pbar = tqdm(total= (totalsize>>10) )
with gzip.open(filename) as infile: #we do not want to load the entire file into memory
iterFile = iter(infile)
headerData = json.loads(next(iterFile).decode('utf-8').replace('\\',''))
for bline in iterFile:
#pbar.update( (infile.tell()>>10) - pbar.n )
i=i+1
line = bline.decode('utf-8')
try:
dj = json.loads(line.replace('\\',''))
fileData.append(dj)
except:
print('Problem loading JSON line')
return fileData
files = ['PCData/news/newsFolha.gz', 'PCData/socialmedia/logFacebook.gz', 'PCData/videostreaming/logYoutube.gz', 'PCData/videostreaming/logYoutube3.gz']
net_data = []
labels = []
for f in files:
data = LoadJoyJson(f)
net_data += data
if 'news' in f:
labels += [0]*len(data)
elif 'socialmedia' in f:
labels += [1]*len(data)
elif 'videostreaming' in f:
labels += [2]*len(data)
#view data from a single flow
net_data[0]
```
# Build Model
We will showcase a simple model that will handle:
- bytes_out, bytes_in, num_pkts_out, num_pkts_in, time_end-time_start in the first level;
- packets as a nested list of dictionaries
- ip with nested out and in, with ttl as a number and id as list
```
from keras import Model
from keras import layers as L
import numpy as np
#add two parent levels to path
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
sys.path.insert(0,parentdir)
%load_ext autoreload
%autoreload 2
import IntelligentElement as IE
```
## IP
We handle 'in' and 'out separately'.
```
def get_ip_out_info(x):
ip_out_data = x.get('ip', {'out': {'ttl': 0,'id': []}, 'in': {'ttl': 0,'id': []}})
return np.array([ip_out_data['out']['ttl']]).astype(int)
ip_out_data = [get_ip_out_info(x) for x in net_data]
ip_out_shape = (1,)
inp=L.Input(ip_out_shape)
x =L.Embedding(256, 8)(inp)
x =L.Flatten()(x)
ip_out_model = Model(inputs=inp, outputs=x)
print('Original model')
ip_out_model.summary()
ip_out_ie = IE.IntelligentElement(ip_out_data, ip_out_model, ip_out_shape, name='ip_out_ie')
m, ii, oo = ip_out_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
def get_ip_in_info(x):
ip_in_data = x.get('ip', {'out': {'ttl': 0,'id': []}, 'in': {'ttl': 0,'id': []}})
if not 'in' in ip_in_data:
ip_in_data['in'] = {'ttl': 0,'id': []}
return np.array([ip_in_data['in']['ttl']]).astype(int)
ip_in_data = [get_ip_in_info(x) for x in net_data]
#share model with ip_out
print('Original model')
ip_out_model.summary()
ip_in_ie = IE.IntelligentElement(ip_in_data, ip_out_model, ip_out_shape, name='ip_in_ie')
m, ii, oo = ip_in_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
def get_ip_id_out_info(x):
ip_id_out_data = x.get('ip', {'out': {'ttl': 0,'id': []}, 'in': {'ttl': 0,'id': []}})
ans = [[x] for x in ip_id_out_data['out']['id']]
if len(ans)==0:
ans=[[0]]
return np.array(ans).astype(int)
ip_id_out_data = [get_ip_id_out_info(x) for x in net_data]
ip_id_out_shape = (None, 1)
inp=L.Input(ip_id_out_shape)
x =L.CuDNNLSTM(8)(inp)
ip_id_out_model = Model(inputs=inp, outputs=x)
print('Original model')
ip_id_out_model.summary()
ip_id_out_ie = IE.IntelligentElement(ip_id_out_data, ip_id_out_model, ip_id_out_shape, name='ip_id_out_ie')
m, ii, oo = ip_id_out_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
ip_id_out_ie.get_batch([0,1,2,3])[0].shape
def get_ip_id_in_info(x):
ip_id_in_data = x.get('ip', {'out': {'ttl': 0,'id': []}, 'in': {'ttl': 0,'id': []}})
if not 'in' in ip_id_in_data:
ip_id_in_data['in'] = {'ttl': 0,'id': []}
ans = [[x] for x in ip_id_in_data['in']['id']]
if len(ans)==0:
ans=[[0]]
return np.array(ans).astype(int)
ip_id_in_data = [get_ip_id_in_info(x) for x in net_data]
#share model
print('Original model')
ip_id_out_model.summary()
ip_id_in_ie = IE.IntelligentElement(ip_id_in_data, ip_id_out_model, ip_id_out_shape, name='ip_id_in_ie')
m, ii, oo = ip_id_in_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
```
## Packets Data
```
def get_pkt_info(x):
pkt_data = x.get('packets', [{'b': 0, 'dir': '>', 'ipt': 0}])
ans = [[y['b'], int(y['dir']=='>'), y['ipt']] for y in pkt_data]
if len(ans) == 0:
ans = [[0,0,0]]
return np.array(ans)
pkt_data = [get_pkt_info(x) for x in net_data]
pkt_shape = (None, 3)
inp=L.Input(pkt_shape)
x =L.CuDNNLSTM(16)(inp)
pkt_model = Model(inputs=inp, outputs=x)
print('Original model')
pkt_model.summary()
pkt_ie = IE.IntelligentElement(pkt_data, pkt_model, pkt_shape, name='pkt_ie')
m, ii, oo = pkt_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
pkt_ie.get_batch([0,1,2,3])[0].shape
len(net_data[3]['packets'])
print(pkt_data[0][0:5])
pkt_ie.get_batch([0,1,2,3])[0][0][0:5]
```
## Root Data
```
def get_root_info(x):
return np.array([x.get('bytes_in', 0), x.get('bytes_out', 0), x.get('num_pkts_in', 0), x.get('num_pkts_out', 0),
x['time_end']-x['time_start']])
root_data = [get_root_info(x) for x in net_data]
root_shape = (5,)
children = [pkt_ie, ip_out_ie, ip_id_out_ie, ip_in_ie, ip_id_in_ie]
inp=L.Input( (root_shape[-1]+IE.get_children_sum_last_output_shapes(children),) )
x=inp
for kk in range(3):
x=L.Dense(10, activation='relu')(x)
x=L.Dense(3,activation='softmax')(x)
root_model = Model(inputs=inp, outputs=x)
print('Original model')
root_model.summary()
root_ie = IE.IntelligentElement(root_data, root_model, root_shape, children_ie=children, name='root_ie')
m, ii, oo = root_ie.retrieve_model_inputs_outputs()
print('\n\nRetrieved model')
m.summary()
root_data[0:5]
root_ie.get_batch([0,1,2])[3].shape
```
# Build Generator
```
from keras.utils import Sequence
class IEDataGenerator(Sequence):
'Generates data for Keras'
def __init__(self, ie, labels, batch_size=128, shuffle=True):
'Initialization'
self.ie = ie
self.batch_size = batch_size
self.labels = labels
self.nsamples = len(ie.data)
assert self.nsamples == len(labels), 'Length of labels must match length of data'
self.shuffle = shuffle
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.floor(self.nsamples / self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
# Generate indexes of the batch
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
# Generate data
X, y = self.__data_generation(indexes)
return X, y
def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(self.nsamples)
if self.shuffle == True:
np.random.shuffle(self.indexes)
def __data_generation(self, list_IDs_temp):
'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
# Initialization
y = np.empty((self.batch_size), dtype=int)
#store samples
X = self.ie.get_batch(list_IDs_temp)
# Generate data
for i, ID in enumerate(list_IDs_temp):
# Store class
y[i] = self.labels[ID]
return X, y
ie_datagen = IEDataGenerator(root_ie, np.expand_dims(labels,axis=1))
xx,yy = ie_datagen.__getitem__(0)
root_model, ii, oo = root_ie.retrieve_model_inputs_outputs()
root_model.summary()
root_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
from keras.callbacks import ReduceLROnPlateau
reduce_lr = ReduceLROnPlateau(monitor='sparse_categorical_accuracy', factor=0.2,
patience=5, min_lr=1e-5, verbose=1)
result = root_model.fit_generator(ie_datagen, epochs=10, callbacks=[reduce_lr])
```
| github_jupyter |
# FBSDE
Ji, Shaolin, Shige Peng, Ying Peng, and Xichuan Zhang. “Three Algorithms for Solving High-Dimensional Fully-Coupled FBSDEs through Deep Learning.” ArXiv:1907.05327 [Cs, Math], February 2, 2020. http://arxiv.org/abs/1907.05327.
For standard $d$-dimensional Brownian motion and $d$-dimensional Poisson process with intensity $\lambda$ (in every component) consider an FBSDE:
$$
\begin{aligned}
dX_t^i &= \frac 1\alpha \exp\left(-\alpha X_t^i\right) \sum_j Z^{ij}_t dW^j_t + \frac 1\alpha \sum_j \log\left(1+r^{ij}_t \exp\left(-\alpha X^i_t\right)\right) dN^j_t & X_0 = x_0 \\
dY_t^i &= \frac 12 \exp\left(-\alpha X^i_t\right) \sum_j \left(Z^{ij}_t\right)^2 dt + \sum_j Z^{ij}_t dW^j_t + \sum_j r^{ij}_t dN^j_t & Y^i_T= \exp\left(X^i_T\right)
\end{aligned}
$$
One can see by Ito's lemma (Oksendal, p.9, 1.2.8) that
$$
Y^i_t = \exp(X^i_t)
$$
```
# working configuration without jumps: time_horizon = 0.1, n_paths = 2 ** 16, n_timesteps = 4, n_dimensions = 50
# working configuration with jumps: time_horizon = 0.1, n_paths = 2 ** 12, n_timesteps = 4, n_dimensions = 2
import os
from makers.gpu_utils import *
os.environ["CUDA_VISIBLE_DEVICES"] = str(pick_gpu_lowest_memory())
import numpy as np
import tensorflow as tf
from keras.layers import Input, Dense, Lambda, Reshape, concatenate, Layer, BatchNormalization
from keras import Model, initializers
from keras.callbacks import ModelCheckpoint
from keras.metrics import mean_squared_error
import matplotlib.pyplot as plt
from datetime import datetime
from keras.metrics import mse
from keras.optimizers import Adam
from keras.callbacks import Callback
import pandas as pd
from tqdm import tqdm
from itertools import product
print("Num GPUs Available: ", len(tf.config.list_physical_devices("GPU")))
```
# Inputs
```
# model parameters
n_paths = 2 ** 12
n_timesteps = 16
alpha = 0.1
time_horizon = 1.
n_dimensions = 2
n_diffusion_factors = 2
n_jump_factors = 2
intensity = 100.
dt = time_horizon / n_timesteps
# create dirs
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
model_name = f"{timestamp}__{n_dimensions}__{n_paths}__{n_timesteps}__{time_horizon}"
tb_log_dir = "/home/tmp/starokon/tensorboard/" + model_name
output_dir = f"_output/models/{model_name}"
os.makedirs(output_dir, exist_ok=True)
def b(t, x, y, z, r):
return [0. for _ in range(n_dimensions)]
def s(t, x, y, z, r):
return [[tf.exp(-alpha * x[i]) * z[i][j] / alpha for j in range(n_diffusion_factors)] for i in range(n_dimensions)]
def v(t, x, y, z, r):
return [[tf.math.log(1 + tf.math.maximum(r[i][j], 0.) * tf.exp(-alpha * x[i])) / alpha for j in range(n_jump_factors)] for i in range(n_dimensions)]
def f(t, x, y, z, r):
return [tf.exp(-alpha * x[i]) * tf.reduce_sum(z[i] ** 2) / 2. for i in range(n_dimensions)]
def g(x):
return [tf.exp(x[i]) for i in range(n_dimensions)]
```
# Custom layers and callbacks
```
class InitialValue(Layer):
def __init__(self, y0, **kwargs):
super().__init__(**kwargs)
self.y0 = y0
def call(self, inputs):
return self.y0
```
# Model
```
def build_model(n_dimensions, n_diffusion_factors, n_jump_factors, n_timesteps, time_horizon):
dt = time_horizon / n_timesteps
def dX(t, x, y, z, r, dW, dN):
def drift(arg):
x, y, z, r = arg
return tf.math.multiply(b(t, x, y, z, r), dt)
a0 = tf.vectorized_map(drift, (x, y, z, r))
def noise(arg):
x, y, z, r, dW = arg
return tf.tensordot(s(t, x, y, z, r), dW, [[1], [0]])
a1 = tf.vectorized_map(noise, (x, y, z, r, dW))
def jump(arg):
x, y, z, r, dN = arg
return tf.tensordot(v(t, x, y, z, r), dN, [[1], [0]])
a2 = tf.vectorized_map(jump, (x, y, z, r, dN))
return a0 + a1 + a2
def dY(t, x, y, z, r, dW, dN):
def drift(arg):
x, y, z, r = arg
return tf.math.multiply(f(t, x, y, z, r), dt)
a0 = tf.vectorized_map(drift, (x, y, z, r))
def noise(arg):
x, y, z, r, dW = arg
return tf.tensordot(z, dW, [[1], [0]])
a1 = tf.vectorized_map(noise, (x, y, z, r, dW))
def jump(arg):
x, y, z, r, dN = arg
return tf.tensordot(r, dN, [[1], [0]])
a2 = tf.vectorized_map(jump, (x, y, z, r, dN))
return a0 + a1 + a2
@tf.function
def hx(args):
i, x, y, z, r, dW, dN = args
return x + dX(i * dt, x, y, z, r, dW, dN)
@tf.function
def hy(args):
i, x, y, z, r, dW, dN = args
return y + dY(i * dt, x, y, z, r, dW, dN)
paths = []
n_hidden_units = n_dimensions + n_diffusion_factors + n_jump_factors + 10
inputs_x0 = Input(shape=(n_dimensions))
inputs_dW = Input(shape=(n_timesteps, n_diffusion_factors))
inputs_dN = Input(shape=(n_timesteps, n_jump_factors))
# variable x0
y0 = Dense(n_hidden_units, activation='elu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='y1_0')(inputs_x0)
y0 = Dense(n_dimensions, activation='elu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='y2_0')(y0)
x = inputs_x0
y = y0
# constant x0
# x0 = tf.Variable([[1. for _ in range(n_dimensions)]], trainable=False)
# y0 = tf.Variable([[0. for _ in range(n_dimensions)]], trainable=True)
# x = InitialValue(x0, trainable=False, name='x_0')(inputs_dW)
# y = InitialValue(y0, trainable=True, name='y_0')(inputs_dW)
z = concatenate([x, y])
z = Dense(n_hidden_units, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='z1_0')(z)
z = Dense(n_dimensions * n_diffusion_factors, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='z2_0')(z)
# z = BatchNormalization(name='zbn_0')(z)
z = Reshape((n_dimensions, n_diffusion_factors), name='zr_0')(z)
r = concatenate([x, y])
r = Dense(n_hidden_units, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='r1_0')(r)
r = Dense(n_dimensions * n_jump_factors, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name='r2_0')(r)
# r = BatchNormalization(name='rbn_0')(r)
r = Reshape((n_dimensions, n_jump_factors), name='rr_0')(r)
paths += [[x, y, z, r]]
# pre-compile lambda layers
for i in range(n_timesteps):
step = InitialValue(tf.Variable(i, dtype=tf.float32, trainable=False))(inputs_dW)
dW = Lambda(lambda x: x[0][:, tf.cast(x[1], tf.int32)])([inputs_dW, step])
dN = Lambda(lambda x: x[0][:, tf.cast(x[1], tf.int32)])([inputs_dN, step])
x, y = (
Lambda(hx, name=f'x_{i+1}')([step, x, y, z, r, dW, dN]),
Lambda(hy, name=f'y_{i+1}')([step, x, y, z, r, dW, dN]),
)
# we don't train z for the last time step; keep for consistency
z = concatenate([x, y])
z = Dense(n_hidden_units, activation='relu', name=f'z1_{i+1}')(z)
z = Dense(n_dimensions * n_diffusion_factors, activation='relu', name=f'z2_{i+1}')(z)
z = Reshape((n_dimensions, n_diffusion_factors), name=f'zr_{i+1}')(z)
# z = BatchNormalization(name=f'zbn_{i+1}')(z)
# we don't train r for the last time step; keep for consistency
r = concatenate([x, y])
r = Dense(n_hidden_units, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name=f'r1_{i+1}')(r)
r = Dense(n_dimensions * n_jump_factors, activation='relu', kernel_initializer=initializers.RandomNormal(stddev=1e-1), name=f'r2_{i+1}')(r)
r = Reshape((n_dimensions, n_jump_factors), name=f'rr_{i+1}')(r)
# r = BatchNormalization(name=f'rbn_{i+1}')(r)
paths += [[x, y, z, r]]
outputs_loss = Lambda(lambda r: r[1] - tf.transpose(tf.vectorized_map(g, r[0])))([x, y])
outputs_paths = tf.stack(
[tf.stack([p[0] for p in paths[1:]], axis=1), tf.stack([p[1] for p in paths[1:]], axis=1)] +
[tf.stack([p[2][:, :, i] for p in paths[1:]], axis=1) for i in range(n_diffusion_factors)] +
[tf.stack([p[3][:, :, i] for p in paths[1:]], axis=1) for i in range(n_jump_factors)], axis=2)
model_loss = Model([inputs_x0, inputs_dW, inputs_dN], outputs_loss)
# (n_sample, n_timestep, x/y/z_k, n_dimension)
# skips the first time step
model_paths = Model([inputs_x0, inputs_dW, inputs_dN], outputs_paths)
model_y0 = Model([inputs_x0], y0)
return model_loss, model_paths, model_y0
```
# Training
```
np.set_printoptions(edgeitems=11, linewidth=90, formatter=dict(float=lambda x: "%7.5g" % x))
# create model
dt = time_horizon / n_timesteps
model_loss, model_paths, model_y0 = build_model(n_dimensions=n_dimensions, n_diffusion_factors=n_dimensions, n_jump_factors=n_dimensions, n_timesteps=n_timesteps, time_horizon=time_horizon)
# model_loss.summary()
# x0 = tf.constant(np.full((n_paths, n_dimensions), 1.))
x0 = 1. + 0. * tf.random.normal((n_paths, n_dimensions))
dW = tf.sqrt(dt) * tf.random.normal((n_paths, n_timesteps, n_diffusion_factors))
dN = tf.random.poisson((n_paths, n_timesteps), tf.constant(dt * np.array([intensity for _ in range(n_jump_factors)])))
target = tf.zeros((n_paths, n_dimensions))
class Y0Callback(Callback):
def __init__(self, filepath=None):
super(Y0Callback, self).__init__()
self.filepath = filepath
self.y0s = []
def on_epoch_end(self, epoch, logs=None):
y0 = model_y0(tf.constant([[1. for _ in range(n_dimensions)]]))
self.y0s += [y0[0]]
print(f"{y0}\n")
def on_train_end(self, logs=None):
if self.filepath is not None:
pd.DataFrame(self.y0s).to_csv(self.filepath)
# define callbacks
callbacks = []
callbacks += [Y0Callback(filepath=os.path.join(output_dir, "y0.csv"))]
callbacks += [ModelCheckpoint(os.path.join(output_dir, "model.h5"), monitor="loss", save_weights_only=True, save_best_only=True, overwrite=True)]
# callbacks += [tf.keras.callbacks.TensorBoard(log_dir=tb_log_dir, histogram_freq=1, profile_batch=1)]
callbacks += [tf.keras.callbacks.TerminateOnNaN()]
callbacks += [tf.keras.callbacks.EarlyStopping(monitor="loss", min_delta=1e-4, patience=10)]
# leave it here to readjust learning rate on the fly
adam = Adam(learning_rate=1e-3)
model_loss.compile(loss='mse', optimizer=adam)
history = model_loss.fit([x0, dW, dN], target, batch_size=128, initial_epoch=0, epochs=1000, callbacks=callbacks)
df_loss = pd.DataFrame(history.history['loss'])
df_loss.to_csv(os.path.join(output_dir, 'loss.csv'))
```
# Transfer weights (if needed)
```
# try transfer learning from another starting point
model_loss.get_layer('y_0').set_weights(m_large.get_layer('y_0').get_weights())
for i in range(n_timesteps):
model_loss.get_layer(f'z1_{i}').set_weights(m_large.get_layer(f'z1_{i}').get_weights())
model_loss.get_layer(f'z2_{i}').set_weights(m_large.get_layer(f'z2_{i}').get_weights())
# transfer learning from cruder discretization
model_loss.get_layer('y_0').set_weights(m_small.get_layer('y_0').get_weights())
n_small = 4
for i in range(n_small):
for j in range(n_timesteps // n_small):
model_loss.get_layer(f'z1_{n_timesteps // n_small * i}').set_weights(m_small.get_layer(f'z1_{i}').get_weights())
model_loss.get_layer(f'z2_{n_timesteps // n_small * i}').set_weights(m_small.get_layer(f'z2_{i}').get_weights())
model_loss.get_layer(f'z1_{n_timesteps // n_small * i + j}').set_weights(m_small.get_layer(f'z1_{i}').get_weights())
model_loss.get_layer(f'z2_{n_timesteps // n_small * i + j}').set_weights(m_small.get_layer(f'z2_{i}').get_weights())
# check for exploding gradients before training
with tf.GradientTape() as tape:
loss = mse(model_loss([dW, dN]), target)
# bias of the last dense layer
variables = model_loss.variables[-1]
tape.gradient(loss, variables)
```
# Training loop
```
for time_horizon, n_paths, n_timesteps, n_dimensions in tqdm(list(product([0.1], [2**12], [4], [2]))):
# create model
dt = time_horizon / n_timesteps
model_loss, model_paths = build_model(n_dimensions=n_dimensions, n_diffusion_factors=n_dimensions, n_jump_factors=n_dimensions, n_timesteps=n_timesteps, time_horizon=time_horizon)
# generate paths
dW = tf.sqrt(dt) * tf.random.normal((n_paths, n_timesteps, n_diffusion_factors))
dN = tf.random.poisson((n_paths, n_timesteps), tf.constant(dt * np.array([intensity for _ in range(n_jump_factors)]).transpose().reshape(-1)))
target = tf.zeros((n_paths, n_dimensions))
# create dirs
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
model_name = f"{timestamp}__{n_dimensions}__{n_paths}__{n_timesteps}__{time_horizon}"
tb_log_dir = "/home/tmp/starokon/tensorboard/" + model_name
output_dir = f"_output/models/{model_name}"
os.makedirs(output_dir, exist_ok=True)
# define callbacks
y0_callback = Y0Callback(filepath=os.path.join(output_dir, "y0.csv"))
checkpoint_callback = ModelCheckpoint(os.path.join(output_dir, "model.h5"), monitor="loss", save_weights_only=True, save_best_only=True, overwrite=True)
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=tb_log_dir, histogram_freq=1, profile_batch=1)
nan_callback = tf.keras.callbacks.TerminateOnNaN()
loss_callback = tf.keras.callbacks.EarlyStopping(monitor="loss", min_delta=1e-4, patience=20)
# callbacks
callbacks = [
nan_callback,
checkpoint_callback,
# tensorboard_callback,
y0_callback,
loss_callback,
]
# leave it here to readjust learning rate on the fly
adam = Adam(learning_rate=1e-3)
model_loss.compile(loss='mse', optimizer=adam)
# train
history = model_loss.fit([dW, dN], target, batch_size=128, initial_epoch=0, epochs=3000, callbacks=callbacks)
df_loss = pd.DataFrame(history.history['loss'])
df_loss.to_csv(os.path.join(output_dir, 'loss.csv'))
```
# Validate
```
dW_test = tf.sqrt(dt) * tf.random.normal((n_paths//8, n_timesteps, n_diffusion_factors))
dN_test = tf.random.poisson((n_paths//8, n_timesteps), tf.constant(dt * np.array([1., 1.]).transpose().reshape(-1)))
target_test = tf.zeros((n_paths//8, n_dimensions))
model_loss.evaluate([dW_test, dN_test], target_test)
```
# Display paths and loss
```
# load bad model
model_loss.load_weights('_models/weights0011.h5')
loss = model_loss([dW, dN]).numpy()
loss
paths = model_paths([dW, dN]).numpy()
```
| github_jupyter |
# 4-Model the Data
> "All models are wrong, Some of them are useful"
- The power and limits of models
- Tradeoff between Prediction Accuracy and Model Interpretability
- Assessing Model Accuracy
- Regression models (Simple, Multiple)
- Classification model
```
# Load the libraries
import numpy as np
import pandas as pd
from scipy import stats
from sklearn import linear_model
# Load the data again!
df = pd.read_csv("data/Weed_Price.csv", parse_dates=[-1])
df.sort(columns=['State','date'], inplace=True)
df1 = df[df.State=="California"].copy()
df1.set_index("date", inplace=True)
print df1.shape
idx = pd.date_range(df1.index.min(), df1.index.max())
df1 = df1.reindex(idx)
df1.fillna(method = "ffill", inplace=True)
print df1.shape
df1.head()
#Reading demographics data
demographics = pd.DataFrame.from_csv("data/Demographics_State.csv",header=0,index_col=False,sep=',')
demographics.rename(columns={'region':'State'}, inplace=True)
demographics.head()
df['State'] = df['State'].str.lower()
df.head()
df_demo = pd.merge(df, demographics, how="inner", on="State")
df_demo.head()
```
### Correlation
```
corr_bw_percapita_highq = stats.pearsonr(df_demo.per_capita_income, df_demo.HighQ)[0]
print corr_bw_percapita_highq
```
**Exercise** Find correlation between percent_white and highQ
Impact of de-regulation
```
state_location = pd.read_csv("data/State_Location.csv")
state_location.head()
pd.unique(state_location.status)
```
**Exercise** Find mean prices of HighQ weed for states that are legal and for states that are illegal
Finding good time of the week to buy weed in California
```
df['year'] = pd.DatetimeIndex(df['date']).year
df['month'] = pd.DatetimeIndex(df['date']).month
df['week'] = pd.DatetimeIndex(df['date']).week
df['weekday'] = pd.DatetimeIndex(df['date']).weekday
df_demo_ca = df_demo[df_demo.State=="california"].copy()
df_demo_ca['year'] = pd.DatetimeIndex(df_demo_ca['date']).year
df_demo_ca['month'] = pd.DatetimeIndex(df_demo_ca['date']).month
df_demo_ca['week'] = pd.DatetimeIndex(df_demo_ca['date']).week
df_demo_ca['weekday'] = pd.DatetimeIndex(df_demo_ca['date']).weekday
df_demo_ca.head()
df_demo_ca.groupby("weekday").HighQ.mean()
```
**Exercise** If I need to buy weed on a wednesday, which state should I be in?
```
df.groupby(["State", "weekday"]).HighQ.mean()
df_st_wk = df.groupby(["State", "weekday"]).HighQ.mean()
df_st_wk.reset_index()
#Answer:
```
###Regression
Predicting price of HighQ weed in CA
```
model_data = df1.loc[:,['HighQ']].copy()
idx = pd.date_range(model_data.index.min(), model_data.index.max()+ 30)
model_data.reset_index(inplace=True)
model_data.set_index("index", inplace=True)
model_data = model_data.reindex(idx)
model_data.tail(35)
model_data['IND'] = np.arange(model_data.shape[0])
model_data.tail(35)
model_data['IND_SQ'] = model_data['IND']**2
x = model_data.ix[0:532, ["IND","IND_SQ"]]
y = model_data.ix[0:532, "HighQ"]
x_test = model_data.ix[532:, ["IND","IND_SQ"]]
print x.shape, y.shape
ols = linear_model.LinearRegression(fit_intercept=True)
ols.fit(x, y)
ols_predict = ols.predict(x_test)
ols_predict
ols.coef_
```
**Exercise** Predict prices for MedQ for CA
| github_jupyter |
```
# Pandas for data loading and processing
import pandas as pd
#Data Analysis
from sklearn.linear_model import LogisticRegression
#Data splitting
from sklearn.model_selection import train_test_split
#Numpy for diverse math functions
import numpy as np
#Model validation
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_curve,roc_auc_score
from sklearn.metrics import f1_score
from sklearn.metrics import r2_score
#visualization libraries
import matplotlib.pyplot as plt
import seaborn as sns
#Upsampling
from sklearn.utils import resample
#Keras
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.layers import LSTM
#Keras Plot
from keras.utils.vis_utils import plot_model
from numpy.random import seed
seed(1)
# Reading data from schwartau
schwartau_daily = pd.read_csv('schwartau_daily_filtered.csv')
wurzburg_daily = pd.read_csv('wurzburg_daily_filtered.csv')
#describe our data
schwartau_daily[schwartau_daily.select_dtypes(exclude='object').columns].describe().\
style.background_gradient(axis=1,cmap=sns.light_palette('green', as_cmap=True))
# split into test and train
partition_schwartau=700
train_schwartau = schwartau_daily.loc[:partition_schwartau]
test_schwartau = schwartau_daily.loc[partition_schwartau:]
partition_wurzburg=500
train_wurzburg = wurzburg_daily.loc[:partition_wurzburg]
test_wurzburg = wurzburg_daily.loc[partition_wurzburg:]
train_schwartau.head(5)
x_train = train_schwartau[:-1]
y_train = train_schwartau[1:]
x_test = test_schwartau[:-1]
y_test = test_schwartau[1:]
x_train_schwartau = x_train.drop(['flow_processed','timestamp'], axis=1)
y_train_schwartau = y_train.drop(['timestamp','humidity','temperature','weight'], axis=1)
x_test_schwartau = x_test.drop(['flow_processed','timestamp'], axis=1)
y_test_schwartau = y_test.drop(['timestamp','humidity','temperature','weight'], axis=1)
nn_model = Sequential()
nn_model.add(Dense(15, input_dim=3, activation='relu'))
nn_model.add(Dense(15, activation='sigmoid'))
nn_model.add(Dense(15, activation='relu'))
nn_model.add(Dense(1, activation='sigmoid'))
nn_model.compile(loss='mean_squared_error', optimizer='adam')
early_stop = EarlyStopping(monitor='loss', patience=5, verbose=1)
history = nn_model.fit(x_train_schwartau, y_train_schwartau, epochs=10000, batch_size=300, verbose=1, callbacks=[early_stop], shuffle=False)
y_pred_test_nn = nn_model.predict(x_test_schwartau)
y_train_pred_nn = nn_model.predict(x_train_schwartau)
print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train_schwartau, y_train_pred_nn)))
print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test_schwartau, y_pred_test_nn)))
plot_model(nn_model, to_file="modelo.png",show_shapes=True)
```
| github_jupyter |
# Working With Splitters
When using machine learning, you typically divide your data into training, validation, and test sets. The MoleculeNet loaders do this automatically. But how should you divide up the data? This question seems simple at first, but it turns out to be quite complicated. There are many ways of splitting up data, and which one you choose can have a big impact on the reliability of your results. This tutorial introduces some of the splitting methods provided by DeepChem.
## Colab
This tutorial and the rest in this sequence can be done in Google colab. If you'd like to open this notebook in colab, you can use the following link.
[](https://colab.research.google.com/github/deepchem/deepchem/blob/master/examples/tutorials/Working_With_Splitters.ipynb)
## Setup
To run DeepChem within Colab, you'll need to run the following installation commands. This will take about 5 minutes to run to completion and install your environment. You can of course run this tutorial locally if you prefer. In that case, don't run these cells since they will download and install Anaconda on your local machine.
```
!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import conda_installer
conda_installer.install()
!/root/miniconda/bin/conda info -e
!pip install --pre deepchem
import deepchem
deepchem.__version__
```
## Splitters
In DeepChem, a method of splitting samples into multiple datasets is defined by a `Splitter` object. Choosing an appropriate method for your data is very important. Otherwise, your trained model may seem to work much better than it really does.
Consider a typical drug development pipeline. You might begin by screening many thousands of molecules to see if they bind to your target of interest. Once you find one that seems to work, you try to optimize it by testing thousands of minor variations on it, looking for one that binds more strongly. Then perhaps you test it in animals and find it has unacceptable toxicity, so you try more variations to fix the problems.
This has an important consequence for chemical datasets: they often include lots of molecules that are very similar to each other. If you split the data into training and test sets in a naive way, the training set will include many molecules that are very similar to the ones in the test set, even if they are not exactly identical. As a result, the model may do very well on the test set, but then fail badly when you try to use it on other data that is less similar to the training data.
Let's take a look at a few of the splitters found in DeepChem.
### RandomSplitter
This is one of the simplest splitters. It just selects samples for the training, validation, and test sets in a completely random way.
Didn't we just say that's a bad idea? Well, it depends on your data. If every sample is truly independent of every other, then this is just as good a way as any to split the data. There is no universally best choice of splitter. It all depends on your particular dataset, and for some datasets this is a fine choice.
### RandomStratifiedSplitter
Some datasets are very unbalanced: only a tiny fraction of all samples are positive. In that case, random splitting may sometimes lead to the validation or test set having few or even no positive samples for some tasks. That makes it unable to evaluate performance.
`RandomStratifiedSplitter` addresses this by dividing up the positive and negative samples evenly. If you ask for a 80/10/10 split, the validation and test sets will contain not just 10% of samples, but also 10% of the positive samples for each task.
### ScaffoldSplitter
This splitter tries to address the problem discussed above where many molecules are very similar to each other. It identifies the scaffold that forms the core of each molecule, and ensures that all molecules with the same scaffold are put into the same dataset. This is still not a perfect solution, since two molecules may have different scaffolds but be very similar in other ways, but it usually is a large improvement over random splitting.
### ButinaSplitter
This is another splitter that tries to address the problem of similar molecules. It clusters them based on their molecular fingerprints, so that ones with similar fingerprints will tend to be in the same dataset. The time required by this splitting algorithm scales as the square of the number of molecules, so it is mainly useful for small to medium sized datasets.
### SpecifiedSplitter
This splitter leaves everything up to the user. You tell it exactly which samples to put in each dataset. This is useful when you know in advance that a particular splitting is appropriate for your data.
An example is temporal splitting. Consider a research project where you are continually generating and testing new molecules. As you gain more data, you periodically retrain your model on the steadily growing dataset, then use it to predict results for other not yet tested molecules. A good way of validating whether this works is to pick a particular cutoff date, train the model on all data you had at that time, and see how well it predicts other data that was generated later.
## Effect of Using Different Splitters
Let's look at an example. We will load the Tox21 toxicity dataset using random, scaffold, and Butina splitting. For each one we train a model and evaluate it on the training and test sets.
```
import deepchem as dc
splitters = ['random', 'scaffold', 'butina']
metric = dc.metrics.Metric(dc.metrics.roc_auc_score)
for splitter in splitters:
tasks, datasets, transformers = dc.molnet.load_tox21(featurizer='ECFP', split=splitter)
train_dataset, valid_dataset, test_dataset = datasets
model = dc.models.MultitaskClassifier(n_tasks=len(tasks), n_features=1024, layer_sizes=[1000])
model.fit(train_dataset, nb_epoch=10)
print('splitter:', splitter)
print('training set score:', model.evaluate(train_dataset, [metric], transformers))
print('test set score:', model.evaluate(test_dataset, [metric], transformers))
print()
```
All of them produce very similar performance on the training set, but the random splitter has much higher performance on the test set. Scaffold splitting has a lower test set score, and Butina splitting is even lower. Does that mean random splitting is better? No! It means random splitting doesn't give you an accurate measure of how well your model works. Because the test set contains lots of molecules that are very similar to ones in the training set, it isn't truly independent. It makes the model appear to work better than it really does. Scaffold splitting and Butina splitting give a better indication of what you can expect on independent data in the future.
# Congratulations! Time to join the Community!
Congratulations on completing this tutorial notebook! If you enjoyed working through the tutorial, and want to continue working with DeepChem, we encourage you to finish the rest of the tutorials in this series. You can also help the DeepChem community in the following ways:
## Star DeepChem on [GitHub](https://github.com/deepchem/deepchem)
This helps build awareness of the DeepChem project and the tools for open source drug discovery that we're trying to build.
## Join the DeepChem Gitter
The DeepChem [Gitter](https://gitter.im/deepchem/Lobby) hosts a number of scientists, developers, and enthusiasts interested in deep learning for the life sciences. Join the conversation!
| github_jupyter |
# Active Directory Replication From Non-Domain-Controller Accounts
## Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2018/08/15 |
| modification date | 2020/09/20 |
| playbook related | [] |
## Hypothesis
Adversaries might attempt to pull the NTLM hash of a user via active directory replication apis from a non-domain-controller account with permissions to do so.
## Technical Context
Active Directory replication is the process by which the changes that originate on one domain controller are automatically transferred to other domain controllers that store the same data.
Active Directory data takes the form of objects that have properties, or attributes. Each object is an instance of an object class, and object classes and their respective attributes are defined in the Active Directory schema.
The values of the attributes define the object, and a change to a value of an attribute must be transferred from the domain controller on which it occurs to every other domain controller that stores a replica of that object.
## Offensive Tradecraft
An adversary can abuse this model and request information about a specific account via the replication request.
This is done from an account with sufficient permissions (usually domain admin level) to perform that request.
Usually the accounts performing replication operations in a domain are computer accounts (i.e dcaccount$).
Therefore, it might be abnormal to see other non-dc-accounts doing it.
The following access rights / permissions are needed for the replication request according to the domain functional level
| Control access right symbol | Identifying GUID used in ACE |
| :-----------------------------| :------------------------------|
| DS-Replication-Get-Changes | 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2 |
| DS-Replication-Get-Changes-All | 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2 |
| DS-Replication-Get-Changes-In-Filtered-Set | 89e95b76-444d-4c62-991a-0facbeda640c |
Additional reading
* https://github.com/OTRF/ThreatHunter-Playbook/tree/master/docs/library/windows/active_directory_replication.md
## Security Datasets
| Metadata | Value |
|:----------|:----------|
| docs | https://securitydatasets.com/notebooks/atomic/windows/credential_access/SDWIN-190301174830.html |
| link | [https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/credential_access/host/empire_dcsync_dcerpc_drsuapi_DsGetNCChanges.zip](https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/credential_access/host/empire_dcsync_dcerpc_drsuapi_DsGetNCChanges.zip) |
## Analytics
### Initialize Analytics Engine
```
from openhunt.mordorutils import *
spark = get_spark()
```
### Download & Process Security Dataset
```
sd_file = "https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/credential_access/host/empire_dcsync_dcerpc_drsuapi_DsGetNCChanges.zip"
registerMordorSQLTable(spark, sd_file, "sdTable")
```
### Analytic I
Monitoring for non-dc machine accounts accessing active directory objects on domain controllers with replication rights might be suspicious
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Windows active directory | Microsoft-Windows-Security-Auditing | User accessed AD Object | 4662 |
```
df = spark.sql(
'''
SELECT `@timestamp`, Hostname, SubjectUserName, SubjectLogonId
FROM sdTable
WHERE LOWER(Channel) = "security"
AND EventID = 4662
AND AccessMask = "0x100"
AND (
Properties LIKE "%1131f6aa_9c07_11d1_f79f_00c04fc2dcd2%"
OR Properties LIKE "%1131f6ad_9c07_11d1_f79f_00c04fc2dcd2%"
OR Properties LIKE "%89e95b76_444d_4c62_991a_0facbeda640c%"
)
AND NOT SubjectUserName LIKE "%$"
'''
)
df.show(10,False)
```
### Analytic II
You can use successful authentication events on the domain controller to get information about the source of the AD Replication Service request
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Authentication log | Microsoft-Windows-Security-Auditing | User authenticated Host | 4624 |
| Windows active directory | Microsoft-Windows-Security-Auditing | User accessed AD Object | 4662 |
```
df = spark.sql(
'''
SELECT o.`@timestamp`, o.Hostname, o.SubjectUserName, o.SubjectLogonId, a.IpAddress
FROM sdTable o
INNER JOIN (
SELECT Hostname,TargetUserName,TargetLogonId,IpAddress
FROM sdTable
WHERE LOWER(Channel) = "security"
AND EventID = 4624
AND LogonType = 3
AND NOT TargetUserName LIKE "%$"
) a
ON o.SubjectLogonId = a.TargetLogonId
WHERE LOWER(o.Channel) = "security"
AND o.EventID = 4662
AND o.AccessMask = "0x100"
AND (
o.Properties LIKE "%1131f6aa_9c07_11d1_f79f_00c04fc2dcd2%"
OR o.Properties LIKE "%1131f6ad_9c07_11d1_f79f_00c04fc2dcd2%"
OR o.Properties LIKE "%89e95b76_444d_4c62_991a_0facbeda640c%"
)
AND o.Hostname = a.Hostname
AND NOT o.SubjectUserName LIKE "%$"
'''
)
df.show(10,False)
```
## Known Bypasses
| Idea | Playbook |
|:-----|:---------|
| Adversaries could perform the replication request from a Domain Controller (DC) and with the DC machine account (*$) to make it look like usual/common replication activity. | [None](https://github.com/OTRF/ThreatHunter-Playbook/blob/master/playbooks/None.yaml) |
## False Positives
None
## Hunter Notes
* As stated before, when an adversary utilizes directory replication services to connect to a DC, a RPC Client call operation with the RPC Interface GUID of E3514235-4B06-11D1-AB04-00C04FC2DCD2 is performed pointing to the targeted DC. This activity is recorded at the source endpoint, from where the replication request is being performed from, via the Microsoft-Windows-RPC ETW provider. Even though the Microsoft-Windows-RPC ETW provider provides great visibility for replication operations at the source endpoint level, it does not have an event tracing session writing events to an .evtx file which does not make it practical to use it at scale yet.
* You can collect information from the Microsoft-Windows-RPC ETW provider and filter on RPC Interface GUID E3514235-4B06-11D1-AB04-00C04FC2DCD2 with SilkETW. One example here > https://twitter.com/FuzzySec/status/1127249052175872000
* You can correlate security events 4662 and 4624 (Logon Type 3) by their Logon ID on the Domain Controller (DC) that received the replication request. This will tell you where the AD replication request came from. This will also allow you to know if it came from another DC or not.
## Hunt Output
| Type | Link |
| :----| :----|
| Sigma Rule | [https://github.com/SigmaHQ/sigma/blob/master/rules/windows/builtin/security/win_ad_replication_non_machine_account.yml](https://github.com/SigmaHQ/sigma/blob/master/rules/windows/builtin/security/win_ad_replication_non_machine_account.yml) |
## References
* https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/1522b774-6464-41a3-87a5-1e5633c3fbbb
* https://docs.microsoft.com/en-us/windows/desktop/adschema/c-domain
* https://docs.microsoft.com/en-us/windows/desktop/adschema/c-domaindns
* http://www.harmj0y.net/blog/redteaming/a-guide-to-attacking-domain-trusts/
* https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc782376(v=ws.10)
* https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-drsr/f977faaa-673e-4f66-b9bf-48c640241d47
| github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker
df = pd.read_csv("bunny_1k_com_verts_monday_25.log",names=['k','init','model','l','i'])
mdf = df.groupby(['init','model','k']).mean()
sdf = df.groupby(['init','model','k']).std()
from matplotlib import rc
plt.style.use('fivethirtyeight')
plt.style.use('seaborn-whitegrid')
#plt.rcParams["font.family"] = "sans-serif"
rc('font',**{'family':'sans-serif','sans-serif':['cm']})
pltstuff = 1
if pltstuff == 2:
subplot_order = [1,3,2,4]
else:
subplot_order = [1,2]
fig = plt.figure(figsize=(10,5*pltstuff))
for ii, init in enumerate(['kmeans','random']):
for model in [3,0,1,2]:
ls = '--' if model == 0 or model ==3 else '-'
if model == 0:
label = 'Mesh (approx)'
if model == 1:
label = 'Points (Center of Mass)'
if model == 2:
label = 'Points (Vertices)'
if model == 3:
label = 'Mesh (exact)'
ldf = mdf.loc[(init,model),]
x = np.array(ldf.index)
y = ldf.values[:,0]
error = 2*sdf.loc[(init,model),].values[:,0]
ax = plt.subplot(pltstuff,2,subplot_order[pltstuff*ii])
plt.plot(x,y,ls=ls,label=label)
plt.fill_between(x, y-error, y+error,alpha=0.3)
plt.grid(True)
plt.xlabel('number of mixtures')
plt.title('{} init. fidelity'.format(init))
plt.title('{} initialization'.format(init))
plt.ylabel('likelihood of ground truth\n(higher is better)')
plt.ylim(2,9)
ax.set_xscale("log", nonposx='clip')
ax.tick_params(axis='x', which='minor', bottom=True,width=1,length=5)
plt.grid(True,axis='x',which='minor')
ax.tick_params(axis='x', which='major', bottom=True,width=2,length=5)
y = ldf.values[:,1]
error = sdf.loc[(init,model),].values[:,1]
if pltstuff == 2:
ax = plt.subplot(pltstuff,2,subplot_order[pltstuff*ii+1])
plt.plot(x,y,ls=ls,label=label)
plt.fill_between(x, y-error, y+error,alpha=0.15)
ax.set_xscale("log", nonposx='clip')
plt.grid(True)
plt.xlabel('number of mixtures')
plt.title('{} init. runtime'.format(init))
plt.ylabel('iterations until convergence')
ax.tick_params(axis='x', which='minor', bottom=True,width=1,length=5)
plt.grid(True,axis='x',which='minor')
ax.tick_params(axis='x', which='major', bottom=True,width=2,length=5)
#plt.subplot(2,2,3)
#plt.subplot(2,2,4)
for i in range(pltstuff*2):
plt.subplot(pltstuff,2,1+i)
plt.xlim(6,400)
plt.legend()
fig.tight_layout()
fig.subplots_adjust(top=0.7+pltstuff*0.1)
plt.suptitle('Different Mesh Information',size=24,weight='bold')
plt.savefig('graph_triverts.pdf', facecolor=fig.get_facecolor(), edgecolor='none')
#mdf.loc[('kmeans',0),].values, np.array(mdf.loc[('kmeans',0),].index)
mdf
```
| github_jupyter |
# Neural Networks From Scratch - 01 - A Tiny Neuron is Born in a Cookie Night
We are going to implement neural networks from scratch, that is no tensorflow, pytorch, scikit-learn etc.
Most of the material is taken from my another [repository](https://gitlab.com/QmAuber/basit-ysa-python/-/blob/master/ysa/defterler/YapayZekaMatematik.ipynb)
Here is the list of packages we will be using:
```
import numpy as np ## for matrix operations, you can excange it with something else
# or implement your own array operations, we don't use anything fancy here
from typing import List, Tuple, Callable
```
## Derivatives
The first thing you need to understand when implementing Neural Networks is by and large, derivatives.
So what are derivatives ? Grossly reduced, they are operators that help us to understand how functions behave. Notice that derivative**s**, so there are more than one type.
The simplest derivative can be expressed mathematically as:
$$f'(x) = \lim_{h\to 0} \frac{f(x+h) - f(x)}{h}$$
Here we assume that: $f: \mathbb{R} \to \mathbb{R}$. You can read this as the following:
*Function f takes in a real number and outputs a real number*
In code this would make:
```
def derivative(f: Callable[[float], float], x: float, h=1e-8) -> float:
"Takes the derivative of f"
f_t = (f(x + h) - f(x)) / h
return f_t
```
Simply put I add a tiny bit of something to the argument of f and apply the f to both the original and the added argument, then observe the difference relative to added value. The more I do this, I understand better and better how the function behaves.
Well this is all and good but what if ... just what if the function f takes in multiple values, like a list of values ?
So mathematically what if the definition of $f$ is something like the following:
$$f: \mathbb{R}^N \to R$$
If this is the case, since I only have a single $h$ to add, this raises a question. Which value should receive the $h$ while taking the derivative ? The answer is whichever you want.
But then we would not be able to observe *completely* how the function behaves: YES, that is why this way of taking the derivative is called **partial** derivative, and it is specified as the following:
$$f'(x_1, ..., x_n) = \lim_{h\to0} \frac{f(x_1, ..., x_i+h, ..., x_n) - f(x_1, ..., x_n)}{h}$$
In code this would make:
```
def partial_derivative(f: Callable[[List[float]], float],
arguments: list,
argument_position: int,
h=1e-8) -> np.ndarray:
"""
Basic implementation of partial derivative
"""
arguments_copy = arguments.copy() # in order to leave original arguments untouched
arguments_copy[argument_position] = arguments_copy[argument_position] + h
return (f(arguments_copy) - f(arguments)) / h
```
Well what if I want to observe, the **complete** behaviour of the function $f$.
Then I basically apply the partial derivative to all of the arguments. This is called taking the **gradient** of the function.
In code:
```
def gradient(f: Callable[[List[float]], float],
arguments: list,
h=1e-8) -> List[float]:
"""
Basic implementation of gradient computation
"""
partials: List[float] = []
for argument_pos, argument in enumerate(arguments):
partial = partial_derivative(f=f, arguments=arguments, argument_position=argument_pos)
partials.append(partial)
return partials
```
Let's test our functions:
```
# simple derivative test
def testfn(x): return x * x
d = derivative(testfn, x=5)
print("x^2 derivative = 2x => 5^2 derivative 2 * 5",
10 == round(d, 3))
# testing partial derivative
def test_part_fn(xs: list): return (xs[0] ** 2) + (xs[0] * xs[1]) + (xs[1] ** 2)
# x^2 + xy + y^2
# f_x' = 2x + y , f_y' = 2y + x
xd = partial_derivative(f=test_part_fn, arguments=[2, 6], argument_position=0)
yd = partial_derivative(f=test_part_fn, arguments=[2, 6], argument_position=1)
print("f(x,y) = x^2 + xy + y^2, x=2, y=6")
print("f_x'(x,y) = 2x + y => 4 + 6 = 10")
print("f_y'(x,y) = 2y + x => 2 + 12 = 14")
print("f_x'(x,y) = 10", round(xd, 3) == 10)
print("f_y'(x,y) = 14", round(yd, 3) == 14)
# test gradient
partials = gradient(f=test_part_fn, arguments=[2, 6])
print("∇f(x,y), gradient of f, that is [f_x', f_y'] => [10, 14]")
print("∇f(x,y)= [10, 14], ", [round(p, 3) for p in partials] == [10, 14])
```
What if the signature of the function $f$ is the following:
$$f: \mathbb{R} \to \mathbb{R}^n$$
This is called a vector function, simply a function that outputs a vector. It can also be interpreted as $f(x) = [f_1(x), f_2(x), \dots, f_n(x)]$, that is we can interpret it as a set of functions instead of a single function.
When taking the derivative of this function, we have two cases:
- The member functions, let's call them, sub functions of $f$ are known
- The member functions of $f$ are not known
When we know the member function, the derivative is simply:
$$f'(x) = [f'_1(x), f'_2(x), \dots, f'_n(x)]$$
When we don't know the member functions, the derivative is:
$$f'(x) = \lim_{h\to 0} \frac{f(x+h) - f(x)}{h}$$
The only difference here is that the division is a division of a vector by a scalar.
So in code:
```
def derivative_of_vector_function_with_known_functions(
fs: List[Callable[[float], float]],
x: float,
h=1e-8
)-> List[float]:
"Compute derivative of a vector function when member functions are known"
derivatives = []
for f in fs:
d = derivative(f, x)
derivatives.append(d)
return derivatives
def derivative_of_vector_function(
f: Callable[[float], List[float]],
x: float,
h=1e-8) -> List[float]:
"Derivative of a vector function where member functions are not known"
return list((np.array(f(x + h)) - np.array(f(x))) / h)
```
Let's test all that
```
# testler
def testfn(x): return [x*x, 2 * x, x - 1]
# turevi bunun 2x, 2, 1
vk = derivative_of_vector_function_with_known_functions(fs=[lambda x: x*x,
lambda x: 2 * x,
lambda x: x -1],
x=3)
print("with known functions",
[round(v, 3) for v in vk] == [6, 2, 1])
vnk = derivative_of_vector_function(f=testfn, x=3)
print("with unknown functions",
[round(v, 3) for v in vnk] == [6, 2, 1])
```
So far we have covered the following function signatures:
- $f: \mathbb{R} \to \mathbb{R}$ - goes with simple derivative
- $f: \mathbb{R}^n \to \mathbb{R}$ - goes with partial derivative and the gradient
- $f: \mathbb{R} \to \mathbb{R}^n$ - goes with vector derivative
Now what if the function signature is the last conceivable option, that is:
- $f: \mathbb{R}^n \to \mathbb{R}^m$
How would we compute the derivative of such a function ?
The logic is a mix of what we do with vector functions and gradient.
Again we can interpret the $f$ as a set of functions whose number of elements equals to $m$ where each function takes $n$ arguments.
Basically as the following matrix:
$f(x) = \pmatrix{
f_1(x_1, ..., x_n) \\
f_2(x_1, ..., x_n) \\
... \\
f_m(x_1, ..., x_n)
}$
Then the derivative of such a function would simply be:
$$f'(x)= J(f) = \pmatrix{
f'_1(x_1, ..., x_n) \\
f'_2(x_1, ..., x_n) \\
... \\
f'_m(x_1, ..., x_n)
}$$
If we make it even more explicit:
$$J(f) = \pmatrix{
f_{x_1, 1}'(x) = \frac{f(x_1+h, ..., x_n) - f(x)}{h} & ... & f_{x_n, 1}'(x) = \frac{f(x_1, ..., x_n+h) - f(x)}{h} \\
f_{x_1, 2}'(x) = \frac{f(x_1+h, ..., x_n) - f(x)}{h} & ... & f_{x_n, 2}'(x) = \frac{f(x_1, ..., x_n+h) - f(x)}{h} \\
\vdots & ... & \vdots \\
f_{x_1, m}'(x) = \frac{f(x_1+h, ..., x_n) - f(x)}{h} & ... & f_{x_n, m}'(x) = \frac{f(x_1, ..., x_n+h) - f(x)}{h}
}$$
Here is an example: $ f(x,y,z)=[(2x+y),3z/2,y2+z,6x]$.
The derivative matrix of $f$ would be:
$$J(f) = \pmatrix{
2 & 1 & 0 \\
0 & 0 & \frac{3}{2} \\
0 & 2y & 1 \\
6 & 0 & 0
}$$
This derivative matrix is called **Jacoby matrix**. Computing this matrix is informally called taking/evaluating the jacobian of a function.
The previous question arises again: What if we don't know the member functions ?
Then taking the jacobian means simply:
$$f'(x) = \lim_{h\to 0} \frac{f(x+h) - f(x)}{h}$$
The only difference is that we divide a matrix by a scalar at the end.
In code this would be:
```
def jacoby_with_known_functions(fs: List[Callable[[List[float]], float]],
args: List[float], h=1e-8) -> List[List[float]]:
j_mat = []
for f in fs:
d = gradient(f=f, arguments=args, h=h)
j_mat.append(d)
return j_mat
def jacoby_pure_python(f: Callable[[List[float]], List[float]],
args: List[float],
h=1e-8) -> List[List[float]]:
""
nargs = [a for a in args]
j_mat = []
for i, a in enumerate(args):
narg = a + h
nargs[i] = narg
d = list((np.array(f(nargs)) - np.array(f(args))) / h)
j_mat.append(d)
nargs[i] = a
return j_mat
def jacobian(f: Callable[[np.ndarray], np.ndarray],
args: np.ndarray, h=1e-8) -> np.ndarray:
"""
Compute jacobian with numpy
"""
result = f(args)
j_mat = np.zeros((*args.shape, *result.shape), dtype=np.float)
for index in np.ndindex(args.shape):
narg = args.copy()
narg[index] += h
j_mat[index] = (f(narg) - f(args)) / h
return j_mat.reshape((result.size, args.size))
def f1(arg: List[float]): return 2*arg[0] + arg[1]
def f2(arg: List[float]): return (3 * arg[2]) / 2
def f3(arg: List[float]): return arg[1]*arg[1] + arg[2]
def f4(arg: List[float]): return 6*arg[0]
def testfn(arg: List[float]):
return [
f1(arg),
f2(arg),
f3(arg),
f4(arg)
]
j_known = jacoby_with_known_functions(
fs=[f1,f2,f3,f4], args=[2,1, 3])
print("jacobian with known functions: ",
np.around(np.array(j_known), 3))
j_unknown = jacoby_pure_python(f=testfn, args=[2,1,3])
print("jacobian with unknown function: ", np.around(np.array(j_unknown), 3))
def testfn1(arg):
return np.array([arg[0].sum() * 2,
arg[1].sum() * 3,
arg[2].sum() * 4],
dtype=np.float)
def testfn2(arg):
return np.array([arg[0] * 2,
arg[1] * 3,
arg[2] * 4],
dtype=np.float)
j_np_n1 = jacobian(f=testfn1,
args=np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
],
dtype=np.float)
)
j_np_n2 = jacobian(f=testfn2,
args=np.array(
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
],
dtype=np.float)
)
print("jacobian with numpy: ")
print(np.around(j_np_n1, 3))
print("jacobian with numpy: ")
print(np.around(j_np_n2, 3))
```
We have one last option to consider and that is composite functions.
Armed with the knowledge of jacobian, we can apply the derivative to most of the functions in everyday use. However what if our function is composed of a sequential application of a series of functions, so what if it is something like: $f(x) = k(p(x))$
Notice that this is not truly the same case with the vector functions or the jacobian.
In jacobian, or vector functions, the order of evaluation, or let's say the order in which we apply the functions or the derivative does not change the result.
Here we have a clear sense of time, a sequential relation. The function $p$ has to be evaluated first.
In any case how do we compute its derivative ?
Let's start with the simplest case again:
Suppose that $f,k,p: \mathbb{R} \to \mathbb{R}$
The derivative of $f$ is defined by the following:
$$f'(x) = k'( p(x) ) * p'(x)$$
This equivalence is also known as the **chain rule**.
Let's see that in code:
```
def chain1d(f: Callable[[float], float], g: Callable[[float], float], x: float):
""
delta_g = derivative(g, x)
g_value = g(x)
delta_f = derivative(f, g_value)
return delta_f * delta_g
# chain test
def f(x): return 2 * x
def g(x): return x * x
# derivative 2 * 2x = 4x =1
def testfn(x): return f(g(x))
print("We have equal derivatives, right ? ",
round(derivative(testfn, x=2), 3) == round(chain1d(f=f, g=g, x=2), 3))
```
Again what if our function signature is $f: \mathbb{R}^n \to \mathbb{R}^m$
where the interior signatures are something like:
- $p:\mathbb{R}^n \to \mathbb{R}^z$
- $k:\mathbb{R}^z \to \mathbb{R}^m$
Well by the hand of God, the chain rule is strictly the same, we just use the Jacobian:
$f'(x) = J_k(g(x)) * J_g(x)$
In code this would be:
```
def chain(f: Callable[[np.ndarray], np.ndarray],
g: Callable[[np.ndarray], np.ndarray],
x: np.ndarray
) -> np.ndarray:
""
g_val = g(x)
g_j = jacobian(f=g, args=x)
f_j = jacobian(f=f, args=g_val)
return np.matmul(f_j, g_j)
# test jacoby
# test fn
def f(x: np.ndarray): return np.array([x[0]*3 + 2, x[1], x[2]*2,
x[0] + x[1]], dtype=np.float)
def g(x: np.ndarray): return np.array([x[0] / 2, x[1]*2, x[2]/2], dtype=np.float)
args = np.array([3, 1, 3], dtype=np.float)
jmat = chain(f, g, args)
print(np.around(jmat, 3))
```
## Computation Graphs
Here is the last bit of knowledge required for understanding neural networks.
It turns out, composing functions are quite cool, and that we can express almost anything in terms of composite functions.
Wouldn't it be better if we can represent function composition in an intuitive way.
Well computation graphs are mostly that, meaning a nice a way of expressing sequence of computations.
They also allow us to know the general form of the computation before evaluation which gives you a margin for optimizing and/or serializing the computation.
From the perspective of graph theory, computation graphs are almost always acyclic and directed.
So basically if we have $f(x) = g(k(p(x)))$
We represent it as:
```
p k g
x ---> x_p -----> x_k ----> x_g
```
If we take the derivative of the function $f$, the resulting computational graph would be something like:
```
p k g
x ---> x_p -------> x_k ------------> x_g
/
p'(x) k'(x) g'(x)
x'_p <-------- x'_k <------- x'_g <------
```
So each node of this graph is a computation. In code that would make:
```
class AbstractComputation:
def __init__(self):
self.args = None
def result(self, arg: np.ndarray):
raise NotImplemented
def delta(self):
raise NotImplemented
@property
def output(self):
raise NotImplemented
@property
def d(self):
raise NotImplemented
class Computation(AbstractComputation):
def __init__(self, inpt=None, function=lambda x: x):
super().__init__()
self.args = inpt
self.f = function
def __str__(self):
return ("Computation Node:\nInput: "
+ str(self.args.shape)
+ "\nOutput:" + str(self.output)
+ "\nFunction" + str(self.f)
)
@property
def output(self):
return self.compute()
@property
def d(self):
return jacobian(f=self.f, args=self.args)
def result(self, arg):
return self.f(arg)
def compute(self):
res = self.result(arg=self.args)
return res.copy()
# test computation node
n = Computation()
n.args = np.array([1, 3, 2], dtype=np.float)
n.f = lambda x: x ** 2
print("node output: ", n.output) # 1 9 4
print("node derivative", np.around(n.d, 3)) # 2 6 4
```
A layer is an instance of a computational graph. In the simplest case, it is a sequence of computations.
A network can be composed of more than one layers.
However let's implement the layer as a computation node as well, since we ultimately we require the same set of operations from them anyway.
```
class Layer(AbstractComputation):
def __init__(self, flst: List[Callable[[np.ndarray], np.ndarray]],
arg: np.ndarray):
"Genel hesap katmani (layer)"
self.args = arg
self.computations = [Computation(function=f) for f in flst]
self.is_computed = False
def compute(self):
previous = self.args.copy()
current = self.computations[0]
current.args = previous
for n in self.computations[1:]:
n.args = current.output
current = n
self.is_computed = True
def compute_until(self, limit: int):
"""
"""
if limit > len(self.computations):
raise ValueError(
"Limit out of bounds for available number of computations " + str(limit)
+ " limit " + str(len(self.computations))
)
ns = self.computations[:limit]
previous_args = self.args.copy()
current = ns[0]
current.args = previous_args
for n in ns[1:]:
n.args = current.output
current = n
return ns
def compute_until_with_arg(self, limit: int, args: np.ndarray):
"""
"""
if limit > len(self.computations):
raise ValueError(
"Limit out of bounds for available number of computations " + str(limit)
+ " limit " + str(len(self.computations))
)
ns = self.computations[:limit]
previous_args = args.copy()
current = ns[0]
current.args = previous_args
for n in ns[1:]:
n.args = current.output
current = n
return ns
def delta_from(self, start: int):
"""
"""
self.compute()
if start >= len(self.computations):
raise ValueError("Start out of bounds " + str(start) +" number of "+
" computations: "+ str(len(self.computations)))
current = self.computations[start]
current_d = current.d
for n in self.computations[start+1:]:
d = n.d
current_d = np.matmul(d,current_d)
return current_d
@property
def output(self):
self.compute()
return self.computations[-1].output
@property
def delta_backwards(self):
"backward accumulation of derivative"
self.compute()
reversed_cs = list(reversed(self.computations))
last = reversed_cs[0]
ld = last.d
for n in reversed_cs[1:]:
d = n.d
ld = np.matmul(ld, d)
return ld
@property
def delta(self):
"forward accumulation of derivative"
return self.delta_from(start=0)
# test layer
def mx(x: np.ndarray): return x * x
def gx(x: np.ndarray): return x + 5
layer = Layer(flst=[mx, gx], arg=np.array([1,0,3], dtype=np.float))
"""
f'(x): [
[2. 0. 0.]
[0. 0. 0.]
[0. 0. 6.]
]
g'(x): [
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
]
"""
print(layer.output)
print(np.around(layer.delta_backwards, 3))
print(np.around(layer.delta, 3))
```
Let's implement a linear regression layer, just to get a feel for how to do familiar computations with computation graphs.
```
class LinearRegressionLayer(Layer):
def __init__(self, arg: np.ndarray):
""
self.mx = np.random.randn(*arg.shape)
self.b = np.zeros_like(self.mx)
def m_x(x: np.ndarray): return x * self.mx
def b_x(x: np.ndarray): return x + self.b
def mx_b(x: np.ndarray): return b_x(m_x(x))
super().__init__(flst=[m_x, b_x], arg=arg.copy())
@property
def predict(self):
"""
y = mx + b = f(x)
y = f(x)
mx = M(x)
+b = B(x)
f(x) = B(M(x)) = mx + b
"""
return self.output
arg = np.array([[6, 5], [2, 1], [9, 3]], dtype=np.float)
LRL = LinearRegressionLayer(arg=arg)
# ideal values
lrl_slope = np.array([[0.5, 0.5], [0.5, 0.5], [3, 3]], dtype=np.float)
lrl_intercept = np.array([[1,1], [1,1], [0,0]], dtype=np.float)
lrl_target = np.array([[4, 3.5], [2, 1.5], [27, 9]])
print("prediction: \n", LRL.output)
print("expected output: \n", lrl_target)
print("derivative matrix: \n", np.around(LRL.mx, 3))
print("expected derivative matrix: \n", lrl_slope)
print("layer derivative/slope: \n", np.around(LRL.delta, 3))
```
Congragulations you have implemented your first fully functional neural network with a single layer.
Now you have the correct structure, but the results should be mostly gibbrish.
That is absolutely normal, because we have not yet seen how to **train** the neural network.
We will see that in another tutorial, because I am too sleepy now.
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.