text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Time series forecasting using ARIMA ### Import necessary libraries ``` %matplotlib notebook import numpy import pandas import datetime import sys import time import matplotlib.pyplot as ma import statsmodels.tsa.seasonal as st import statsmodels.tsa.arima_model as arima import statsmodels.tsa.stattools as tools ``` ### Load necessary CSV file ``` try: ts = pandas.read_csv('../../datasets/srv-1-art-5m.csv') except: print("I am unable to connect to read .csv file", sep=',', header=1) ts.index = pandas.to_datetime(ts['ts']) # delete unnecessary columns del ts['id'] del ts['ts'] del ts['min'] del ts['max'] del ts['sum'] del ts['cnt'] del ts['p50'] del ts['p95'] del ts['avg'] # print table info ts.info() ``` ### Get values from specified range ``` ts = ts['2018-06-16':'2018-07-15'] ``` ### Remove possible zero and NA values (by interpolation) We are using MAPE formula for counting the final score, so there cannot occure any zero values in the time series. Replace them with NA values. NA values are later explicitely removed by linear interpolation. ``` def print_values_stats(): print("Zero Values:\n",sum([(1 if x == 0 else 0) for x in ts.values]),"\n\nMissing Values:\n",ts.isnull().sum(),"\n\nFilled in Values:\n",ts.notnull().sum(), "\n") idx = pandas.date_range(ts.index.min(), ts.index.max(), freq="5min") ts = ts.reindex(idx, fill_value=None) print("Before interpolation:\n") print_values_stats() ts = ts.replace(0, numpy.nan) ts = ts.interpolate(limit_direction="both") print("After interpolation:\n") print_values_stats() ``` ### Plot values ``` # Idea: Plot figure now and do not wait on ma.show() at the end of the notebook ma.ion() ma.show() fig1 = ma.figure(1) ma.plot(ts, color="blue") ma.draw() try: ma.pause(0.001) # throws NotImplementedError, ignore it except: pass ``` ### Ignore timestamps, make the time series single dimensional Since now the time series is represented by continuous single-dimensional Python list. ARIMA does not need timestamps or any irrelevant data. ``` dates = ts.index # save dates for further use ts = [x[0] for x in ts.values] ``` ### Split time series into train and test series We have decided to split train and test time series by two weeks. ``` train_data_length = 12*24*7 ts_train = ts[:train_data_length] ts_test = ts[train_data_length+1:] ``` ### Estimate integrated (I) parameter Check time series stationarity and estimate it's integrated parameter (maximum integration value is 2). The series itself is highly seasonal, so we can assume that the time series is not stationary. ``` def check_stationarity(ts, critic_value = 0.05): try: result = tools.adfuller(ts) return result[0] < 0.0 and result[1] < critic_value except: # Program may raise an exception when there are NA values in TS return False integrate_param = 0 ts_copy = pandas.Series(ts_train, copy=True) # Create copy for stationarizing while not check_stationarity(ts_copy) and integrate_param < 2: integrate_param += 1 ts_copy = ts_copy - ts_copy.shift() ts_copy.dropna(inplace=True) # Remove initial NA values print("Estimated integrated (I) parameter: ", integrate_param, "\n") ``` ### Print ACF and PACF graphs for AR(p) and MA(q) order estimation AutoCorellation and Parcial AutoCorellation Functions are necessary for ARMA order estimation. Configure the *NLagsACF* and *NlagsPACF* variables for number of lagged values in ACF and PACF graphs. ``` def plot_bar(ts, horizontal_line=None): ma.bar(range(0, len(ts)), ts, width=0.5) ma.axhline(0) if horizontal_line != None: ma.axhline(horizontal_line, linestyle="-") ma.axhline(-horizontal_line, linestyle="-") ma.draw() try: ma.pause(0.001) # throws NotImplementedError, ignore it except: pass NlagsACF = 100 NLagsPACF = 50 # ACF ma.figure(2) plot_bar(tools.acf(ts_train, nlags=NlagsACF), 1.96 / numpy.sqrt(len(ts))) # PACF ma.figure(3) plot_bar(tools.pacf(ts_train, nlags=NLagsPACF), 1.96 / numpy.sqrt(len(ts))) ``` ### ARIMA order estimation According to the Box-Jenkins model (https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc446.htm) we assumed that this time series is an AR(p) model. We can that the ACF graph is exponentially decreasing and followed by some mixture of sinusoid. The PACF graph shows that there is one significant spike at index 0. We can also see large anomalies in the time series, so in my opinion we should consider ARIMA(1,1,0) model, even though it should be already stationary (we are aware of overdifferencing problem). You can specify how many values you want to use for ARIMA model fitting (by setting *N_train_data* variable) and how many new values you want to predict in single step (by setting *N_values_to_forecast* variable). ### Prediction configuration ``` ARIMA_order = (1,1,0) M_train_data = sys.maxsize N_values_to_forecast = 1 ``` ### Forecast new values Unexpectedly, we have a very large time series (over 8 thousand samples), so the forecasting takes much time. ``` predictions = [] confidence = [] print("Forecasting started...") start_time = time.time() ts_len = len(ts) for i in range(train_data_length+1, ts_len, N_values_to_forecast): try: start = i-M_train_data if i-M_train_data >= 0 else 0 arima_model = arima.ARIMA(ts[start:i], order=ARIMA_order).fit(disp=0) forecast = arima_model.forecast(steps=N_values_to_forecast) for j in range(0, N_values_to_forecast): predictions.append(forecast[0][j]) confidence.append(forecast[2][j]) except: print("Error during forecast: ", i, i+N_values_to_forecast) # Push back last successful predictions for j in range(0, N_values_to_forecast): predictions.append(predictions[-1] if len(predictions) > 0 else 0) confidence.append(confidence[-1] if len(confidence) > 0 else 0) print("Forecasting finished") print("Time elapsed: ", time.time() - start_time) ``` ### Count mean absolute percentage error We use MAPE (https://www.forecastpro.com/Trends/forecasting101August2011.html) instead of MSE because the result of MAPE does not depend on size of values. ``` values_sum = 0 for value in zip(ts_test, predictions): actual = value[0] predicted = value[1] values_sum += abs((actual - predicted) / actual) values_sum *= 100/len(predictions) print("MAPE: ", values_sum, "%\n") ``` ### Plot forecasted values ``` fig2 = ma.figure(4) ma.plot(ts_test, color="blue") ma.plot(predictions, color="red") ts_len = len(ts) date_offset_indices = ts_len // 6 num_date_ticks = ts_len // date_offset_indices + 1 ma.xticks(range(0, ts_len, date_offset_indices), [x.date().strftime('%Y-%m-%d') for x in dates[::date_offset_indices]]) ma.draw() ```
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/FeatureCollection/simplify_polygons.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/FeatureCollection/simplify_polygons.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=FeatureCollection/simplify_polygons.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/FeatureCollection/simplify_polygons.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The following script checks if the geehydro package has been installed. If not, it will install geehydro, which automatically install its dependencies, including earthengine-api and folium. ``` import subprocess try: import geehydro except ImportError: print('geehydro package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geehydro']) ``` Import libraries ``` import ee import folium import geehydro ``` Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. ``` try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize() ``` ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. ``` Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID') ``` ## Add Earth Engine Python script ``` waterSurface = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') waterChange = waterSurface.select('transition') # Select Permanent Water Only: Permanent_Water = 1 # value 1 represents pixels of permenant water, no change waterMask = waterChange.eq(Permanent_Water) # Water mask boolean = 1 to detect whater bodies # Map.setCenter(24.43874, 61.58173, 10) # Map.addLayer(waterMask, {}, 'Water Mask') # Map.centerObject(masked) OnlyLakes = waterMask.updateMask(waterMask) roi = ee.Geometry.Polygon( [[[22.049560546875, 61.171214253920965], [22.0330810546875, 60.833021871926185], [22.57415771484375, 60.83168327936567], [22.5714111328125, 61.171214253920965]]]) classes = OnlyLakes.reduceToVectors(**{ 'reducer': ee.Reducer.countEvery(), 'geometry': roi, 'scale': 30, 'maxPixels': 1e10 }) simpleClasses = classes.geometry().simplify(50) Map.centerObject(ee.FeatureCollection(roi), 10) Map.addLayer(ee.Image().paint(classes, 0, 2),{'palette': 'red'}, "original") Map.addLayer(ee.Image().paint(simpleClasses, 0, 2),{'palette': 'blue'}, "simplified") ``` ## Display Earth Engine data layers ``` Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map ```
github_jupyter
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/education-toolkit/blob/main/02_ml-demos-with-gradio.ipynb) 💡 **Welcome!** We’ve assembled a toolkit that university instructors and organizers can use to easily prepare labs, homework, or classes. The content is designed in a self-contained way such that it can easily be incorporated into the existing curriculum. This content is free and uses widely known Open Source technologies (`transformers`, `gradio`, etc). Alternatively, you can request for someone on the Hugging Face team to run the tutorials for your class via the [ML demo.cratization tour](https://huggingface2.notion.site/ML-Demo-cratization-tour-with-66847a294abd4e9785e85663f5239652) initiative! You can find all the tutorials and resources we’ve assembled [here](https://huggingface2.notion.site/Education-Toolkit-7b4a9a9d65ee4a6eb16178ec2a4f3599). # Tutorial: Build and Host Machine Learning Demos with Gradio ⚡ & Hugging Face 🤗 **Learning goals:** The goal of this tutorial is to learn How To 1. Build a quick demo for your machine learning model in Python using the `gradio` library 2. Host the demos for free with Hugging Face Spaces 3. Add your demo to the Hugging Face org for your class or conference. This includes: * A setup step for instructors (or conference organizers) * Upload instructions for students (or conference participants) **Duration**: 20-40 minutes **Prerequisites:** Knowledge of Python and basic familiarity with machine learning **Author**: [Abubakar Abid](https://twitter.com/abidlabs) (feel free to ping me with any questions about this tutorial) All of these steps can be done for free! All you need is an Internet browser and a place where you can write Python 👩‍💻 ## Why Demos? **Demos** of machine learning models are an increasingly important part of machine learning _courses_ and _conferences_. Demos allow: * model developers to easily **present** their work to a wide audience * increase **reproducibility** of machine learning research * diverse users to more easily **identify and debug** failure points of models As a quick example of what we would like to build, check out the [Keras Org on Hugging Face](https://huggingface.co/keras-io), which includes a description card and a collection of Models and Spaces built by Keras community. Any Space can be opened in your browser and you can use the model immediately, as shown here: ![](https://i.ibb.co/7y6DGjB/ezgif-5-cc52b7e590.gif) ## 1. Build Quick ML Demos in Python Using the Gradio Library `gradio` is a handy Python library that lets you build web demos simply by specifying the list of input and output **components** expected by your machine learning model. What do I mean by input and output components? Gradio comes with a bunch of predefined components for different kinds of machine learning models. Here are some examples: * For an **image classifier**, the expected input type is an `Image` and the output type is a `Label`. * For a **speech recognition model**, the expected input component is an `Microphone` (which lets users record from the browser) or `Audio` (which lets users drag-and-drop audio files), while the output type is `Text`. * For a **question answering model**, we expect **2 inputs**: [`Text`, `Text`], one textbox for the paragraph and one for the question, and the output type is a single `Text` corresponding to the answer. You get the idea... (for all of the supported components, [see the docs](https://gradio.app/docs/)) In addition to the input and output types, Gradio expects a third parameter, which is the prediction function itself. This parameter can be ***any* regular Python function** that takes in parameter(s) corresponding to the input component(s) and returns value(s) corresponding to the output component(s) Enough words. Let's see some code! ``` # First, install Gradio !pip install --quiet gradio import numpy as np def sepia(image): sepia_filter = np.array( [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]] ) sepia_img = image.dot(sepia_filter.T) sepia_img /= sepia_img.max() return sepia_img import gradio as gr # Write 1 line of Python to create a simple GUI gr.Interface(fn=sepia, inputs="image", outputs="image").launch(); ``` Running the code above should produce a simple GUI inside this notebook allowing you to type example inputs and see the output returned by your function. Notice that we define an `Interface` using the 3 ingredients mentioned earlier: * A function * Input component(s) * Output component(s) This is a simple example for images, but the same principle holds true for any other kind of data type. For example, here is an interface that generates a musical tone when provided a few different parameters (the specific code inside `generate_tone()` is not important for the purpose of this tutorial): ``` import numpy as np import gradio as gr def generate_tone(note, octave, duration): sampling_rate = 48000 a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9) frequency = a4_freq * 2 ** (tones_from_a4 / 12) audio = np.linspace(0, int(duration), int(duration) * sampling_rate) audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16) return sampling_rate, audio gr.Interface( generate_tone, [ gr.Dropdown(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"], type="index"), gr.Slider(4, 6, step=1), gr.Number(value=1, label="Duration in seconds"), ], "audio", title="Generate a Musical Tone!" ).launch() ``` **Challenge #1**: build a Gradio demo that takes in an image and returns the same image *flipped upside down* in less than 10 lines of Python code. There are a lot more examples you can try in Gradio's [getting started page](https://gradio.app/getting_started/), which cover additional features such as: * Adding example inputs * Adding _state_ (e.g. for chatbots) * Sharing demos easily using one parameter called `share` (<-- this is pretty cool 😎) It is especially easy to demo a `transformers` model from Hugging Face's Model Hub, using the special `gr.Interface.load` method. Let's try a text-to-speech model built by Facebook: ``` import gradio as gr gr.Interface.load("huggingface/facebook/fastspeech2-en-ljspeech").launch(); ``` Here is the code to build a demo for [GPT-J](https://huggingface.co/EleutherAI/gpt-j-6B), a large language model & add a couple of examples inputs: ``` import gradio as gr examples = [["The Moon's orbit around Earth has"], ["There once was a pineapple"]] gr.Interface.load("huggingface/EleutherAI/gpt-j-6B", examples=examples).launch(); ``` **Challenge #2**: Go to the [Hugging Face Model Hub](https://huggingface.co/models), and pick a model that performs one of the other tasks supported in the `transformers` library (other than the two you just saw: text generation or text-to-speech). Create a Gradio demo for that model using `gr.Interface.load`. ## 2. Host the Demo (for free) on Hugging Face Spaces Once you made a Gradio demo, you can host it permanently on Hugging Spaces very easily: Here are the steps to that (shown in the GIF below): A. First, create a Hugging Face account if you do not already have one, by visiting https://huggingface.co/ and clicking "Sign Up" B. Once you are logged in, click on your profile picture and then click on "New Space" underneath it to get to this page: https://huggingface.co/new-space C. Give your Space a name and a license. Select "Gradio" as the Space SDK, and then choose "Public" if you are fine with everyone accessing your Space and the underlying code D. Then you will find a page that provides you instructions on how to upload your files into the Git repository for that Space. You may also need to add a `requirements.txt` file to specify any Python package dependencies. E. Once you have pushed your files, that's it! Spaces will automatically build your Gradio demo allowing you to share it with anyone, anywhere! ![GIF](https://huggingface.co/blog/assets/28_gradio-spaces/spaces-demo-finalized.gif) You can even embed your Gradio demo on any website -- in a blog, a portfolio page, or even in a colab notebook, like I've done with a Pictionary sketch recognition model below: ``` from IPython.display import IFrame IFrame(src='https://hf.space/gradioiframe/abidlabs/Draw/+', width=1000, height=800) ``` **Challenge #3**: Upload your Gradio demo to Hugging Face Spaces and get a permanent URL for it. Share the permanent URL with someone (a colleague, a collaborator, a friend, a user, etc.) -- what kind of feedback do you get on your machine learning model? ## 3. Add your demo to the Hugging Face org for your class or conference #### **Setup** (for instructors or conference organizers) A. First, create a Hugging Face account if you do not already have one, by visiting https://huggingface.co/ and clicking "Sign Up" B. Once you are logged in, click on your profile picture and then click on "New Organization" underneath it to get to this page: https://huggingface.co/organizations/new C. Fill out the information for your class or conference. We recommend creating a separate organization each time that a class is taught (for example, "Stanford-CS236g-20222") and for each year of the conference. D. Your organization will be created and now now users will be able request adding themselves to your organizations by visiting the organization page. E. Optionally, you can change the settings by clicking on the "Organization settings" button. Typically, for classes and conferences, you will want to navigate to `Settings > Members` and set the "Default role for new members" to be "write", which allows them to submit Spaces but not change the settings. #### For students or conference participants A. Ask your instructor / coneference organizer for the link to the Organization page if you do not already have it B. Visit the Organization page and click "Request to join this org" button, if you are not yet part of the org. C. Then, once you have been approved to join the organization (and built your Gradio Demo and uploaded it to Spaces -- see Sections 1 and 2), then simply go to your Space and go to `Settings > Rename or transfer this space` and then select the organization name under `New owner`. Click the button and the Space will now be added to your class or conference Space!
github_jupyter
# Time Domain and Gating ## Intro This notebooks demonstrates how to use [scikit-rf](www.scikit-rf.org) for time-domain analysis and gating. A quick example is given first, followed by a more detailed explanation. S-parameters are measured in the frequency domain, but can be analyzed in time domain if you like. In many cases, measurements are not made down to DC. This implies that the time-domain transform is not complete, but it can be very useful non-theless. A major application of time-domain analysis is to use *gating* to isolate a single response in space. More information about the details of time domain analysis see [1]. References * [1] Agilent Time Domain Analysis Using a Network Analyzer (Application Note 1287-12) [pdf](http://cp.literature.agilent.com/litweb/pdf/5989-5723EN.pdf) ## Quick Example ``` import skrf as rf %matplotlib inline rf.stylely() from pylab import * # load data for the waveguide to CPW probe probe = rf.Network('../metrology/oneport_tiered_calibration/probe.s2p') # we will focus on s11 s11 = probe.s11 # time-gate the first largest reflection s11_gated = s11.time_gate(center=0, span=.2) s11_gated.name='gated probe' # plot frequency and time-domain s-parameters figure(figsize=(8,4)) subplot(121) s11.plot_s_db() s11_gated.plot_s_db() title('Frequency Domain') subplot(122) s11.plot_s_db_time() s11_gated.plot_s_db_time() title('Time Domain') tight_layout() ``` ## Interpreting Time Domain Out DUT in this example is a waveguide-to-CPW probe, that was measured in [this other example](./oneport_tiered_calibration/One Port Tiered Calibration.ipynb). ``` # load data for the waveguide to CPW probe probe = rf.Network('../metrology/oneport_tiered_calibration/probe.s2p') probe ``` Note there are two time-domain plotting functions in scikit-rf: * `Network.plot_s_db_time()` * `Network.plot_s_time_db()` The difference is that the former, `plot_s_db_time()`, employs windowing before plotting to enhance impluse resolution. Windowing will be discussed in a bit, but for now we just use `plot_s_db_time()`. Plotting all four s-parameters of the probe in both frequency and time-domain. ``` # plot frequency and time-domain s-parameters figure(figsize=(8,4)) subplot(121) probe.plot_s_db() title('Frequency Domain') subplot(122) probe.plot_s_db_time() title('Time Domain') tight_layout() ``` Focusing on the reflection coefficient from the waveguide port (s11), you can see there is an interference pattern present. ``` probe.plot_s_db(0,0) title('Reflection Coefficient From \nWaveguide Port') ``` This ripple is evidence of several discrete reflections. Plotting s11 in the time-domain allows us to see where, or *when*, these reflections occur. ``` probe_s11 = probe.s11 probe_s11.plot_s_db_time(0,0) title('Reflection Coefficient From \nWaveguide Port, Time Domain') ylim(-100,0) ``` From this plot we can see two dominant reflections; * one at $t=0$ns (the test-port) * and another at $t=.2$ns (who knows?). ## Gating The Reflection of Interest To isolate the reflection from the waveguide port, we can use time-gating. This can be done by using the method `Network.time_gate()`, and provide it an appropriate center and span (in ns). To see the effects of the gate, both the original and gated reponse are compared. ``` probe_s11_gated = probe_s11.time_gate(center=0, span=.2) probe_s11_gated.name='gated probe' s11.plot_s_db_time() s11_gated.plot_s_db_time() ``` Next, compare both responses in frequency domain to see the effect of the gate. ``` s11.plot_s_db() s11_gated.plot_s_db() ``` ### Auto-gate The time-gating method in `skrf` has an auto-gating feature which can also be used to gate the largest reflection. When no gate parameters are provided, `time_gate()` does the following: 1. find the two largest peaks * center the gate on the tallest peak * set span to distance between two tallest peaks You may want to plot the gated network in time-domain to see what the determined gate shape looks like. ``` title('Waveguide Interface of Probe') s11.plot_s_db(label='original') s11.time_gate().plot_s_db(label='autogated') #autogate on the fly ``` Might see how the autogate does on the other proben interface, ``` title('Other Interface of Probe') probe.s22.plot_s_db() probe.s22.time_gate().plot_s_db() ``` ## Determining Distance To make time-domain useful as a diagnostic tool, one would like to convert the x-axis to distance. This requires knowledge of the propagation velocity in the device. **skrf** provides some transmission-line models in the module [skrf.media](http://scikit-rf.readthedocs.org/en/latest/reference/media/index.html), which can be used for this. **However...** For dispersive media, such as rectangular waveguide, the phase velocity is a function of frequency, and transforming time to distance is not straightforward. As an approximation, you can normalize the x-axis to the speed of light. Alternativly, you can simulate the a known device and compare the two time domain responses. This allows you to attribute quantatative meaning to the axes. For example, you could create an ideal delayed load as shown below. Note: the magnitude of a response *behind* a large impulse doesn not have meaningful units. ``` from skrf.media import RectangularWaveguide # create a rectangular waveguide media to gererate a theoretical network wr1p5 = RectangularWaveguide(frequency=probe.frequency, a=15*rf.mil,z0=1) # create an ideal delayed load, parameters are adjusted until the # theoretical response agrees with the measurement theory = wr1p5.delay_load(Gamma0=rf.db_2_mag(-20), d=2.4, unit='cm') probe.plot_s_db_time(0,0, label = 'Measurement') theory.plot_s_db_time(label='-20dB @ 2.4cm from test-port') ylim(-100,0) ``` This plot demonstrates a few important points: * the theortical delayed load is not a perfect impulse in time. This is due to the dispersion in waveguide. * the peak of the magnitude in time domain is not identical to that specified, also due to disperison (and windowing). ## What the hell is Windowing? The `'plot_s_db_time()'` function does a few things. 1. windows the s-parameters. * converts to time domain * takes magnitude component, convert to dB * calculates time-axis s * plots A word about step 1: **windowing**. A FFT represents a signal with a basis of periodic signals (sinusoids). If your frequency response is not periodic, which in general it isnt, taking a FFT will introduces artifacts in the time-domain results. To minimize these effects, the frequency response is *windowed*. This makes the frequency response more periodic by tapering off the band-edges. Windowing is just applied to improve the plot appearance,d it does not affect the original network. In skrf this can be done explicitly using the `'windowed()'` function. By default this function uses the hamming window, but can be adjusted through arguments. The result of windowing is show below. ``` probe_w = probe.windowed() probe.plot_s_db(0,0, label = 'Original') probe_w.plot_s_db(0,0, label = 'Windowed') ``` Comparing the two time-domain plotting functions, we can see the difference between windowed and not. ``` probe.plot_s_time_db(0,0, label = 'Original') probe_w.plot_s_time_db(0,0, label = 'Windowed') ```
github_jupyter
# Getting object labels and positions ### Generating ZTF cutouts requires knowing object positions (RA and DEC), and image classification requires knowing truth labels ('star', 'galaxy'). ZTF catalogs do *not* include type labels, so we are unable to identify objects in the ZTF catalog as stars or galaxies. ### In this notebook, we show how to crossmatch catalogs with another survey (the Legacy Survey), to get the sky positions and truth labels for various objects. We then apply various data cuts that return us a sample of stars and galaxies that we know will be visible in the ZTF survey data (and therefore, able to make cutouts from). More information about the Legacy Survey: https://www.legacysurvey.org ``` import astropy.io.fits as fits import pandas as pd import matplotlib.pyplot as plt import numpy as np from astropy.coordinates import search_around_sky, SkyCoord from astropy import units as u ``` ### Import the data using a URL to the full data you would like to use. We use a Legacy Survey "sweep" catalog that contains all objects between ra = (0, 10) degrees and dec = (-5, 0) degrees. ***Note:*** When crossmatching catalogs with other surveys, you need to make sure their "footprints", or where they are imaging the sky, overlap. If you pick a region where ZTF doesn't have data, you won't be able to make a cutout of that object. More information on Legacy Survey sweep catalogs: https://www.legacysurvey.org/dr7/files/#sweep-catalogs ``` target_url = 'https://portal.nersc.gov/cfs/cosmo/data/legacysurvey/dr9/south/sweep/9.0/sweep-000m005-010p000.fits' data_raw = fits.getdata(target_url, header=True) data = data_raw[0] ``` ### Save all galaxy types as 'gals', and all stars as 'stars' #### Galaxy type labels: - "REX" = round exponential galaxy model - "DEV" = de Vaucouleurs model - "EXP" = exponential model - "SER" = Sersic model #### Star type label: - "PSF" = point source More about morphological type determination here: https://www.legacysurvey.org/dr9/catalogs/ (bottom) ``` gal_mask = (data['type'] == 'REX') | (data['type'] == 'DEV') | (data['type'] == 'EXP') | (data['type'] == 'SER') gals = data[gal_mask] print("# of all galaxies in catalog: ", len(gals)) psf_mask = (data['TYPE'] == 'PSF') stars = data[psf_mask] print("# of all stars in catalog: ", len(stars)) ``` ### Optional "right ascension" (RA) and "declination" (DEC) cut: RA and DEC are to the sky, what longitutde and lattitude are to Earth. A helpful introduction to RA and DEC can be found here: https://skyandtelescope.org/astronomy-resources/right-ascension-declination-celestial-coordinates/ Even though you generated a sweep file of a certain region, you may only want objects within a certain ra and dec of that. Let's cut our 10° (RA) by 5° (DEC) region down to a 5° by 5° region, with a cut to RA: ``` gals = gals[(gals['RA'] > 5) & (gals['RA'] < 10)] stars = stars[(stars['RA'] > 5) & (stars['RA'] < 10)] ``` ### Magnitude cuts: Astronomers make magnitude cuts to objects according to the "limiting magnitude" of a telecope. Limiting magnitude is essentially the magnitude of the faintest object the telescope can detect. Flux and magnitude are mathematically related and describe the "brightness" of the object. The Legacy Survey suppplies us with fluxes that we must convert to magnitudes. **It is important to note that the magnitude system is reversed! (i.e. a lower magnitude corresponds to a brighter object).** For more information on the magnitude system: https://www.e-education.psu.edu/astro801/content/l4_p5.html. ***Note:*** Converting flux to magnitude involves taking the log of the flux (which means we don't want negative values). Flux should always be positive, but in very rare cases, like when you know an object is there in another band, but aren't seeing it in the current image, flux can show up as a negative value in the catalog. For that reason, we first apply a cut to ensure flux > 0. ``` # Ensure all fluxes > 0 for mag conversion gals = gals[(gals['FLUX_G'] > 0) & (gals['FLUX_R'] > 0) & (gals['FLUX_Z'] > 0)] stars = stars[(stars['FLUX_G'] > 0) & (stars['FLUX_R'] > 0) & (stars['FLUX_Z'] > 0)] ``` Once there are no negative values, flux can be converted to magnitude using: $Magnitude = 22.5-2.5log_{10}(Flux)$ ``` # Calculate the magnitudes from the fluxes gal_mag_g = 22.5-2.5*np.log10(np.array(gals['FLUX_G'])) gal_mag_r = 22.5-2.5*np.log10(np.array(gals['FLUX_R'])) gal_mag_z = 22.5-2.5*np.log10(np.array(gals['FLUX_Z'])) star_mag_g = 22.5-2.5*np.log10(np.array(stars['FLUX_G'])) star_mag_r = 22.5-2.5*np.log10(np.array(stars['FLUX_R'])) star_mag_z = 22.5-2.5*np.log10(np.array(stars['FLUX_Z'])) ``` Because we will be obtaining object positions from Legacy, and then using those positions to get their images from ZTF, we want to make cuts on the ZTF limiting magnitudes, to ensure ZTF can detect them! The limiting magnitudes for ZTF are: $g<20.8$, $r<20.6$, and $i<19.9$ This means that in the g-band, ZTF can detect objects as faint as magnitude 20.8, and so-on. More info on photometric bands here: https://en.wikipedia.org/wiki/Photometric_system ***Note***: ZTF uses the g, r, and i bands, while the Legacy Survey consists of g-band, r-band, and z-band images. The further down the list the band, less faint objects can be detect (*usually*). We can roughly estimate that if ZTF can detect i-band to magnitude 19.9, it can probably detect in z-band to *roughly* 19.5. For each band we also round down a bit as we don't want to test the classifier on the faintest objects, *yet*. ``` # Make a magnitude cut to satisfy (and undershoot) the limiting magnitude cutoffs for ZTF gals = gals[(gal_mag_g < 20.5) & (gal_mag_r < 20) & (gal_mag_z < 19)] stars = stars[(star_mag_g < 20.5) & (star_mag_r < 20) & (star_mag_z < 19)] print("# of galaxies after magnitude cuts: ", len(gals)) print("# of stars after magnitude cuts: ", len(stars)) ``` ### Basic blend cut: A "blend" simply means that there are two objects overlapping each other in the line-of-sight. Because the classifier uses "cutouts" (each image consists of just one object), we don't want any images with more than one object. A "basic" blend cut can be made on "fractional flux", a value that tells you if there are flux contributions from nearby sources. A value closer to 0 means there is little flux contribution from nearby objects, whereas a value closer to 1 means the flux of the object is almost *entirely* from nearby sources. ***Note:*** Objects with negative flux, or objects with a neighbor with negative flux, may cause a negative frac flux, so again, we cut out the negative values. ``` # Discard objects with high FRACFLUX's, as they are typically blends gals = gals[(gals['FRACFLUX_G'] <= .1) & (gals['FRACFLUX_G'] >= 0) & (gals['FRACFLUX_R'] <= .1) & (gals['FRACFLUX_R'] >= 0) & (gals['FRACFLUX_Z'] <= .1) & (gals['FRACFLUX_Z'] >= 0)] stars = stars[(stars['FRACFLUX_G'] <= .1) & (stars['FRACFLUX_G'] >= 0) & (stars['FRACFLUX_R'] <= .1) & (stars['FRACFLUX_R'] >= 0) & (stars['FRACFLUX_Z'] <= .1) & (stars['FRACFLUX_Z'] >= 0)] print("# of galaxies after basic blend cuts: ", len(gals)) print("# of stars after basic blend cuts: ", len(stars)) ``` ### More sophisticated blend cut: One can do a *better* blend cut by compairing each objects RA and DEC to each other objects RA and DEC, and removing every object that is within a specified distance of another object. We are making square cutouts of 20" by 20". ***Note:*** The double quote here means "arc second", where $1"=\frac{1}{3600}°$ Astropy's `search_around_sky` searches in a circular region. If our square is 20" x 20", we need the radius of a circle that can inscribe our cutout square: $20\sqrt{2}$. (Because cutouts are always in the center of the image, we terchnically only need to remove objects that are within *half* a cutout length of each other. But let's do the full cutout length anyways.) Once we determine which objects are within a cutout width of another object, we cut them out! ``` # Some data manipulation for changing data from a fits recarray to a pandas DataFrame gal_ra = gals['RA'].byteswap().newbyteorder() gal_dec = gals['DEC'].byteswap().newbyteorder() gal_type = gals['TYPE'].byteswap().newbyteorder() star_ra = stars['RA'].byteswap().newbyteorder() star_dec = stars['DEC'].byteswap().newbyteorder() star_type = stars['TYPE'].byteswap().newbyteorder() # Save data as pandas DataFrame for using astropy data = pd.DataFrame({'ra': np.concatenate((gal_ra, star_ra)), 'dec': np.concatenate((gal_dec, star_dec)), 'type': np.concatenate((gal_type, star_type))}) # Define our coordinate system c = SkyCoord(ra=data['ra']*u.degree, dec=data['dec']*u.degree) # Use search_around_sky to see if any two objects are within half a cutout width of each other idx1, idx2, sep2, dist3 = search_around_sky(c, c, (20*np.sqrt(2))*u.arcsec) # Get a list of unique indices where blends occur idx = (idx1 != idx2) idx1 = idx1[idx] # Drop these rows from our dataframe, as we don't want blends! data.drop(data.index[idx1], axis=0, inplace=True) # Separate back into galaxies and stars for writing to .csv gal_mask2 = (data['type'] == 'REX') | (data['type'] == 'DEV') | (data['type'] == 'EXP') | (data['type'] == 'SER') psf_mask2 = (data['type'] == 'PSF') gals = data[gal_mask2] stars = data[psf_mask2] print("# of galaxies after sophisticated blend cuts: ", len(gals)) print("# of stars after sophisticated blend cuts: ", len(stars)) ``` **We now have a complete dataset of stars and galaxies that are:** - Within the ra and dec region we want - Have magnitudes that are detectable by ZTF - Should not be blended with other objects ### Randomly sample 10k galaxies and 10k stars (this should be plenty), and save their RA, DEC, and type labels to a .csv for use in the next step! ``` # Get data into a pandas dataframe for easy writing to .csv gals = pd.DataFrame({'ra': gals['ra'], 'dec': gals['dec'], 'type': gals['type']}) stars = pd.DataFrame({'ra': stars['ra'], 'dec': stars['dec'], 'type': stars['type']}) # Sample 10k of each object final_gals = gals.sample(10000) final_stars = stars.sample(10000) final_stars.to_csv('stars.csv', index=False) final_gals.to_csv('gals.csv', index=False) ```
github_jupyter
<a href="http://cocl.us/pytorch_link_top"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " /> </a> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/cc-logo-square.png" width="200" alt="cognitiveclass.ai logo" /> <h1>Torch Tensors in 1D</h1> <h2>Table of Contents</h2> <p>In this lab, you will learn the basics of tensor operations. Tensors are an essential part of PyTorch; there are complex mathematical objects in and of themselves. Fortunately, most of the intricacies are not necessary. In this section, you will compare them to vectors and numpy arrays.</p> <ul> <li><a href="#Types_Shape">Types and Shape</a></li> <li><a href="#Index_Slice">Indexing and Slicing</a></li> <li><a href="#Tensor_Func">Tensor Functions</a></li> <li><a href="#Tensor_Op">Tensor Operations</a></li> </ul> <p>Estimated Time Needed: <b>25 min</b></p> <hr> <h2>Preparation</h2> Import the following libraries that you'll use for this lab: ``` # These are the libraries will be used for this lab. import torch import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline ``` This is the function for plotting diagrams. You will use this function to plot the vectors in Coordinate system. ``` # Plot vecotrs, please keep the parameters in the same length # @param: Vectors = [{"vector": vector variable, "name": name of vector, "color": color of the vector on diagram}] def plotVec(vectors): ax = plt.axes() # For loop to draw the vectors for vec in vectors: ax.arrow(0, 0, *vec["vector"], head_width = 0.05,color = vec["color"], head_length = 0.1) plt.text(*(vec["vector"] + 0.1), vec["name"]) plt.ylim(-2,2) plt.xlim(-2,2) ``` <!--Empty Space for separating topics--> <h2 id="Types_Shape">Types and Shape</h2> You can find the type of the following list of integers <i>[0, 1, 2, 3, 4]</i> by applying the method <code>torch.tensor()</code>: ``` # Convert a integer list with length 5 to a tensor ints_to_tensor = torch.tensor([0, 1, 2, 3, 4]) print("The dtype of tensor object after converting it to tensor: ", ints_to_tensor.dtype) print("The type of tensor object after converting it to tensor: ", ints_to_tensor.type()) ``` As a result, the integer list has been converted to a long tensor. <!--Empty Space for separate topics--> You can find the type of this float list <i>[0.0, 1.0, 2.0, 3.0, 4.0]</i> by applying the method <code>torch.tensor()</code>: ``` # Convert a float list with length 5 to a tensor floats_to_tensor = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0]) print("The dtype of tensor object after converting it to tensor: ", floats_to_tensor.dtype) print("The type of tensor object after converting it to tensor: ", floats_to_tensor.type()) ``` The float list is converted to a float tensor. <b>Note: The elements in the list that will be converted to tensor must have the same type.</b> <!--Empty Space for separating topics--> From the previous examples, you see that <code>torch.tensor()</code> converts the list to the tensor type, which is similar to the original list type. However, what if you want to convert the list to a certain tensor type? <code>torch</code> contains the methods required to do this conversion. The following code converts an integer list to float tensor: ``` # Convert a integer list with length 5 to float tensor new_float_tensor = torch.FloatTensor([0, 1, 2, 3, 4]) new_float_tensor.type() print("The type of the new_float_tensor:", new_float_tensor.type()) ``` <!--Empty Space for separating topics--> You can also convert an existing tensor object (<code><i>tensor_obj</i></code>) to another tensor type. Convert the integer tensor to a float tensor: ``` # Another method to convert the integer list to float tensor old_int_tensor = torch.tensor([0, 1, 2, 3, 4]) new_float_tensor = old_int_tensor.type(torch.FloatTensor) print("The type of the new_float_tensor:", new_float_tensor.type()) ``` <!--Empty Space for separating topics--> The <code><i>tensor_obj</i>.size()</code> helps you to find out the size of the <code><i>tensor_obj</i></code>. The <code><i>tensor_obj</i>.ndimension()</code> shows the dimension of the tensor object. ``` # Introduce the tensor_obj.size() & tensor_ndimension.size() methods print("The size of the new_float_tensor: ", new_float_tensor.size()) print("The dimension of the new_float_tensor: ",new_float_tensor.ndimension()) ``` <!--Empty Space for separating topics--> The <code><i>tensor_obj</i>.view(<i>row, column</i>)</code> is used for reshaping a tensor object.<br> What if you have a tensor object with <code>torch.Size([5])</code> as a <code>new_float_tensor</code> as shown in the previous example?<br> After you execute <code>new_float_tensor.view(5, 1)</code>, the size of <code>new_float_tensor</code> will be <code>torch.Size([5, 1])</code>.<br> This means that the tensor object <code>new_float_tensor</code> has been reshaped from a one-dimensional tensor object with 5 elements to a two-dimensional tensor object with 5 rows and 1 column. ``` # Introduce the tensor_obj.view(row, column) method twoD_float_tensor = new_float_tensor.view(5, 1) print("Original Size: ", new_float_tensor) print("Size after view method", twoD_float_tensor) ``` Note that the original size is 5. The tensor after reshaping becomes a 5X1 tensor analog to a column vector. <b>Note: The number of elements in a tensor must remain constant after applying view.</b> <!--Empty Space for separating topics--> What if you have a tensor with dynamic size but you want to reshape it? You can use <b>-1</b> to do just that. ``` # Introduce the use of -1 in tensor_obj.view(row, column) method twoD_float_tensor = new_float_tensor.view(-1, 1) print("Original Size: ", new_float_tensor) print("Size after view method", twoD_float_tensor) ``` You get the same result as the previous example. The <b>-1</b> can represent any size. However, be careful because you can set only one argument as <b>-1</b>. <!--Empty Space for separating topics--> You can also convert a <b>numpy</b> array to a <b>tensor</b>, for example: ``` # Convert a numpy array to a tensor numpy_array = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) new_tensor = torch.from_numpy(numpy_array) print("The dtype of new tensor: ", new_tensor.dtype) print("The type of new tensor: ", new_tensor.type()) ``` <!--Empty Space for separating topics--> Converting a <b>tensor</b> to a <b>numpy</b> is also supported in PyTorch. The syntax is shown below: ``` # Convert a tensor to a numpy array back_to_numpy = new_tensor.numpy() print("The numpy array from tensor: ", back_to_numpy) print("The dtype of numpy array: ", back_to_numpy.dtype) ``` <code>back_to_numpy</code> and <code>new_tensor</code> still point to <code>numpy_array</code>. As a result if we change <code>numpy_array</code> both <code>back_to_numpy</code> and <code>new_tensor</code> will change. For example if we set all the elements in <code>numpy_array</code> to zeros, <code>back_to_numpy</code> and <code> new_tensor</code> will follow suit. ``` # Set all elements in numpy array to zero numpy_array[:] = 0 print("The new tensor points to numpy_array : ", new_tensor) print("and back to numpy array points to the tensor: ", back_to_numpy) ``` <!--Empty Space for separating topics--> <b>Pandas Series</b> can also be converted by using the numpy array that is stored in <code>pandas_series.values</code>. Note that <code>pandas_series</code> can be any pandas_series object. ``` # Convert a panda series to a tensor pandas_series=pd.Series([0.1, 2, 0.3, 10.1]) new_tensor=torch.from_numpy(pandas_series.values) print("The new tensor from numpy array: ", new_tensor) print("The dtype of new tensor: ", new_tensor.dtype) print("The type of new tensor: ", new_tensor.type()) ``` <!--Empty Space for separating topics--> <h3>Practice</h3> Try to convert <code>your_tensor</code> to a 1X5 tensor. ``` # Practice: convert the following tensor to a tensor object with 1 row and 5 columns your_tensor = torch.tensor([1, 2, 3, 4, 5]) ``` Double-click <b>here</b> for the solution. <!-- your_new_tensor = your_tensor.view(1, 5) print("Original Size: ", your_tensor) print("Size after view method", your_new_tensor) --> <!--Empty Space for separating topics--> <h2 id="Index_Slice">Indexing and Slicing</h2> In Python, <b>the index starts with 0</b>. Therefore, the last index will always be 1 less than the length of the tensor object. You can access the value on a certain index by using the square bracket, for example: ``` # A tensor for showing how the indexs work on tensors index_tensor = torch.tensor([0, 1, 2, 3, 4]) print("The value on index 0:",index_tensor[0]) print("The value on index 1:",index_tensor[1]) print("The value on index 2:",index_tensor[2]) print("The value on index 3:",index_tensor[3]) print("The value on index 4:",index_tensor[4]) ``` <b>Note that the <code>index_tensor[5]</code> will create an error.</b> <!--Empty Space for separating topics--> The index is shown in the following figure: <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter%201/idex_1.png" width="500" alt="Python Index" /> <!--Empty Space for separating topics--> Now, you'll see how to change the values on certain indexes. Suppose you have a tensor as shown here: ``` # A tensor for showing how to change value according to the index tensor_sample = torch.tensor([20, 1, 2, 3, 4]) ``` Assign the value on index 0 as 100: ``` # Change the value on the index 0 to 100 print("Inital value on index 0:", tensor_sample[0]) tensor_sample[0] = 100 print("Modified tensor:", tensor_sample) ``` As you can see, the value on index 0 changes. Change the value on index 4 to 0: ``` # Change the value on the index 4 to 0 print("Inital value on index 4:", tensor_sample[4]) tensor_sample[4] = 0 print("Modified tensor:", tensor_sample) ``` The value on index 4 turns to 0. <!--Empty Space for separating topics--> If you are familiar with Python, you know that there is a feature called slicing on a list. Tensors support the same feature. Get the subset of <code>tensor_sample</code>. The subset should contain the values in <code>tensor_sample</code> from index 1 to index 3. ``` # Slice tensor_sample subset_tensor_sample = tensor_sample[1:4] print("Original tensor sample: ", tensor_sample) print("The subset of tensor sample:", subset_tensor_sample) ``` As a result, the <code>subset_tensor_sample</code> returned only the values on index 1, index 2, and index 3. Then, it stored them in a <code>subset_tensor_sample</code>. <b>Note: The number on the left side of the colon represents the index of the first value. The number on the right side of the colon is always 1 larger than the index of the last value. For example, <code>tensor_sample[1:4]</code> means you get values from the index 1 to index 3 <i>(4-1)</i></b>. <!--Empty Space for separating topics--> As for assigning values to the certain index, you can also assign the value to the slices: Change the value of <code>tensor_sample</code> from index 3 to index 4: ``` # Change the values on index 3 and index 4 print("Inital value on index 3 and index 4:", tensor_sample[3:5]) tensor_sample[3:5] = torch.tensor([300.0, 400.0]) print("Modified tensor:", tensor_sample) ``` The values on both index 3 and index 4 were changed. The values on other indexes remain the same. <!--Empty Space for separating topics--> You can also use a variable to contain the selected indexes and pass that variable to a tensor slice operation as a parameter, for example: ``` # Using variable to contain the selected index, and pass it to slice operation selected_indexes = [3, 4] subset_tensor_sample = tensor_sample[selected_indexes] print("The inital tensor_sample", tensor_sample) print("The subset of tensor_sample with the values on index 3 and 4: ", subset_tensor_sample) ``` <!--Empty Space for separating topics--> You can also assign one value to the selected indexes by using the variable. For example, assign 100,000 to all the <code>selected_indexes</code>: ``` #Using variable to assign the value to the selected indexes print("The inital tensor_sample", tensor_sample) selected_indexes = [1, 3] tensor_sample[selected_indexes] = 100000 print("Modified tensor with one value: ", tensor_sample) ``` The values on index 1 and index 3 were changed to 100,000. Others remain the same. <b>Note: You can use only one value for the assignment.</b> <!--Empty Space for separating topics--> <h3>Practice</h3> Try to change the values on index 3, 4, 7 of the following tensor to 0. ``` # Practice: Change the values on index 3, 4, 7 to 0 practice_tensor = torch.tensor([2, 7, 3, 4, 6, 2, 3, 1, 2]) ``` Double-click <b>here</b> for the solution. <!-- selected_indexes = [3, 4, 7] practice_tensor[selected_indexes] = 0 print("New Practice Tensor: ", practice_tensor) --> <!--Empty Space for separating topics--> <h2 id="Tensor_Func">Tensor Functions</h2> For this section, you'll work with some methods that you can apply to tensor objects. <h3>Mean and Standard Deviation</h3> You'll review the mean and standard deviation methods first. They are two basic statistical methods. <!--Empty Space for separating topics--> Create a tensor with values <i>[1.0, -1, 1, -1]</i>: ``` # Sample tensor for mathmatic calculation methods on tensor math_tensor = torch.tensor([1.0, -1.0, 1, -1]) print("Tensor example: ", math_tensor) ``` <!--Empty Space for separating topics--> Here is the mean method: ``` #Calculate the mean for math_tensor mean = math_tensor.mean() print("The mean of math_tensor: ", mean) ``` <!--Empty Space for separating topics--> The standard deviation can also be calculated by using <code><i>tensor_obj</i>.std()</code>: ``` #Calculate the standard deviation for math_tensor standard_deviation = math_tensor.std() print("The standard deviation of math_tensor: ", standard_deviation) ``` <!--Empty Space for separating topics--> <h3>Max and Min</h3> Now, you'll review another two useful methods: <code><i>tensor_obj</i>.max()</code> and <code><i>tensor_obj</i>.min()</code>. These two methods are used for finding the maximum value and the minimum value in the tensor. <!--Empty Space for separating topics--> Create a <code>max_min_tensor</code>: ``` # Sample for introducing max and min methods max_min_tensor = torch.tensor([1, 1, 3, 5, 5]) print("Tensor example: ", max_min_tensor) ``` <b>Note: There are two minimum numbers as 1 and two maximum numbers as 5 in the tensor. Can you guess how PyTorch is going to deal with the duplicates?</b> <!--Empty Space for separating topics--> Apply <code><i>tensor_obj</i>.max()</code> on <code>max_min_tensor</code>: ``` # Method for finding the maximum value in the tensor max_val = max_min_tensor.max() print("Maximum number in the tensor: ", max_val) ``` The answer is <code>tensor(5)</code>. Therefore, the method <code><i>tensor_obj</i>.max()</code> is grabbing the maximum value but not the elements that contain the maximum value in the tensor. <!--Empty Space for separating topics--> Use <code><i>tensor_obj</i>.min()</code> on <code>max_min_tensor</code>: ``` # Method for finding the minimum value in the tensor min_val = max_min_tensor.min() print("Minimum number in the tensor: ", min_val) ``` The answer is <code>tensor(1)</code>. Therefore, the method <code><i>tensor_obj</i>.min()</code> is grabbing the minimum value but not the elements that contain the minimum value in the tensor. <!--Empty Space for separating topics--> <h3>Sin</h3> Sin is the trigonometric function of an angle. Again, you will not be introducedvto any mathematic functions. You'll focus on Python. <!--Empty Space for separating topics--> Create a tensor with 0, π/2 and π. Then, apply the sin function on the tensor. Notice here that the <code>sin()</code> is not a method of tensor object but is a function of torch: ``` # Method for calculating the sin result of each element in the tensor pi_tensor = torch.tensor([0, np.pi/2, np.pi]) sin = torch.sin(pi_tensor) print("The sin result of pi_tensor: ", sin) ``` The resultant tensor <code>sin</code> contains the result of the <code>sin</code> function applied to each element in the <code>pi_tensor</code>.<br> This is different from the previous methods. For <code><i>tensor_obj</i>.mean()</code>, <code><i>tensor_obj</i>.std()</code>, <code><i>tensor_obj</i>.max()</code>, and <code><i>tensor_obj</i>.min()</code>, the result is a tensor with only one number because these are aggregate methods.<br> However, the <code>torch.sin()</code> is not. Therefore, the resultant tensors have the same length as the input tensor. <!--Empty Space for separating topics--> <h3>Create Tensor by <code>torch.linspace()</code></h3> A useful function for plotting mathematical functions is <code>torch.linspace()</code>. <code>torch.linspace()</code> returns evenly spaced numbers over a specified interval. You specify the starting point of the sequence and the ending point of the sequence. The parameter <code>steps</code> indicates the number of samples to generate. Now, you'll work with <code>steps = 5</code>. ``` # First try on using linspace to create tensor len_5_tensor = torch.linspace(-2, 2, steps = 5) print ("First Try on linspace", len_5_tensor) ``` <!--Empty Space for separating topics--> Assign <code>steps</code> with 9: ``` # Second try on using linspace to create tensor len_9_tensor = torch.linspace(-2, 2, steps = 9) print ("Second Try on linspace", len_9_tensor) ``` <!--Empty Space for separating topics--> Use both <code>torch.linspace()</code> and <code>torch.sin()</code> to construct a tensor that contains the 100 sin result in range from 0 (0 degree) to 2π (360 degree): ``` # Construct the tensor within 0 to 360 degree pi_tensor = torch.linspace(0, 2*np.pi, 100) sin_result = torch.sin(pi_tensor) ``` Plot the result to get a clearer picture. You must cast the tensor to a numpy array before plotting it. ``` # Plot sin_result plt.plot(pi_tensor.numpy(), sin_result.numpy()) ``` If you know the trigonometric function, you will notice this is the diagram of the sin result in the range 0 to 360 degrees. <!--Empty Space for separating topics--> <h3>Practice</h3> Construct a tensor with 25 steps in the range 0 to π/2. Print out the Maximum and Minimum number. Also, plot a graph showing the diagram that shows the result. ``` # Practice: Create your tensor, print max and min number, plot the sin result diagram # Type your code here ``` Double-click <b>here</b> for the solution. <!-- pi_tensor = torch.linspace(0, np.pi/2, 100) print("Max Number: ", pi_tensor.max()) print("Min Number", pi_tensor.min()) sin_result = torch.sin(pi_tensor) plt.plot(pi_tensor.numpy(), sin_result.numpy()) --> <!--Empty Space for separating topics--> <h2 id="Tensor_Op">Tensor Operations</h2> In the following section, you'll work with operations that you can apply to a tensor. <!--Empty Space for separating topics--> <h3>Tensor Addition</h3> You can perform addition between two tensors. Create a tensor <code>u</code> with 1 dimension and 2 elements. Then, create another tensor <code>v</code> with the same number of dimensions and the same number of elements: ``` # Create two sample tensors u = torch.tensor([1, 0]) v = torch.tensor([0, 1]) ``` Add <code>u</code> and <code>v</code> together: ``` # Add u and v w = u + v print("The result tensor: ", w) ``` The result is <code>tensor([1, 1])</code>. The behavior is <i>[1 + 0, 0 + 1]</i>. Plot the result to to get a clearer picture. ``` # Plot u, v, w plotVec([ {"vector": u.numpy(), "name": 'u', "color": 'r'}, {"vector": v.numpy(), "name": 'v', "color": 'b'}, {"vector": w.numpy(), "name": 'w', "color": 'g'} ]) ``` <!--Empty Space for separating topics--> <h3>Try</h3> Implement the tensor subtraction with <code>u</code> and <code>v</code> as u-v. ``` # Try by yourself to get a result of u-v u = torch.tensor([1, 0]) v = torch.tensor([0, 1]) ``` Double-click <b>here</b> for the solution. <!-- print("The result tensor: ", u-v) --> <!--Empty Space for separating topics--> You can add a scalar to the tensor. Use <code>u</code> as the sample tensor: ``` # tensor + scalar u = torch.tensor([1, 2, 3, -1]) v = u + 1 print ("Addition Result: ", v) ``` The result is simply adding 1 to each element in tensor <code>u</code> as shown in the following image: <img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter%201/brodcasting.gif" width = "500" alt="tensor addition" /> <!--Empty Space for separating topics--> <h3>Tensor Multiplication </h3> Now, you'll review the multiplication between a tensor and a scalar. Create a tensor with value <code>[1, 2]</code> and then multiply it by 2: ``` # tensor * scalar u = torch.tensor([1, 2]) v = 2 * u print("The result of 2 * u: ", v) ``` The result is <code>tensor([2, 4])</code>, so the code <code>2 * u</code> multiplies each element in the tensor by 2. This is how you get the product between a vector or matrix and a scalar in linear algebra. <!--Empty Space for separating topics--> You can use multiplication between two tensors. Create two tensors <code>u</code> and <code>v</code> and then multiply them together: ``` # tensor * tensor u = torch.tensor([1, 2]) v = torch.tensor([3, 2]) w = u * v print ("The result of u * v", w) ``` The result is simply <code>tensor([3, 4])</code>. This result is achieved by multiplying every element in <code>u</code> with the corresponding element in the same position <code>v</code>, which is similar to <i>[1 * 3, 2 * 2]</i>. <!--Empty Space for separating topics--> <h3>Dot Product</h3> The dot product is a special operation for a vector that you can use in Torch. Here is the dot product of the two tensors <code>u</code> and <code>v</code>: ``` # Calculate dot product of u, v u = torch.tensor([1, 2]) v = torch.tensor([3, 2]) print("Dot Product of u, v:", torch.dot(u,v)) ``` The result is <code>tensor(7)</code>. The function is <i>1 x 3 + 2 x 2 = 7</i>. <!--Empty Space for separating topics--> <h3>Practice</h3> Convert the list <i>[-1, 1]</i> and <i>[1, 1]</i> to tensors <code>u</code> and <code>v</code>. Then, plot the tensor <code>u</code> and <code>v</code> as a vector by using the function <code>plotVec</code> and find the dot product: ``` # Practice: calculate the dot product of u and v, and plot out two vectors # Type your code here ``` Double-click <b>here</b> for the solution. <!-- u= torch.tensor([-1, 1]) v= torch.tensor([1, 1]) plotVec([ {"vector": u.numpy(), "name": 'u', "color": 'r'}, {"vector": v.numpy(), "name": 'v', "color": 'b'} ]) print("The Dot Product is",np.dot(u, v)) --> <!--Empty Space for separating topics--> See <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html">Broadcasting</a> for more information on numpy that is similar to PyTorch. <a href="http://cocl.us/pytorch_link_bottom"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/notebook_bottom%20.png" width="750" alt="PyTorch Bottom" /> </a> <h2>About the Authors:</h2> <a href="https://www.linkedin.com/in/joseph-s-50398b136/">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD. Other contributors: <a href="https://www.linkedin.com/in/michelleccarey/">Michelle Carey</a>, <a href="www.linkedin.com/in/jiahui-mavis-zhou-a4537814a">Mavis Zhou</a> <hr> Copyright &copy; 2018 <a href="cognitiveclass.ai?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu">cognitiveclass.ai</a>. This notebook and its source code are released under the terms of the <a href="https://bigdatauniversity.com/mit-license/">MIT License</a>.
github_jupyter
# 第2章 最小二乗法:機械学習理論の第一歩 ## 「02-square_error.py」の解説 ITエンジニアための機械学習理論入門「第2章 最小二乗法:機械学習理論の第一歩」で使用しているサンプルコード「02-square_error.py」の解説です。 ※ 解説用にコードの内容は少し変更しています。 ### データ数 N=10 の場合 はじめに必要なモジュールをインポートしておきます。 関数 normal は、正規分布に従う乱数を生成するために利用します。 ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame from numpy.random import normal import matplotlib matplotlib.rcParams['font.size'] = 12 ``` 正弦関数に正規分布のノイズを載せたデータセットを生成する関数を定義します。 これは、0≦x≦1 の区間を等分した num 個の点 x に対して、対応する y の値を生成します。 ``` # データセット {x_n,y_n} (n=1...num) を用意 def create_dataset(num): dataset = DataFrame(columns=['x', 'y']) for i in range(num): x = float(i)/float(num-1) y = np.sin(2*np.pi*x) + normal(scale=0.3) dataset = dataset.append(Series([x, y], index=['x', 'y']), ignore_index=True) return dataset ``` 例として、10個のデータをトレーニングセットとして生成します。 ``` N=10 # サンプルを取得する位置 x の個数 train_set = create_dataset(N) train_set ``` x と y の値のリストは、train_set.x と train_set.y で取得できます。 グラフ上にプロットすると次のようになります。 ``` plt.scatter(train_set.x, train_set.y, marker='o', color='blue') ``` このデータに対して、最小二乗法でフィッティングした m 次多項式を決定する関数を用意します。 引数 dataset と m にトレーニングセットと多項式の次数を代入すると、多項式に対応する関数 f(x) のオブジェクトが返ります。 ``` # 最小二乗法で解を求める def resolve(dataset, m): t = dataset.y phi = DataFrame() for i in range(0, m+1): p = dataset.x**i p.name="x**%d" % i phi = pd.concat([phi, p], axis=1) tmp = np.linalg.inv(np.dot(phi.T, phi)) ws = np.dot(np.dot(tmp, phi.T), t) def f(x): y = 0 for i, w in enumerate(ws): y += w * (x ** i) return y return f ``` また、得られた関数 f(x) に対して、トレーニングセットに対する平方根平均二乗誤差(RMS)を求める関数を用意します。 ``` # 平方根平均二乗誤差(Root mean square error)を計算 def rms_error(dataset, f): err = 0.0 for index, line in dataset.iterrows(): x, y = line.x, line.y err += 0.5 * (y - f(x))**2 return np.sqrt(2 * err / len(dataset)) ``` これらを用いて、結果をグラフに可視化する関数が次になります。 ``` def show_result(subplot, train_set, m): f = resolve(train_set, m) subplot.set_xlim(-0.05, 1.05) subplot.set_ylim(-1.5, 1.5) subplot.set_title("M=%d" % m, fontsize=10) # トレーニングセットを表示 subplot.scatter(train_set.x, train_set.y, marker='o', color='blue', label=None) # 真の曲線を表示 linex = np.linspace(0, 1, 101) liney = np.sin(2*np.pi*linex) subplot.plot(linex, liney, color='green', linestyle='--') # 多項式近似の曲線を表示 linex = np.linspace(0, 1, 101) liney = f(linex) label = "E(RMS)=%.2f" % rms_error(train_set, f) subplot.plot(linex, liney, color='red', label=label) subplot.legend(loc=1, fontsize=10) ``` 先ほど生成したトレーニングセットを用いて、0, 1, 3, 9次多項式(定数関数)でフィッティングした結果を表示します。 ``` fig = plt.figure(figsize=(10, 7)) for i, m in enumerate([0, 1, 3, 9]): subplot = fig.add_subplot(2, 2, i+1) show_result(subplot, train_set, m) ``` 多項式の次数が上がるにつれてデータポイントの近くを通るようになり、平方根平均二乗誤差が減少していることがわかります。 ここで、トレーニングセットとテストセットに対する平方根平均二乗誤差の変化を確認します。 多項式の次数を0〜10に変化させながら、平方根平均二乗誤差のグラフを描く関数を用意します。 ``` # トレーニングセットとテストセットでの誤差の変化を表示 def show_rms_trend(train_set, test_set): df = DataFrame(columns=['Training set', 'Test set']) for m in range(0,10): # 多項式の次数 f = resolve(train_set, m) train_error = rms_error(train_set, f) test_error = rms_error(test_set, f) df = df.append( Series([train_error, test_error], index=['Training set','Test set']), ignore_index=True) df.plot(title='RMS Error', style=['-','--'], grid=True, xticks=range(0, 10), figsize=(8, 5), ylim=(0, 0.9)) ``` トレーニングセットとは独立に生成したテストセットを用意します。 ``` test_set = create_dataset(N) test_set ``` 多項式の次数を0〜10に変化させながら、トレーニングセットとテストセットに対する平方根平均二条誤差を計算して、結果をグラフ表示します。 ``` show_rms_trend(train_set, test_set) ``` 次数が3を超えるとテストセットに対する誤差が減少しなくなることがわかります。 ### データ数 N=100 の場合 同じ計算をデータ数を増やして実施してみます。 N=100 でトレーニングセットとテストセットを用意します。 ``` N=100 # サンプルを取得する位置 x の個数 train_set = create_dataset(N) test_set = create_dataset(N) ``` 最小二乗法でフィッティングした結果を表示します。 ``` fig = plt.figure(figsize=(10, 7)) for i, m in enumerate([0, 1, 3, 9]): subplot = fig.add_subplot(2, 2, i+1) show_result(subplot, train_set, m) ``` 多項式の次数があがってもオーバーフィッティングが発生しにくくなっていることがわかります。 トレーニングセットとテストセットに対する平方根平均二乗誤差の変化を表示します。 ``` show_rms_trend(train_set, test_set) ``` 次数が3を超えると平方根平均二乗誤差が約0.3で一定になります。これは、このデータが本質的に±0.3程度の誤差を持っている事を示します。
github_jupyter
##### Copyright 2018 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. #@title MIT License # # Copyright (c) 2017 François Chollet # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ``` # Image Classification with Convolutional Neural Networks <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/courses/udacity_intro_to_tensorflow_for_deep_learning/l04c01_image_classification_with_cnns.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/courses/udacity_intro_to_tensorflow_for_deep_learning/l04c01_image_classification_with_cnns.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> In this tutorial, we'll build and train a neural network to classify images of clothing, like sneakers and shirts. It's okay if you don't understand everything. This is a fast-paced overview of a complete TensorFlow program, with explanations along the way. The goal is to get the general sense of a TensorFlow project, not to catch every detail. This guide uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow. ## Install and import dependencies We'll need [TensorFlow Datasets](https://www.tensorflow.org/datasets/), an API that simplifies downloading and accessing datasets, and provides several sample datasets to work with. We're also using a few helper libraries. ``` !pip install -U tensorflow_datasets from __future__ import absolute_import, division, print_function # Import TensorFlow and TensorFlow Datasets import tensorflow as tf import tensorflow_datasets as tfds # Helper libraries import math import numpy as np import matplotlib.pyplot as plt # Improve progress bar display import tqdm print(tf.__version__) ``` ## Import the Fashion MNIST dataset This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset, which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 $\times$ 28 pixels), as seen here: <table> <tr><td> <img src="https://tensorflow.org/images/fashion-mnist-sprite.png" alt="Fashion MNIST sprite" width="600"> </td></tr> <tr><td align="center"> <b>Figure 1.</b> <a href="https://github.com/zalandoresearch/fashion-mnist">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp; </td></tr> </table> Fashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset—often used as the "Hello, World" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc) in an identical format to the articles of clothing we'll use here. This guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code. We will use 60,000 images to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow, using the [Datasets](https://www.tensorflow.org/datasets) API: ``` dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True) train_dataset, test_dataset = dataset['train'], dataset['test'] ``` Loading the dataset returns metadata as well as a *training dataset* and *test dataset*. * The model is trained using `train_dataset`. * The model is tested against `test_dataset`. The images are 28 $\times$ 28 arrays, with pixel values in the range `[0, 255]`. The *labels* are an array of integers, in the range `[0, 9]`. These correspond to the *class* of clothing the image represents: <table> <tr> <th>Label</th> <th>Class</th> </tr> <tr> <td>0</td> <td>T-shirt/top</td> </tr> <tr> <td>1</td> <td>Trouser</td> </tr> <tr> <td>2</td> <td>Pullover</td> </tr> <tr> <td>3</td> <td>Dress</td> </tr> <tr> <td>4</td> <td>Coat</td> </tr> <tr> <td>5</td> <td>Sandal</td> </tr> <tr> <td>6</td> <td>Shirt</td> </tr> <tr> <td>7</td> <td>Sneaker</td> </tr> <tr> <td>8</td> <td>Bag</td> </tr> <tr> <td>9</td> <td>Ankle boot</td> </tr> </table> Each image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images: ``` class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] ``` ### Explore the data Let's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, and 10000 images in the test set: ``` num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.splits['test'].num_examples print("Number of training examples: {}".format(num_train_examples)) print("Number of test examples: {}".format(num_test_examples)) ``` ## Preprocess the data The value of each pixel in the image data is an integer in the range `[0,255]`. For the model to work properly, these values need to be normalized to the range `[0,1]`. So here we create a normalization function, and then apply it to each image in the test and train datasets. ``` def normalize(images, labels): images = tf.cast(images, tf.float32) images /= 255 return images, labels # The map function applies the normalize function to each element in the train # and test datasets train_dataset = train_dataset.map(normalize) test_dataset = test_dataset.map(normalize) ``` ### Explore the processed data Let's plot an image to see what it looks like. ``` # Take a single image, and remove the color dimension by reshaping for image, label in test_dataset.take(1): break image = image.numpy().reshape((28,28)) # Plot the image - voila a piece of fashion clothing plt.figure() plt.imshow(image, cmap=plt.cm.binary) plt.colorbar() plt.grid(False) plt.show() ``` Display the first 25 images from the *training set* and display the class name below each image. Verify that the data is in the correct format and we're ready to build and train the network. ``` plt.figure(figsize=(10,10)) i = 0 for (image, label) in test_dataset.take(25): image = image.numpy().reshape((28,28)) plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(image, cmap=plt.cm.binary) plt.xlabel(class_names[label]) i += 1 plt.show() ``` ## Build the model Building the neural network requires configuring the layers of the model, then compiling the model. ### Setup the layers The basic building block of a neural network is the *layer*. A layer extracts a representation from the data fed into it. Hopefully, a series of connected layers results in a representation that is meaningful for the problem at hand. Much of deep learning consists of chaining together simple layers. Most layers, like `tf.keras.layers.Dense`, have internal parameters which are adjusted ("learned") during training. ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), padding='same', activation=tf.nn.relu, input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) ``` This network layers are: * **"convolutions"** `tf.keras.layers.Conv2D and MaxPooling2D`— Network start with two pairs of Conv/MaxPool. The first layer is a Conv2D filters (3,3) being applied to the input image, retaining the original image size by using padding, and creating 32 output (convoluted) images (so this layer creates 32 convoluted images of the same size as input). After that, the 32 outputs are reduced in size using a MaxPooling2D (2,2) with a stride of 2. The next Conv2D also has a (3,3) kernel, takes the 32 images as input and creates 64 outputs which are again reduced in size by a MaxPooling2D layer. So far in the course, we have described what a Convolution does, but we haven't yet covered how you chain multiples of these together. We will get back to this in lesson 4 when we use color images. At this point, it's enough if you understand the kind of operation a convolutional filter performs * **output** `tf.keras.layers.Dense` — A 128-neuron, followed by 10-node *softmax* layer. Each node represents a class of clothing. As in the previous layer, the final layer takes input from the 128 nodes in the layer before it, and outputs a value in the range `[0, 1]`, representing the probability that the image belongs to that class. The sum of all 10 node values is 1. ### Compile the model Before the model is ready for training, it needs a few more settings. These are added during the model's *compile* step: * *Loss function* — An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss. * *Optimizer* —An algorithm for adjusting the inner parameters of the model in order to minimize loss. * *Metrics* —Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified. ``` model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` ## Train the model First, we define the iteration behavior for the train dataset: 1. Repeat forever by specifying `dataset.repeat()` (the `epochs` parameter described below limits how long we perform training). 2. The `dataset.shuffle(60000)` randomizes the order so our model cannot learn anything from the order of the examples. 3. And `dataset.batch(32)` tells `model.fit` to use batches of 32 images and labels when updating the model variables. Training is performed by calling the `model.fit` method: 1. Feed the training data to the model using `train_dataset`. 2. The model learns to associate images and labels. 3. The `epochs=5` parameter limits training to 5 full iterations of the training dataset, so a total of 5 * 60000 = 300000 examples. (Don't worry about `steps_per_epoch`, the requirement to have this flag will soon be removed.) ``` BATCH_SIZE = 32 train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE) test_dataset = test_dataset.batch(BATCH_SIZE) model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE)) ``` As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.97 (or 97%) on the training data. ## Evaluate accuracy Next, compare how the model performs on the test dataset. Use all examples we have in the test dataset to assess accuracy. ``` test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32)) print('Accuracy on test dataset:', test_accuracy) ``` As it turns out, the accuracy on the test dataset is smaller than the accuracy on the training dataset. This is completely normal, since the model was trained on the `train_dataset`. When the model sees images it has never seen during training, (that is, from the `test_dataset`), we can expect performance to go down. ## Make predictions and explore With the model trained, we can use it to make predictions about some images. ``` for test_images, test_labels in test_dataset.take(1): test_images = test_images.numpy() test_labels = test_labels.numpy() predictions = model.predict(test_images) predictions.shape ``` Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction: ``` predictions[0] ``` A prediction is an array of 10 numbers. These describe the "confidence" of the model that the image corresponds to each of the 10 different articles of clothing. We can see which label has the highest confidence value: ``` np.argmax(predictions[0]) ``` So the model is most confident that this image is a shirt, or `class_names[6]`. And we can check the test label to see this is correct: ``` test_labels[0] ``` We can graph this to look at the full set of 10 channels ``` def plot_image(i, predictions_array, true_labels, images): predictions_array, true_label, img = predictions_array[i], true_labels[i], images[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img[...,0], cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array[i], true_label[i] plt.grid(False) plt.xticks([]) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') ``` Let's look at the 0th image, predictions, and prediction array. ``` i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) ``` Let's plot several images with their predictions. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percent (out of 100) for the predicted label. Note that it can be wrong even when very confident. ``` # Plot the first X test images, their predicted label, and the true label # Color correct predictions in blue, incorrect predictions in red num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions, test_labels, test_images) plt.subplot(num_rows, 2*num_cols, 2*i+2) plot_value_array(i, predictions, test_labels) ``` Finally, use the trained model to make a prediction about a single image. ``` # Grab an image from the test dataset img = test_images[0] print(img.shape) ``` `tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. So even though we're using a single image, we need to add it to a list: ``` # Add the image to a batch where it's the only member. img = np.array([img]) print(img.shape) ``` Now predict the image: ``` predictions_single = model.predict(img) print(predictions_single) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45) ``` `model.predict` returns a list of lists, one for each image in the batch of data. Grab the predictions for our (only) image in the batch: ``` np.argmax(predictions_single[0]) ``` And, as before, the model predicts a label of 6 (shirt). # Exercises Experiment with different models and see how the accuracy results differ. In particular change the following parameters: * Set training epochs set to 1 * Number of neurons in the Dense layer following the Flatten one. For example, go really low (e.g. 10) in ranges up to 512 and see how accuracy changes * Add additional Dense layers between the Flatten and the final Dense(10, activation=tf.nn.softmax), experiment with different units in these layers * Don't normalize the pixel values, and see the effect that has Remember to enable GPU to make everything run faster (Runtime -> Change runtime type -> Hardware accelerator -> GPU). Also, if you run into trouble, simply reset the entire environment and start from the beginning: * Edit -> Clear all outputs * Runtime -> Reset all runtimes
github_jupyter
``` import tensorflow as tf import tensorflow.keras as keras import matplotlib.pyplot as plt from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.preprocessing.text import Tokenizer sentences = ['I love my dog', 'I love my cat'] tokenizer = Tokenizer(num_words = 100) tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index print(word_index) sentences = ['I love my dog', 'I love my cat', 'you love my dog!', 'do you think my dog is amazing'] tokenizer = Tokenizer(num_words = 100, oov_token = "<OOV>") tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index sequences = tokenizer.texts_to_sequences(sentences) print(word_index) print(sequences) ``` # Padding ``` padded = pad_sequences(sequences,maxlen=6,truncating=trunc_type) padded ``` # Embedding show difference degree from similarity ``` #IMDB import tensorflow_datasets as tfds from tensorflow.keras.preprocessing.sequence import pad_sequences padded = pad_sequences(sequences, padding='post', truncating='post', maxlen=5) print(padded) imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True) import numpy as np # data are tensors foramt train_data, test_data = imdb['train'], imdb['test'] training_sentences = [] trainging_labels = [] testing_sentences =[] testing_labels = [] for s,l in train_data: training_sentences.append(str(s.numpy())) trainging_labels.append(l.numpy()) for s,l in test_data: testing_sentences.append(str(s.numpy())) testing_labels.append(l.numpy()) training_labels_final = np.array(trainging_labels) testing_labels_final = np.array(testing_labels) #Hyper parameters vocab_size = 10000 embedding_dim = 16 max_length = 100 trunc_type = 'post' oov_tok = '<OOV>' from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok) tokenizer.fit_on_texts(training_sentences) word_index = tokenizer.word_index sequences = tokenizer.texts_to_sequences(training_sentences) padded = pad_sequences(sequences,maxlen=max_length,truncating=trunc_type) testing_sentences = tokenizer.texts_to_sequences(testing_sentences) testing_padded = pad_sequences(testing_sentences, maxlen=max_length) reverse_word_index = dict([(value,key) for (key,value) in word_index.items()]) def decode_review(text): return ' '.join([reverse_word_index.get(i, '?') for i in text]) print(decode_review(padded[1])) print(training_sentences[1]) model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.GlobalAveragePooling1D(),#Flatten(), # tf.keras.layers.Dense(6, activation='relu'), tf.keras.layers.Dense(1,activation='sigmoid') ]) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) model.summary() num_epochs = 15 history = model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final)) import matplotlib.pyplot as plt def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string]) plt.xlabel("Epochs") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show() plot_graphs(history, 'accuracy') plot_graphs(history, 'loss') model.save("NlpModel.h5") ``` # LSTM ``` model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(embedding_dim, return_sequences=True)), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(8)), tf.keras.layers.Dense(embedding_dim, activation='relu'), tf.keras.layers.Dense(1,activation='sigmoid') ]) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) model.summary() num_epochs = 15 history = model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final)) plot_graphs(history, 'accuracy') plot_graphs(history, 'loss') #Layer 0 is the Embedding layer e = model.layers[0] weights = e.get_weights()[0] print(weights.shape) ``` ## cnn ``` model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Conv1D(128,5, activation='relu'), tf.keras.layers.GlobalAveragePooling1D(),#Flatten(), # tf.keras.layers.Dense(embedding_dim, activation='relu'), tf.keras.layers.Dense(1,activation='sigmoid') ]) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) model.summary() ``` # Using predifine token ``` num_epochs = 15 history = model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final)) plot_graphs(history, 'accuracy') plot_graphs(history, 'loss') import tensorflow_datasets as tfds imdb, info = tfds.load("imdb_reviews/subwords8k", with_info=True, as_supervised=True) tokenizer = info.features['text'].encoder ```
github_jupyter
# Hierarchical Search Hierarchical search is a a planning algorithm in high level of abstraction. <br> Instead of actions as in classical planning (chapter 10) (primitive actions) we now use high level actions (HLAs) (see planning.ipynb) <br> ## Refinements Each __HLA__ has one or more refinements into a sequence of actions, each of which may be an HLA or a primitive action (which has no refinements by definition).<br> For example: - (a) the high level action "Go to San Fransisco airport" (Go(Home, SFO)), might have two possible refinements, "Drive to San Fransisco airport" and "Taxi to San Fransisco airport". <br> - (b) A recursive refinement for navigation in the vacuum world would be: to get to a destination, take a step, and then go to the destination. <br> ![title](images/refinement.png) <br> - __implementation__: An HLA refinement that contains only primitive actions is called an implementation of the HLA - An implementation of a high-level plan (a sequence of HLAs) is the concatenation of implementations of each HLA in the sequence - A high-level plan __achieves the goal__ from a given state if at least one of its implementations achieves the goal from that state <br> The refinements function input is: - __hla__: the HLA of which we want to compute its refinements - __state__: the knoweledge base of the current problem (Problem.init) - __library__: the hierarchy of the actions in the planning problem ``` from planning import * from notebook import psource psource(Problem.refinements) ``` ## Hierarchical search Hierarchical search is a breadth-first implementation of hierarchical forward planning search in the space of refinements. (i.e. repeatedly choose an HLA in the current plan and replace it with one of its refinements, until the plan achieves the goal.) <br> The algorithms input is: problem and hierarchy - __problem__: is of type Problem - __hierarchy__: is a dictionary consisting of all the actions and the order in which they are performed. <br> In top level call, initialPlan contains [act] (i.e. is the action to be performed) ``` psource(Problem.hierarchical_search) ``` ## Example Suppose that somebody wants to get to the airport. The possible ways to do so is either get a taxi, or drive to the airport. <br> Those two actions have some preconditions and some effects. If you get the taxi, you need to have cash, whereas if you drive you need to have a car. <br> Thus we define the following hierarchy of possible actions. ##### hierarchy ``` library = { 'HLA': ['Go(Home,SFO)', 'Go(Home,SFO)', 'Drive(Home, SFOLongTermParking)', 'Shuttle(SFOLongTermParking, SFO)', 'Taxi(Home, SFO)'], 'steps': [['Drive(Home, SFOLongTermParking)', 'Shuttle(SFOLongTermParking, SFO)'], ['Taxi(Home, SFO)'], [], [], []], 'precond': [['At(Home) & Have(Car)'], ['At(Home)'], ['At(Home) & Have(Car)'], ['At(SFOLongTermParking)'], ['At(Home)']], 'effect': [['At(SFO) & ~At(Home)'], ['At(SFO) & ~At(Home) & ~Have(Cash)'], ['At(SFOLongTermParking) & ~At(Home)'], ['At(SFO) & ~At(LongTermParking)'], ['At(SFO) & ~At(Home) & ~Have(Cash)']] } ``` the possible actions are the following: ``` go_SFO = HLA('Go(Home,SFO)', precond='At(Home)', effect='At(SFO) & ~At(Home)') taxi_SFO = HLA('Taxi(Home,SFO)', precond='At(Home)', effect='At(SFO) & ~At(Home) & ~Have(Cash)') drive_SFOLongTermParking = HLA('Drive(Home, SFOLongTermParking)', 'At(Home) & Have(Car)','At(SFOLongTermParking) & ~At(Home)' ) shuttle_SFO = HLA('Shuttle(SFOLongTermParking, SFO)', 'At(SFOLongTermParking)', 'At(SFO) & ~At(LongTermParking)') ``` Suppose that (our preconditionds are that) we are Home and we have cash and car and our goal is to get to SFO and maintain our cash, and our possible actions are the above. <br> ##### Then our problem is: ``` prob = Problem('At(Home) & Have(Cash) & Have(Car)', 'At(SFO) & Have(Cash)', [go_SFO]) ``` ##### Refinements The refinements of the action Go(Home, SFO), are defined as: <br> ['Drive(Home,SFOLongTermParking)', 'Shuttle(SFOLongTermParking, SFO)'], ['Taxi(Home, SFO)'] ``` for sequence in Problem.refinements(go_SFO, prob, library): print (sequence) print([x.__dict__ for x in sequence ], '\n') ``` Run the hierarchical search ##### Top level call ``` plan= Problem.hierarchical_search(prob, library) print (plan, '\n') print ([x.__dict__ for x in plan]) ``` ## Example 2 ``` library_2 = { 'HLA': ['Go(Home,SFO)', 'Go(Home,SFO)', 'Bus(Home, MetroStop)', 'Metro(MetroStop, SFO)' , 'Metro(MetroStop, SFO)', 'Metro1(MetroStop, SFO)', 'Metro2(MetroStop, SFO)' ,'Taxi(Home, SFO)'], 'steps': [['Bus(Home, MetroStop)', 'Metro(MetroStop, SFO)'], ['Taxi(Home, SFO)'], [], ['Metro1(MetroStop, SFO)'], ['Metro2(MetroStop, SFO)'],[],[],[]], 'precond': [['At(Home)'], ['At(Home)'], ['At(Home)'], ['At(MetroStop)'], ['At(MetroStop)'],['At(MetroStop)'], ['At(MetroStop)'] ,['At(Home) & Have(Cash)']], 'effect': [['At(SFO) & ~At(Home)'], ['At(SFO) & ~At(Home) & ~Have(Cash)'], ['At(MetroStop) & ~At(Home)'], ['At(SFO) & ~At(MetroStop)'], ['At(SFO) & ~At(MetroStop)'], ['At(SFO) & ~At(MetroStop)'] , ['At(SFO) & ~At(MetroStop)'] ,['At(SFO) & ~At(Home) & ~Have(Cash)']] } plan_2 = Problem.hierarchical_search(prob, library_2) print(plan_2, '\n') print([x.__dict__ for x in plan_2]) ```
github_jupyter
# Get electricity data from the ENTSO-E API To run this notebook, you must have the following environment variables set: * BENTSO_DATA_DIR: Directory to cache data from ENTSO-E API * ENTSOE_API_TOKEN: API token you get from signing up to ENTSO-E transparency platform ## Get data ``` from bentso import CachingDataClient as CDC from entsoe.exceptions import NoMatchingDataError import time cdc = CDC() from bentso.constants import ENTSO_COUNTRIES, TRADE_PAIRS for country in ENTSO_COUNTRIES: print(country) for year in (2019, 2020, 2021): success, tries = False, 0 while not success and tries < 5: try: cdc.get_generation(country=country, year=year) success = True except ConnectionError: tries += 1 time.sleep(5) except NoMatchingDataError: print(f"Can't get data for {country}") success=True for dst, lst in TRADE_PAIRS.items(): print(dst) for src in lst: for year in (2018, 2019, 2020, 2021): success, tries = False, 0 while not success and tries < 5: try: cdc.get_trade(from_country=src, to_country=dst, year=year) success = True except ConnectionError: tries += 1 time.sleep(5) except: print("Error with:", dst, src, year) success = True ``` # Errors We don't have generation data for Luxembourg or Malta. We will just leave the existing ecoinvent values for these countries. We don't have trade from Bulgaria to Croatia, but this is small ($10^{-5}$), so we can ignore it. We don't have trade from Russia to Norway, but this is small ($10^{-4}$), so we can ignore it. We don't have trade from Morocco to Spain, but this is small ($10^{-4}$), so we can ignore it. ## Get generation types ``` gt = set([]) for country in ENTSO_COUNTRIES: df = cdc.get_generation(country=country, year=2020) for obj in df.columns: if isinstance(obj, tuple): gt.add(obj[0]) else: gt.add(obj) gt ``` # Graph sources ``` import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = cdc.get_generation(country='DE', year=2019) df = df.drop(labels=[ ( 'Fossil Gas', 'Actual Consumption'), ('Fossil Oil', 'Actual Consumption'), ( 'Hydro Pumped Storage', 'Actual Consumption'), ( 'Nuclear', 'Actual Consumption'), ( 'Hydro Water Reservoir', 'Actual Consumption'), ], axis=1 ) df.columns = df.columns.droplevel(level=1) df['Wind'] = df['Wind Offshore'] + df['Wind Onshore'] df['Coal'] = df['Fossil Brown coal/Lignite'] + df['Fossil Hard coal'] df['Gas'] = df['Fossil Gas'] df['Hydro'] = df['Hydro Run-of-river and poundage'] + df['Hydro Water Reservoir'] df = df.drop(labels=['Hydro Pumped Storage', 'Wind Onshore', 'Wind Offshore', 'Fossil Brown coal/Lignite', 'Fossil Hard coal', 'Fossil Gas', 'Hydro Run-of-river and poundage', 'Hydro Water Reservoir'], axis=1) df['Total'] = df.sum(axis=1) for column in df.columns: if column != 'Total': df[column] = df[column] / df['Total'] df.columns sb.pairplot(df[['Nuclear', 'Solar', 'Wind', 'Coal', 'Gas', 'Hydro']], kind='kde') plt.savefig("de-2019-kde.png", dpi=300) ```
github_jupyter
![data-x](http://oi64.tinypic.com/o858n4.jpg) # Image Classification with CNNs #### Author: Alexander Fred Ojala **Sources:** * **Training + explanations**: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html **Copright:** Feel free to do whatever you want with this code. --- ## Part 1-4: Build your own Cats vs Dogs binary classifier In this notebook we will implement a binary Cats vs Dogs classifier by removing the top layer of a pretrained network (VGG16 on Imagenet), extracting the features of the training and validation images and then just train the top layer of that network. This way we will be able to make accurate predictions even though we just have a small data set. We want you to extract the bottleneck features of your images, train the top layer and lastly make predicitons on images not presented to the CNN so far. The data conists of 2000 training images (1000 cats and 1000 dogs), 800 validation images (400 cats and 400 dogs), and 100 test images (cats and dogs mixed). Find the data here (or in the Github folder): https://www.dropbox.com/s/y2suimh2lt5btam/data.zip?dl=1 The reason why we are using a pretrained network, extracting bottleneck features and training only the top layers is that this is a great way to obtain a high prediction accuracy without having to train from scratch (which takes a long time). it would take up to several days to run this analysis and training your own CNN / DNN on a personal computer (in order to obtain the same level of accuracy). # Table of Contents ## [Part 1: Install Keras Tensorflow + all dependencies](#sec1) ## [Part 2: Extract bottleneck features from the data set](#sec2) ## [Part 3: Train the top layer of your CNN](#sec3) ## [Part 4: Make predicitons on the mixed test images](#sec4) # Additional Material ## [TRAIN NETWORK TO CLASSIFY 50 IMAGE CLASSES w/ Theano](#sec5) ## [Train Neural Network from Scratch + Image Augmentation](#sec6) ___ <a id='sec1'></a> # Part 1: Install Keras + Tensorflow As a data scientist you will have to be comfortable with installing and setting up your work environment on different systems. Therefore, this first part will be a valuable lesson on how to troubleshoot if you run into problems. If you want you can also try to use Theano (not supported for future development) as your Keras backend (instead of TensorFlow). Note that there some syntax and dimension handling differences between these two libraries. Install OpenCV by running: `pip install opencv-python` # Important set correct backend and image_dim_ordering **Set tensorflow backend and image_dim_ordering tf** set it in the **keras.json** file On mac it is loacted: ``~/.keras/keras.json`` and / or look here https://keras.io/backend/#switching-from-one-backend-to-another #### For Windows: Start up your python-binary and do the following import os print(os.path.expanduser('~')) # >>> C:\\Users\\Sascha' # will look different for different OS - This should be the base-directory - Keras will build a folder .keras there where keras.json resides (if it was already created). If it's not there, create it there - Example: C:\\Users\\Sascha\\.keras\\keras.json' ``` import warnings warnings.simplefilter("ignore") from keras import backend as K K.set_image_dim_ordering('tf') # note that we need to have tensorflow dimension ordering still because of the weigths. print('The backend is:',K.backend()) import tensorflow as tf print(K.image_dim_ordering()) # should say tf print(tf.__version__) # Import relevant packages import h5py import os, cv2, random import numpy as np import pandas as pd import matplotlib.pyplot as plt #from matplotlib import ticker #import seaborn as sns %matplotlib inline from keras.models import Sequential from keras.layers import Input, Dropout, Flatten, Convolution2D, MaxPooling2D, Dense, Activation, ZeroPadding2D from keras.optimizers import RMSprop from keras.callbacks import ModelCheckpoint, Callback, EarlyStopping from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing.image import array_to_img, img_to_array, load_img from keras.models import model_from_json from keras.preprocessing import image from IPython.display import display from PIL import Image # fix random seed for reproducibility seed = 150 np.random.seed(seed) # Load in and process data !ls # Look at files, note all cat images and dog images are unique from __future__ import absolute_import, division, print_function # make it compatible w Python 2 import os for path, dirs, files in os.walk('./data'): print('FOLDER',path) for f in files[:2]: print(f) print('Number of cat training images:', len(next(os.walk('./data/train/cats'))[2])) print('Number of dog training images:', len(next(os.walk('./data/train/dogs'))[2])) print('Number of cat validation images:', len(next(os.walk('./data/validation/cats'))[2])) print('Number of dog validation images:', len(next(os.walk('./data/validation/dogs'))[2])) #print('Number of uncategorized test images:', len(next(os.walk('./data/test/catvdog'))[2])) # There should be 1000 train cat images, 1000 train dogs, 400 validation cats, 400 validation dogs, 100 uncategorized # Define variables TRAIN_DIR = './data/train/' VAL_DIR = './data/validation/' TEST_DIR = './data/test/' #one mixed category img_width, img_height = 150, 150 n_train_samples = 2000 n_validation_samples = 800 n_epoch = 30 n_test_samples = 100 ``` <a id='sec2'></a> # Part 2: Extract bottleneck features from the data set In the second part you will use the pre-trained VGG network structure (loading in the pretrained VGG16 ImageNET weights). Then you will run your data set through that CNN once to extract the image features. A good explanation on how this works (rewritten from source: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html) #### Using the bottleneck features of a pre-trained network: 90% accuracy in 1 min (GPU) / 10 mins (CPU) We are leveraging the predictive power of a network pre-trained on a large dataset. Such a network would have already learned features that are useful for most computer vision problems, and leveraging such features would allow us to reach a better accuracy than any method that would only rely on the available data. We will use the VGG16 architecture, pre-trained on the ImageNet dataset. Because the ImageNet dataset contains several "cat" classes (persian cat, siamese cat...) and many "dog" classes among its total of 1000 classes, this model will already have learned features that are relevant to our classification problem. In fact, it is possible that merely recording the softmax predictions of the model over our data rather than the bottleneck features would be enough to solve our dogs vs. cats classification problem extremely well. The method presented here is more likely to generalize well to a broader range of problems, including problems featuring classes absent from ImageNet. Here's what the VGG16 architecture looks like: ![VGG16](https://blog.keras.io/img/imgclf/vgg16_original.png) ### Horizontal visualization ![https://datatoanalytics.files.wordpress.com/2017/04/vgg161.png](https://datatoanalytics.files.wordpress.com/2017/04/vgg161.png) **Strategy to extract bottleneck features:** We will only instantiate the convolutional part of the model, everything up to the fully-connected layers. We will then run this model on our training, validation and test data once, recording the output (the "bottleneck features" from the VGG16 model: the last activation maps before the fully-connected layers) in two numpy arrays. The reason why we are storing the features offline rather than adding our fully-connected model directly on top of a frozen convolutional base and running the whole thing, is computational effiency. Running VGG16 is expensive, especially if you're working on CPU, and we want to only do it once. Note, therefore we will not use data augmentation. Store the bottleneck features as .npy files. # This is how the VGG16 net looks in code You can see the full implementation here of the network we're building and loading in: https://github.com/fchollet/keras/blob/master/keras/applications/vgg16.py ```python # VGG 16 model architecture model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(img_width, img_height, 3))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) ``` # IMAGEnet Benchmarks (the Network Structure we're using today won 2014) ![https://qph.ec.quoracdn.net/main-qimg-fbd17e02f01e60b38ff8ee864c647303](https://qph.ec.quoracdn.net/main-qimg-fbd17e02f01e60b38ff8ee864c647303) ``` # Function for saving bottleneck features # This can take ~20mins to run # Run model once to record the bottleneck features using image data generators: def save_bottleneck_features(): from keras import applications model = applications.vgg16.VGG16(include_top=False, weights='imagenet', \ input_tensor=None, input_shape=(img_width, img_height,3)) print('TensorFlow VGG16 model architecture loaded') # include_top = False, because we drop last layer, then we also only need to # download weight file that is small, input_shape with channels last # Rescale value, feature scaling, we multiply the data before any other processing. # Our original images consist in RGB coefficients in the 0-255, # but such values would be too high for our models to process (given typical learning rate), # so we target values between 0 and 1 instead by scaling with a 1/255. factor. datagen = ImageDataGenerator(rescale=1./255) def generate_features(DIR,n_samples,name_str): '''This is a generator that will read pictures found in subfolers of 'data/*', and indefinitely generate batches of image rescaled images used to predict the bottleneck features of the images once using model.predict_generator(**args**)''' print('Generate '+name_str+' image features') generator = datagen.flow_from_directory( DIR, target_size=(img_width, img_height), batch_size=32, class_mode=None, # this means our generator will only yield batches of data, no labels shuffle=False) # our data will be in order, so all first 1000 images will be cats, then 1000 dogs features = model.predict_generator(generator, verbose=1) # the predict_generator method returns the output of a model, given # a generator that yields batches of numpy data np.save('features_'+name_str+'.npy', features) # save bottleneck features to file generate_features(TEST_DIR, n_test_samples, 'test') #generate_features(TRAIN_DIR, n_train_samples, 'train') #generate_features(VAL_DIR, n_validation_samples, 'validation') print('\nDone! Bottleneck features have been saved') print('This has been done before the lecture! Takes 20+ mins to run.') save_bottleneck_features() # Extra # Obtain class labels and binary classification for validation data datagen = ImageDataGenerator(rescale=1./255) val_gen = datagen.flow_from_directory(VAL_DIR,target_size=(img_width, img_height), batch_size=32,class_mode=None,shuffle=False) val_labels = val_gen.classes print('\nClassifications:\n',val_gen.class_indices) print('\nClass labels:\n',val_labels) ``` <a id='sec3'></a> # Part 3: Train the top layer of your CNN Once you have extracted and written the bottleneck features to files, read them in again and use them to train the top layer of your network, i.e. the small fully-connected model on top of the stored features. When you have done this record and answer with your prediciton accuracy. **Question:** What is the validation accuracy for the last training epoch, and how is it that we can reach such high accuracy with such small amount of data in a short amount of time? ``` # Load in bottleneck features # Run the code below to train your CNN with the training data def train_model(): train_data = np.load('features_train.npy') # the features were saved in order, so recreating the labels is easy train_labels = np.array([0] * (n_train_samples // 2) + [1] * (n_train_samples // 2)) validation_data = np.load('features_validation.npy') # same as val_labels above validation_labels = np.array([0] * (n_validation_samples // 2) + [1] * (n_validation_samples // 2)) # Add top layers trained ontop of extracted VGG features # Small fully connected model trained on top of the stored features model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(256, activation='relu')) model.add(Dropout(0.4)) model.add(Dense(1, activation='sigmoid')) ''' #We end the model with a single unit and a sigmoid activation, which is perfect for a binary classification. #To go with it we will also use the binary_crossentropy loss to train our model. ''' model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.fit(train_data, train_labels, nb_epoch=n_epoch, batch_size=32, validation_data=(validation_data, validation_labels),shuffle=True) # fit the model # Save weights to disk # Save model architecture to disk model_json = model.to_json() with open("mod_appendix.json", "w") as json_file: # save model json_file.write(model_json) # Save model weights # save weights print("Saved model to disk") print('Done!') return(model) model = train_model() ``` <a id='sec4'></a> # Part 4: Validate accuracy and make predictions on unlabeled data **Question:** First use the model trained in Part 3 to determine the accuracy on the validation data set (is it the same as one the last training epoch? Lastly, use the model trained in Part 3 to classify the test data images. I.e., create a function that loads one image from the test data and then predicts if it is a cat or a dog and with what probability it thinks it is a cat or a dog ``` validation_data = np.load('features_validation.npy') val_pred_class = model.predict_classes(validation_data,verbose=0) # predict image classes val_pred_prob = model.predict_proba(validation_data,verbose=0) # predict image probabilities print('Accuracy on validation set: ',np.mean(val_pred_class.ravel()==val_labels)*100,'%') print('\nVal loss & val_acc') print(model.evaluate(validation_data,val_labels,verbose=0)) # First number is validation loss, loss of the objective function # Second number validation accuracy # Alternative print('Model accuracy on validation set:',model.evaluate(validation_data,val_labels,verbose=0)[1]*100,'%') ## Print try images: # Use the model trained in Problem 1 to classify the test data images. # Create a function that loads one image from the test data and then predicts # if it is a cat or a dog and with what probability it thinks it is a cat or a dog # # Use variable test_data to make predictions # Use list test_images to obtain the file name for all images (Note: test_images[0] corresponds to test_data[0]) # Use function plot_pic(img) to plot the image file ## Load in processed images feature to feed into bottleneck model from PIL import Image test_data = np.load('features_validation.npy') test_images = [VAL_DIR+'cats/'+img for img in os.listdir(VAL_DIR+'cats/')] test_images = test_images + [VAL_DIR+'dogs/'+img for img in os.listdir(VAL_DIR+'dogs/')] def read_image(file_path): # For image visualization im = np.array(Image.open(file_path)) # img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE return im def plot_pic(img): # Plot openCV pic pic = read_image(img) plt.figure(figsize=(5,5)) plt.imshow(pic) plt.show() # shuffle cats and dogs from random import shuffle shuffle_idx=list(range(800)) shuffle(shuffle_idx) test_data = test_data[shuffle_idx] test_images = [test_images[idx] for idx in shuffle_idx] ## Answer import warnings warnings.filterwarnings('ignore') # filter eventual warning def predict(mod,i=0,r=None): if r==None: r=[i] for idx in r: class_pred = mod.predict_classes(test_data,verbose=0)[idx] prob_pred = mod.predict_proba(test_data,verbose=0)[idx] if class_pred ==0: prob_pred = 1-prob_pred class_guess='CAT' else: class_guess='DOG' print('\n\nI think this is a ' + class_guess + ' with ' +str(round(float(prob_pred)*100,5)) + '% probability') if test_images[idx]=='./data/test/catvdog/.DS_Store': continue plot_pic(test_images[idx]) predict(model,r=range(0,20)) # seems to be doing really well ``` <a id='sec5'></a> # Part 5 (right now built for Theano): Redo the model and pipeline created in Part 1-4 in order to make predictions on the 50 image classes. Note that you might have to change how you read in the images, so that when you train the model you do a cross validation split (25 / 75) instead of specifying a specific validation set. And, you will want to use a `softmax` activation layer instead of a `sigmoid` one (to do multiclass classification). The data can be downloaded here: https://www.dropbox.com/s/suy8u0hnthwr2su/50_categories.tar.gz?dl=1 Note that you do not have to additional data to make predictions on data not used in the training (however you can easily download 3-5 images like that from Google to try your model). ``` # Look at files, note all cat images and dog images are unique for path, dirs, files in os.walk('./50_categories'): print('FOLDER',path) for f in files[:2]: print(f) categories = next(os.walk('./50_categories')) print(categories) categories = categories[1] # Map categories to an integer cat_dic = dict() for idx, cat in enumerate(categories): cat_dic[cat] = idx print(cat_dic) n_imgs = 0 for cat in categories: nbr_cat_imgs = len(next(os.walk('./50_categories/'+cat))[2]) print('Number of '+cat+' images:', nbr_cat_imgs) n_imgs+=nbr_cat_imgs n_imgs from glob import glob len(glob("./50_categories/*/*.jpg")) #4244 images # plot with opencv img = cv2.imread('./50_categories/airplanes/airplanes_0001.jpg') img.shape plt.imshow(img) path_all_images = glob("./50_categories/*/*.jpg") path_all_images[0:10] def get_image_categories(images): """Get the true categories of a set of paths to images, based on the directory they are located in. The paths should have the form: path/to/image/category/image.jpg Where the image filename is the last item in the path, and the directory (category name) is the second to last item in the path. Parameters ---------- images : list List of paths to images Returns ------- categories : numpy.ndarray An array of integers in order of the images, corresponding to each image's category category_map : list A list of category names. The category integers in `categories` are indices into this list. """ get_category = lambda x: os.path.split(os.path.split(x)[0])[1] categories = list(map(get_category, images)) category_map = sorted(set(categories)) categories = np.array(map(category_map.index, categories)) return categories, category_map img_cats, img_cat_map = get_image_categories(path_all_images) img_cat_map[0:3] # Define variables DATA_DIR = './50_categories/' img_width, img_height = 150, 150 n_samples = n_imgs n_epoch = 40 # Run model once to record the bottleneck features using image data generators: # Note: This can take a lot of time def save_bottleneck_features(): # build the VGG16 network model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) # load the weights of the VGG16 networks # note: when there is a complete match between your model definition # and your weight savefile, you can simply call model.load_weights(filename) assert os.path.exists('vgg16_weights.h5'), 'Model weights not found (Download file vgg16_weights.h5 from bcourses).' f = h5py.File('vgg16_weights.h5') for k in range(f.attrs['nb_layers']): if k >= len(model.layers): # we don't look at the last (fully-connected) layers in the savefile break g = f['layer_{}'.format(k)] weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] model.layers[k].set_weights(weights) f.close() print('Model loaded.') # Rescale value we multiply the data before any other processing. # Our original images consist in RGB coefficients in the 0-255, # but such values would be too high for our models to process (given typical learning rate), # so we target values between 0 and 1 instead by scaling with a 1/255. factor. datagen = ImageDataGenerator(rescale=1./255) def generate_features(DIR,n_samples,name_str): ''' This is a generator that will read pictures found in subfolers of 'data/*', and indefinitely generate batches of image rescaled images used to predict the bottleneck features of the images once using model.predict_generator(**args**) ''' print('Generate '+name_str+' image features') generator = datagen.flow_from_directory( DIR, target_size=(img_width, img_height), batch_size=32, class_mode=None, # this means our generator will only yield batches of data, no labels shuffle=False) # our data will be in order, so all first 1000 images will be cats, then 1000 dogs features = model.predict_generator(generator, n_samples) # the predict_generator method returns the output of a model, given # a generator that yields batches of numpy data np.save(open('50_classes_features.npy', 'w'), features) # save bottleneck features to file generate_features(DATA_DIR, n_samples, 'data') save_bottleneck_features() # Obtain image labels and binary classification datagen = ImageDataGenerator(rescale=1./255) class_gen = datagen.flow_from_directory(DATA_DIR,target_size=(img_width, img_height), batch_size=32,class_mode=None,shuffle=False) class_labels = class_gen.classes print('\nClassifications:\n',class_gen.class_indices) print('\nClass labels:\n',class_labels) print(class_gen.class_indices.keys() == cat_dic.keys()) # since all of our features are stored in order # and we have not split up our training data into training and validation folders # in order to not only train on the first classes we need to randomize our samples # this can easily be done with scikit-learn's test_train_split module # we train on the X_train and y_train sets # then we evaluate our model on the X_test and y_test sets from sklearn.model_selection import train_test_split class_data = np.load('50_classes_features.npy') # load in bottleneck features print(class_data.shape) X_train, X_test, y_train, y_test, path_train, path_test = train_test_split(class_data, class_labels, path_all_images,\ test_size=0.2, random_state=150) print(X_train.shape) print(path_train[0:4]) print([img_cat_map[i] for i in y_train[0:4]]) # the img_paths have been mapped correctly # Load in bottleneck features # Run the code below to train your CNN with the training data from keras.optimizers import SGD # the features were saved in order, so recreating the labels is easy # Add top layers trained ontop of extracted VGG features # Small fully connected model trained on top of the stored features model = Sequential() model.add(Flatten(input_shape=class_data.shape[1:])) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(50, activation='softmax')) #model.add(Dense(4096, activation='relu')) #model.add(Dropout(0.5)) #model.add(Dense(4096, activation='relu')) #model.add(Dropout(0.5)) #model.add(Dense(50, activation='softmax')) sgd = SGD(lr=0.01) model.compile(optimizer=sgd, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, nb_epoch=40,validation_split=0, verbose=1) # we don't need a validation split print('Done!') val_pred_class = model.predict_classes(X_test,verbose=1) #val_pred_prob = model.predict_proba(class_data,verbose=0) print(model.evaluate(X_test,y_test,verbose=0)) # First number is validation loss, loss of the objective function # Second number validation accuracy print(np.unique(val_pred_class)) #ok 50 classes in our prediction np.sum(val_pred_class==y_test)/len(y_test) # ~60% accuracy print(model.evaluate(X_test,y_test,verbose=0)) print(DATA_DIR) def read_image(file_path): # For image visualization img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE #return cv2.resize(img, (img_height, img_width), interpolation=cv2.INTER_CUBIC) return img def plot_pic(img): # Plot openCV pic pic = read_image(img) plt.figure(figsize=(5,5)) plt.imshow(pic) plt.show() #alternative plotpic function import matplotlib.pyplot as plt import matplotlib.image as mpimg def plot_pic(img): image = mpimg.imread(img) plt.figure(figsize=(9,9)) plt.imshow(image) plt.grid(False) plt.show() def predict(mod,i=0,r=None): preds = mod.predict_classes(X_test,verbose=0) if r==None: r=[i] for idx in r: img_path = path_test[idx] img = image.load_img(img_path, target_size=(150, 150)) #x = image.img_to_array(img) #x = np.expand_dims(x, axis=0) class_pred = preds[idx] class_guess = img_cat_map[class_pred] print('\n\nProbable category: ' + class_guess) plot_pic(path_test[idx]) predict(model,r=range(0,100)) # As we can see below it is pretty accurate, however, for the case when we don't have many # training samples the accuracy is not as good. ``` <a id='sec6'></a> # Appendix: Training a small convnet from scratch: 80% accuracy in 40 lines of code The right tool for an image classification job is a convnet, so let's try to train one on our data, as an initial baseline. Since we only have few examples, our number one concern should be overfitting. Overfitting happens when a model exposed to too few examples learns patterns that do not generalize to new data, i.e. when the model starts using irrelevant features for making predictions. For instance, if you, as a human, only see three images of people who are lumberjacks, and three, images of people who are sailors, and among them only one lumberjack wears a cap, you might start thinking that wearing a cap is a sign of being a lumberjack as opposed to a sailor. You would then make a pretty lousy lumberjack/sailor classifier. Data augmentation is one way to fight overfitting, but it isn't enough since our augmented samples are still highly correlated. Your main focus for fighting overfitting should be the entropic capacity of your model --how much information your model is allowed to store. A model that can store a lot of information has the potential to be more accurate by leveraging more features, but it is also more at risk to start storing irrelevant features. Meanwhile, a model that can only store a few features will have to focus on the most significant features found in the data, and these are more likely to be truly relevant and to generalize better. There are different ways to modulate entropic capacity. The main one is the choice of the number of parameters in your model, i.e. the number of layers and the size of each layer. Another way is the use of weight regularization, such as L1 or L2 regularization, which consists in forcing model weights to taker smaller values. In our case we will use a very small convnet with few layers and few filters per layer, alongside data augmentation and dropout. Dropout also helps reduce overfitting, by preventing a layer from seeing twice the exact same pattern, thus acting in a way analoguous to data augmentation (you could say that both dropout and data augmentation tend to disrupt random correlations occuring in your data). The code snippet below is our first model, a simple stack of 3 convolution layers with a ReLU activation and followed by max-pooling layers. This is very similar to the architectures that Yann LeCun advocated in the 1990s for image classification (with the exception of ReLU). In order to make the most of our few training examples, we will "augment" them via a number of random transformations, so that our model would never see twice the exact same picture. This helps prevent overfitting and helps the model generalize better. In Keras this can be done via the keras.preprocessing.image.ImageDataGenerator class. This class allows you to: configure random transformations and normalization operations to be done on your image data during training instantiate generators of augmented image batches (and their labels) via .flow(data, labels) or .flow_from_directory(directory). These generators can then be used with the Keras model methods that accept data generators as inputs, fit_generator, evaluate_generator and predict_generator. ``` # Import image data generator datagen = ImageDataGenerator( rotation_range=40, #rotation_range degrees (0-180), range that randomly rotate pictures width_shift_range=0.2, #width_shift range (fraction of total width) within which to randomly translate pic height_shift_range=0.2, # -ii- #rescale value we multiply the data before any other processing. #Our original images consist in RGB coefficients in the 0-255, #but such values would be too high for our models to process (given typical learning rate), # so we target values between 0 and 1 instead by scaling with a 1/255. factor. rescale=1./255, #randomly applying shearing transformations (shear mapping is a linear map that #displaces each point in fixed direction, by an amount proportional to its #signed distance from a line that is parallel to that direction) shear_range=0.2, zoom_range=0.2, #randomly zooming inside pictures #is for randomly flipping half of the images horizontally #--relevant when there are no assumptions of horizontal assymetry (e.g. real-world pictures). horizontal_flip=True, #is the strategy used for filling in newly created pixels, #which can appear after a rotation or a width/height shift. fill_mode='nearest') ``` Now let's start generating some pictures using this tool and save them to a temporary directory, so we can get a feel for what our augmentation strategy is doing --we disable rescaling in this case to keep the images displayable: ``` img = load_img(TRAIN_DIR+'cats/cat0001.jpg') # this is a PIL image x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150) x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150) # the .flow() command below generates batches of randomly transformed images # and saves the results to the `preview/` directory i = 0 from PIL import Image if not os.path.exists('preview'): os.makedirs('preview') for batch in datagen.flow(x, batch_size=1, save_to_dir='preview', save_prefix='cat', save_format='jpeg'): i += 1 if i > 20: break # otherwise the generator would loop indefinitely prev_files = next(os.walk('./preview'))[2] print(prev_files[:4]) def read_image(file_path): # For image visualization im = np.array(Image.open(file_path)) img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE return im def plot_pic(img): # Plot openCV pic pic = read_image(img) plt.figure(figsize=(5,5)) plt.imshow(pic) plt.show() for img in prev_files[:4]: print('Image '+img) plot_pic('./preview/'+img) def first_model(): model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=(img_height, img_width, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) ''' On top of it we stick two fully-connected layers. We end the model with a single unit and a sigmoid activation, which is perfect for a binary classification. To go with it we will also use the binary_crossentropy loss to train our model. ''' model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors 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']) # Let's prepare our data. We will use .flow_from_directory() # to generate batches of image data (and their labels) directly from our jpgs in their respective folders. # Below is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing: # only rescaling test_datagen = ImageDataGenerator(rescale=1./255) # this is a generator that will read pictures found in # subfolers of 'data/train', and indefinitely generate # batches of augmented image data print('Train generator') train_generator = train_datagen.flow_from_directory( TRAIN_DIR, # this is the target directory target_size=(img_height, img_width), # all images will be resized to 150x150 batch_size=32, class_mode='binary') # since we use binary_crossentropy loss, we need binary labels # this is a similar generator, for validation data print('Validation generator') validation_generator = test_datagen.flow_from_directory( VAL_DIR, target_size=(img_height, img_width), batch_size=32, class_mode='binary') return model, train_generator, validation_generator # Look at class indices from our generators _, train_gen,val_gen =first_model() print('') print(val_gen.class_indices) print(val_gen.classes) # Define and fit the first model n_epoch = 50 # should be around 50 epochs for 80% accuracy def fit_first_model(): mod1, train_generator, validation_generator = first_model() mod1.fit_generator( train_generator, samples_per_epoch=n_train_samples, nb_epoch=n_epoch, validation_data=validation_generator, nb_val_samples=n_validation_samples) # save model to disk mod1.save_weights('w_appendix.h5') # always save your weights after training or during training model_json = mod1.to_json() with open("mod_appendix.json", "w") as json_file: json_file.write(model_json) print("Saved model to disk") #fit_first_model() print('This has already been run!') ### DONE ### # FIRST MODEL EXPLORATION # load model 1 and weights json_file = open('mod_appendix.json', 'r') loaded_model_json = json_file.read() json_file.close() mod1 = model_from_json(loaded_model_json) # load weights into new model mod1.load_weights("w_appendix.h5") print("Loaded model from disk") mod1.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Extract image features from test set - to make predictions datagen = ImageDataGenerator(rescale=1./255) # this is a similar generator, for validation data val_generator = datagen.flow_from_directory( VAL_DIR, target_size=(img_height, img_width), batch_size=32,class_mode='binary') preds = mod1.evaluate_generator(val_generator,n_validation_samples) print('\nModel 1 accuracy on 800 validation images:', round(sum(preds)/2,4)*100,'%') # Plot picture and print class prediction on cats vs dogs (unsorted) try_images = [TEST_DIR+'catvdog/'+img for img in os.listdir(TEST_DIR+'catvdog/')] def predict(mod,i=0,r=None): if r==None: r=[i] for idx in r: if 'DS_Store' in try_images[idx]: continue img_path = try_images[idx] img = image.load_img(img_path, target_size=(150, 150)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) class_pred = mod.predict_classes(x,verbose=0) if class_pred == 0: class_guess='CAT' else: class_guess='DOG' print('\n\nI think this is a ' + class_guess) plot_pic(try_images[idx]) predict(mod1,r=range(len(try_images)-64)) ```
github_jupyter
``` import numpy as np import pandas as pd import talib def fix_data(path): tmp = pd.read_csv(path, encoding="gbk", engine='python') tmp.rename(columns={'Unnamed: 0':'trading_time'}, inplace=True) tmp['trading_point'] = pd.to_datetime(tmp.trading_time) del tmp['trading_time'] tmp.set_index(tmp.trading_point, inplace=True) return tmp def High_2_Low(tmp, freq): """处理从RiceQuant下载的分钟线数据, 从分钟线数据合成低频数据 2017-08-11 """ # 分别处理bar数据 tmp_open = tmp['open'].resample(freq).ohlc() tmp_open = tmp_open['open'].dropna() tmp_high = tmp['high'].resample(freq).ohlc() tmp_high = tmp_high['high'].dropna() tmp_low = tmp['low'].resample(freq).ohlc() tmp_low = tmp_low['low'].dropna() tmp_close = tmp['close'].resample(freq).ohlc() tmp_close = tmp_close['close'].dropna() tmp_price = pd.concat([tmp_open, tmp_high, tmp_low, tmp_close], axis=1) # 处理成交量 tmp_volume = tmp['volume'].resample(freq).sum() tmp_volume.dropna(inplace=True) return pd.concat([tmp_price, tmp_volume], axis=1) def get_factors(index, Open, Close, High, Low, Volume, rolling = 26, drop=False, normalization=True): tmp = pd.DataFrame() tmp['tradeTime'] = index #累积/派发线(Accumulation / Distribution Line,该指标将每日的成交量通过价格加权累计, #用以计算成交量的动量。属于趋势型因子 tmp['AD'] = talib.AD(High, Low, Close, Volume) # 佳庆指标(Chaikin Oscillator),该指标基于AD曲线的指数移动均线而计算得到。属于趋势型因子 tmp['ADOSC'] = talib.ADOSC(High, Low, Close, Volume, fastperiod=3, slowperiod=10) # 平均动向指数,DMI因子的构成部分。属于趋势型因子 tmp['ADX'] = talib.ADX(High, Low, Close,timeperiod=14) # 相对平均动向指数,DMI因子的构成部分。属于趋势型因子 tmp['ADXR'] = talib.ADXR(High, Low, Close,timeperiod=14) # 绝对价格振荡指数 tmp['APO'] = talib.APO(Close, fastperiod=12, slowperiod=26) # Aroon通过计算自价格达到近期最高值和最低值以来所经过的期间数,帮助投资者预测证券价格从趋势到区域区域或反转的变化, #Aroon指标分为Aroon、AroonUp和AroonDown3个具体指标。属于趋势型因子 tmp['AROONDown'], tmp['AROONUp'] = talib.AROON(High, Low,timeperiod=14) tmp['AROONOSC'] = talib.AROONOSC(High, Low,timeperiod=14) # 均幅指标(Average TRUE Ranger),取一定时间周期内的股价波动幅度的移动平均值, #是显示市场变化率的指标,主要用于研判买卖时机。属于超买超卖型因子。 tmp['ATR14']= talib.ATR(High, Low, Close, timeperiod=14) tmp['ATR6']= talib.ATR(High, Low, Close, timeperiod=6) # 布林带 tmp['Boll_Up'],tmp['Boll_Mid'],tmp['Boll_Down']= talib.BBANDS(Close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) # 均势指标 tmp['BOP'] = talib.BOP(Open, High, Low, Close) #5日顺势指标(Commodity Channel Index),专门测量股价是否已超出常态分布范围。属于超买超卖型因子。 tmp['CCI5'] = talib.CCI(High, Low, Close, timeperiod=5) tmp['CCI10'] = talib.CCI(High, Low, Close, timeperiod=10) tmp['CCI20'] = talib.CCI(High, Low, Close, timeperiod=20) tmp['CCI88'] = talib.CCI(High, Low, Close, timeperiod=88) # 钱德动量摆动指标(Chande Momentum Osciliator),与其他动量指标摆动指标如相对强弱指标(RSI)和随机指标(KDJ)不同, # 钱德动量指标在计算公式的分子中采用上涨日和下跌日的数据。属于超买超卖型因子 tmp['CMO_Close'] = talib.CMO(Close,timeperiod=14) tmp['CMO_Open'] = talib.CMO(Close,timeperiod=14) # DEMA双指数移动平均线 tmp['DEMA6'] = talib.DEMA(Close, timeperiod=6) tmp['DEMA12'] = talib.DEMA(Close, timeperiod=12) tmp['DEMA26'] = talib.DEMA(Close, timeperiod=26) # DX 动向指数 tmp['DX'] = talib.DX(High, Low, Close,timeperiod=14) # EMA 指数移动平均线 tmp['EMA6'] = talib.EMA(Close, timeperiod=6) tmp['EMA12'] = talib.EMA(Close, timeperiod=12) tmp['EMA26'] = talib.EMA(Close, timeperiod=26) # KAMA 适应性移动平均线 tmp['KAMA'] = talib.KAMA(Close, timeperiod=30) # MACD tmp['MACD_DIF'],tmp['MACD_DEA'],tmp['MACD_bar'] = talib.MACD(Close, fastperiod=12, slowperiod=24, signalperiod=9) # 中位数价格 不知道是什么意思 tmp['MEDPRICE'] = talib.MEDPRICE(High, Low) # 负向指标 负向运动 tmp['MiNUS_DI'] = talib.MINUS_DI(High, Low, Close,timeperiod=14) tmp['MiNUS_DM'] = talib.MINUS_DM(High, Low,timeperiod=14) # 动量指标(Momentom Index),动量指数以分析股价波动的速度为目的,研究股价在波动过程中各种加速, #减速,惯性作用以及股价由静到动或由动转静的现象。属于趋势型因子 tmp['MOM'] = talib.MOM(Close, timeperiod=10) # 归一化平均值范围 tmp['NATR'] = talib.NATR(High, Low, Close,timeperiod=14) # OBV 能量潮指标(On Balance Volume,OBV),以股市的成交量变化来衡量股市的推动力, #从而研判股价的走势。属于成交量型因子 tmp['OBV'] = talib.OBV(Close, Volume) # PLUS_DI 更向指示器 tmp['PLUS_DI'] = talib.PLUS_DI(High, Low, Close,timeperiod=14) tmp['PLUS_DM'] = talib.PLUS_DM(High, Low, timeperiod=14) # PPO 价格振荡百分比 tmp['PPO'] = talib.PPO(Close, fastperiod=6, slowperiod= 26, matype=0) # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较, #通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。 tmp['ROC6'] = talib.ROC(Close, timeperiod=6) tmp['ROC20'] = talib.ROC(Close, timeperiod=20) #12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较, #通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向, #达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿, #属于成交量的反趋向指标。属于成交量型因子 tmp['VROC6'] = talib.ROC(Volume, timeperiod=6) tmp['VROC20'] = talib.ROC(Volume, timeperiod=20) # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较, #通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。 tmp['ROCP6'] = talib.ROCP(Close, timeperiod=6) tmp['ROCP20'] = talib.ROCP(Close, timeperiod=20) #12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较, #通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向, #达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿, #属于成交量的反趋向指标。属于成交量型因子 tmp['VROCP6'] = talib.ROCP(Volume, timeperiod=6) tmp['VROCP20'] = talib.ROCP(Volume, timeperiod=20) # RSI tmp['RSI'] = talib.RSI(Close, timeperiod=14) # SAR 抛物线转向 tmp['SAR'] = talib.SAR(High, Low, acceleration=0.02, maximum=0.2) # TEMA tmp['TEMA6'] = talib.TEMA(Close, timeperiod=6) tmp['TEMA12'] = talib.TEMA(Close, timeperiod=12) tmp['TEMA26'] = talib.TEMA(Close, timeperiod=26) # TRANGE 真实范围 tmp['TRANGE'] = talib.TRANGE(High, Low, Close) # TYPPRICE 典型价格 tmp['TYPPRICE'] = talib.TYPPRICE(High, Low, Close) # TSF 时间序列预测 tmp['TSF'] = talib.TSF(Close, timeperiod=14) # ULTOSC 极限振子 tmp['ULTOSC'] = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28) # 威廉指标 tmp['WILLR'] = talib.WILLR(High, Low, Close, timeperiod=14) # 标准化 if normalization: factors_list = tmp.columns.tolist()[1:] if rolling >= 26: for i in factors_list: tmp[i] = (tmp[i] - tmp[i].rolling(window=rolling, center=False).mean())\ /tmp[i].rolling(window=rolling, center=False).std() elif rolling < 26 & rolling > 0: print ('Recommended rolling range greater than 26') elif rolling <=0: for i in factors_list: tmp[i] = (tmp[i] - tmp[i].mean())/tmp[i].std() if drop: tmp.dropna(inplace=True) tmp.set_index('tradeTime', inplace=True) return tmp tmp = fix_data('HS300.csv') tmp = High_2_Low(tmp, '5min') Dtmp = High_2_Low(tmp, '1d') Index = tmp.index High = tmp.high.values Low = tmp.low.values Close = tmp.close.values Open = tmp.open.values Volume = tmp.volume.values factors = get_factors(Index, Open, Close, High, Low, Volume, rolling = 188, drop=True) Dtmp['returns'] = np.log(Dtmp['close'].shift(-1)/Dtmp['close']) Dtmp.dropna(inplace=True) start_date = pd.to_datetime('2011-01-12') end_date = pd.to_datetime('2016-12-29') Dtmp = Dtmp.loc[start_date:end_date] Dtmp = Dtmp.iloc[5:] factors = factors.loc[start_date:end_date] flist = [] for i in range(len(Dtmp)): s = i * 50 e = (i + 5) * 50 f = np.array(factors.iloc[s:e]) flist.append(np.expand_dims(f, axis=0)) fac_array = np.concatenate(flist, axis=0) shape = [fac_array.shape[0], 5, 50, fac_array.shape[2]] fac_array = fac_array.reshape(shape) fac_array = np.transpose(fac_array, [0,2,3,1]) data_quotes = Dtmp data_fac = fac_array class Account(object): def __init__(self, data_quotes, data_fac): self.data_close = data_quotes['close'] self.data_open = data_quotes['open'] self.data_observation = data_fac self.action_space = ['long', 'short', 'close'] self.free = 1e-4 self.reset() def reset(self): self.step_counter = 0 self.cash = 1e5 self.position = 0 self.total_value = self.cash + self.position self.flags = 0 def get_initial_state(self): return np.expand_dims(self.data_observation[0],axis=0) def get_action_space(self): return self.action_space def long(self): self.flags = 1 quotes = self.data_open[self.step_counter] * 10 self.cash -= quotes * (1 + self.free) self.position = quotes def short(self): self.flags = -1 quotes = self.data_open[self.step_counter] * 10 self.cash += quotes * (1 - self.free) self.position = - quotes def keep(self): quotes = self.data_open[self.step_counter] * 10 self.position = quotes * self.flags def close_long(self): self.flags = 0 quotes = self.data_open[self.step_counter] * 10 self.cash += quotes * (1 - self.free) self.position = 0 def close_short(self): self.flags = 0 quotes = self.data_open[self.step_counter] * 10 self.cash -= quotes * (1 + self.free) self.position = 0 def step_op(self, action): if action == 'long': if self.flags == 0: self.long() elif self.flags == -1: self.close_short() self.long() else: self.keep() elif action == 'close': if self.flags == 1: self.close_long() elif self.flags == -1: self.close_short() else: pass elif action == 'short': if self.flags == 0: self.short() elif self.flags == 1: self.close_long() self.short() else: self.keep() else: raise ValueError("action should be elements of ['long', 'short', 'close']") position = self.data_close[self.step_counter] * 10 * self.flags reward = self.cash + position - self.total_value self.step_counter += 1 self.total_value = position + self.cash next_observation = self.data_observation[self.step_counter] done = False if self.total_value < 4000: done = True if self.step_counter > 1000: done = True return reward, np.expand_dims(next_observation, axis=0), done def step(self, action): if action == 0: return self.step_op('long') elif action == 1: return self.step_op('short') elif action == 2: return self.step_op('close') else: raise ValueError("action should be one of [0,1,2]") env = Account(data_quotes, data_fac) ```
github_jupyter
# 範例 : 計程車費率預測 https://www.kaggle.com/c/new-york-city-taxi-fare-prediction *** - 使用並觀察特徵組合在計程車費率預測競賽的影響 ``` # 做完特徵工程前的所有準備 import pandas as pd import numpy as np import datetime from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn.ensemble import GradientBoostingRegressor data_path = 'data/' df = pd.read_csv(data_path + 'taxi_data1.csv') train_Y = df['fare_amount'] df = df.drop(['fare_amount'] , axis=1) df.head() # 時間特徵分解方式:使用datetime df['pickup_datetime'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S UTC')) df['pickup_year'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%Y')).astype('int64') df['pickup_month'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%m')).astype('int64') df['pickup_day'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%d')).astype('int64') df['pickup_hour'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%H')).astype('int64') df['pickup_minute'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%M')).astype('int64') df['pickup_second'] = df['pickup_datetime'].apply(lambda x: datetime.datetime.strftime(x, '%S')).astype('int64') df.head() # 將結果使用線性迴歸 / 梯度提升樹分別看結果 df = df.drop(['pickup_datetime'] , axis=1) scaler = MinMaxScaler() train_X = scaler.fit_transform(df) Linear = LinearRegression() print(f'Linear Reg Score : {cross_val_score(Linear, train_X, train_Y, cv=5).mean()}') GDBT = GradientBoostingRegressor() print(f'Gradient Boosting Reg Score : {cross_val_score(GDBT, train_X, train_Y, cv=5).mean()}') # 增加緯度差, 經度差, 座標距離等三個特徵 df['longitude_diff'] = df['dropoff_longitude'] - df['pickup_longitude'] df['latitude_diff'] = df['dropoff_latitude'] - df['pickup_latitude'] df['distance_2D'] = (df['longitude_diff']**2 + df['latitude_diff']**2)**0.5 df[['distance_2D', 'longitude_diff', 'latitude_diff', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude']].head() # 結果 : 準確度上升 train_X = scaler.fit_transform(df) print(f'Linear Reg Score : {cross_val_score(Linear, train_X, train_Y, cv=5).mean()}') print(f'Gradient Boosting Reg Score : {cross_val_score(GDBT, train_X, train_Y, cv=5).mean()}') ``` # 作業1 * 參考今日教材,試著使用經緯度一圈的長度比這一概念,組合出一個新特徵,再觀察原特徵加上新特徵是否提升了正確率? Ans:有,迴歸方法顯著提升 ``` import math """ Your Code Here, set new character at df['distance_real'] """ df['distance_real']=(df['longitude_diff']**2 + (df['latitude_diff']*0.75756)**2)**0.5 # 觀察結果 train_X = scaler.fit_transform(df) print(f'Linear Reg Score : {cross_val_score(Linear, train_X, train_Y, cv=5).mean()}') print(f'Gradient Boosting Reg Score : {cross_val_score(GDBT, train_X, train_Y, cv=5).mean()}') ``` # 作業2 * 試著只使用新特徵估計目標值(忽略原特徵),效果跟作業1的結果比較起來效果如何? ans:單使用新特徵估計目標值效果,不管再迴歸或GDBT上效果皆顯著地降低 ``` train_X = scaler.fit_transform(df[['distance_real']]) print(f'Linear Reg Score : {cross_val_score(Linear, train_X, train_Y, cv=5).mean()}') print(f'Gradient Boosting Reg Score : {cross_val_score(GDBT, train_X, train_Y, cv=5).mean()}') train_X = scaler.fit_transform(df[['distance_2D']]) print(f'Linear Reg Score : {cross_val_score(Linear, train_X, train_Y, cv=5).mean()}') print(f'Gradient Boosting Reg Score : {cross_val_score(GDBT, train_X, train_Y, cv=5).mean()}') ```
github_jupyter
``` try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import numpy as np import tensorflow as tf ``` ## Fetching the Data This is a bit annoying. But to download from kaggle we need to upload the kaggle API key here. Then we need to move the file to the correct folder after which we need to change the permissions. The error messages will not provide super helpful information so I've added the correct code here. You can also upload the dataset from kaggle manually or you can download all of this locally. The kaggle dataset can be found [here](https://www.kaggle.com/therohk/million-headlines). Then again, this code works; ``` # from google.colab import files # files.upload() # ! cp kaggle.json ~/.kaggle/} # ! chmod 600 ~/.kaggle/kaggle.json # ! kaggle datasets download -d therohk/million-headlines import pandas as pd headlines = pd.read_csv('million-headlines.zip')['headline_text'] ``` ## Sequence of Letters Let's now take these headlines and grab sequences of letters out of them. ``` headlines[0] import itertools as it def sliding_window(txt): for i in range(len(txt) - 1): yield txt[i], txt[i + 1] window = list(it.chain(*[sliding_window(_) for _ in headlines[:10000]])) mapping = {c: i for i, c in enumerate(pd.DataFrame(window)[0].unique())} integers_in = np.array([mapping[w[0]] for w in window]) integers_out = np.array([mapping[w[1]] for w in window]).reshape(-1, 1) integers_in.shape from tensorflow.keras.layers import Embedding, Dense, Flatten from tensorflow.keras.models import Sequential num_letters = len(mapping) # typically 36 -> 26 letters + 10 numbers # this one is so we might grab the embeddings model_emb = Sequential() embedding = Embedding(num_letters, 2, input_length=1) model_emb.add(embedding) output_array = model_emb.predict(integers_in) output_array.shape import matplotlib.pylab as plt idx_to_calc = list(mapping.values()) idx_to_calc = np.array([idx_to_calc]).T translator = {v:k for k,v in mapping.items()} preds = model_emb.predict(idx_to_calc) plt.scatter(preds[:, 0, 0], preds[:, 0, 1], alpha=0) for i, idx in enumerate(idx_to_calc): plt.text(preds[i, 0, 0], preds[i, 0, 1], translator[idx[0]]) from tensorflow.keras.optimizers import Adam # this one is so we might learn the mapping model_pred = Sequential() model_pred.add(embedding) model_pred.add(Flatten()) model_pred.add(Dense(num_letters, activation="softmax")) adam = Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) model_pred.compile(adam, 'categorical_crossentropy', metrics=['accuracy']) output_array = model_pred.predict(integers_in) output_array.shape from sklearn.preprocessing import OneHotEncoder to_predict = OneHotEncoder(sparse=False).fit_transform(integers_out) model_pred.fit(integers_in, to_predict, epochs=30, verbose=1) preds = model_emb.predict(idx_to_calc) plt.scatter(preds[:, 0, 0], preds[:, 0, 1], alpha=0) for i, idx in enumerate(idx_to_calc): plt.text(preds[i, 0, 0], preds[i, 0, 1], translator[idx[0]]) ```
github_jupyter
``` %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import os import numpy as np import csv import re import itertools import copy from sklearn import * from collections import Counter def iterate_rows(): filename = 'simbadresult.csv' if not os.path.isfile(filename): compressed_filename = '{}.xz'.format(filename) if os.path.isfile(compressed_filename): raise OSError('Found compressed file: {}. Uncompress with unxz'.format( compressed_filename)) else: raise OSError('Cannot find {}.'.format(filename)) with open('simbadresult.csv') as infile: reader = csv.DictReader(infile) for row in reader: yield row # SPTYPE_REGEX = re.compile(r'[OBAFGKM][0-9](I|II|III|IV|V)') # For now only handle main sequence stars SPTYPE_REGEX = re.compile(r'(?P<typ>[OBAFGKM])(?P<cls>[0-9](\.[0-9]+)?)V') SPTYPES = ['O', 'B', 'A', 'F', 'G', 'K', 'M'] SP_TYPE_MAPPING = {value: index for (index, value) in enumerate(SPTYPES)} def parse_sptype(sptype): match = SPTYPE_REGEX.match(sptype) if match: return match.group(0) def spclass_to_number(cls): match = SPTYPE_REGEX.match(cls) assert match int_part = SP_TYPE_MAPPING[match.group('typ')] float_part = float(match.group('cls')) / 10.0 return int_part + float_part def number_to_spclass(num): int_part = int(num) float_part = float((num % 1) * 10) label = SPTYPES[int_part] + "{:.1f}".format(float_part) + 'V' if '.0' in label: return label.replace('.0', '') return label required_bands = ['B', 'V', 'R', 'J', 'H', 'K'] wavelength_centres = { 'U': 365, 'B': 445, 'V': 551, 'J': 1220, 'H': 1630, 'K': 2190, } rows = {} for i, row in enumerate(iterate_rows()): sp_type = parse_sptype(row['sp_type']) if not sp_type: continue mag_label = row['filter'] if mag_label not in required_bands: continue mag_value = float(row['flux']) obj_id = row['main_id'] if obj_id in rows: if 'sp_type' not in rows[obj_id]: rows[obj_id]['sp_type'] = sp_type rows[obj_id][mag_label] = mag_value else: rows[obj_id] = {'sp_type': sp_type} for filt in required_bands: rows[obj_id][filt] = float('nan') rows[obj_id][mag_label] = mag_value rows = list(rows.values()) def all_filters_valid(entry): return np.all([np.isfinite(entry[filt]) for filt in required_bands]) def interpolate_magnitudes(entry): if not np.isfinite(entry[required_bands[0]]) or not np.isfinite(entry[required_bands[-1]]): return None out = copy.deepcopy(entry) i = 0 while True: for filt in required_bands[1:-1]: if not np.isfinite(out[filt]): index = required_bands.index(filt) prev_index, next_index = index - 1, index + 1 prev_mag, next_mag = required_bands[prev_index], required_bands[next_index] if np.isfinite(out[prev_mag]) and np.isfinite(out[next_mag]): new_value = (out[prev_mag] + out[next_mag]) / 2. out[filt] = new_value else: return None if all_filters_valid(out): break return out valid_rows = list(filter(None, [interpolate_magnitudes(entry) for entry in rows])) for i, row in enumerate(valid_rows): assert np.all([np.isfinite(row[filt]) for filt in required_bands]), (row, i) valid_colours = [] for (start_band, end_band) in itertools.product(required_bands, required_bands): if required_bands.index(start_band) < required_bands.index(end_band): valid_colours.append((start_band, end_band)) print(valid_colours) X, y = [], [] for row in valid_rows: entry = [] for (start_band, end_band) in valid_colours: colour_value = row[start_band] - row[end_band] assert np.isfinite(colour_value), (start_band, end_band, row) entry.append(colour_value) X.append(entry) y.append(row['sp_type']) X, y = [np.array(data) for data in [X, y]] assert np.all([np.isfinite(val) for val in X.ravel()]) c = Counter(y) subtypes_to_remove = set([entry[0] for entry in c.most_common() if entry[1] < 10]) newX, newy = [], [] for i in range(X.shape[0]): if y[i] not in subtypes_to_remove: newX.append(X[i]) newy.append(spclass_to_number(y[i])) X, y = [np.array(data) for data in [newX, newy]] # params = {'n_estimators': [10]} # clf = model_selection.GridSearchCV(svm.SVR(), params) # clf.fit(X, y) clf = svm.SVR(kernel='linear') clf.fit(X, y) cv_score = model_selection.cross_val_score(clf, X, y).mean() print('Mean score when cross-validating: {}'.format(cv_score)) prediction = model_selection.cross_val_predict(clf, X, y) prediction_labels = np.array([number_to_spclass(p) for p in prediction]) y_labels = np.array([number_to_spclass(l) for l in y]) print(np.std(prediction - y)) plt.hist(np.abs(prediction - y), 50, range=(0, 1)) list(zip(y_labels, prediction_labels))[:100] plt.scatter(y, prediction) plt.grid(True) plt.plot(y, prediction - y, '.') plt.grid(True) fit = np.poly1d(np.polyfit(prediction, y, 3)) plt.plot(prediction, y, '.') plt.plot(prediction, fit(prediction), '.') plt.grid(True) def predict(X, clf): clf_prediction = clf.predict(X) return fit(clf_prediction) print(y[0], predict(np.atleast_2d(X[0]), clf)) plt.plot(y, predict(X, clf) - y, '.') plt.grid(True) ```
github_jupyter
# TensorFlow Fold Quick Start TensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors. ``` # boilerplate import random import tensorflow as tf sess = tf.InteractiveSession() import tensorflow_fold as td ``` The basic elements of Fold are *blocks*. We'll start with some blocks that work on simple data types. ``` scalar_block = td.Scalar() vector3_block = td.Vector(3) ``` Blocks are functions with associated input and output types. ``` def block_info(block): print("%s: %s -> %s" % (block, block.input_type, block.output_type)) block_info(scalar_block) block_info(vector3_block) ``` We can use `eval()` to see what a block does with its input: ``` scalar_block.eval(42) vector3_block.eval([1,2,3]) ``` Not very exciting. We can compose simple blocks together with `Record`, like so: ``` record_block = td.Record({'foo': scalar_block, 'bar': vector3_block}) block_info(record_block) ``` We can see that Fold's type system is a bit richer than vanilla TF; we have tuple types! Running a record block does what you'd expect: ``` record_block.eval({'foo': 1, 'bar': [5, 7, 9]}) ``` One useful thing you can do with blocks is wire them up to create pipelines using the `>>` operator, which performs function composition. For example, we can take our tuple two tensors and compose it with `Concat`, like so: ``` record2vec_block = record_block >> td.Concat() record2vec_block.eval({'foo': 1, 'bar': [5, 7, 9]}) ``` Note that because Python dicts are unordered, Fold always sorts the outputs of a record block by dictionary key. If you want preserve order you can construct a Record block from an OrderedDict. The whole point of Fold is to get your data into TensorFlow; the `Function` block lets you convert a TITO (Tensors On, Tensors Out) function to a block: ``` negative_block = record2vec_block >> td.Function(tf.negative) negative_block.eval({'foo': 1, 'bar': [5, 7, 9]}) ``` This is all very cute, but where's the beef? Things start to get interesting when our inputs contain sequences of indeterminate length. The `Map` block comes in handy here: ``` map_scalars_block = td.Map(td.Scalar()) ``` There's no TF type for sequences of indeterminate length, but Fold has one: ``` block_info(map_scalars_block) ``` Right, but you've done the TF [RNN Tutorial](https://www.tensorflow.org/tutorials/recurrent/) and even poked at [seq-to-seq](https://www.tensorflow.org/tutorials/seq2seq/). You're a wizard with [dynamic rnns](https://www.tensorflow.org/api_docs/python/nn/recurrent_neural_networks#dynamic_rnn). What does Fold offer? Well, how about jagged arrays? ``` jagged_block = td.Map(td.Map(td.Scalar())) block_info(jagged_block) ``` The Fold type system is fully compositional; any block you can create can be composed with `Map` to create a sequence, or `Record` to create a tuple, or both to create sequences of tuples or tuples of sequences: ``` seq_of_tuples_block = td.Map(td.Record({'foo': td.Scalar(), 'bar': td.Scalar()})) seq_of_tuples_block.eval([{'foo': 1, 'bar': 2}, {'foo': 3, 'bar': 4}]) tuple_of_seqs_block = td.Record({'foo': td.Map(td.Scalar()), 'bar': td.Map(td.Scalar())}) tuple_of_seqs_block.eval({'foo': range(3), 'bar': range(7)}) ``` Most of the time, you'll eventually want to get one or more tensors out of your sequence, for wiring up to your particular learning task. Fold has a bunch of built-in reduction functions for this that do more or less what you'd expect: ``` ((td.Map(td.Scalar()) >> td.Sum()).eval(range(10)), (td.Map(td.Scalar()) >> td.Min()).eval(range(10)), (td.Map(td.Scalar()) >> td.Max()).eval(range(10))) ``` The general form of such functions is `Reduce`: ``` (td.Map(td.Scalar()) >> td.Reduce(td.Function(tf.multiply))).eval(range(1,10)) ``` If the order of operations is important, you should use `Fold` instead of `Reduce` (but if you can use `Reduce` you should, because it will be faster): ``` ((td.Map(td.Scalar()) >> td.Fold(td.Function(tf.divide), tf.ones([]))).eval(range(1,5)), (td.Map(td.Scalar()) >> td.Reduce(td.Function(tf.divide), tf.ones([]))).eval(range(1,5))) # bad, not associative! ``` Now, let's do some learning! This is the part where "magic" happens; if you want a deeper understanding of what's happening here you might want to jump right to our more formal [blocks tutorial](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md) or learn more about [running blocks in TensorFlow](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/running.md) ``` def reduce_net_block(): net_block = td.Concat() >> td.FC(20) >> td.FC(1, activation=None) >> td.Function(lambda xs: tf.squeeze(xs, axis=1)) return td.Map(td.Scalar()) >> td.Reduce(net_block) ``` The `reduce_net_block` function creates a block (`net_block` that contains a two-layer fully connected (FC) network that takes a pair of scalar tensors as input and produces a scalar tensor as output. This network gets applied in a binary tree to reduce a sequence of scalar tensors to a single scalar tensor. One thing to notice here is that we are calling [`tf.squeeze`](https://www.tensorflow.org/versions/r1.0/api_docs/python/array_ops/shapes_and_shaping#squeeze) with `axis=1`, even though the Fold output type of `td.FC(1, activation=None)` (and hence the input type of the enclosing `Function` block) is a `TensorType` with shape `(1)`). This is because all Fold blocks actually run on TF tensors with an implicit leading batch dimension, which enables execution via [*dynamic batching*](https://openreview.net/pdf?id=ryrGawqex). It is important to bear this in mind when creating `Function` blocks that wrap functions that are not applied elementwise. ``` def random_example(fn): length = random.randrange(1, 10) data = [random.uniform(0,1) for _ in range(length)] result = fn(data) return data, result ``` The `random_example` function generates training data consisting of `(example, fn(example)` pairs, where `example` is a random list of numbers, e.g.: ``` random_example(sum) random_example(min) def train(fn, batch_size=100): net_block = reduce_net_block() compiler = td.Compiler.create((net_block, td.Scalar())) y, y_ = compiler.output_tensors loss = tf.nn.l2_loss(y - y_) train = tf.train.AdamOptimizer().minimize(loss) sess.run(tf.global_variables_initializer()) validation_fd = compiler.build_feed_dict(random_example(fn) for _ in range(1000)) for i in range(2000): sess.run(train, compiler.build_feed_dict(random_example(fn) for _ in range(batch_size))) if i % 100 == 0: print(i, sess.run(loss, validation_fd)) return net_block ``` Now we're going to train a neural network to approximate a reduction function of our choosing. Calling `eval()` repeatedly is super-slow and cannot exploit batch-wise parallelism, so we create a [`Compiler`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#compiler). See our page on [running blocks in TensorFlow](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/running.md) for more on Compilers and how to use them effectively. ``` sum_block = train(sum) sum_block.eval([1, 1]) ``` Breaking news; deep neural network learns to calculate 1 + 1!!!! Of course we've done something a little sneaky here by constructing a model that can only represent associative functions and then training it to compute an associative function. The technical term for being sneaky in machine learning is [inductive bias](https://en.wikipedia.org/wiki/Inductive_bias). ``` min_block = train(min) min_block.eval([2, -1, 4]) ``` Oh noes! What went wrong? Note that we trained our network to compute `min` on positive numbers; negative numbers are outside of it's input distribution. ``` min_block.eval([0.3, 0.2, 0.9]) ``` Well, that's better. What happens if you train the network on negative numbers as well as on positives? What if you only train on short lists and then evaluate the net on long ones? What if you used a `Fold` block instead of a `Reduce`? ... Happy Folding!
github_jupyter
### This is a simple/fast tutorial for creating experiments ``` from scheduling_functions import * from scheduling_algorithms import * import numpy as np import sys import copy from random import sample, randint, seed from math import isclose, ceil, floor from statistics import mean from decimal import * from fractions import * import matplotlib.pyplot as plt from operator import add ``` ## General instructions/restrictions 1. Usually job instances are denoted by J_something. They are python dictionaries in which every element is a tuple (job_weight, release_time, deadline). By convention we will refer to the job that arrives at time t as the job with id (key in the dictionary representation) t+1. 2. __Job weights should be integers >=0__. 3. The robustness parameter epsilon should be rational, e.g. epsilon = Fraction(1,10). Most internal operations in the scheduling libraries use the __fraction module__ to avoid errors due to arithmetic precision. 4. To create a job instance easily, use the job_instance_creation function, the inputs should be a weights list, and D. The i-th element of the weights list (ws[i-1]) represents the job which is released at time i-1. 5. To create a bounded random walk as described in the paper, use random_walk_creation 6. The functions __AVR_energy_ratio__, __OA_energy_ratio__, __BKP_energy_ratio__ and __LAS_energy_ratio__ take as input a job instance as described before and give as output the competitive ratios of the respective algorithms. ``` #creates a bounded random walk: def random_walk_creation(num_jobs, step_size, random_seed, m, M): seed(random_seed) ws = [0]*num_jobs ws[0] = randint(m,M) steps = [randint(-step_size,step_size) for i in range(1,num_jobs)] for i in range(1, num_jobs): ws[i] = ws[i-1] + steps[i-1] ws[i] = min(ws[i], M) ws[i] = max(ws[i], m) return ws #creates a job instance given a list of weights and T def job_instance_creation(ws, T): # dictionary: key --> job id # value --> (weight, release time , deadline) J = {} job_id = 1 i = 0 for job_weight in ws: J[job_id] = (job_weight , i, i+T) i+=1 job_id+=1 return J #returns the energy ratio AVR_energy/Optimal_energy def AVR_energy_ratio(_J, alpha): J = copy.deepcopy(_J) #speed list of average rate AVR_speed_list = Avg_rate(J) #energy consumption of AVR energy_AVR = compute_energy(AVR_speed_list, alpha) J = copy.deepcopy(_J) #speed list of the optimal schedule optimal_alg_speed_list, _ = Optimal_Alg(J) #energy consumption of the optimal schedule energy_optimal = compute_energy(optimal_alg_speed_list, alpha) return float(energy_AVR)/energy_optimal #returns the energy ratio OA_energy/Optimal_energy def OA_energy_ratio(_J, alpha): J = copy.deepcopy(_J) #speed list of Optimal Available OA_speed_list = OptimalOnline(J) #energy consumption of Optimal Available energy_OA = sum([s**alpha for s in OA_speed_list]) J = copy.deepcopy(_J) #speed list of the optimal schedule optimal_alg_speed_list, _ = Optimal_Alg(J) #energy consumption of the optimal schedule energy_optimal = compute_energy(optimal_alg_speed_list, alpha) return float(energy_OA)/energy_optimal #returns the energy ratio BKP_energy/Optimal_energy def BKP_energy_ratio(_J, granularity, alpha): J = copy.deepcopy(_J) #energy consumption of the BKP algorithm energy_BKP = BKP_alg(J, granularity, alpha) J = copy.deepcopy(_J) #speed list of the optimal schedule optimal_alg_speed_list, _ = Optimal_Alg(J) #energy consumption of the optimal schedule energy_optimal = compute_energy(optimal_alg_speed_list, alpha) return float(energy_BKP)/energy_optimal #returns the energy ratio LAS_energy/Optimal_energy def LAS_energy_ratio(_J_true, _J_pred, epsilon, alpha, dt): #compute energy of LAS algorithm J_true = copy.deepcopy(_J_true) J_pred = copy.deepcopy(_J_pred) speed_sol = LAS(J_pred, J_true, epsilon, dt, alpha) energy_LAS = sum([s**alpha for s in speed_sol])*dt #compute speedlist and energu consumption of the optimal schedule of the true instance J_true = copy.deepcopy(_J_true) J_pred = copy.deepcopy(_J_pred) optimal_alg_speed_list, _ = Optimal_Alg(J_true) energy_optimal = compute_energy(optimal_alg_speed_list, alpha) return float(energy_LAS)/energy_optimal ``` ### First experiment #### parameters setting ``` num_jobs = 80 D = 10 alpha = 3 epsilon = Fraction(1,20) dt = 0.01 bkp_granularity = 0.25 ``` #### we create a random ground truth instance ``` w_min = 10 w_max = 100 w_true = [randint(w_min,w_max) for _ in range(0,num_jobs)] J_true = job_instance_creation(w_true, D) ``` #### we create a very accurate predictor by adding pointwise a small integer error between [-3,3] ``` s = 3 error = [randint(-s,s) for _ in range(0,num_jobs)] w_pred = list(map(add,w_true, error)) J_pred = job_instance_creation(w_pred, D) ``` #### now we will calculate the competitive ratio of the online algorithms AVR, OA and BKP ``` AVR = AVR_energy_ratio(J_true, alpha) print("AVR competitive ratio: ", AVR) OA = OA_energy_ratio(J_true, alpha) print("OA competitive ratio: ", OA) BKP = BKP_energy_ratio(J_true, bkp_granularity, alpha) print("BKP competitive ratio: ", BKP) ``` #### now we will calculate the competitive ratio of LAS algorithm with $\epsilon = 1/20$ ``` LAS_ratio = LAS_energy_ratio(J_true, J_pred, epsilon, alpha, dt) print("LAS competitive ratio: ", LAS_ratio) ``` #### we will repeat the experiment by using a perfect predictor and LAS algorithm with $\epsilon = 1/20$ ``` LAS_ratio = LAS_energy_ratio(J_true, J_true, epsilon, alpha, dt) print("LAS competitive ratio: ", LAS_ratio) ``` ### Second experiment #### we will create an instance which mimics a bounded random walk and an accurate predictor ``` M = 100 m = 10 random_seed = 10 step_size = 10 s = 10 w_true = random_walk_creation(num_jobs, step_size, random_seed, m, M) J_true = job_instance_creation(w_true, D) error = [randint(-s,s) for _ in range(0,num_jobs)] w_pred = list(map(add,w_true, error)) J_pred = job_instance_creation(w_pred, D) ``` #### we will plot the weights of the true and the predicted instance ``` x = range(0, num_jobs) plt.plot(x, w_true, label = "True instance") plt.plot(x, w_pred, label = "Predicted instance") plt.legend(loc="upper left") plt.show() ``` #### performance of LAS with $\epsilon = 1/20$ ``` LAS_ratio = LAS_energy_ratio(J_true, J_pred, epsilon, alpha, dt) print("LAS competitive ratio: ", LAS_ratio) ```
github_jupyter
# About this Notebook --- **Bayesian Gaussian CP decomposition** (or **BGCP** for short) is a type of Bayesian tensor decomposition that achieves state-of-the-art results on challenging the missing data imputation problem. In the following, we will discuss: - What the Bayesian Gaussian CP decomposition is. - How to implement BGCP mainly using Python `numpy` with high efficiency. - How to make imputations with real-world spatiotemporal datasets. If you want to understand BGCP and its modeling tricks in detail, our paper is for you: > Xinyu Chen, Zhaocheng He, Lijun Sun (2019). **A Bayesian tensor decomposition approach for spatiotemporal traffic data imputation**. Transportation Research Part C: Emerging Technologies, 98: 73-84. [[**data**](https://doi.org/10.5281/zenodo.1205228)] [[**Matlab code**](https://github.com/lijunsun/bgcp_imputation)] ## Quick Run This notebook is publicly available for any usage at our data imputation project. Please click [**transdim - GitHub**](https://github.com/xinychen/transdim). We start by importing the necessary dependencies. We will make use of `numpy` and `scipy`. ``` import numpy as np from numpy.random import multivariate_normal as mvnrnd from scipy.stats import wishart from numpy.linalg import inv as inv ``` # Part 1: Matrix Computation Concepts ## 1) Kronecker product - **Definition**: Given two matrices $A\in\mathbb{R}^{m_1\times n_1}$ and $B\in\mathbb{R}^{m_2\times n_2}$, then, the **Kronecker product** between these two matrices is defined as $$A\otimes B=\left[ \begin{array}{cccc} a_{11}B & a_{12}B & \cdots & a_{1m_2}B \\ a_{21}B & a_{22}B & \cdots & a_{2m_2}B \\ \vdots & \vdots & \ddots & \vdots \\ a_{m_11}B & a_{m_12}B & \cdots & a_{m_1m_2}B \\ \end{array} \right]$$ where the symbol $\otimes$ denotes Kronecker product, and the size of resulted $A\otimes B$ is $(m_1m_2)\times (n_1n_2)$ (i.e., $m_1\times m_2$ columns and $n_1\times n_2$ rows). - **Example**: If $A=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ \end{array} \right]$ and $B=\left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10 \\ \end{array} \right]$, then, we have $$A\otimes B=\left[ \begin{array}{cc} 1\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] & 2\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] \\ 3\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] & 4\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] \\ \end{array} \right]$$ $$=\left[ \begin{array}{cccccc} 5 & 6 & 7 & 10 & 12 & 14 \\ 8 & 9 & 10 & 16 & 18 & 20 \\ 15 & 18 & 21 & 20 & 24 & 28 \\ 24 & 27 & 30 & 32 & 36 & 40 \\ \end{array} \right]\in\mathbb{R}^{4\times 6}.$$ ## 2) Khatri-Rao product (`kr_prod`) - **Definition**: Given two matrices $A=\left( \boldsymbol{a}_1,\boldsymbol{a}_2,...,\boldsymbol{a}_r \right)\in\mathbb{R}^{m\times r}$ and $B=\left( \boldsymbol{b}_1,\boldsymbol{b}_2,...,\boldsymbol{b}_r \right)\in\mathbb{R}^{n\times r}$ with same number of columns, then, the **Khatri-Rao product** (or **column-wise Kronecker product**) between $A$ and $B$ is given as follows, $$A\odot B=\left( \boldsymbol{a}_1\otimes \boldsymbol{b}_1,\boldsymbol{a}_2\otimes \boldsymbol{b}_2,...,\boldsymbol{a}_r\otimes \boldsymbol{b}_r \right)\in\mathbb{R}^{(mn)\times r},$$ where the symbol $\odot$ denotes Khatri-Rao product, and $\otimes$ denotes Kronecker product. - **Example**: If $A=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ \end{array} \right]=\left( \boldsymbol{a}_1,\boldsymbol{a}_2 \right) $ and $B=\left[ \begin{array}{cc} 5 & 6 \\ 7 & 8 \\ 9 & 10 \\ \end{array} \right]=\left( \boldsymbol{b}_1,\boldsymbol{b}_2 \right) $, then, we have $$A\odot B=\left( \boldsymbol{a}_1\otimes \boldsymbol{b}_1,\boldsymbol{a}_2\otimes \boldsymbol{b}_2 \right) $$ $$=\left[ \begin{array}{cc} \left[ \begin{array}{c} 1 \\ 3 \\ \end{array} \right]\otimes \left[ \begin{array}{c} 5 \\ 7 \\ 9 \\ \end{array} \right] & \left[ \begin{array}{c} 2 \\ 4 \\ \end{array} \right]\otimes \left[ \begin{array}{c} 6 \\ 8 \\ 10 \\ \end{array} \right] \\ \end{array} \right]$$ $$=\left[ \begin{array}{cc} 5 & 12 \\ 7 & 16 \\ 9 & 20 \\ 15 & 24 \\ 21 & 32 \\ 27 & 40 \\ \end{array} \right]\in\mathbb{R}^{6\times 2}.$$ ``` def kr_prod(a, b): return np.einsum('ir, jr -> ijr', a, b).reshape(a.shape[0] * b.shape[0], -1) A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8], [9, 10]]) print(kr_prod(A, B)) ``` ## 3) CP decomposition ### CP Combination (`cp_combine`) - **Definition**: The CP decomposition factorizes a tensor into a sum of outer products of vectors. For example, for a third-order tensor $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$, the CP decomposition can be written as $$\hat{\mathcal{Y}}=\sum_{s=1}^{r}\boldsymbol{u}_{s}\circ\boldsymbol{v}_{s}\circ\boldsymbol{x}_{s},$$ or element-wise, $$\hat{y}_{ijt}=\sum_{s=1}^{r}u_{is}v_{js}x_{ts},\forall (i,j,t),$$ where vectors $\boldsymbol{u}_{s}\in\mathbb{R}^{m},\boldsymbol{v}_{s}\in\mathbb{R}^{n},\boldsymbol{x}_{s}\in\mathbb{R}^{f}$ are columns of factor matrices $U\in\mathbb{R}^{m\times r},V\in\mathbb{R}^{n\times r},X\in\mathbb{R}^{f\times r}$, respectively. The symbol $\circ$ denotes vector outer product. - **Example**: Given matrices $U=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ \end{array} \right]\in\mathbb{R}^{2\times 2}$, $V=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ 5 & 6 \\ \end{array} \right]\in\mathbb{R}^{3\times 2}$ and $X=\left[ \begin{array}{cc} 1 & 5 \\ 2 & 6 \\ 3 & 7 \\ 4 & 8 \\ \end{array} \right]\in\mathbb{R}^{4\times 2}$, then if $\hat{\mathcal{Y}}=\sum_{s=1}^{r}\boldsymbol{u}_{s}\circ\boldsymbol{v}_{s}\circ\boldsymbol{x}_{s}$, then, we have $$\hat{Y}_1=\hat{\mathcal{Y}}(:,:,1)=\left[ \begin{array}{ccc} 31 & 42 & 65 \\ 63 & 86 & 135 \\ \end{array} \right],$$ $$\hat{Y}_2=\hat{\mathcal{Y}}(:,:,2)=\left[ \begin{array}{ccc} 38 & 52 & 82 \\ 78 & 108 & 174 \\ \end{array} \right],$$ $$\hat{Y}_3=\hat{\mathcal{Y}}(:,:,3)=\left[ \begin{array}{ccc} 45 & 62 & 99 \\ 93 & 130 & 213 \\ \end{array} \right],$$ $$\hat{Y}_4=\hat{\mathcal{Y}}(:,:,4)=\left[ \begin{array}{ccc} 52 & 72 & 116 \\ 108 & 152 & 252 \\ \end{array} \right].$$ ``` def cp_combine(U, V, X): return np.einsum('is, js, ts -> ijt', U, V, X) U = np.array([[1, 2], [3, 4]]) V = np.array([[1, 3], [2, 4], [5, 6]]) X = np.array([[1, 5], [2, 6], [3, 7], [4, 8]]) print(cp_combine(U, V, X)) print() print('tensor size:') print(cp_combine(U, V, X).shape) ``` ## 4) Tensor Unfolding (`ten2mat`) Using numpy reshape to perform 3rd rank tensor unfold operation. [[**link**](https://stackoverflow.com/questions/49970141/using-numpy-reshape-to-perform-3rd-rank-tensor-unfold-operation)] ``` def ten2mat(tensor, mode): return np.reshape(np.moveaxis(tensor, mode, 0), (tensor.shape[mode], -1), order = 'F') X = np.array([[[1, 2, 3, 4], [3, 4, 5, 6]], [[5, 6, 7, 8], [7, 8, 9, 10]], [[9, 10, 11, 12], [11, 12, 13, 14]]]) print('tensor size:') print(X.shape) print('original tensor:') print(X) print() print('(1) mode-1 tensor unfolding:') print(ten2mat(X, 0)) print() print('(2) mode-2 tensor unfolding:') print(ten2mat(X, 1)) print() print('(3) mode-3 tensor unfolding:') print(ten2mat(X, 2)) ``` ## 5) Computing Covariance Matrix (`cov_mat`) For any matrix $X\in\mathbb{R}^{m\times n}$, `cov_mat` can return a $n\times n$ covariance matrix for special use in the following. ``` def cov_mat(mat): dim1, dim2 = mat.shape new_mat = np.zeros((dim2, dim2)) mat_bar = np.mean(mat, axis = 0) for i in range(dim1): new_mat += np.einsum('i, j -> ij', mat[i, :] - mat_bar, mat[i, :] - mat_bar) return new_mat ``` # Part 2: Bayesian Gaussian CP decomposition (BGCP) ## 1) Model Description #### Gaussian assumption Given a matrix $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$ which suffers from missing values, then the factorization can be applied to reconstruct the missing values within $\mathcal{Y}$ by $$y_{ijt}\sim\mathcal{N}\left(\sum_{s=1}^{r}u_{is} v_{js} x_{ts},\tau^{-1}\right),\forall (i,j,t),$$ where vectors $\boldsymbol{u}_{s}\in\mathbb{R}^{m},\boldsymbol{v}_{s}\in\mathbb{R}^{n},\boldsymbol{x}_{s}\in\mathbb{R}^{f}$ are columns of latent factor matrices, and $u_{is},v_{js},x_{ts}$ are their elements. The precision term $\tau$ is an inverse of Gaussian variance. #### Bayesian framework Based on the Gaussian assumption over tensor elements $y_{ijt},(i,j,t)\in\Omega$ (where $\Omega$ is a index set indicating observed tensor elements), the conjugate priors of model parameters (i.e., latent factors and precision term) and hyperparameters are given as $$\boldsymbol{u}_{i}\sim\mathcal{N}\left(\boldsymbol{\mu}_{u},\Lambda_{u}^{-1}\right),\forall i,$$ $$\boldsymbol{v}_{j}\sim\mathcal{N}\left(\boldsymbol{\mu}_{v},\Lambda_{v}^{-1}\right),\forall j,$$ $$\boldsymbol{x}_{t}\sim\mathcal{N}\left(\boldsymbol{\mu}_{x},\Lambda_{x}^{-1}\right),\forall t,$$ $$\tau\sim\text{Gamma}\left(a_0,b_0\right),$$ $$\boldsymbol{\mu}_{u}\sim\mathcal{N}\left(\boldsymbol{\mu}_0,\left(\beta_0\Lambda_u\right)^{-1}\right),\Lambda_u\sim\mathcal{W}\left(W_0,\nu_0\right),$$ $$\boldsymbol{\mu}_{v}\sim\mathcal{N}\left(\boldsymbol{\mu}_0,\left(\beta_0\Lambda_v\right)^{-1}\right),\Lambda_v\sim\mathcal{W}\left(W_0,\nu_0\right),$$ $$\boldsymbol{\mu}_{x}\sim\mathcal{N}\left(\boldsymbol{\mu}_0,\left(\beta_0\Lambda_x\right)^{-1}\right),\Lambda_x\sim\mathcal{W}\left(W_0,\nu_0\right).$$ ## 2) Posterior Inference In the following, we will apply Gibbs sampling to implement our Bayesian inference for the matrix factorization task. #### - Sampling latent factors $\boldsymbol{u}_{i},i\in\left\{1,2,...,m\right\}$ Draw $\boldsymbol{u}_{i}\sim\mathcal{N}\left(\boldsymbol{\mu}_i^{*},(\Lambda_{i}^{*})^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{i}^{*}=\left(\Lambda_{i}^{*}\right)^{-1}\left\{\tau\sum_{j,t:(i,j,t)\in\Omega}y_{ijt}\left(\boldsymbol{v}_{j}\circledast\boldsymbol{x}_{t}\right)+\Lambda_u\boldsymbol{\mu}_u\right\},$$ $$\Lambda_{i}^{*}=\tau\sum_{j,t:(i,j,t)\in\Omega}\left(\boldsymbol{v}_{j}\circledast\boldsymbol{x}_{t}\right)\left(\boldsymbol{v}_{j}\circledast\boldsymbol{x}_{t}\right)^{T}+\Lambda_u.$$ #### - Sampling latent factors $\boldsymbol{v}_{j},j\in\left\{1,2,...,n\right\}$ Draw $\boldsymbol{v}_{j}\sim\mathcal{N}\left(\boldsymbol{\mu}_j^{*},(\Lambda_{j}^{*})^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{j}^{*}=\left(\Lambda_{j}^{*}\right)^{-1}\left\{\tau\sum_{i,t:(i,j,t)\in\Omega}y_{ijt}\left(\boldsymbol{u}_{i}\circledast\boldsymbol{x}_{t}\right)+\Lambda_v\boldsymbol{\mu}_v\right\}$$ $$\Lambda_{j}^{*}=\tau\sum_{i,t:(i,j,t)\in\Omega}\left(\boldsymbol{u}_{i}\circledast\boldsymbol{x}_{t}\right)\left(\boldsymbol{u}_{i}\circledast\boldsymbol{x}_{t}\right)^{T}+\Lambda_v.$$ #### - Sampling latent factors $\boldsymbol{x}_{t},t\in\left\{1,2,...,f\right\}$ Draw $\boldsymbol{x}_{t}\sim\mathcal{N}\left(\boldsymbol{\mu}_t^{*},(\Lambda_{t}^{*})^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{t}^{*}=\left(\Lambda_{t}^{*}\right)^{-1}\left\{\tau\sum_{i,j:(i,j,t)\in\Omega}y_{ijt}\left(\boldsymbol{u}_{i}\circledast\boldsymbol{v}_{j}\right)+\Lambda_x\boldsymbol{\mu}_x\right\}$$ $$\Lambda_{t}^{*}=\tau\sum_{i,j:(i,j,t)\in\Omega}\left(\boldsymbol{u}_{i}\circledast\boldsymbol{v}_{j}\right)\left(\boldsymbol{u}_{i}\circledast\boldsymbol{v}_{j}\right)^{T}+\Lambda_x.$$ #### - Sampling precision term $\tau$ Draw $\tau\in\text{Gamma}\left(a^{*},b^{*}\right)$ with following parameters: $$a^{*}=a_0+\frac{1}{2}|\Omega|,~b^{*}=b_0+\frac{1}{2}\sum_{(i,j,t)\in\Omega}\left(y_{ijt}-\sum_{s=1}^{r}u_{is}v_{js}x_{ts}\right)^2.$$ #### - Sampling hyperparameters $\left(\boldsymbol{\mu}_{u},\Lambda_{u}\right)$ Draw - $\Lambda_{u}\sim\mathcal{W}\left(W_u^{*},\nu_u^{*}\right)$ - $\boldsymbol{\mu}_{u}\sim\mathcal{N}\left(\boldsymbol{\mu}_{u}^{*},\left(\beta_u^{*}\Lambda_u\right)^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{u}^{*}=\frac{m\boldsymbol{\bar{u}}+\beta_0\boldsymbol{\mu}_0}{m+\beta_0},~\beta_u^{*}=m+\beta_0,~\nu_u^{*}=m+\nu_0,$$ $$\left(W_u^{*}\right)^{-1}=W_0^{-1}+mS_u+\frac{m\beta_0}{m+\beta_0}\left(\boldsymbol{\bar{u}}-\boldsymbol{\mu}_0\right)\left(\boldsymbol{\bar{u}}-\boldsymbol{\mu}_0\right)^T,$$ where $\boldsymbol{\bar{u}}=\sum_{i=1}^{m}\boldsymbol{u}_{i},~S_u=\frac{1}{m}\sum_{i=1}^{m}\left(\boldsymbol{u}_{i}-\boldsymbol{\bar{u}}\right)\left(\boldsymbol{u}_{i}-\boldsymbol{\bar{u}}\right)^T$. #### - Sampling hyperparameters $\left(\boldsymbol{\mu}_{v},\Lambda_{v}\right)$ Draw - $\Lambda_{v}\sim\mathcal{W}\left(W_v^{*},\nu_v^{*}\right)$ - $\boldsymbol{\mu}_{v}\sim\mathcal{N}\left(\boldsymbol{\mu}_{v}^{*},\left(\beta_v^{*}\Lambda_v\right)^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{v}^{*}=\frac{n\boldsymbol{\bar{v}}+\beta_0\boldsymbol{\mu}_0}{n+\beta_0},~\beta_v^{*}=n+\beta_0,~\nu_v^{*}=n+\nu_0,$$ $$\left(W_v^{*}\right)^{-1}=W_0^{-1}+nS_v+\frac{n\beta_0}{n+\beta_0}\left(\boldsymbol{\bar{v}}-\boldsymbol{\mu}_0\right)\left(\boldsymbol{\bar{v}}-\boldsymbol{\mu}_0\right)^T,$$ where $\boldsymbol{\bar{v}}=\sum_{j=1}^{n}\boldsymbol{v}_{j},~S_v=\frac{1}{n}\sum_{j=1}^{n}\left(\boldsymbol{v}_{j}-\boldsymbol{\bar{v}}\right)\left(\boldsymbol{v}_{j}-\boldsymbol{\bar{v}}\right)^T$. #### - Sampling hyperparameters $\left(\boldsymbol{\mu}_{x},\Lambda_{x}\right)$ Draw - $\Lambda_{x}\sim\mathcal{W}\left(W_x^{*},\nu_x^{*}\right)$ - $\boldsymbol{\mu}_{x}\sim\mathcal{N}\left(\boldsymbol{\mu}_{x}^{*},\left(\beta_x^{*}\Lambda_x\right)^{-1}\right)$ with following parameters: $$\boldsymbol{\mu}_{x}^{*}=\frac{f\boldsymbol{\bar{x}}+\beta_0\boldsymbol{\mu}_0}{f+\beta_0},~\beta_x^{*}=f+\beta_0,~\nu_x^{*}=f+\nu_0,$$ $$\left(W_x^{*}\right)^{-1}=W_0^{-1}+fS_x+\frac{f\beta_0}{f+\beta_0}\left(\boldsymbol{\bar{x}}-\boldsymbol{\mu}_0\right)\left(\boldsymbol{\bar{x}}-\boldsymbol{\mu}_0\right)^T,$$ where $\boldsymbol{\bar{x}}=\sum_{t=1}^{f}\boldsymbol{x}_{t},~S_x=\frac{1}{f}\sum_{t=1}^{f}\left(\boldsymbol{x}_{t}-\boldsymbol{\bar{x}}\right)\left(\boldsymbol{x}_{t}-\boldsymbol{\bar{x}}\right)^T$. ``` def BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2): """Bayesian Gaussian CP (BGCP) decomposition.""" dim1, dim2, dim3 = sparse_tensor.shape binary_tensor = np.zeros((dim1, dim2, dim3)) dim = np.array([dim1, dim2, dim3]) pos = np.where((dense_tensor != 0) & (sparse_tensor == 0)) position = np.where(sparse_tensor != 0) binary_tensor[position] = 1 U = init["U"] V = init["V"] X = init["X"] beta0 = 1 nu0 = rank mu0 = np.zeros((rank)) W0 = np.eye(rank) tau = 1 alpha = 1e-6 beta = 1e-6 U_plus = np.zeros((dim1, rank)) V_plus = np.zeros((dim2, rank)) X_plus = np.zeros((dim3, rank)) tensor_hat_plus = np.zeros((dim1, dim2, dim3)) for iters in range(maxiter1): for order in range(dim.shape[0]): if order == 0: mat = U.copy() elif order == 1: mat = V.copy() else: mat = X.copy() mat_bar = np.mean(mat, axis = 0) var_mu_hyper = (dim[order] * mat_bar + beta0 * mu0)/(dim[order] + beta0) var_W_hyper = inv(inv(W0) + cov_mat(mat) + dim[order] * beta0/(dim[order] + beta0) * np.outer(mat_bar - mu0, mat_bar - mu0)) var_Lambda_hyper = wishart(df = dim[order] + nu0, scale = var_W_hyper, seed = None).rvs() var_mu_hyper = mvnrnd(var_mu_hyper, inv((dim[order] + beta0) * var_Lambda_hyper)) if order == 0: var1 = kr_prod(X, V).T elif order == 1: var1 = kr_prod(X, U).T else: var1 = kr_prod(V, U).T var2 = kr_prod(var1, var1) var3 = (tau * np.matmul(var2, ten2mat(binary_tensor, order).T).reshape([rank, rank, dim[order]]) + np.dstack([var_Lambda_hyper] * dim[order])) var4 = (tau * np.matmul(var1, ten2mat(sparse_tensor, order).T) + np.dstack([np.matmul(var_Lambda_hyper, var_mu_hyper)] * dim[order])[0, :, :]) for i in range(dim[order]): var_Lambda = var3[ :, :, i] inv_var_Lambda = inv((var_Lambda + var_Lambda.T)/2) vec = mvnrnd(np.matmul(inv_var_Lambda, var4[:, i]), inv_var_Lambda) if order == 0: U[i, :] = vec.copy() elif order == 1: V[i, :] = vec.copy() else: X[i, :] = vec.copy() if iters + 1 > maxiter1 - maxiter2: U_plus += U V_plus += V X_plus += X tensor_hat = cp_combine(U, V, X) if iters + 1 > maxiter1 - maxiter2: tensor_hat_plus += tensor_hat rmse = np.sqrt(np.sum((dense_tensor[pos] - tensor_hat[pos]) ** 2)/dense_tensor[pos].shape[0]) var_alpha = alpha + 0.5 * sparse_tensor[position].shape[0] error = sparse_tensor - tensor_hat var_beta = beta + 0.5 * np.sum(error[position] ** 2) tau = np.random.gamma(var_alpha, 1/var_beta) if (iters + 1) % 200 == 0 and iters < maxiter1 - maxiter2: print('Iter: {}'.format(iters + 1)) print('RMSE: {:.6}'.format(rmse)) print() U = U_plus/maxiter2 V = V_plus/maxiter2 X = X_plus/maxiter2 tensor_hat = tensor_hat_plus/maxiter2 final_mape = np.sum(np.abs(dense_tensor[pos] - tensor_hat[pos])/dense_tensor[pos])/dense_tensor[pos].shape[0] final_rmse = np.sqrt(np.sum((dense_tensor[pos] - tensor_hat[pos]) ** 2)/dense_tensor[pos].shape[0]) print('Final MAPE: {:.6}'.format(final_mape)) print('Final RMSE: {:.6}'.format(final_rmse)) print() ``` # Part 3: Data Organization ## 1) Matrix Structure We consider a dataset of $m$ discrete time series $\boldsymbol{y}_{i}\in\mathbb{R}^{f},i\in\left\{1,2,...,m\right\}$. The time series may have missing elements. We express spatio-temporal dataset as a matrix $Y\in\mathbb{R}^{m\times f}$ with $m$ rows (e.g., locations) and $f$ columns (e.g., discrete time intervals), $$Y=\left[ \begin{array}{cccc} y_{11} & y_{12} & \cdots & y_{1f} \\ y_{21} & y_{22} & \cdots & y_{2f} \\ \vdots & \vdots & \ddots & \vdots \\ y_{m1} & y_{m2} & \cdots & y_{mf} \\ \end{array} \right]\in\mathbb{R}^{m\times f}.$$ ## 2) Tensor Structure We consider a dataset of $m$ discrete time series $\boldsymbol{y}_{i}\in\mathbb{R}^{nf},i\in\left\{1,2,...,m\right\}$. The time series may have missing elements. We partition each time series into intervals of predifined length $f$. We express each partitioned time series as a matrix $Y_{i}$ with $n$ rows (e.g., days) and $f$ columns (e.g., discrete time intervals per day), $$Y_{i}=\left[ \begin{array}{cccc} y_{11} & y_{12} & \cdots & y_{1f} \\ y_{21} & y_{22} & \cdots & y_{2f} \\ \vdots & \vdots & \ddots & \vdots \\ y_{n1} & y_{n2} & \cdots & y_{nf} \\ \end{array} \right]\in\mathbb{R}^{n\times f},i=1,2,...,m,$$ therefore, the resulting structure is a tensor $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$. **How to transform a data set into something we can use for time series imputation?** # Part 4: Experiments on Guangzhou Data Set ``` import scipy.io tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/tensor.mat') dense_tensor = tensor['tensor'] random_matrix = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_matrix.mat') random_matrix = random_matrix['random_matrix'] random_tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_tensor.mat') random_tensor = random_tensor['random_tensor'] missing_rate = 0.4 # ============================================================================= ### Random missing (RM) scenario: # binary_tensor = np.round(random_tensor + 0.5 - missing_rate) # ============================================================================= # ============================================================================= ### Non-random missing (NM) scenario: binary_tensor = np.zeros(dense_tensor.shape) for i1 in range(dense_tensor.shape[0]): for i2 in range(dense_tensor.shape[1]): binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate) # ============================================================================= sparse_tensor = np.multiply(dense_tensor, binary_tensor) ``` **Question**: Given only the partially observed data $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$, how can we impute the unknown missing values? The main influential factors for such imputation model are: - `rank`. - `maxiter1`. - `maxiter2`. ``` import time start = time.time() dim1, dim2, dim3 = sparse_tensor.shape rank = 10 init = {"U": 0.1 * np.random.rand(dim1, rank), "V": 0.1 * np.random.rand(dim2, rank), "X": 0.1 * np.random.rand(dim3, rank)} maxiter1 = 1100 maxiter2 = 100 BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2) end = time.time() print('Running time: %d seconds'%(end - start)) ``` **Experiment results** of missing data imputation using Bayesian Gaussian CP decomposition (BGCP): | scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse | |:----------|-----:|---------:|---------:|-----------:|----------:| |**20%, RM**| 80 | 1100 | 100 | **0.0828** | **3.5729**| |**40%, RM**| 80 | 1100 | 100 | **0.0829** | **3.5869**| |**20%, NM**| 10 | 1100 | 100 | **0.1023** | **4.2756**| |**40%, NM**| 10 | 1100 | 100 | **0.1023** | **4.3214**| # Part 5: Experiments on Birmingham Data Set ``` import scipy.io tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat') dense_tensor = tensor['tensor'] random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat') random_matrix = random_matrix['random_matrix'] random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/random_tensor.mat') random_tensor = random_tensor['random_tensor'] missing_rate = 0.1 # ============================================================================= ### Random missing (RM) scenario: binary_tensor = np.round(random_tensor + 0.5 - missing_rate) # ============================================================================= # ============================================================================= ### Non-random missing (NM) scenario: # binary_tensor = np.zeros(dense_tensor.shape) # for i1 in range(dense_tensor.shape[0]): # for i2 in range(dense_tensor.shape[1]): # binary_tensor[i1,i2,:] = np.round(random_matrix[i1,i2] + 0.5 - missing_rate) # ============================================================================= sparse_tensor = np.multiply(dense_tensor, binary_tensor) import time start = time.time() dim1, dim2, dim3 = sparse_tensor.shape rank = 30 init = {"U": 0.1 * np.random.rand(dim1, rank), "V": 0.1 * np.random.rand(dim2, rank), "X": 0.1 * np.random.rand(dim3, rank)} maxiter1 = 1100 maxiter2 = 100 BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2) end = time.time() print('Running time: %d seconds'%(end - start)) ``` **Experiment results** of missing data imputation using Bayesian Gaussian CP decomposition (BGCP): | scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse | |:----------|-----:|---------:|---------:|-----------:|----------:| |**10%, RM**| 30 | 1100 | 100 | **0.0650** |**19.6926**| |**30%, RM**| 30 | 1100 | 100 | **0.0623** | **19.982**| |**10%, NM**| 10 | 1100 | 100 | **0.1364** |**43.1498**| |**30%, NM**| 10 | 1100 | 100 | **0.1593** |**57.0697**| # Part 6: Experiments on Hangzhou Data Set ``` import scipy.io tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat') dense_tensor = tensor['tensor'] random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat') random_matrix = random_matrix['random_matrix'] random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_tensor.mat') random_tensor = random_tensor['random_tensor'] missing_rate = 0.4 # ============================================================================= ### Random missing (RM) scenario: binary_tensor = np.round(random_tensor + 0.5 - missing_rate) # ============================================================================= # ============================================================================= ### Non-random missing (NM) scenario: # binary_tensor = np.zeros(dense_tensor.shape) # for i1 in range(dense_tensor.shape[0]): # for i2 in range(dense_tensor.shape[1]): # binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate) # ============================================================================= sparse_tensor = np.multiply(dense_tensor, binary_tensor) import time start = time.time() dim1, dim2, dim3 = sparse_tensor.shape rank = 50 init = {"U": 0.1 * np.random.rand(dim1, rank), "V": 0.1 * np.random.rand(dim2, rank), "X": 0.1 * np.random.rand(dim3, rank)} maxiter1 = 1100 maxiter2 = 100 BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2) end = time.time() print('Running time: %d seconds'%(end - start)) ``` **Experiment results** of missing data imputation using Bayesian Gaussian CP decomposition (BGCP): | scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse | |:----------|-----:|---------:|---------:|-----------:|----------:| |**20%, RM**| 50 | 1100 | 100 | **0.1901**|**41.1558**| |**40%, RM**| 50 | 1100 | 100 | **0.1959**|**32.7057**| |**20%, NM**| 10 | 1100 | 100 | **0.2557**|**35.9867**| |**40%, NM**| 10 | 1100 | 100 | **0.2437**|**49.6438**| # Part 7: Experiments on New York Data Set ``` import scipy.io tensor = scipy.io.loadmat('../datasets/NYC-data-set/tensor.mat') dense_tensor = tensor['tensor'] rm_tensor = scipy.io.loadmat('../datasets/NYC-data-set/rm_tensor.mat') rm_tensor = rm_tensor['rm_tensor'] nm_tensor = scipy.io.loadmat('../datasets/NYC-data-set/nm_tensor.mat') nm_tensor = nm_tensor['nm_tensor'] missing_rate = 0.3 # ============================================================================= ### Random missing (RM) scenario ### Set the RM scenario by: binary_tensor = np.round(rm_tensor + 0.5 - missing_rate) # ============================================================================= # ============================================================================= ### Non-random missing (NM) scenario ### Set the NM scenario by: # binary_tensor = np.zeros(dense_tensor.shape) # for i1 in range(dense_tensor.shape[0]): # for i2 in range(dense_tensor.shape[1]): # for i3 in range(61): # binary_tensor[i1, i2, i3 * 24 : (i3 + 1) * 24] = np.round(nm_tensor[i1, i2, i3] + 0.5 - missing_rate) # ============================================================================= sparse_tensor = np.multiply(dense_tensor, binary_tensor) import time start = time.time() dim1, dim2, dim3 = sparse_tensor.shape rank = 30 init = {"U": 0.1 * np.random.rand(dim1, rank), "V": 0.1 * np.random.rand(dim2, rank), "X": 0.1 * np.random.rand(dim3, rank)} maxiter1 = 1100 maxiter2 = 100 BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2) end = time.time() print('Running time: %d seconds'%(end - start)) ``` **Experiment results** of missing data imputation using Bayesian Gaussian CP decomposition (BGCP): | scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse | |:----------|-----:|---------:|---------:|-----------:|----------:| |**10%, RM**| 30 | 1100 | 100 | **0.5202** | **4.7106**| |**30%, RM**| 30 | 1100 | 100 | **0.5252** | **4.8218**| |**10%, NM**| 30 | 1100 | 100 | **0.5295** | **4.7879**| |**30%, NM**| 30 | 1100 | 100 | **0.5282** | **4.8664**| # Part 8: Experiments on Seattle Data Set ``` import pandas as pd dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0) RM_mat = pd.read_csv('../datasets/Seattle-data-set/RM_mat.csv', index_col = 0) NM_mat = pd.read_csv('../datasets/Seattle-data-set/NM_mat.csv', index_col = 0) dense_mat = dense_mat.values RM_mat = RM_mat.values NM_mat = NM_mat.values dense_tensor = dense_mat.reshape([dense_mat.shape[0], 28, 288]) missing_rate = 0.2 # ============================================================================= ### Random missing (RM) scenario ### Set the RM scenario by: # binary_tensor = np.round(RM_mat.reshape([RM_mat.shape[0], 28, 288]) + 0.5 - missing_rate) # ============================================================================= # ============================================================================= ### Non-random missing (NM) scenario ### Set the NM scenario by: binary_tensor = np.zeros((dense_mat.shape[0], 28, 288)) for i1 in range(binary_tensor.shape[0]): for i2 in range(binary_tensor.shape[1]): binary_tensor[i1, i2, :] = np.round(NM_mat[i1, i2] + 0.5 - missing_rate) # ============================================================================= sparse_tensor = np.multiply(dense_tensor, binary_tensor) import time start = time.time() dim1, dim2, dim3 = sparse_tensor.shape rank = 10 init = {"U": 0.1 * np.random.rand(dim1, rank), "V": 0.1 * np.random.rand(dim2, rank), "X": 0.1 * np.random.rand(dim3, rank)} maxiter1 = 1100 maxiter2 = 100 BGCP(dense_tensor, sparse_tensor, init, rank, maxiter1, maxiter2) end = time.time() print('Running time: %d seconds'%(end - start)) ``` **Experiment results** of missing data imputation using Bayesian Gaussian CP decomposition (BGCP): | scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse | |:----------|-----:|---------:|---------:|-----------:|----------:| |**20%, RM**| 50 | 1100 | 100 | **0.0745** | **4.50**| |**40%, RM**| 50 | 1100 | 100 | **0.0758** | **4.54**| |**20%, NM**| 10 | 1100 | 100 | **0.0993** | **5.65**| |**40%, NM**| 10 | 1100 | 100 | **0.0994** | **5.68**|
github_jupyter
<img src="http://akhavanpour.ir/notebook/images/srttu.gif" alt="SRTTU" style="width: 150px;"/> [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://notebooks.azure.com/import/gh/Alireza-Akhavan/class.vision) # <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> عملیات ریاضی (Arithmetic Operations) </div> <div style="direction:rtl;text-align:right;font-family:Tahoma"> عملیات ساده‌ای است که به ما این امکان را می‌دهد که به طور مستقیم شدت رنگ را اضافه یا کم کنیم. <br> عملیات بر روی خانه های نظیر به نظیر دو آرایه با ابعاد یکسان انجام شده و نتیجه نهایی کاهش یا افزایش روشنایی تصویر خواهد بود. </div> ## <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> یادآوری</div> <div style="direction:rtl;text-align:right;font-family:Tahoma"> با توجه به اینکه برای تصاویر در OpenCV ار نوع داده‌ای uint8 یعنی عدد صحیح بدون علامت 8 بیتی استفاده میکنیم <br> و یا توجه به 8 بیتی بودن، این نوع 2 به توان 8 یا 256 عدد مختلف را در خود می‌تواند جای دهد مقادیر خارج از 0 تا 255 امکان پذیر نبود و در صورتی که عددی بزرگتر قرار میدادیم متغیر سر ریز می‌شد... </div> ``` import numpy as np a = np.ones([2], dtype = "uint8") b = a * 100 print(b) print(b + 155) print(b + 160) ``` <div style="direction:rtl;text-align:right;font-family:Tahoma"> طبیعتا وقتی broadcast انجام نشود و ماتریس هم اندازه را نیز با هم جمع کنیم به نتایج مشابه می‌رسیم. </div> ``` import numpy as np m1 = np.array([[150, 155], [156, 157]], dtype = "uint8") m2 = np.ones([2,2], dtype = "uint8") * 100 print(m1 + m2) ``` <div style="direction:rtl;text-align:right;font-family:Tahoma"> برای رفع این مشکل راه حل‌های مختلفی وجود داشت، از جمله ...</div> ``` import numpy as np m1 = np.array([[150, 155], [156, 157]], dtype = "uint8") value_to_add = 100 max_threshold = 255 - 100 m1[m1 >= max_threshold] = 255 m1[m1 < max_threshold] += value_to_add print(m1) ``` ## <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> عملیات ریاضی در OpenCV</div> <div style="direction:rtl;text-align:right;font-family:Tahoma"> اگر از توابع **cv2.add** و **cv2.subtract** استفاده کنیم این مشکل را مشاهده نخواهیم کرد و مقادیر کمتر از 0 همان 0 و مقادیر بیش از 255 همان 255 باقی خواهد ماند. </div> ``` import cv2 import numpy as np image = cv2.imread('images/input.jpg') # Create a matrix of ones, then multiply it by a scaler of 100 # This gives a matrix with same dimesions of our image with all values being 100 M = np.ones(image.shape, dtype = "uint8") * 100 cv2.imshow("Original", image) cv2.waitKey(0) # We use this to add this matrix M, to our image # Notice the increase in brightness added = cv2.add(image, M) cv2.imshow("Added", added) # Likewise we can also subtract # Notice the decrease in brightness subtracted = cv2.subtract(image, M) cv2.imshow("Subtracted", subtracted) cv2.waitKey(0) cv2.destroyAllWindows() ``` ## <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> مثال عملی ترکیب تصاویر رنگی </div> ``` import cv2 import numpy as np img1 = cv2.imread('./images/ml.jpg') img2 = cv2.imread('./images/opencv.jpg') cv2.imshow("ml", img1) cv2.imshow("opencv", img2) cv2.waitKey(0) output_image = cv2.add(img1,img2) cv2.imshow("out", output_image) print(img1.shape) print(img2.shape) print(output_image.shape) cv2.waitKey(0) cv2.destroyAllWindows() ``` ## <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> ترکیب دو تصویر با جمع وزن‌دار </div> **addWeighted(src1, alpha, src2, beta, gamma)** <br> <div style="direction:rtl;text-align:right;font-family:Tahoma"> آلفا و بتا در فرمول دوم مشاهده میشود. </div> <br> g(x)=(1−α)f0(x)+αf1(x) <br> dst=α⋅img1+β⋅img2+γ <br> https://docs.opencv.org/3.2.0/d0/d86/tutorial_py_image_arithmetics.html ``` import cv2 import numpy as np img1 = cv2.imread('./images/ml.jpg') img2 = cv2.imread('./images/opencv.jpg') dst = cv2.addWeighted(img1,0.7,img2,0.3,0) cv2.imshow('dst',dst) cv2.waitKey(0) cv2.destroyAllWindows() ``` <div class="alert alert-block alert-info"> <div style="direction:rtl;text-align:right;font-family:B Lotus, B Nazanin, Tahoma"> دانشگاه تربیت دبیر شهید رجایی<br>مباحث ویژه - آشنایی با بینایی کامپیوتر<br>علیرضا اخوان پور<br>96-97<br> </div> <a href="https://www.srttu.edu/">SRTTU.edu</a> - <a href="http://class.vision">Class.Vision</a> - <a href="http://AkhavanPour.ir">AkhavanPour.ir</a> </div>
github_jupyter
# Exercise 03 - Columnar Vs Row Storage - The columnar storage extension used here: - cstore_fdw by citus_data [https://github.com/citusdata/cstore_fdw](https://github.com/citusdata/cstore_fdw) - The data tables are the ones used by citus_data to show the storage extension ``` %load_ext sql ``` ## STEP 0 : Connect to the local database where Pagila is loaded ### Create the database ``` !sudo -u postgres psql -c 'CREATE DATABASE reviews;' !wget http://examples.citusdata.com/customer_reviews_1998.csv.gz !wget http://examples.citusdata.com/customer_reviews_1999.csv.gz !gzip -d customer_reviews_1998.csv.gz !gzip -d customer_reviews_1999.csv.gz !mv customer_reviews_1998.csv /tmp/customer_reviews_1998.csv !mv customer_reviews_1999.csv /tmp/customer_reviews_1999.csv ``` ### Connect to the database ``` DB_ENDPOINT = "127.0.0.1" DB = 'reviews' DB_USER = 'student' DB_PASSWORD = 'student' DB_PORT = '5432' # postgresql://username:password@host:port/database conn_string = "postgresql://{}:{}@{}:{}/{}" \ .format(DB_USER, DB_PASSWORD, DB_ENDPOINT, DB_PORT, DB) print(conn_string) %sql $conn_string ``` ## STEP 1 : Create a table with a normal (Row) storage & load data **TODO:** Create a table called customer_reviews_row with the column names contained in the `customer_reviews_1998.csv` and `customer_reviews_1999.csv` files. ``` %%sql DROP TABLE IF EXISTS customer_reviews_row; CREATE TABLE customer_reviews_row ( customer_id TEXT, review_date DATE, review_rating INTEGER, review_votes INTEGER, review_helpful_votes INTEGER, product_id CHAR(10), product_title TEXT, product_sales_rank BIGINT, product_group TEXT, product_category TEXT, product_subcategory TEXT, similar_product_ids CHAR(10)[] ); ``` **TODO:** Use the [COPY statement](https://www.postgresql.org/docs/9.2/sql-copy.html) to populate the tables with the data in the `customer_reviews_1998.csv` and `customer_reviews_1999.csv` files. You can access the files in the `/tmp/` folder. ``` %%sql COPY customer_reviews_row FROM '/tmp/customer_reviews_1998.csv' WITH CSV; COPY customer_reviews_row FROM '/tmp/customer_reviews_1999.csv' WITH CSV; ``` ## STEP 2 : Create a table with columnar storage & load data First, load the extension to use columnar storage in Postgres. ``` %%sql -- load extension first time after install CREATE EXTENSION cstore_fdw; -- create server object CREATE SERVER cstore_server FOREIGN DATA WRAPPER cstore_fdw; ``` **TODO:** Create a `FOREIGN TABLE` called `customer_reviews_col` with the column names contained in the `customer_reviews_1998.csv` and `customer_reviews_1999.csv` files. ``` %%sql -- create foreign table DROP FOREIGN TABLE IF EXISTS customer_reviews_col; ------------- CREATE FOREIGN TABLE customer_reviews_col ( customer_id TEXT, review_date DATE, review_rating INTEGER, review_votes INTEGER, review_helpful_votes INTEGER, product_id CHAR(10), product_title TEXT, product_sales_rank BIGINT, product_group TEXT, product_category TEXT, product_subcategory TEXT, similar_product_ids CHAR(10)[] ) ------------- -- leave code below as is SERVER cstore_server OPTIONS(compression 'pglz'); ``` **TODO:** Use the [COPY statement](https://www.postgresql.org/docs/9.2/sql-copy.html) to populate the tables with the data in the `customer_reviews_1998.csv` and `customer_reviews_1999.csv` files. You can access the files in the `/tmp/` folder. ``` %%sql COPY customer_reviews_col FROM '/tmp/customer_reviews_1998.csv' WITH CSV; COPY customer_reviews_col FROM '/tmp/customer_reviews_1999.csv' WITH CSV; ``` ## Step 3: Compare perfromamce Now run the same query on the two tables and compare the run time. Which form of storage is more performant? **TODO**: Write a query that calculates the average `review_rating` by `product_title` for all reviews in 1995. Sort the data by `review_rating` in descending order. Limit the results to 20. First run the query on `customer_reviews_row`: ``` %%time %%sql SELECT AVG(review_rating) AS avg_review_rating, product_id FROM customer_reviews_row WHERE EXTRACT(year FROM review_date) = 1995 GROUP BY product_id LIMIT 20 ``` Then on `customer_reviews_col`: ``` %%time %%sql SELECT AVG(review_rating) AS avg_review_rating, product_id FROM customer_reviews_col WHERE EXTRACT(year FROM review_date) = 1995 GROUP BY product_id LIMIT 20 ``` ## Conclusion: We can see that the columnar storage is faster!
github_jupyter
# Processing cellpy batch - Output and plots ### `{{cookiecutter.project_name}}::{{cookiecutter.session_id}}` **Experimental-id:** `{{cookiecutter.notebook_name}}` **Short-name:** `{{cookiecutter.session_id}}` **Project:** `{{cookiecutter.project_name}}` **By:** `{{cookiecutter.author_name}}` **Date:** `{{cookiecutter.date}}` Use this notebook to collect your main plots. The easiest way to do it is to pickle the `HoloViews` figures in the other notebooks and then load it again in this one. ``` import os import pathlib from contextlib import contextmanager from IPython.utils import io import numpy as np import pandas as pd import matplotlib.pyplot as plt import holoviews as hv from holoviews.core.io import Pickler, Unpickler import hvplot.pandas from holoviews import opts import cellpy from cellpy import prms from cellpy import prmreader from cellpy.utils import batch, helpers, plotutils %matplotlib inline pd.set_option('display.max_columns', 70) with io.capture_output() as captured: hv.extension('bokeh', logo=False) print(f"cellpy version: {cellpy.__version__}") ``` ### Your pickled HoloViews figures ``` out = pathlib.Path("out") pickles = list(out.glob("*.hvz")) if pickles: print("You got some pickles:") for i, f in enumerate(pickles): print(f"[{i}]: {f}") else: print("No pickles for you, my friend!") ``` **Example 1. Loading the first pickled hv figure:** ``` if pickles: fig00 = Unpickler.load(pickles[0]) # # Show the figure # fig00 ``` **Example 2. Rendering as a matplotlib figure:** ``` # fig00_m = hv.render(fig00, backend="matplotlib") # fig00_m ``` **Example 3. Using context manager for rendering in matplotlib:** ``` @contextmanager def matplotlib_renderer(*args, **kwds): print("-> entering matplotlib rendering mode") with io.capture_output() as captured: hv.extension('matplotlib', logo=False) try: yield hv.render finally: with io.capture_output() as captured: hv.extension('bokeh', logo=False); print("-> resume with original renderer") # with matplotlib_renderer() as render: # fig00_m = render(fig00) # fig00_m ``` ### Life-time plots ### Rate-plots ### Cycle plots ### ICA plots ### OCV plots ### Summary plots ## Links ### Notebooks - notes and information [link](00_{{cookiecutter.notebook_name}}_notes.ipynb) - processing raw data [link](01_{{cookiecutter.notebook_name}}_loader.ipynb) - life [link](02_{{cookiecutter.notebook_name}}_life.ipynb) - cycles [link](03_{{cookiecutter.notebook_name}}_cycles.ipynb) - ica [link](04_{{cookiecutter.notebook_name}}_ica.ipynb) - plots [link](05_{{cookiecutter.notebook_name}}_plots.ipynb)
github_jupyter
# Imports ``` %reload_ext autoreload %autoreload 2 %matplotlib inline from VAE1D import * from IPython.core.debugger import set_trace ``` # Build model and loss function Initially designed for 2D input images, modified for 1D time-series data. Based on this paper: https://arxiv.org/abs/1807.01349 ``` # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) model beta = 10 # KL term relative weight criterion = VAE1DLoss(beta) ``` # Load hydraulic test data From this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems# ``` data_path = Path('data/hydraulic') train_dl, val_dl, test_dl = load_datasets(data_path) print(len(train_dl), len(val_dl), len(test_dl)) ``` # Prepare for training ``` desc = 'hydraulic' log_freq = 10 # batches # Training parameters epochs = 100 lr = 1e-2 # learning rate lr_decay = 0.1 # lr decay factor schedule = [25, 50, 75] # decrease lr at these epochs batch_size = 32 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) # scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, schedule, lr_decay) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ``` # Train the model ``` def train_VAE1D(dl): """ Execute the training loop """ loss_tracker = AvgTracker() kl_tracker = AvgTracker() logp_tracker = AvgTracker() timer = StopWatch() for i, (X, _) in enumerate(tqdm(dl)): X = X.to(device) timer.lap() # load time # Generate transient and compute loss X_hat, mu, logvar = model(X) loss, loss_desc = criterion(X_hat, X, mu, logvar) timer.lap() # gen time loss_tracker.update(loss.item()) kl_tracker.update(loss_desc['KL'].item()) logp_tracker.update(loss_desc['logp'].item()) if model.training: # Update weights optimizer.zero_grad() loss.backward() optimizer.step() timer.lap() # backprop time if (i + 1) % log_freq == 0: # Print progress print(f'Epoch: {epoch + 1} ({i + 1}/{len(dl)})') print(f'\tData load time: {timer.elapsed[0]:.3f} sec') print(f'\tGeneration time: {timer.elapsed[1]:.3f} sec') if model.training: print(f'\tBackprop time: {timer.elapsed[2]:.3f} sec') print(f'\tLog probability: {logp_tracker.val:.4f} ' f'(avg {logp_tracker.avg:.4f})') print(f'\tKL: {kl_tracker.val:.4f} (avg {kl_tracker.avg:.4f})') print(f'\tLoss: {loss_tracker.val:.4f} (avg {loss_tracker.avg:.4f})') return loss_tracker.avg, kl_tracker.avg, logp_tracker.avg # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ``` ## Sanity check Confirm model output is as expected for a test sample. ``` for X, y in test_dl: break X.shape X[:, :, :4] X = X.to(device) X.shape y X_hat, mu, logvar = model(X) X X_hat ```
github_jupyter
``` import scipy.io as sio import os import numpy as np import tensorflow as tf datapath = r'..\data' dataset = 'INSECT' x = sio.loadmat(os.path.join(datapath, dataset, 'data.mat')) x2 = sio.loadmat(os.path.join(datapath, dataset, 'splits.mat')) barcodes=x['nucleotides'] species=x['labels'] train_loc=x2['trainval_loc'] # Number of training samples and entire data N = len(barcodes) print(len(train_loc[0]), N) # Reading barcodes and labels into python list bcodes=[] labels=[] for i in range(N): if len(barcodes[i][0][0])>0: bcodes.append(barcodes[i][0][0]) labels.append(species[i][0]) print('Sample barcode: %s' % bcodes[0]) from tensorflow.keras.preprocessing.text import Tokenizer # Converting base pairs, ACTG, into numbers tokenizer = Tokenizer(char_level=True) tokenizer.fit_on_texts(bcodes) sequence_of_int = tokenizer.texts_to_sequences(bcodes) # For INSECT dataset, majority of barcodes have a length of 658 cnt = 0 ll = np.zeros((N, 1)) for i in range(N): ll[i] = len(sequence_of_int[i]) if ll[i]==658: #print(i) cnt += 1 print(cnt, np.median(ll)) import numpy as np # Calculating sequence count for each species cl = len(np.unique(species)) seq_len=np.zeros((cl)) seq_cnt=np.zeros((cl)) for i in range(N): k=labels[i]-1 # Accounting for Matlab labeling seq_cnt[k]+=1 #seq_len[k]+=len(sequence_of_int[k]) print('# classes: %d' % cl) # Converting all the data into one-hot encoding. Note that this data is not used during training. # We are getting it ready for the prediction time to get the final DNA embeddings after training is done sl = 658 allX=np.zeros((N,sl,5)) for i in range(N): Nt=len(sequence_of_int[i]) for j in range(sl): if(len(sequence_of_int[i])>j): k=sequence_of_int[i][j]-1 if(k>4): k=4 allX[i][j][k]=1.0 # Initialize the training matrix and labels trainX=np.zeros((N,sl,5)) trainY=np.zeros((N,cl)) labelY=np.zeros(N) # Here is where we cap the class sample size to 50 for a balanced training set Nc=-1 clas_cnt=np.zeros((cl)) for i in range(N): Nt=len(sequence_of_int[i]) k=labels[i]-1 clas_cnt[k]+=1 itl=i+1 if(seq_cnt[k]>=10 and clas_cnt[k]<=50 and itl in train_loc[0]): # Note that samples from training set are only used Nc=Nc+1 for j in range(sl): if(len(sequence_of_int[i])>j): k=sequence_of_int[i][j]-1 if(k>4): k=4 trainX[Nc][j][k]=1.0 k=labels[i]-1 trainY[Nc][k]=1.0 labelY[Nc]=k print('Final training size: %d' % Nc) # selecting the balanced training set trainX=trainX[0:Nc] trainY=trainY[0:Nc] labelY=labelY[0:Nc] print(trainX.shape, trainY.shape, labelY.shape) # To make sure the training data does not include any unseen class nucleotides label_us = species[x2['test_unseen_loc'][0]-1] np.intersect1d(np.unique(labelY), np.unique(label_us)-1) # Cleaning empty classes idx = np.argwhere(np.all(trainY[..., :] == 0, axis=0)) trainY = np.delete(trainY, idx, axis=1) print(len(idx), min(np.sum(trainY,axis=0))) print(trainY.shape) print(labelY.shape) # Expanding the training set shape for CNN trainX=np.expand_dims(trainX, axis=3) allX=np.expand_dims(allX, axis=3) print(trainX.shape) from sklearn.model_selection import train_test_split # Splitting the training set into train and validation X_train, X_test, y_train, y_test = train_test_split(trainX, trainY, test_size=0.2, random_state=42) print(y_train.shape) ``` ### Classic CNN Model ``` from tensorflow.keras import datasets, layers, models, optimizers, callbacks # CNN model architecture model = models.Sequential() model.add(layers.Conv2D(64, (3,3), activation='relu', input_shape=(sl, 5,1),padding="SAME")) model.add(layers.BatchNormalization()) model.add(layers.MaxPooling2D((3,1))) model.add(layers.Conv2D(32, (3,3), activation='relu',padding="SAME")) model.add(layers.BatchNormalization()) model.add(layers.MaxPooling2D((3,1))) model.add(layers.Conv2D(16, (3,3), activation='relu',padding="SAME")) model.add(layers.BatchNormalization()) model.add(layers.MaxPooling2D((3,1))) # model.add(layers.Conv2D(16, (3,3), activation='relu',padding="SAME")) # model.add(layers.BatchNormalization()) # model.add(layers.MaxPooling2D((3,1))) model.add(layers.Flatten()) model.add(layers.BatchNormalization()) model.add(layers.Dense(500, activation='tanh')) model.add(layers.Dense(y_train.shape[1])) model.summary() # Step-decay learning rate scheduler def step_decay(epoch): initial_lrate = 0.001 drop = 0.5 epochs_drop = 2.0 lrate = initial_lrate * np.power(drop, np.floor((1+epoch)/epochs_drop)) return lrate class LossHistory(callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] self.lr = [] def on_epoch_end(self, batch, logs={}): self.losses.append(logs.get('loss')) self.lr.append(step_decay(len(self.losses))) loss_history = LossHistory() lrate = callbacks.LearningRateScheduler(step_decay) callbacks_list = [loss_history, lrate] from tensorflow.keras.metrics import top_k_categorical_accuracy #opt = tf.keras.optimizers.SGD(momentum=0.9, nesterov=True) opt = tf.keras.optimizers.Adam() model.compile(optimizer=opt, loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy','top_k_categorical_accuracy']) # Validation time history = model.fit(X_train, y_train, epochs=5, batch_size = 32, validation_data=(X_test, y_test), callbacks=callbacks_list, verbose=1) # Final Test time #history = model.fit(trainX, trainY, epochs=5, callbacks=callbacks_list) print('Learning rates through epochs:', loss_history.lr) from tensorflow.keras.models import Model # Getting the DNA embeddings of all data from the last dense layer layer_name = 'dense' model2= Model(inputs=model.input, outputs=model.get_layer(layer_name).output) dna_embeddings=model2.predict(allX) print(dna_embeddings.shape) # saving the results into csv file to be later read into matlab np.savetxt("DNA_CNN_embeddings_500_5e_adam.csv", dna_embeddings, delimiter=",") ```
github_jupyter
# 3 The RoboLab simulated on-screen robot (`nbev3devsim`) Within the Jupyter notebook environment, you will be making use of a simple two-dimensional robot simulator, `nbev3devsim`. At times, we will refer to the Jupyter notebook + `nbev3devsim` simulator, or just the simulator itself, as *RoboLab* (it’s somewhat easier to say than `nbev3devsim`!). ## 3.1 The `nbev3devsim` simulator The `nbev3devsim` simulator, which will be the focus of many of the programming activities in this block, is derived from a simpler web-based simulator – the [`ev3devsim` robot simulator](https://github.com/QuirkyCort/ev3dev-sim). `ev3devsim` itself was inspired by the need to create a simulator for testing Python programs written for [`ev3dev`](https://www.ev3dev.org/), _‘a Debian Linux-based operating system that runs on several LEGO® MINDSTORMS compatible platforms including the LEGO® MINDSTORMS EV3 and Raspberry Pi-powered BrickPi.’_ Rather than saving programs to separate files, each individual robot simulator program is defined within its own notebook code cell, and can then be ‘downloaded’ to the simulated robot. This means you can keep track of a how a program develops by writing each version of a program in its own code cell. ![Screenshot of nbev3devsim simulator showing panel display toggle buttons (simulator, settings, output, noise controls, instrumentation, sensor arrays and chart), the simulator controls panel (showing world, positioning and code display toggle buttons), a pen up/pen down and pen colour selector, a clear trace button and a simulator run/stop control, with indicator light and the simulator world panel with a selected background and the simulated robot displayed). The simulator and world toggle buttons are shown as selected.](../images/Section_00_02-nb3devsim_-_Jupyter_Notebook.png) Many predefined worlds are available that can be loaded into the simulator, as image files, from a drop-down menu. (Source code for generating the background image files is also available in a notebook in the `backgrounds/` directory.) When some worlds are loaded in, the robot’s initial (default) location in that world is also specified; other robot settings, such as the positioning of the sensors, may also be initialised when a particular background is loaded. Obstacles can be added to a world using a configuration file opened by clicking the *Obstacles config* button in the simulator *Settings* panel. The simulated robot is also still configured via a configuration panel. The simulated robot can be dragged and placed on the simulated background or moved over and rotated within the simulator world using slider widgets. The `Reset` button will move the robot back to its default location in the world. ## 3.2 The EV3 ‘brick’ The Lego Mindstorms EV3 robots that inspired `ev3dev`, `ev2devsim` and `nbev3devsim` are based around a physical EV3 controller with a 300 MHz ARM9 processor, 16 MB of Flash memory, 64 MB RAM and a Linux-based operating system. ![figure ../tm129-19J-images/tm129_rob_p1_f005.jpg](../images/nogbad_ev3.jpg) _Photo credit: Nigel Gibson, OU residential school tutor_ The controller is capable of supporting four motor outputs referred to as `OUTPUT A`, `OUTPUT B`, `OUTPUT C` and `OUTPUT D`. In the simulator, we define a simple two-wheeled differential drive robot using two motors configured as follows: - `OUTPUT B`: left motor - `OUTPUT C`: right motor. The EV3 brick also supports four input ports to which four different, independent sensors can be attached. These range from touch sensors, to light sensors, infrared sensors, ultrasonic sensors and even gyroscopes. *Ports* are interfaces to the external world. Input *sensors* can be attached to the *input ports*, allowing information about the environment to enter the computer. Output *effectors*, such as *motors* and other actuators, can be attached to the output ports. The brick can switch such effectors on and off and control their direction and power. The `nbev3devsim` simulator is capable of simulating simple robots such as the ones that can be built with Lego Mindstorms. The simulator assumes that the simulated robot works like an EV3 brick. This means that the simulator needs to know what kinds of sensors and actuators are being used, and how the (simulated) EV3 robot is configured. You will see how this is done later. Although I have described the simulated robot in terms of a simple Lego robot, similar considerations would apply to other robotics systems. The control subsystem of any robot is usually flexible and designed to be configured with a variety of sensors and actuators. ## 3.3 Background – `ev3dev` and the original `ev3devsim` simulator (optional) <!-- JD: this line has been deleted in the .ipynb file: *Click on the arrow in the sidebar or run this cell to reveal the optional material.* --> Lego EV3 educational robots are widely used in all levels of education, including the Open University residential school module T176 *Engineering: professions, practice and skills 1*. Low-level functions provided by the `ev3dev` operating system are ‘wrapped’ by the [ev3dev-lang-python](https://github.com/ev3dev/ev3dev-lang-python) Python 3 package. This means that a Lego EV3 robot running the `ev3dev` operating system can be programmed using Python code. The `ev3devsim` package implements a cut-down version of the `ev3dev-lang-python` library to control a browser-based, 2D-simulated robot. The `ev3devsim` Python code runs in a Skulpt interpreter (a browser-based Python interpreter) to control a JavaScript-powered robot simulator. The original [`ev3devsim`](https://github.com/QuirkyCort/ev3dev-sim) simulator ran as a [standalone web application](https://www.aposteriori.com.sg/Ev3devSim/index.html) that could be run, even in an offline mode, using just a web browser. [![Screenshot of original ev3devsim simulator showing robot simulator canvas with simulated robot on a line-following test track, the program editor containing a sample program, simulator program run controls (Run and Stop buttons) and a sensor data output window with example sensor output readings.](../images/EV3DEV_Python_Simulator.png) Program code is entered into the editor window and run by clicking the simulator *Run* button. Program files can be saved from, and loaded into the program editor. An output window displays messages sent from the program, such as sensor log values, as well as error messages if the program throws an error when it is run. A range of predefined worlds can be loaded into the simulator, as image files, from a drop-down menu. Obstacles can be added to a world using a configuration file. The robot can be configured via a configuration menu and if required moved to a specified location. The [`nbev3devsim`](https://github.com/innovationOUtside/nbev3devsim) package builds on the original `ev3devsim` to provide an `ipywidget` that embeds the simulator in a Jupyter notebook. The simulated robot can be programmed using code downloaded from notebook code cells. Sensor data logged within the simulator can be exported to the notebook’s own Python environment and analysed using the full power of Python’s wide range of charting and data analysis packages. Whilst the original `ev3devsim` simulator runs without any software requirements other than a modern web browser, the `nbev3devsim` approach does require the availability of a Jupyter notebook environment. Although this increases the complexity of the software environment, it does provide several benefits: 1. instructional material can be provided within a notebook to support each programming activity 2. data retrieved from the simulator can be analysed and charted in the notebook kernel context (for example, using Python or R) 3. the notebook environment provides a read-write environment within which you can make your own notes and annotations, as well as keep a record of the various steps taken to develop any particular robot control program. ## 3.4 How the simulator relates to the notebooks The simulator we are using is created as an interactive `ipywidget` that is embedded within a Jupyter notebook. The simulator runs as a JavaScript program in the browser tab associated with the notebook the simulator is embedded in. The simulator has various settings that can be configured within the simulator user interface, or from the notebook commands that invoke it. *For more technical details (optional), see the `99.1 nbev3devsim notebook architecture` notebook in the `99. Technical Appendices` notebook directory.* The simulator can be loaded into the notebook environment with the following code commands: ``` from nbev3devsim.load_nbev3devwidget import roboSim, eds %load_ext nbev3devsim ``` When the simulator is loaded, the presentation of the notebook is adjusted to shift the notebook content to a column at the left of the screen, with the simulator in a resizable, draggable widget that pops up on the right-hand side of the screen. You can click on the right-hand edge of the notebook column and drag it to the right or left to make the column wider or narrower respectively. ### 3.4.1 Activity – Load the `nbev3devsim` simulator into the notebook environment Run the code cell below to load in the simulator: ``` from nbev3devsim.load_nbev3devwidget import roboSim, eds %load_ext nbev3devsim ``` Code is ‘downloaded’ from a code cell in the notebook to the simulator by running the code cell with some special IPython *magic* in the first line of the cell. You can also get code into the simulator by highlighting and copying the code (without the IPython magic line) and then clicking the *Paste* button in the *Code display* panel in the simulator. ### 3.4.2 Activity – Downloading code to the simulator and running it there Run the following code cell to download the code to the simulator. You may need to reposition and resize the widget to see the simulated robot in the simulator world view at the bottom of the widget. __Note that a cell block magic identified by a double percent sign (`%%`) MUST be placed on the first line of the code cell.__ Click the *Run* button in the simulator to run the downloaded code there. The robot should drive forwards a short distance and then stop. ``` %%sim_magic_preloaded # Drive the robot forwards a short distance tank_drive.on_for_rotations(SpeedPercent(50), SpeedPercent(50), 2) tank_turn.on_for_rotations(-100, SpeedPercent(75), 2) ``` You will have an opportunity to explore the `nbev3devsim` simulator in a bit more detail in the next notebook. ### 3.4.3 Configuring the simulator layout The simulator environment includes a range of user controls that can be used to configure the layout and view of the simulator user interface, as well as controlling operations performed within it. These include positioning the simulated robot, loading in different simulator backgrounds, loading obstacles into the simulated world, displaying status messages from the robot and dynamically charting logged sensor readings, as well as many other features. You will be introduced to these in more detail as and when they are required. A reference guide to the `nbev3devsim` user interface is also provided in the `99.2 nbev3devsim user interface` notebook in the `99. Technical Appendices` notebook directory. ### 3.4.4 Creating and saving your own robot program code The activities have been created within Jupyter notebooks using the embedded simulator widget. In many activities, you will have the opportunity to create and run your own programs to run within the simulator, as well as within the notebook’s own Python coding environment. Whilst it is possible to download and save code files loaded into the simulator, and load code back into the simulator from a saved file, we will generally download code from within a code cell to the simulator. Saving the notebook will thus keep a record of the code you have downloaded and run in the simulator, although as with the state of the notebook Python environment, the internal state of the simulator is not saved when you save the notebook. ## 3.5 Summary In this notebook, you have been introduced to the `nbev3devsim` simulator and its predecessor, the `ev3devsim` simulator. The `ev3devsim` simulator was itself inspired by `ev3dev`, a Linux-based operating system for the Lego Mindstorms EV3 computer brick. The `nbev3devsim` simulator represents a simple simulator environment that can be used to model the behaviour of real-world EV3 controlled mobile robots, such as the ones used in Open University engineering residential schools. In the next notebook, you will have an opportunity to explore how to configure and use the `nbev3devsim` simulator. *But first: would you like to create your own summary cell for this notebook, and colour it to highlight it as your own work?*
github_jupyter
# WWLayerIterator This Notebook explains how to use the internal WeightWatcher Layer Iterators Includes the WWStackerLayerIterator - Stacks all weight matrices into a single, large, rectangular matrix - Probably should normalize each layer in some consistent way *(not done yet) ``` # Suppress the powerlaw package warnings # "powerlaw.py:700: RuntimeWarning: divide by zero encountered in true_divide" # "powerlaw.py:700: RuntimeWarning: invalid value encountered in true_divide" import warnings warnings.simplefilter(action='ignore', category=RuntimeWarning) import numpy as np import pandas as pd from tqdm import tqdm import matplotlib import matplotlib.pyplot as plt %matplotlib inline %load_ext watermark %watermark ``` ### Import WeightWatcher set custom Logging at WARN Level ``` import logging import weightwatcher as ww import torchvision.models as models logger = logging.getLogger(ww.__name__) logger.setLevel(logging.WARNING) ww.__version__ ``` ### How to create a WWLayerIterator ``` model = models.vgg11(pretrained=True) watcher = ww.WeightWatcher(model=model) ww_layer_iterator = watcher.make_layer_iterator(model=model) ``` ### The Iterator lets you loop over WWLayer instances - The WWLayer instance (object) is a wrapper to the underlying framework layers - The intent is to only access the WWLayer instance and not the underlying framework methods - This lets weightwatcher apply different functions / transformations on each layer individually ``` for ww_layer in ww_layer_iterator: print(ww_layer) ``` ### The WWLayerIterator constructor method takes - layers=[LAYER_ID, ...] to specify filters, as in the watcher.analyze(..,) and watcher.describe(...) methods - other parameters, like ww2x and channels, are specified in the parameters dict ``` logger = logging.getLogger('weightwatcher') logger.setLevel(logging.WARNING) layers = [60] DEFAULT_PARAMS = {'glorot_fix': False, 'normalize':False, 'conv2d_norm':True, 'randomize': True, 'savefig':False, 'rescale':True , 'deltaEs':False, 'intra':False, 'channels':None, 'conv2d_fft':False, 'ww2x':False} params = DEFAULT_PARAMS ww_layer_iterator = watcher.make_layer_iterator(model=model, layers=layers, params=params) ``` #### Now only 1 layer is processed ``` for ww_layer in ww_layer_iterator: print(ww_layer) ``` ### WWLayer Instances When a WWLayer instance is created, the weight matrices for the layer are extracted from the underlying framework tensor (i.e. layer.weights and layer.biases) and placed into WMats - WMats = [W,W,W,...] contains 1 or more W matrices, of the same shape NxM, N > M - evals: the *combined* evals for each layer - rf = 1 or (k)x(k) the size of the 'receptive field' - layer_type = an internal enum: known layer types so far include: <pre> LAYER_TYPE.DENSE | LAYER_TYPE.CONV1D | LAYER_TYPE.CONV2D | LAYER_TYPE.FLATTENED | LAYER_TYPE.EMBEDDING | LAYER_TYPE.NORM </pre> - channel_str: string for channel type : "FIRST" | "LAST" | "UNKNOWN" ### WeightWatcher Apply Methods #### The various apply_xxx() methods use basic metaprogramming to set additional instance variables - apply_filters() - apply_normalize_Wmats() - apply_esd() - apply_random_esd() - apply_plot_esd() - apply_fit_powerlaw() - apply_norm_metrics() - apply_plot_deltaEs() - apply_mp_fit() - apply_svdsmoothing() i.e the apply_esd() method runs SVD on all the WMats, then combines them into a single ESD <code> # def apply_esd(self, ww_layer, params=AULT_PARAMS): """run full SVD on layer weight matrices, compute ESD on combined eigenvalues, combine all...""" # ... # ww_layer.evals = evals ww_layer.add_column("has_esd", True) ww_layer.add_column("num_evals", len(evals)) ww_layer.add_column("sv_max", sv_max) ww_layer.add_column("rank_loss", rank_loss) ww_layer.add_column("lambda_max", np.max(evals)) # return ww_layer </code> ### There are different Iterators for different ways of walking the Model Layers ``` type(ww_layer_iterator) from weightwatcher.weightwatcher import WWLayerIterator from weightwatcher.constants import LAYER_TYPE class WWStackedLayerIterator(WWLayerIterator): """Iterator variant that sticaks all weight matrics into a single WWLayer""" from copy import deepcopy def ww_stacked_iter_(self): from copy import deepcopy # find the maximum dimensions so we can pad the matrices ww_stacked_layer = None Wmats = [] for ww_layer in self.ww_layer_iter_(): # Here, Ijust lazizy copy an older layer # really, we should creat the WWLayer using the init() constructor if ww_stacked_layer is None: ww_stacked_layer = deepcopy(ww_layer) ww_stacked_layer.the_type = LAYER_TYPE.COMBINED ww_stacked_layer.layer_id = 0 ww_stacked_layer.name = "Example Stacked Layer" Wmats.extend(ww_layer.Wmats) # Note: Here the matrices should be padded so that they are all the same width # ww_stacked_layer.Wmats = pad(Wmats) # Nmax = np.max([np.max(W.shape) for W in Wmats]) Mmin = np.min([np.min(W.shape) for W in Wmats]) Wmats_padded = [] for W in Wmats: Height, Width = W.shape[0], W.shape[1] if Height > Width: W = W.T Height, Width = W.shape[0], W.shape[1] W = np.pad(W, ((0, 0), (0, Nmax-Width)) ) W = W/np.linalg.norm(W) Wmats_padded.append(W) W_stacked = np.vstack(Wmats_padded) N, M = W_stacked.shape[0], W_stacked.shape[1] if N < M: W_stacked = W_stacked.T N, M = W_stacked.shape[0], W_stacked.shape[1] ww_stacked_layer.Wmats = [W_stacked] # Then, the layer shape has to be set # Just setting dummy variable here ww_stacked_layer.N = N ww_stacked_layer.M = M ww_stacked_layer.rf = 1 #... yield ww_stacked_layer def make_layer_iter_(self): return self.ww_stacked_iter_() layer_iter = WWStackedLayerIterator(model=model) for layer in layer_iter: print(layer) layer.N, layer.M ``` ### Notice: The final matrix is quite large so the SVD will take some time ``` W = layer.Wmats[0] ``` ``` from sklearn.decomposition import TruncatedSVD svd = TruncatedSVD(n_components=5000) svd.fit(W) svals = svd.singular_values_ plt.hist(svals, bins=100); plt.title("VGG11 SVs, all layer W's naively padded and stacked") plt.xlabel(r"Singular Values, $\sigma_{i}$") plt.ylabel(r"Density, $\rho(\sigma)$") evals = svals*svals plt.hist(np.log10(evals), bins=100); plt.title("VGG11 ESD, all layer W's naively padded and stacked") plt.xlabel(r"Log EigenValues, $\log\;\lambda_{i}$") evals_nz = evals[evals>0.01] plt.hist(np.log10(evals_nz), bins=100); plt.title("VGG11 non-zero ESD , all layer W's naively padded and stacked") plt.xlabel(r"Log EigenValues, $\log\;\lambda,\;\;\lambda>0.01$") plt.loglog(evals); plt.title("VGG11 Stacked ESD, log log plot") plt.loglog(evals_nz); plt.title("VGG11 Stacked non-zero ESD, log log plot") import powerlaw results = powerlaw.Fit(evals_nz) results.alpha layer.evals = evals_nz ``` #### The savefig option is not working correctly... ``` params = {'glorot_fix': False, 'normalize':False, 'conv2d_norm':False, 'randomize': True, 'savedir':'ww-img', 'savefig':True, 'rescale':True, 'plot':True, 'deltaEs':False, 'intra':False, 'channels':None, 'conv2d_fft':False, 'ww2x':False, 'vectors':False, 'smooth':None} watcher.apply_fit_powerlaw(layer, params=params) W = layer.Wmats[0] Wrand = W.flatten() np.random.shuffle(Wrand) np.random.shuffle(Wrand) np.random.shuffle(Wrand) np.random.shuffle(Wrand) np.random.shuffle(Wrand) W = Wrand.reshape(W.shape) W = W.astype(float) svd = TruncatedSVD(n_components=5000) svd.fit(W) svals = svd.singular_values_ rand_evals = svals*svals layer.rand_evals = rand_evals plt.hist(np.log10(layer.rand_evals), bins=100, color='red', alpha=0.5, density=True, label='random'); plt.hist(np.log10(evals), bins=100, color='green', alpha=0.5, density=True, label='stacked'); plt.legend() plt.xlabel("Log10 Eigenvalues") plt.title("log10 Eigenvalues: n\n Stacked Layers X vs Randomized(X) ") layer.evals = layer.rand_evals watcher.apply_fit_powerlaw(layer, params=params) details = watcher.describe(model) details Ntot = int(np.sum(details.N.to_numpy())) Mtot = int(np.sum(details.M.to_numpy()*np.sqrt(details.rf.to_numpy()))) Ntot, Mtot Ntot/ Mtot, Ntot/3 layer.N = Ntot layer.M = Ntot/20 watcher.apply_mp_fit(layer, params=params) ```
github_jupyter
# Tutorial 01: Running Sumo Simulations This tutorial walks through the process of running non-RL traffic simulations in Flow. Simulations of this form act as non-autonomous baselines and depict the behavior of human dynamics on a network. Similar simulations may also be used to evaluate the performance of hand-designed controllers on a network. This tutorial focuses primarily on the former use case, while an example of the latter may be found in `tutorial09_controllers.ipynb`. In this tutorial, we simulate a initially perturbed single lane ring road. We witness in simulation that as time advances the initially perturbations do not dissipate, but instead propagates and expands until vehicles are forced to periodically stop and accelerate. For more information on this behavior, we refer the reader to the following article [1]. ## 1. Components of a Simulation All simulations, both in the presence and absence of RL, require two components: a *network*, and an *environment*. Networks describe the features of the transportation network used in simulation. This includes the positions and properties of nodes and edges constituting the lanes and junctions, as well as properties of the vehicles, traffic lights, inflows, etc. in the network. Environments, on the other hand, initialize, reset, and advance simulations, and act the primary interface between the reinforcement learning algorithm and the network. Moreover, custom environments may be used to modify the dynamical features of an network. ## 2. Setting up a Network Flow contains a plethora of pre-designed networks used to replicate highways, intersections, and merges in both closed and open settings. All these networks are located in `flow/networks`. In order to recreate a ring road network, we begin by importing the network `RingNetwork`. ``` from flow.networks.ring import RingNetwork ``` This network, as well as all other networks in Flow, is parametrized by the following arguments: * name * vehicles * net_params * initial_config * traffic_lights These parameters allow a single network to be recycled for a multitude of different network settings. For example, `RingNetwork` may be used to create ring roads of variable length with a variable number of lanes and vehicles. ### 2.1 Name The `name` argument is a string variable depicting the name of the network. This has no effect on the type of network created. ``` name = "ring_example" ``` ### 2.2 VehicleParams The `VehicleParams` class stores state information on all vehicles in the network. This class is used to identify the dynamical behavior of a vehicle and whether it is controlled by a reinforcement learning agent. Morover, information pertaining to the observations and reward function can be collected from various get methods within this class. The initial configuration of this class describes the number of vehicles in the network at the start of every simulation, as well as the properties of these vehicles. We begin by creating an empty `VehicleParams` object. ``` from flow.core.params import VehicleParams vehicles = VehicleParams() ``` Once this object is created, vehicles may be introduced using the `add` method. This method specifies the types and quantities of vehicles at the start of a simulation rollout. For a description of the various arguements associated with the `add` method, we refer the reader to the following documentation ([VehicleParams.add](https://flow.readthedocs.io/en/latest/flow.core.html?highlight=vehicleparam#flow.core.params.VehicleParams)). When adding vehicles, their dynamical behaviors may be specified either by the simulator (default), or by user-generated models. For longitudinal (acceleration) dynamics, several prominent car-following models are implemented in Flow. For this example, the acceleration behavior of all vehicles will be defined by the Intelligent Driver Model (IDM) [2]. ``` from flow.controllers.car_following_models import IDMController ``` Another controller we define is for the vehicle's routing behavior. For closed network where the route for any vehicle is repeated, the `ContinuousRouter` controller is used to perpetually reroute all vehicles to the initial set route. ``` from flow.controllers.routing_controllers import ContinuousRouter ``` Finally, we add 22 vehicles of type "human" with the above acceleration and routing behavior into the `Vehicles` class. ``` vehicles.add("human", acceleration_controller=(IDMController, {}), routing_controller=(ContinuousRouter, {}), num_vehicles=22) ``` ### 2.3 NetParams `NetParams` are network-specific parameters used to define the shape and properties of a network. Unlike most other parameters, `NetParams` may vary drastically depending on the specific network configuration, and accordingly most of its parameters are stored in `additional_params`. In order to determine which `additional_params` variables may be needed for a specific network, we refer to the `ADDITIONAL_NET_PARAMS` variable located in the network file. ``` from flow.networks.ring import ADDITIONAL_NET_PARAMS print(ADDITIONAL_NET_PARAMS) ``` Importing the `ADDITIONAL_NET_PARAMS` dictionary from the ring road network, we see that the required parameters are: * **length**: length of the ring road * **lanes**: number of lanes * **speed**: speed limit for all edges * **resolution**: resolution of the curves on the ring. Setting this value to 1 converts the ring to a diamond. At times, other inputs may be needed from `NetParams` to recreate proper network features/behavior. These requirements can be found in the network's documentation. For the ring road, no attributes are needed aside from the `additional_params` terms. Furthermore, for this tutorial, we use the network's default parameters when creating the `NetParams` object. ``` from flow.core.params import NetParams net_params = NetParams(additional_params=ADDITIONAL_NET_PARAMS) ``` ### 2.4 InitialConfig `InitialConfig` specifies parameters that affect the positioning of vehicle in the network at the start of a simulation. These parameters can be used to limit the edges and number of lanes vehicles originally occupy, and provide a means of adding randomness to the starting positions of vehicles. In order to introduce a small initial disturbance to the system of vehicles in the network, we set the `perturbation` term in `InitialConfig` to 1m. ``` from flow.core.params import InitialConfig initial_config = InitialConfig(spacing="uniform", perturbation=1) ``` ### 2.5 TrafficLightParams `TrafficLightParams` are used to describe the positions and types of traffic lights in the network. These inputs are outside the scope of this tutorial, and instead are covered in `tutorial10_traffic_lights.ipynb`. For our example, we create an empty `TrafficLightParams` object, thereby ensuring that none are placed on any nodes. ``` from flow.core.params import TrafficLightParams traffic_lights = TrafficLightParams() ``` ## 3. Setting up an Environment Several envionrments in Flow exist to train autonomous agents of different forms (e.g. autonomous vehicles, traffic lights) to perform a variety of different tasks. These environments are often network- or task-specific; however, some can be deployed on an ambiguous set of networks as well. One such environment, `AccelEnv`, may be used to train a variable number of vehicles in a fully observable network with a *static* number of vehicles. ``` from flow.envs.ring.accel import AccelEnv ``` Although we will not be training any autonomous agents in this tutorial, the use of an environment allows us to view the cumulative reward simulation rollouts receive in the absence of autonomy. Although we will not be training any autonomous agents in this exercise, the use of an environment allows us to view the cumulative reward simulation rollouts receive in the absence of autonomy. Envrionments in Flow are parametrized by several components, including the following attributes: * `sim_params` * `env_params` * `network` * `net_params` * `initial_config` * `network` * `simulator` where `sim_params`, `env_params`, and `network` are the primary parameters of an environment. For the full list of attributes, please check `class Env` in `flow/envs/base.py`. Sumo envrionments in Flow are parametrized by three components: * `SumoParams` * `EnvParams` * `Network` ### 3.1 SumoParams `SumoParams` specifies simulation-specific variables (e.g. `SumoParams` and `AimsunParams` are the variables related to SUMO and Aimsun simulator, respectively). These variables maay include the length a simulation step (in seconds), whether to render the GUI when running the experiment, and other variables. For this example, we consider a SUMO simulation, step length of 0.1s, and activate the GUI. Another useful parameter is `emission_path`, which is used to specify the path where the emissions output will be generated. They contain a lot of information about the simulation, for instance the position and speed of each car at each time step. If you do not specify any emission path, the emission file will not be generated. More on this in Section 5. ### 3.1 SumoParams `SumoParams` specifies simulation-specific variables. These variables include the length a simulation step (in seconds) and whether to render the GUI when running the experiment. For this example, we consider a simulation step length of 0.1s and activate the GUI. Another useful parameter is `emission_path`, which is used to specify the path where the emissions output will be generated. They contain a lot of information about the simulation, for instance the position and speed of each car at each time step. If you do not specify any emission path, the emission file will not be generated. More on this in Section 5. ``` from flow.core.params import SumoParams sim_params = SumoParams(sim_step=0.1, render=True, emission_path='data') ``` ### 3.2 EnvParams `EnvParams` specify environment and experiment-specific parameters that either affect the training process or the dynamics of various components within the network. Much like `NetParams`, the attributes associated with this parameter are mostly environment-specific, and can be found in the environment's `ADDITIONAL_ENV_PARAMS` dictionary. ``` from flow.envs.ring.accel import ADDITIONAL_ENV_PARAMS print(ADDITIONAL_ENV_PARAMS) ``` Importing the `ADDITIONAL_ENV_PARAMS` variable, we see that it consists of only one entry, "target_velocity", which is used when computing the reward function associated with the environment. We use this default value when generating the `EnvParams` object. ``` from flow.core.params import EnvParams env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS) ``` ## 4. Setting up and Running the Experiment Once the inputs to the network and environment classes are ready, we are ready to set up a `Experiment` object. ``` from flow.core.experiment import Experiment ``` This object may be used to simulate rollouts in the absence of reinforcement learning agents, as well as acquire behaviors and rewards that may be used as a baseline with which to compare the performance of the learning agent. In this case, we choose to run our experiment for one rollout consisting of 3000 steps (300 s). **Note**: When executing the below code, remeber to click on the <img style="display:inline;" src="img/play_button.png"> Play button after the GUI is rendered. ``` flow_params = dict( exp_tag='ring_example', env_name=AccelEnv, network=RingNetwork, simulator='traci', sim=sim_params, env=env_params, net=net_params, veh=vehicles, initial=initial_config, tls=traffic_lights, ) # number of time steps flow_params['env'].horizon = 3000 exp = Experiment(flow_params) # run the sumo simulation _ = exp.run(1, convert_to_csv=True) ``` As we can see from the above simulation, the initial perturbations in the network instabilities propogate and intensify, eventually leading to the formation of stop-and-go waves after approximately 180s. ## 5. Visualizing Post-Simulation Once the simulation is done, a .xml file will be generated in the location of the specified `emission_path` in `SumoParams` (assuming this parameter has been specified) under the name of the network. In our case, this is: ``` import os emission_location = os.path.join(exp.env.sim_params.emission_path, exp.env.network.name) print(emission_location + '-emission.xml') ``` The .xml file contains various vehicle-specific parameters at every time step. This information is transferred to a .csv file if the `convert_to_csv` parameter in `exp.run()` is set to True. This file looks as follows: ``` import pandas as pd pd.read_csv(emission_location + '-emission.csv') ``` As you can see, each row contains vehicle information for a certain vehicle (specified under the *id* column) at a certain time (specified under the *time* column). These information can then be used to plot various representations of the simulation, examples of which can be found in the `flow/visualize` folder. ## 6. Modifying the Simulation This tutorial has walked you through running a single lane ring road experiment in Flow. As we have mentioned before, these simulations are highly parametrizable. This allows us to try different representations of the task. For example, what happens if no initial perturbations are introduced to the system of homogenous human-driven vehicles? ``` initial_config = InitialConfig() ``` In addition, how does the task change in the presence of multiple lanes where vehicles can overtake one another? ``` net_params = NetParams( additional_params={ 'length': 230, 'lanes': 2, 'speed_limit': 30, 'resolution': 40 } ) ``` Feel free to experiment with all these problems and more! ## Bibliography [1] Sugiyama, Yuki, et al. "Traffic jams without bottlenecks—experimental evidence for the physical mechanism of the formation of a jam." New journal of physics 10.3 (2008): 033001. [2] Treiber, Martin, Ansgar Hennecke, and Dirk Helbing. "Congested traffic states in empirical observations and microscopic simulations." Physical review E 62.2 (2000): 1805.
github_jupyter
# 基于U-Net卷积神经网络实现宠物图像分割 **作者:** [PaddlePaddle](https://github.com/PaddlePaddle)<br> **日期:** 2021.10<br> **摘要:** 本示例教程使用U-Net实现图像分割。 ## 一、简要介绍 在计算机视觉领域,图像分割指的是将数字图像细分为多个图像子区域的过程。图像分割的目的是简化或改变图像的表示形式,使得图像更容易理解和分析。图像分割通常用于定位图像中的物体和边界(线,曲线等)。更精确的,图像分割是对图像中的每个像素加标签的一个过程,这一过程使得具有相同标签的像素具有某种共同视觉特性。图像分割的领域非常多,无人车、地块检测、表计识别等等。 本示例简要介绍如何通过飞桨开源框架,实现图像分割。这里采用了一个在图像分割领域比较熟知的U-Net网络结构,是一个基于FCN做改进后的一个深度学习网络,包含下采样(编码器,特征提取)和上采样(解码器,分辨率还原)两个阶段,因模型结构比较像U型而命名为U-Net。 ## 二、环境设置 导入一些比较基础常用的模块,确认自己的飞桨版本。 ``` import os import io import numpy as np import matplotlib.pyplot as plt from PIL import Image as PilImage import paddle from paddle.nn import functional as F paddle.__version__ ``` ## 三、数据集 ### 3.1 数据集下载 本案例使用Oxford-IIIT Pet数据集,官网:https://www.robots.ox.ac.uk/~vgg/data/pets 。 数据集统计如下: ![alt 数据集统计信息](https://www.robots.ox.ac.uk/~vgg/data/pets/breed_count.jpg) 数据集包含两个压缩文件: 1. 原图:https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz 2. 分割图像:https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz ``` !wget http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz !wget http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz !tar -xf images.tar.gz !tar -xf annotations.tar.gz ``` ### 3.2 数据集概览 首先先看看下载到磁盘上的文件结构是什么样,来了解一下数据集。 1. 首先看一下images.tar.gz这个压缩包,该文件解压后得到一个images目录,这个目录比较简单,里面直接放的是用类名和序号命名好的图片文件,每个图片是对应的宠物照片。 ```bash . ├── samoyed_7.jpg ├── ...... └── samoyed_81.jpg ``` 2. 然后在看下annotations.tar.gz,文件解压后的目录里面包含以下内容,目录中的README文件将每个目录和文件做了比较详细的介绍,可以通过README来查看每个目录文件的说明。 ```bash . ├── README ├── list.txt ├── test.txt ├── trainval.txt ├── trimaps │ ├── Abyssinian_1.png │ ├── Abyssinian_10.png │ ├── ...... │ └── yorkshire_terrier_99.png └── xmls ├── Abyssinian_1.xml ├── Abyssinian_10.xml ├── ...... └── yorkshire_terrier_190.xml ``` 本次主要使用到images和annotations/trimaps两个目录,即原图和三元图像文件,前者作为训练的输入数据,后者是对应的标签数据。 来看看这个数据集提供了多少个训练样本。 ``` IMAGE_SIZE = (160, 160) train_images_path = "images/" label_images_path = "annotations/trimaps/" image_count = len([os.path.join(train_images_path, image_name) for image_name in os.listdir(train_images_path) if image_name.endswith('.jpg')]) print("用于训练的图片样本数量:", image_count) # 对数据集进行处理,划分训练集、测试集 def _sort_images(image_dir, image_type): """ 对文件夹内的图像进行按照文件名排序 """ files = [] for image_name in os.listdir(image_dir): if image_name.endswith('.{}'.format(image_type)) \ and not image_name.startswith('.'): files.append(os.path.join(image_dir, image_name)) return sorted(files) def write_file(mode, images, labels): with open('./{}.txt'.format(mode), 'w') as f: for i in range(len(images)): f.write('{}\t{}\n'.format(images[i], labels[i])) """ 由于所有文件都是散落在文件夹中,在训练时需要使用的是数据集和标签对应的数据关系, 所以第一步是对原始的数据集进行整理,得到数据集和标签两个数组,分别一一对应。 这样可以在使用的时候能够很方便的找到原始数据和标签的对应关系,否则对于原有的文件夹图片数据无法直接应用。 在这里是用了一个非常简单的方法,按照文件名称进行排序。 因为刚好数据和标签的文件名是按照这个逻辑制作的,名字都一样,只有扩展名不一样。 """ images = _sort_images(train_images_path, 'jpg') labels = _sort_images(label_images_path, 'png') eval_num = int(image_count * 0.15) write_file('train', images[:-eval_num], labels[:-eval_num]) write_file('test', images[-eval_num:], labels[-eval_num:]) write_file('predict', images[-eval_num:], labels[-eval_num:]) ``` ### 3.3 PetDataSet数据集抽样展示 划分好数据集之后,来查验一下数据集是否符合预期,通过划分的配置文件读取图片路径后再加载图片数据来用matplotlib进行展示,这里要注意的是对于分割的标签文件因为是1通道的灰度图片,需要在使用imshow接口时注意下传参cmap='gray'。 ``` with open('./train.txt', 'r') as f: i = 0 for line in f.readlines(): image_path, label_path = line.strip().split('\t') image = np.array(PilImage.open(image_path)) label = np.array(PilImage.open(label_path)) if i > 2: break # 进行图片的展示 plt.figure() plt.subplot(1,2,1), plt.title('Train Image') plt.imshow(image.astype('uint8')) plt.axis('off') plt.subplot(1,2,2), plt.title('Label') plt.imshow(label.astype('uint8'), cmap='gray') plt.axis('off') plt.show() i = i + 1 ``` ### 3.4 数据集类定义 飞桨(PaddlePaddle)数据集加载方案是统一使用Dataset(数据集定义) + DataLoader(多进程数据集加载)。 首先进行数据集的定义,数据集定义主要是实现一个新的Dataset类,继承父类paddle.io.Dataset,并实现父类中以下两个抽象方法,`__getitem__`和`__len__`: ```python class MyDataset(Dataset): def __init__(self): ... # 每次迭代时返回数据和对应的标签 def __getitem__(self, idx): return x, y # 返回整个数据集的总数 def __len__(self): return count(samples) ``` 在数据集内部可以结合图像数据预处理相关API进行图像的预处理(改变大小、反转、调整格式等)。 由于加载进来的图像不一定都符合自己的需求,举个例子,已下载的这些图片里面就会有RGBA格式的图片,这个时候图片就不符合所需3通道的需求,需要进行图片的格式转换,那么这里直接实现了一个通用的图片读取接口,确保读取出来的图片都是满足需求。 另外图片加载出来的默认shape是HWC,这个时候要看看是否满足后面训练的需要,如果Layer的默认格式和这个不是符合的情况下,需要看下Layer有没有参数可以进行格式调整。不过如果layer较多的话,还是直接调整原数据Shape比较好,否则每个layer都要做参数设置,如果有遗漏就会导致训练出错,那么在本案例中是直接对数据源的shape做了统一调整,从HWC转换成了CHW,因为飞桨的卷积等API的默认输入格式为CHW,这样处理方便后续模型训练。 ``` import random from paddle.io import Dataset from paddle.vision.transforms import transforms as T class PetDataset(Dataset): """ 数据集定义 """ def __init__(self, mode='train'): """ 构造函数 """ self.image_size = IMAGE_SIZE self.mode = mode.lower() assert self.mode in ['train', 'test', 'predict'], \ "mode should be 'train' or 'test' or 'predict', but got {}".format(self.mode) self.train_images = [] self.label_images = [] with open('./{}.txt'.format(self.mode), 'r') as f: for line in f.readlines(): image, label = line.strip().split('\t') self.train_images.append(image) self.label_images.append(label) def _load_img(self, path, color_mode='rgb', transforms=[]): """ 统一的图像处理接口封装,用于规整图像大小和通道 """ with open(path, 'rb') as f: img = PilImage.open(io.BytesIO(f.read())) if color_mode == 'grayscale': # if image is not already an 8-bit, 16-bit or 32-bit grayscale image # convert it to an 8-bit grayscale image. if img.mode not in ('L', 'I;16', 'I'): img = img.convert('L') elif color_mode == 'rgba': if img.mode != 'RGBA': img = img.convert('RGBA') elif color_mode == 'rgb': if img.mode != 'RGB': img = img.convert('RGB') else: raise ValueError('color_mode must be "grayscale", "rgb", or "rgba"') return T.Compose([ T.Resize(self.image_size) ] + transforms)(img) def __getitem__(self, idx): """ 返回 image, label """ train_image = self._load_img(self.train_images[idx], transforms=[ T.Transpose(), T.Normalize(mean=127.5, std=127.5) ]) # 加载原始图像 label_image = self._load_img(self.label_images[idx], color_mode='grayscale', transforms=[T.Grayscale()]) # 加载Label图像 # 返回image, label train_image = np.array(train_image, dtype='float32') label_image = np.array(label_image, dtype='int64') return train_image, label_image def __len__(self): """ 返回数据集总数 """ return len(self.train_images) ``` ## 四、模型组网 U-Net是一个U型网络结构,可以看做两个大的阶段,图像先经过Encoder编码器进行下采样得到高级语义特征图,再经过Decoder解码器上采样将特征图恢复到原图片的分辨率。 ### 4.1 定义SeparableConv2D接口 为了减少卷积操作中的训练参数来提升性能,是继承paddle.nn.Layer自定义了一个SeparableConv2D Layer类,整个过程是把`filter_size * filter_size * num_filters`的Conv2D操作拆解为两个子Conv2D,先对输入数据的每个通道使用`filter_size * filter_size * 1`的卷积核进行计算,输入输出通道数目相同,之后在使用`1 * 1 * num_filters`的卷积核计算。 ``` from paddle.nn import functional as F class SeparableConv2D(paddle.nn.Layer): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=None, weight_attr=None, bias_attr=None, data_format="NCHW"): super(SeparableConv2D, self).__init__() self._padding = padding self._stride = stride self._dilation = dilation self._in_channels = in_channels self._data_format = data_format # 第一次卷积参数,没有偏置参数 filter_shape = [in_channels, 1] + self.convert_to_list(kernel_size, 2, 'kernel_size') self.weight_conv = self.create_parameter(shape=filter_shape, attr=weight_attr) # 第二次卷积参数 filter_shape = [out_channels, in_channels] + self.convert_to_list(1, 2, 'kernel_size') self.weight_pointwise = self.create_parameter(shape=filter_shape, attr=weight_attr) self.bias_pointwise = self.create_parameter(shape=[out_channels], attr=bias_attr, is_bias=True) def convert_to_list(self, value, n, name, dtype=np.int): if isinstance(value, dtype): return [value, ] * n else: try: value_list = list(value) except TypeError: raise ValueError("The " + name + "'s type must be list or tuple. Received: " + str( value)) if len(value_list) != n: raise ValueError("The " + name + "'s length must be " + str(n) + ". Received: " + str(value)) for single_value in value_list: try: dtype(single_value) except (ValueError, TypeError): raise ValueError( "The " + name + "'s type must be a list or tuple of " + str( n) + " " + str(dtype) + " . Received: " + str( value) + " " "including element " + str(single_value) + " of type" + " " + str(type(single_value))) return value_list def forward(self, inputs): conv_out = F.conv2d(inputs, self.weight_conv, padding=self._padding, stride=self._stride, dilation=self._dilation, groups=self._in_channels, data_format=self._data_format) out = F.conv2d(conv_out, self.weight_pointwise, bias=self.bias_pointwise, padding=0, stride=1, dilation=1, groups=1, data_format=self._data_format) return out ``` ### 4.2 定义Encoder编码器 将网络结构中的Encoder下采样过程进行了一个Layer封装,方便后续调用,减少代码编写,下采样是有一个模型逐渐向下画曲线的一个过程,这个过程中是不断的重复一个单元结构将通道数不断增加,形状不断缩小,并且引入残差网络结构,将这些都抽象出来进行统一封装。 ``` class Encoder(paddle.nn.Layer): def __init__(self, in_channels, out_channels): super(Encoder, self).__init__() self.relus = paddle.nn.LayerList( [paddle.nn.ReLU() for i in range(2)]) self.separable_conv_01 = SeparableConv2D(in_channels, out_channels, kernel_size=3, padding='same') self.bns = paddle.nn.LayerList( [paddle.nn.BatchNorm2D(out_channels) for i in range(2)]) self.separable_conv_02 = SeparableConv2D(out_channels, out_channels, kernel_size=3, padding='same') self.pool = paddle.nn.MaxPool2D(kernel_size=3, stride=2, padding=1) self.residual_conv = paddle.nn.Conv2D(in_channels, out_channels, kernel_size=1, stride=2, padding='same') def forward(self, inputs): previous_block_activation = inputs y = self.relus[0](inputs) y = self.separable_conv_01(y) y = self.bns[0](y) y = self.relus[1](y) y = self.separable_conv_02(y) y = self.bns[1](y) y = self.pool(y) residual = self.residual_conv(previous_block_activation) y = paddle.add(y, residual) return y ``` ### 4.3 定义Decoder解码器 在通道数达到最大得到高级语义特征图后,网络结构会开始进行decode操作,进行上采样,通道数逐渐减小,对应图片尺寸逐步增加,直至恢复到原图像大小,那么这个过程里面也是通过不断的重复相同结构的残差网络完成,也是为了减少代码编写,将这个过程定义一个Layer来放到模型组网中使用。 ``` class Decoder(paddle.nn.Layer): def __init__(self, in_channels, out_channels): super(Decoder, self).__init__() self.relus = paddle.nn.LayerList( [paddle.nn.ReLU() for i in range(2)]) self.conv_transpose_01 = paddle.nn.Conv2DTranspose(in_channels, out_channels, kernel_size=3, padding=1) self.conv_transpose_02 = paddle.nn.Conv2DTranspose(out_channels, out_channels, kernel_size=3, padding=1) self.bns = paddle.nn.LayerList( [paddle.nn.BatchNorm2D(out_channels) for i in range(2)] ) self.upsamples = paddle.nn.LayerList( [paddle.nn.Upsample(scale_factor=2.0) for i in range(2)] ) self.residual_conv = paddle.nn.Conv2D(in_channels, out_channels, kernel_size=1, padding='same') def forward(self, inputs): previous_block_activation = inputs y = self.relus[0](inputs) y = self.conv_transpose_01(y) y = self.bns[0](y) y = self.relus[1](y) y = self.conv_transpose_02(y) y = self.bns[1](y) y = self.upsamples[0](y) residual = self.upsamples[1](previous_block_activation) residual = self.residual_conv(residual) y = paddle.add(y, residual) return y ``` ### 4.4 训练模型组网 按照U型网络结构格式进行整体的网络结构搭建,三次下采样,四次上采样。 ``` class PetNet(paddle.nn.Layer): def __init__(self, num_classes): super(PetNet, self).__init__() self.conv_1 = paddle.nn.Conv2D(3, 32, kernel_size=3, stride=2, padding='same') self.bn = paddle.nn.BatchNorm2D(32) self.relu = paddle.nn.ReLU() in_channels = 32 self.encoders = [] self.encoder_list = [64, 128, 256] self.decoder_list = [256, 128, 64, 32] # 根据下采样个数和配置循环定义子Layer,避免重复写一样的程序 for out_channels in self.encoder_list: block = self.add_sublayer('encoder_{}'.format(out_channels), Encoder(in_channels, out_channels)) self.encoders.append(block) in_channels = out_channels self.decoders = [] # 根据上采样个数和配置循环定义子Layer,避免重复写一样的程序 for out_channels in self.decoder_list: block = self.add_sublayer('decoder_{}'.format(out_channels), Decoder(in_channels, out_channels)) self.decoders.append(block) in_channels = out_channels self.output_conv = paddle.nn.Conv2D(in_channels, num_classes, kernel_size=3, padding='same') def forward(self, inputs): y = self.conv_1(inputs) y = self.bn(y) y = self.relu(y) for encoder in self.encoders: y = encoder(y) for decoder in self.decoders: y = decoder(y) y = self.output_conv(y) return y ``` ### 4.5 模型可视化 调用飞桨提供的summary接口对组建好的模型进行可视化,方便进行模型结构和参数信息的查看和确认。 ``` num_classes = 4 network = PetNet(num_classes) model = paddle.Model(network) model.summary((-1, 3,) + IMAGE_SIZE) ``` ## 五、模型训练 ### 5.1 启动模型训练 使用模型代码进行Model实例生成,使用prepare接口定义优化器、损失函数和评价指标等信息,用于后续训练使用。在所有初步配置完成后,调用fit接口开启训练执行过程,调用fit时只需要将前面定义好的训练数据集、测试数据集、训练轮次(Epoch)和批次大小(batch_size)配置好即可。 ``` train_dataset = PetDataset(mode='train') # 训练数据集 val_dataset = PetDataset(mode='test') # 验证数据集 optim = paddle.optimizer.RMSProp(learning_rate=0.001, rho=0.9, momentum=0.0, epsilon=1e-07, centered=False, parameters=model.parameters()) model.prepare(optim, paddle.nn.CrossEntropyLoss(axis=1)) model.fit(train_dataset, val_dataset, epochs=15, batch_size=32, verbose=1) ``` ## 六、模型预测 ### 6.1 预测数据集准备和预测 继续使用PetDataset来实例化待预测使用的数据集。这里为了方便没有在另外准备预测数据,复用了评估数据。 可以直接使用model.predict接口来对数据集进行预测操作,只需要将预测数据集传递到接口内即可。 ``` predict_dataset = PetDataset(mode='predict') predict_results = model.predict(predict_dataset) ``` ### 6.2 预测结果可视化 从预测数据集中抽3个动物来看看预测的效果,展示一下原图、标签图和预测结果。 ``` plt.figure(figsize=(10, 10)) i = 0 mask_idx = 0 with open('./predict.txt', 'r') as f: for line in f.readlines(): image_path, label_path = line.strip().split('\t') resize_t = T.Compose([ T.Resize(IMAGE_SIZE) ]) image = resize_t(PilImage.open(image_path)) label = resize_t(PilImage.open(label_path)) image = np.array(image).astype('uint8') label = np.array(label).astype('uint8') if i > 8: break plt.subplot(3, 3, i + 1) plt.imshow(image) plt.title('Input Image') plt.axis("off") plt.subplot(3, 3, i + 2) plt.imshow(label, cmap='gray') plt.title('Label') plt.axis("off") # 模型只有一个输出,所以通过predict_results[0]来取出1000个预测的结果 # 映射原始图片的index来取出预测结果,提取mask进行展示 data = predict_results[0][mask_idx][0].transpose((1, 2, 0)) mask = np.argmax(data, axis=-1) plt.subplot(3, 3, i + 3) plt.imshow(mask.astype('uint8'), cmap='gray') plt.title('Predict') plt.axis("off") i += 3 mask_idx += 1 plt.show() ```
github_jupyter
``` #Import required packages from keras.models import Sequential from keras.layers import Dense import numpy as np import ipdb # deb # Getting the data ready # Generate train dummy data for 1000 Students and dummy test # for 500 #Columns :Age, Hours of Study &Avg Previous test scores np.random.seed(2018) #Setting seed for reproducibility train_data, test_data = np.random.random((1000, 3)), np.random.random((500, 3)) #Generate dummy results for 1000 students : Whether Passed (1) # or Failed (0) labels = np.random.randint(2, size=(1000, 2)) #Defining the model structure with the required layers, # of neurons, activation function and optimizers model = Sequential() model.add(Dense(5, input_dim=3, activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(2, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #Train the model and make predictions model.fit(train_data, labels, epochs=10, batch_size=32) #Make predictions from the trained model predictions = model.predict(test_data) predictions[:10] ``` ## Train, Test and validation ``` import numpy as np from keras.models import Sequential from keras.layers import Dense, Activation # Generate dummy training dataset np.random.seed(2019) x_train = np.random.random((6000,10)) y_train = np.random.randint(2, size=(6000, 1)) # Generate dummy validation dataset x_val = np.random.random((2000,10)) y_val = np.random.randint(2, size=(2000, 1)) # Generate dummy test dataset x_test = np.random.random((2000,10)) y_test = np.random.randint(2, size=(2000, 1)) #Define the model architecture model = Sequential() model.add(Dense(64, input_dim=10,activation = "relu")) #Layer 1 model.add(Dense(32,activation = "relu")) #Layer 2 model.add(Dense(16,activation = "relu")) #Layer 3 model.add(Dense(8,activation = "relu")) #Layer 4 model.add(Dense(4,activation = "relu")) #Layer 5 model.add(Dense(1,activation = "sigmoid")) #Output Layer #Configure the model model.compile(optimizer='Adam',loss='binary_crossentropy', metrics=['accuracy']) #Train the model model.fit(x_train, y_train, batch_size=64, epochs=3, validation_data=(x_val,y_val)) print(model.metrics_names) print(model.evaluate(x_test,y_test)) #Make predictions on the test dataset and print the first 10 predictions pred = model.predict(x_test) pred[:10] ``` # Boston House Prices dataset ``` from keras.datasets import boston_housing import numpy as np from keras.models import Sequential from keras.layers import Dense, Activation (x_train, y_train), (x_test, y_test) = boston_housing.load_data() #Explore the data structure using basic python commands print("Type of the Dataset:",type(y_train)) print("Shape of training data :",x_train.shape) print("Shape of training labels :",y_train.shape) print("Shape of testing data :",type(x_test)) print("Shape of testing labels :",y_test.shape) ``` Column Name Description : - **CriM** per capita crime rate by town - **Zn** proportion of residential land zoned for lots over 25,000 sq. ft. - **inDUs** proportion of nonretail business acres per town - **Chas** Charles river dummy variable (= 1 if tract bounds river; 0 otherwise) - **noX** nitric oxide concentration (parts per 10 million) - **rM** average number of rooms per dwelling - **aGe** proportion of owner-occupied units built prior to 1940 - **Dis** weighted distances to five Boston employment centers - **raD** index of accessibility to radial highways - **taX** full-value property tax rate per $\$10,000$ - **ptratio** pupil-teacher ratio by town - **B** $1000(Bk – 0.63)^2$, where Bk is the proportion of blacks by town - **Lstat** \% lower status of the population - **MeDV** median value of owner-occupied homes in $\$1000's$ ``` x_train[:5,:] ``` It a good idea, to split the training data in training set and validation set. ``` # Extract the last 100 rows from the training # data to create the validation datasets. x_val = x_train[300:,] y_val = y_train[300:,] #Define the model architecture model = Sequential() model.add(Dense(13, input_dim=13, kernel_initializer='normal', activation='relu')) model.add(Dense(6, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal')) # Compile model model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_absolute_percentage_error']) #Train the model model.fit(x_train, y_train, batch_size=32, epochs=3, validation_data=(x_val,y_val)) ``` We have created a simple two-hidden-layer model for the regression use case. We have chosen _MAPE_ as the metric. Generally, this is not the best metric to choose for studying model performance, but its advantage is simplicity in terms of comprehending the results. It gives a simple percentage value for the error, say $10\%$ error. So, if you know the average range of your prediction, you can easily estimate what the predictions are going to look like ``` results = model.evaluate(x_test, y_test) for i in range(len(model.metrics_names)): print(model.metrics_names[i]," : ", results[i]) ``` We can see that __MAPE__ is around $96\%$, which is actually not a great number to have for model performance. This would translate into our model predictions at around $96\%$ error. So, in general, if a house was priced at $10K$, our model would have predicted $\approx20K$. ``` #Train the model model.fit(x_train, y_train, batch_size=32, epochs=30, validation_data=(x_val,y_val)) ``` # Regression ## Rossmann Store sales dataset Rossmann is one of the largest drugstore chains in Germany, with operations across Europe. As of 2018, they have well over 3,900 stores in Europe with an annual turnover of 9 billion euros. Our task is to predict the sales for a few identified stores on a given day. ### Data fields Most of the fields are self-explanatory. The following are descriptions for those that aren't. - **Id** - an Id that represents a (Store, Date) duple within the test set - **Store** - a unique Id for each store - **Sales** - the turnover for any given day (this is what you are predicting) - **Customers** - the number of customers on a given day - **Open** - an indicator for whether the store was open: 0 = closed, 1 = open - **StateHoliday** - indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays. Note that all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None - **SchoolHoliday** - indicates if the (Store, Date) was affected by the closure of public schools - **StoreType** - differentiates between 4 different store models: a, b, c, d - **Assortment** - describes an assortment level: a = basic, b = extra, c = extended - **CompetitionDistance** - distance in meters to the nearest competitor store - **CompetitionOpenSince[Month/Year]** - gives the approximate year and month of the time the nearest competitor was opened - **Promo** - indicates whether a store is running a promo on that day - **Promo2** - Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating - **Promo2Since[Year/Week]** - describes the year and calendar week when the store started participating in Promo2 - **PromoInterval** - describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. "Feb,May,Aug,Nov" means each round starts in February, May, August, November of any given year for that store ``` import pandas as pd import numpy as np df = pd.read_csv("./data/Rossmann Store Sales/train.csv") print("Shape of the Dataset:",df.shape) #the head method displays the first 5 rows of the data df.head(5) store = pd.read_csv("./data/Rossmann Store Sales/store.csv") print("Shape of the Dataset:",store.shape) #Display the first 5 rows of data using the head method of pandas dataframe store.head(5) ``` To have all the data points together, we need to create one single dataframe with the store and promotion features. We can achieve this by joining the two dataframes on the ‘store’ column, which represents the store ID. Pandas provides a ‘merge’ function that is analogous to the join statement in SQL. We can perform left, right, inner, and full outer joins on one or more dataframes using one or more columns as the joining key. ``` df_new = df.merge(store,on=["Store"], how="inner") print(df_new.shape) df_new.tail() print("Distinct number of Stores :", len(df_new["Store"].unique())) print("Distinct number of Days :", len(df_new["Date"].unique())) print("Average daily sales of all stores : ",round(df_new["Sales"].mean(),2)) df_new.dtypes df_new["DayOfWeek"].value_counts() ``` Let’s create additional features that will help our model learn patterns better. We will create the week number, month, day, quarter, and year as features from the date variable. Similarly, since we are already creating time-related features, we can add a new feature based on climate and seasons. Considering that the stores are in Europe, we can refer to the standard season cycles and create a new season feature with values of Spring, Summer, Fall, and Winter. Pandas provides easy-to-use functions to extract date-related features; the season-related feature can be created with a simple ‘if else’ equivalent convention. ``` #We can extract all date properties from a datetime datatype df_new['Date'] = pd.to_datetime(df_new['Date'], infer_datetime_format=True) df_new["Month"] = df_new["Date"].dt.month df_new["Quarter"] = df_new["Date"].dt.quarter df_new["Year"] = df_new["Date"].dt.year df_new["Day"] = df_new["Date"].dt.day df_new["Week"] = df_new["Date"].dt.week df_new["Season"] = np.where(df_new["Month"].isin([3,4,5]),"Spring", np.where(df_new["Month"].isin([6,7,8]),"Summer", np.where(df_new["Month"].isin([9,10,11]),"Fall", np.where(df_new["Month"].isin([12,1,2]),"Winter","None")))) df_new[["Date","Year","Month","Day","Week","Quarter","Season"]].head() #Import matplotlib, python most popular data visualizing library import matplotlib.pyplot as plt %matplotlib inline #Create a histogram to study the Daily Sales for the stores plt.figure(figsize=(15,8)) plt.hist(df_new["Sales"]) plt.title("Histogram for Store Sales") plt.xlabel("bins") plt.xlabel("Frequency") plt.show() ``` The histogram helps us understand the distribution of the data at a high level. From the preceding plot, we can see that the data range is from 0 to 40,000, but there is barely any data after 20,000. This indicates that most of the stores have sales in the range 0–20,000, and just a few stores have sales greater than 20,000. It might be worthwhile to remove these outliers, as it helps the model learn better. ``` #Use the histogram function provided by the Pandas object #The function returns a cross-tab histogram plot for all numeric columns in the data df_new.hist(figsize=(20,15)) ``` Let’s have a look at the number of missing data points in each column (if any) in its associated percentage form. ``` df_new.isnull().sum()/df_new.shape[0] * 100 ``` We can see that Promo2SinceWeek, Promo2SinceYear, PromoInterval, CompetitionOpenSinceMonth, and CompetitionOpenSinceYear have over 30% null values. This is a big loss and there is nothing much we can do to fix this. As a rule of thumb, if there is a loss of anything between 0% and 10%, we can make a few attempts to fill the missing points and use the feature. But, 30% technically becomes beyond the usable range. On the other hand, we can see CompetitionDistance has around 0.25% missing values. This would much easier to handle and fix. ``` #Replace nulls with the mode df_new["CompetitionDistance"]=df_new["CompetitionDistance"].fillna(df_new["CompetitionDistance"].mode()[0]) #Double check if we still see nulls for the column df_new["CompetitionDistance"].isnull().sum()/df_new.shape[0] * 100 ``` The best way to study a categorical variable is to study the impact on the target variable from its individual classes. We can do this by plotting the mean sales across different values of the classes in the feature. To accomplish this, we can leverage “seaborn,” another powerful and easy-to-use Python visualization library, similar to matplotlib but providing much more beautiful visuals. ``` import seaborn as sns #Seaborn is another powerful visualization library for Python sns.set(style="whitegrid") #Create the bar plot for Average Sales across different Seasons ax = sns.barplot(x="Season", y="Sales", data=df_new) #Create the bar plot for Average Sales across different Assortments ax = sns.barplot(x="Assortment", y="Sales", data=df_new) #Create the bar plot for Average Sales across different Store Types ax = sns.barplot(x="StoreType", y="Sales", data=df_new) ``` As you can see, the seaborn package has internally calculated the average sales across its classes for the provided categorical column and displayed a beautiful bar plot showcasing the relationship with our target variable. We can change the aggregation function to a different one if required; this can be changed by using the ‘estimator’ parameter within the barplot function. Sales across seasons barely seem to differ; however, there seems to be an increasing trend for sales across assortments. Stores with assortment “b” generally have the highest sales. Store type also shows a unique relationship with sales across store types. We can see fairly higher sales for “b” store types also. However, before we conclude our observations, there is one more sanity check required to validate these hypotheses. What if the number of stores in the different types mentioned in the preceding is disproportionate or skewed? In such a scenario, our observation might be flawed. To cement our understanding about the observation, we can simply check the number of data points across each category using the same barplot function with one additional parameter setting. We will use a new aggregation function to showcase the counts as the metric for bar charts. The following code snippet visualizes the bar plots for the same set of categorical variables we studied earlier, albeit for counts. ``` ax = sns.barplot(x="Season", y="Sales", data=df_new, estimator=np.size) ax = sns.barplot(x="Assortment", y="Sales", data=df_new, estimator=np.size) ax = sns.barplot(x="StoreType", y="Sales", data=df_new, estimator=np.size) ``` we will start with treating Season, Assortment, Month, Year, Quarter, DayOfWeek, and StoreType in one-hot encoded form and keep aside Day, Week, and Store as continuous for the time being. We will revisit this after we build a few models and study their performance. To transform a categorical column into a one-hot encoded version, Python provides the preprocessing module in the sklearn package with rich and easy-to-use functions. The following code snippet engineers the training dataframe into the final required form for model development. ``` # Define a variable for each type of feature from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder target = ["Sales"] numeric_columns = ["Customers","Open","Promo","Promo2", "StateHoliday","SchoolHoliday","CompetitionDistance"] categorical_columns = ["DayOfWeek","Quarter","Month","Year", "StoreType","Assortment","Season"] # note that we left aside (Day, Week, and Store) # Define a function that will intake the raw dataframe and the # column name and return a one hot encoded DF def create_ohe(df, col): le = LabelEncoder() a = le.fit_transform(df_new[col]).reshape(-1,1) #; ipdb.set_trace() ohe = OneHotEncoder(sparse=False) column_names = [col+ "_"+ str(i) for i in le.classes_] return(pd.DataFrame(ohe.fit_transform(a),columns =column_names)) # Since the above function converts the column, one at a time # We create a loop to create the final dataset with all features temp = df_new[numeric_columns] for column in categorical_columns: temp_df = create_ohe(df_new, column) temp = pd.concat([temp,temp_df], axis=1) print("Shape of Data:",temp.shape) print("Distinct Datatypes:",temp.dtypes.unique()) print(temp.columns[temp.dtypes=="object"]) temp["StateHoliday"].unique() ``` The feature seems to have incorrect values. Ideally, StateHoliday should have either a 0 or 1 as the possible values to indicate whether it is a holiday or not. Let’s repair the feature by replacing all values of “a,” “b,” and “c” with 1 and the rest with 0, therefore converting the variable as numeric. ``` temp["StateHoliday"]= np.where(temp["StateHoliday"]== '0',0,1) # One last check of the data type temp.dtypes.unique() ``` Spliting data ``` from sklearn.model_selection import train_test_split #Create train and test dataset with an 80:20 split x_train, x_test, y_train, y_test = train_test_split( temp, df_new[target],test_size=0.2,random_state=2018) #Further divide training dataset into train and validation # dataset with an 90:10 split x_train, x_val, y_train, y_val = train_test_split( x_train, y_train,test_size=0.1,random_state=2018) #Check the sizes of all newly created datasets print("Shape of x_train:",x_train.shape) print("Shape of x_val:",x_val.shape) print("Shape of x_test:",x_test.shape) print("Shape of y_train:",y_train.shape) print("Shape of y_val:",y_val.shape) print("Shape of y_test:",y_test.shape) ``` ### Defining Model For a regression model, if we assume the mean value of sales in the training dataset to be the prediction for all samples in the test dataset, we would have a basic benchmark score. The DL model should at least score better than this score to be considered as useful. ``` #calculate the average score of the train dataset mean_sales = y_train.mean() print("Average Sales :",mean_sales) ``` Now, if we assume the average sales as the prediction for all samples in the test dataset, what does the MAE metric look like? ``` #Calculate the Mean Absolute Error on the test dataset print("MAE for Test Data : ",abs(y_test - mean_sales).mean()[0]) ``` So, our baseline performance is 2,883.58. If our DL model doesn’t deliver results better (i.e., lower) than the baseline score, then it would barely add any value. ## Designing the DNN Here are a few guidelines. - **Rule 1: Start with small architectures.** In the case of DNNs, it is always advised to start with a single-layer network with around 100–300 neurons. Train the network and measure performance using the defined metrics (while defining the baseline score). If the results are not encouraging, try adding one more layer with the same number of neurons and repeating the process. - __Rule 2: When small architectures (with two layers)__ fail, increase the size. When the results from small networks are not great, you need to increase the number of neurons in layers by three to five times (i.e., around 1,000 neurons in each layer). Also, increase regularization (to be covered in depth in Chapter 5) to 0.3, 0.4, or 0.5 for both layers and repeat the process for training and performance measurement. - **Rule 3: When larger networks with two layers fail, go deeper.** Try increasing the depth of the network with more and more layers while maintaining regularization with dropout layers (if required) after each dense (or your selected layer) with a dropout rate between 0.2 and 0.5. - **Rule 4: When larger and deeper networks also fail, go even larger and even deeper.** In case large networks with ~1000 neurons and five or six layers also don’t give the desired performance, try increasing the width and depth of the network. Try adding layers with 8,000–10,000 neurons per layer and a dropout of 0.6 to 0.8. - **Rule 5: When everything fails, revisit the data.** If all the aforementioned rules fail, revisit the data for improved feature engineering and normalization, and then you will need to try other ML alternatives. ``` #Create Deep Neural Network Architecture from keras.models import Sequential from keras.layers import Dense, Dropout model = Sequential() model.add(Dense(150,input_dim = 44,activation="relu")) #The input_dim =44, since the width of the training data=44 (refer data engg section) model.add(Dense(1,activation = "linear")) #Configure the model model.compile(optimizer='adam',loss="mean_absolute_error", metrics=["mean_absolute_error"]) #Train the model model.fit(x_train.values,y_train.values, validation_data= (x_val,y_val),epochs=10,batch_size=64) #Use the model's evaluate method to predict and evaluate the test datasets result = model.evaluate(x_test.values,y_test.values) # ,value to moove from data set to array #Print the results for i in range(len(model.metrics_names)): print("Metric ",model.metrics_names[i],":",str(round(result[i],2))) ``` (Mean) 2883.587604303127 vs 685.43 (DNN) ### Improoving model In the following network, we have added two more layers with similar numbers of neurons. We will update our loss function to mean squared error instead of MAE. Let’s train the network and have a look at the performance on the test dataset. ``` model = Sequential() model.add(Dense(150,input_dim = 44,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(1,activation = "linear")) model.compile(optimizer='adam', loss="mean_squared_error", metrics=["mean_absolute_error"]) history = model.fit(x_train,y_train, validation_data=(x_val, y_val), epochs=10, batch_size=64) result = model.evaluate(x_test,y_test) for i in range(len(model.metrics_names)): print("Metric ",model.metrics_names[i],":",str(round(result[i],2))) ``` Let’s try a couple of more experiments to see if we can expect further improved performance. We can develop another deeper model with five hidden layers having 150 neurons each. In this case, we have increased the number of epochs from 10 to 15. This would therefore increase computation. ``` model = Sequential() model.add(Dense(150,input_dim = 44,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(150,activation="relu")) model.add(Dense(1,activation = "linear")) model.compile(optimizer='adam', loss="mean_squared_error", metrics=["mean_absolute_error"]) model.fit(x_train, y_train, validation_data=(x_val,y_val), epochs=15, batch_size=64) result = model.evaluate(x_test,y_test) for i in range(len(model.metrics_names)): print("Metric ",model.metrics_names[i],":",str(round(result[i],2))) ``` ## Increasing the Number of Neurons ``` model = Sequential() model.add(Dense(350,input_dim = 44,activation="relu")) model.add(Dense(350,activation="relu")) model.add(Dense(1,activation = "linear")) model.compile(optimizer='adam', loss="mean_squared_error", metrics=["mean_absolute_error"]) model.fit(x_train,y_train, validation_data=(x_val,y_val), epochs=15,batch_size=64) result = model.evaluate(x_test,y_test) for i in range(len(model.metrics_names)): print("Metric ",model.metrics_names[i],":", str(round(result[i],2))) ``` We can see quite a bit of improvement when we use an architecture that was built with a higher number of neurons. This was a considerable improvement for the model. Let us now try deeper models for the same architecture. Additionally, we add a new [optional] configuration to the model to record the history of various metrics during the training process. This can be done by adding the callbacks parameter, as shown in the following example. We can use the history, post training, to visualize and understand the model’s learning curve. ``` from keras.callbacks import History history = History() model = Sequential() model.add(Dense(350,input_dim = 44,activation="relu")) model.add(Dense(350,activation="relu")) model.add(Dense(350,activation="relu")) model.add(Dense(350,activation="relu")) model.add(Dense(350,activation="relu")) model.add(Dense(1,activation = "linear")) model.compile(optimizer='adam', loss="mean_squared_error", metrics=["mean_absolute_error"]) model.fit(x_train,y_train, validation_data=(x_val,y_val), epochs=15, batch_size=64, callbacks=[history]) result = model.evaluate(x_test,y_test) for i in range(len(model.metrics_names)): print("Metric ",model.metrics_names[i],":",str(round(result[i],2))) ``` ## Plotting the Loss Metric Across Epochs ``` plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title("Model's Training & Validation loss across epochs") plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend(['Train', 'Validation'], loc='upper right') plt.show() ``` ### Testing the Model Manually ``` #Manually predicting from the model, instead of using model's # evaluate function y_test["Prediction"] = model.predict(x_test) y_test.columns = ["Actual Sales","Predicted Sales"] print(y_test.head(10)) from sklearn.metrics import mean_squared_error, mean_absolute_error print("MSE :",mean_squared_error(y_test["Actual Sales"].values,y_test["Predicted Sales"].values)) print("MAE :",mean_absolute_error(y_test["Actual Sales"].values,y_test["Predicted Sales"].values)) ``` # Hyperparameters in DL We will then look at various approaches for selecting the right set of hyperparameters for a ## Number of Neurons in a Layer Generally, a simple rule of thumb for selecting the number of neurons in the first layer is to refer to the number of input dimensions. If the final number of input dimensions in a given training dataset (this includes the one-hot encoded features also) is x, we should use at least the closest number to 2x in the power of 2. Let’s say you have 100 input dimensions in your training dataset: preferably start with 2 × 100 = 200, and take the closest power of 2, so 256. It is good to have the number of neurons in the power of 2, as it helps the computation of the network to be faster. Also, good choices for the number of neurons would be 8, 16, 32, 64, 128, 256, 512, 1024, and so on. Based on the number of input dimensions, take the number closest to 2 times the size. So, when you have 300 input dimensions, try using 512 neurons. ## Number of Layers It is true that just adding a few more layers will generally increase the performance, at least marginally. But the problem is that with an increased number of layers, the training time and computation increase significantly. Moreover, you would need a higher number of epochs to see promising results. Not using deeper networks is not an always an option; in cases when you have to, try using a few best practices. In case you are using a very large network, say more than 20 layers, try using a tapering size architecture (i.e., gradually reduce the number of neurons in each layer as the depth increases). So, if you are using an architecture of 30 layers with 512 neurons in each layer, try reducing the number of neurons in the layers slowly. An improved architecture would be with the first 8 layers having 512 neurons, the next 8 with 256, the next 8 with 128, and so on. For the last hidden layer (not the output layer), try keeping the number of neurons to at least around 30–40% of the input size. Alternatively, if you are using wider networks (i.e., not reducing the number of neurons in the lower layers), always use L2 regularization or dropout layers with a drop rate of around 30%. The chances of overfitting are highly reduced. ## Weight Initialization Initializing the weights for your network also has a tremendous impact on the overall performance. A good weight initialization technique not only speeds up the training process but also circumvents deadlocks in the model training process. By default, the Keras framework uses glorot uniform initialization, also called Xavier uniform initialization, but this can be changed as per your needs. We can initialize the weights for a layer using the kernel initializer parameter as well as bias using a bias initializer. Other popular options to select are ‘He Normal’ and ‘He Uniform’ initialization and ‘lecun normal’ and ‘lecun uniform’ initialization. There are quite a few other options available in Keras too, but the aforementioned choices are the most popular. ``` from keras import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(64,activation="relu", input_dim = 32, kernel_ initializer = "random_uniform",bias_initializer = "zeros")) model.add(Dense(1,activation="sigmoid")) ``` ## Batch Size Using a moderate batch size always helps achieve a smoother learning process for the model. A batch size of 32 or 64, irrespective of the dataset size and the number of samples, will deliver a smooth learning curve in most cases. Even in scenarios where your hardware environment has large RAM memory to accommodate a bigger batch size, I would still recommend staying with a batch size of 32 or 64. ## Dropout In addition to L1 and L2 regularization, there is another popular technique in DL to reduce overfitting. This technique is to use a dropout mechanism. In this method, the model arbitrarily drops or deactivates a few neurons for a layer during each iteration The following code snippet showcases dropout added to the dense hidden layer. The parameter value of 0.25 indicates the dropout rate (i.e., the percentage of the neurons to be dropped). ``` from keras import Sequential from keras.layers.core import Dropout, Dense model = Sequential() model.add(Dense(100, input_dim= 50, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(1,activation="linear")) ```
github_jupyter
### Setup ``` %reload_ext autoreload %autoreload 2 %matplotlib inline # 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) # 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 os import shutil # Any results you write to the current directory are saved as output. 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 * import pandas as pd import numpy as np from sklearn import metrics ``` ### Data Inspection ``` PATH = '../data/driver' driver_imgs_list_df = pd.read_csv(f'{PATH}/driver_imgs_list.csv') print(driver_imgs_list_df.head()) # plt.imread(f'{PATH}/train{}') img_sample_filename = driver_imgs_list_df.loc[driver_imgs_list_df.count()['img']-1, 'img'] img_sample_classname = driver_imgs_list_df.loc[driver_imgs_list_df.count()['classname']-1, 'classname'] img = plt.imread(f'{PATH}/train/{img_sample_classname}/{img_sample_filename}') plt.imshow(img) ``` ### Split validation set ``` driver_list = driver_imgs_list_df.subject.unique() print(driver_list) def get_val_filenames(val_ration = 0.15): train_size = 0 validation_size = 0 driver_index = 0 result = {} train_category_filenames = os.listdir(f'{PATH}/train') for category in train_category_filenames: if category != '.DS_Store': filenames = os.listdir(f'{PATH}/train/{category}') train_size += len(filenames) print(f'Training size: {train_size}') while (validation_size / train_size) < val_ration: driver = driver_list[driver_index] for category in train_category_filenames: result[category] = result[category] if category in result else [] if category != '.DS_Store': tmp_df = driver_imgs_list_df[(driver_imgs_list_df.subject == driver) & (driver_imgs_list_df.classname == category)] result[category] += tmp_df.img.tolist() validation_size += tmp_df.img.count() driver_index += 1 print(f'Actual Ratio: {validation_size/train_size}') return result if (not os.path.isdir(f'{PATH}/valid')): cat_filename_map = get_val_filenames() os.makedirs(f'{PATH}/valid') for cat in cat_filename_map: os.makedirs(f'{PATH}/valid/{cat}') for filename in cat_filename_map[cat]: shutil.move(f'{PATH}/train/{cat}/{filename}', f'{PATH}/valid/{cat}/{filename}') ``` ### Train ``` arch = resnet34 def get_data(img_size=226, batch_size=64): tfms = tfms_from_model(arch, img_size, aug_tfms=transforms_side_on, max_zoom=1.1) return ImageClassifierData.from_paths(f'{PATH}', batch_size, test_name='test', tfms=tfms) data = get_data(64) learn = ConvLearner.pretrained(arch, data) learn.lr_find() learn.sched.plot() learning_rate = 2e-2 learn.fit(learning_rate, 2, cycle_len=1) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_last_64') learn.load('driver_last_64') learn.unfreeze() learning_rates = np.array([learning_rate/9, learning_rate/3, learning_rate]) learn.fit(learning_rates, 3, cycle_len=1, cycle_mult=2) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_full_64') learn.load('driver_full_64') data = get_data(128) learn.set_data(data) learn.freeze() learn.fit(learning_rate, 2, cycle_len=1) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_last_128') learn.load('driver_last_128') learn.unfreeze() learn.fit(learning_rates, 3, cycle_len=1, cycle_mult=2) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_full_128') learn.load('driver_full_128') data = get_data(226) learn.set_data(data) learn.freeze() learn.fit(learning_rate, 2, cycle_len=1) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_last_226') learn.load('driver_last_226') learn.unfreeze() learn.fit(learning_rates, 3, cycle_len=1, cycle_mult=2) log_preds, y = learn.TTA() preds = np.mean(np.exp(log_preds), 0) print(metrics.log_loss(y, preds)) learn.save('driver_full_226') learn.load('driver_full_226') probs = np.argmax(preds, 1) cm = metrics.confusion_matrix(y, probs) plot_confusion_matrix(cm, data.classes) ``` ### Submit ``` log_preds, y = learn.TTA(is_test=True) preds = np.mean(np.exp(log_preds), 0) submit_df = pd.DataFrame(preds) submit_df.head() submit_df.columns = data.classes submit_df.insert(0, 'img', os.listdir(f'{PATH}/test')) submit_df.head() submit_df.to_csv(f'submit/driver.gz', index=False, compression="gzip") FileLink(f'submit/driver.gz') ```
github_jupyter
``` %matplotlib inline ``` # Classifier Chain Example of using classifier chain on a multilabel dataset. For this example we will use the `yeast <https://www.openml.org/d/40597>`_ dataset which contains 2417 datapoints each with 103 features and 14 possible labels. Each data point has at least one label. As a baseline we first train a logistic regression classifier for each of the 14 labels. To evaluate the performance of these classifiers we predict on a held-out test set and calculate the `jaccard score <jaccard_similarity_score>` for each sample. Next we create 10 classifier chains. Each classifier chain contains a logistic regression model for each of the 14 labels. The models in each chain are ordered randomly. In addition to the 103 features in the dataset, each model gets the predictions of the preceding models in the chain as features (note that by default at training time each model gets the true labels as features). These additional features allow each chain to exploit correlations among the classes. The Jaccard similarity score for each chain tends to be greater than that of the set independent logistic models. Because the models in each chain are arranged randomly there is significant variation in performance among the chains. Presumably there is an optimal ordering of the classes in a chain that will yield the best performance. However we do not know that ordering a priori. Instead we can construct an voting ensemble of classifier chains by averaging the binary predictions of the chains and apply a threshold of 0.5. The Jaccard similarity score of the ensemble is greater than that of the independent models and tends to exceed the score of each chain in the ensemble (although this is not guaranteed with randomly ordered chains). ``` # Author: Adam Kleczewski # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_openml from sklearn.multioutput import ClassifierChain from sklearn.model_selection import train_test_split from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import jaccard_score from sklearn.linear_model import LogisticRegression print(__doc__) # Load a multi-label dataset from https://www.openml.org/d/40597 X, Y = fetch_openml('yeast', version=4, return_X_y=True) Y = Y == 'TRUE' X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.2, random_state=0) # Fit an independent logistic regression model for each class using the # OneVsRestClassifier wrapper. base_lr = LogisticRegression() ovr = OneVsRestClassifier(base_lr) ovr.fit(X_train, Y_train) Y_pred_ovr = ovr.predict(X_test) ovr_jaccard_score = jaccard_score(Y_test, Y_pred_ovr, average='samples') # Fit an ensemble of logistic regression classifier chains and take the # take the average prediction of all the chains. chains = [ClassifierChain(base_lr, order='random', random_state=i) for i in range(10)] for chain in chains: chain.fit(X_train, Y_train) Y_pred_chains = np.array([chain.predict(X_test) for chain in chains]) chain_jaccard_scores = [jaccard_score(Y_test, Y_pred_chain >= .5, average='samples') for Y_pred_chain in Y_pred_chains] Y_pred_ensemble = Y_pred_chains.mean(axis=0) ensemble_jaccard_score = jaccard_score(Y_test, Y_pred_ensemble >= .5, average='samples') model_scores = [ovr_jaccard_score] + chain_jaccard_scores model_scores.append(ensemble_jaccard_score) model_names = ('Independent', 'Chain 1', 'Chain 2', 'Chain 3', 'Chain 4', 'Chain 5', 'Chain 6', 'Chain 7', 'Chain 8', 'Chain 9', 'Chain 10', 'Ensemble') x_pos = np.arange(len(model_names)) # Plot the Jaccard similarity scores for the independent model, each of the # chains, and the ensemble (note that the vertical axis on this plot does # not begin at 0). fig, ax = plt.subplots(figsize=(7, 4)) ax.grid(True) ax.set_title('Classifier Chain Ensemble Performance Comparison') ax.set_xticks(x_pos) ax.set_xticklabels(model_names, rotation='vertical') ax.set_ylabel('Jaccard Similarity Score') ax.set_ylim([min(model_scores) * .9, max(model_scores) * 1.1]) colors = ['r'] + ['b'] * len(chain_jaccard_scores) + ['g'] ax.bar(x_pos, model_scores, alpha=0.5, color=colors) plt.tight_layout() plt.show() ```
github_jupyter
``` import torch import torchvision from PIL import Image import torchvision.transforms as transforms %matplotlib inline import matplotlib.pyplot as plt import torchvision.transforms.functional as F import numpy as np import cv2 from cv2 import resize,merge,split colors = torch.tensor([[0,0,128],[0,0,64],[0,0,32],[0,128,0],[0,64,0],[0,32,0],[0,16,0],[0,8,0],[0,4,0],[0,2,0], [0,1,0],[128,0,0],[64,0,0],[32,0,0],[16,0,0],[8,0,0],[4,0,0],[1,0,0]]) colormap = torch.tensor([ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], [235, 12, 255] ]) img = Image.open('./gtFine/test/VWI10001 2020-02-02-08-04-50_labelIds.png') img = cv2.imread('./gtFine/test/VWI10001 2020-02-02-08-04-50_labelIds.png') real = Image.open('./leftImg8bit/test/VWI10001 2020-02-02-08-04-50.png') # img_transform = transforms.Compose([ # transforms.ToTensor(), # ]) # img = img_transform(img) class ConvertMaskColors: """Convert Mask colors to reflect the pretrained data colors""" def __init__(self,): pass def __call__(self,img): pass class TopLeftCornerErase: def __init__(self, n_pixels: int): self.n_pixels = n_pixels def __call__(self, img: torch.Tensor) -> torch.Tensor: all_pixels = img.reshape(4, -1).transpose(1, 0) idx = torch.randint(len(all_pixels), (1,))[0] random_pixel = all_pixels[idx][:, None, None] return F.erase(img, 0, 0, self.n_pixels, self.n_pixels, random_pixel) erase = transforms.Compose([ TopLeftCornerErase(100) # reverse_preprocess, ]) trans = transforms.Compose([ transforms.ToPILImage(), ]) cls = img.unique() # res = torch.stack([torch.where(img==cls_val, torch.tensor(1), torch.tensor(0)) for cls_val in cls]) res = [torch.where(img==cls_val, torch.tensor(1), torch.tensor(0)) for cls_val in cls] res = torch.stack(res) img = cv2.imread('./gtFine/test/VWI10001 2020-02-02-08-04-50_labelIds.png') b,g,r = cv2.split(img) shape = b.shape b = b.reshape(-1) g = g.reshape(-1) r = r.reshape(-1) color_b = {} color_g = {} color_r = {} colors = colors.numpy() colormap = colormap.numpy() for i,color in enumerate(colors): # print(colors[i]) color_b[colors[i][0]] = colormap[i][0].item() color_g[colors[i][1]] = colormap[i][1].item() color_r[colors[i][2]] = colormap[i][2].item() ``` colormap ``` for i in color_b: b = np.where(b == i, color_b[i], b) for i in color_g: g = np.where(g == i, color_g[i], g) for i in color_r: r = np.where(r == i, color_r[i], r) b = b.reshape(shape) g = g.reshape(shape) r = r.reshape(shape) new_img = cv2.merge((b,g,r)) trans(img) trans(new_img) class ConvertMaskColors: """Convert Mask colors to reflect the pretrained data colors""" def __init__(self,): self.colors = torch.tensor([[0,0,128],[0,0,64],[0,0,32],[0,128,0],[0,64,0],[0,32,0],[0,16,0],[0,8,0],[0,4,0],[0,2,0], [0,1,0],[128,0,0],[64,0,0],[32,0,0],[16,0,0],[8,0,0],[4,0,0],[1,0,0]]) self.colormap = torch.tensor([ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], [235, 12, 255] ]) def __call__(self,image): ''' - split the image into BGR channels - map each channel color to the colormap - merge the BGR channels together ''' b,g,r = split(image) shape = b.shape b = b.reshape(-1) g = g.reshape(-1) r = r.reshape(-1) color_b = {} color_g = {} color_r = {} colors = self.colors.numpy() colormap = self.colormap.numpy() for i,color in enumerate(colors): color_b[colors[i][0]] = colormap[i][0].item() color_g[colors[i][1]] = colormap[i][1].item() color_r[colors[i][2]] = colormap[i][2].item() for i in color_b: b = np.where(b == i, color_b[i], b) for i in color_g: g = np.where(g == i, color_g[i], g) for i in color_r: r = np.where(r == i, color_r[i], r) b = b.reshape(shape) g = g.reshape(shape) r = r.reshape(shape) masked_img = merge((b,g,r)) return masked_img maskColors = transforms.Compose([ ConvertMaskColors() ]) type(maskColors(img)) type(img) ```
github_jupyter
<table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Marc Spiegelman</td> </table> ``` %matplotlib inline import numpy import matplotlib.pyplot as plt ``` # Plotting Bifurcations **GOAL:** Find where $f(x,r) = 0$ and label the stable and unstable branches. A bifurcation diagram provides information on how the fixed points of a dynamical system $f(x,r)=0$ vary as a function of the control parameter $r$ Here we write a snazzy little python function to extract the zero contour and label it with respect to whether it is a stable branch with ($\partial f/\partial x < 0$) or an unstable branch ($\partial f/\partial x > 0 $) ``` def bifurcation_plot(f,f_x,r,x,rlabel='r'): """ produce a bifurcation diagram for a function f(r,x) given f and its partial derivative f_x(r,x) over a domain given by numpy arrays r and x f(r,x) : RHS function of autonomous ode dx/dt = f(r,x) f_x(r,x): partial derivative of f with respect to x r : numpy array giving r coordinates of domain x : numpy array giving x coordinates of domain rlabel : string for x axis parameter label """ # set up a mesh grid and extract the 0 level set of f R,X = numpy.meshgrid(r,x) plt.figure() CS = plt.contour(R,X,f(R,X),[0],colors='k') plt.clf() c0 = CS.collections[0] # for each path in the contour extract vertices and mask by the sign of df/dx for path in c0.get_paths(): vertices = path.vertices vr = vertices[:,0] vx = vertices[:,1] mask = numpy.sign(f_x(vr,vx)) stable = mask < 0. unstable = mask > 0. # plot the stable and unstable branches for each path plt.plot(vr[stable],vx[stable],'b') plt.hold(True) plt.plot(vr[unstable],vx[unstable],'b--') plt.xlabel('parameter {0}'.format(rlabel)) plt.ylabel('x') plt.legend(('stable','unstable'),loc='best') plt.xlim(r[0],r[-1]) plt.ylim(x[0],x[-1]) ``` ### Example #1: Saddle node bifurcation consider the problem $$ f(r,x) = r + x^2$$ and we will define $f$ and $\partial f/\partial x$ using inlined python lambda functions ``` f = lambda r,x: r + x*x f_x = lambda r,x: 2.*x x = numpy.linspace(-4,4,100) r = numpy.linspace(-4,4,100) bifurcation_plot(f,f_x,r,x) ``` ### Example #2: Logistic equation with constant harvesting $$ dx/dt = x(1-x) - h $$ ``` f = lambda h,x: x*(1-x) - h f_x = lambda h,x: 1. - 2.*x x = numpy.linspace(0,1.,100) h = numpy.linspace(0,.5,100) bifurcation_plot(f,f_x,h,x,rlabel='h') ``` ### Example #3: transcritical bifurcation $$f(r,x) = rx - x^2$$ ``` f = lambda r,x: r*x - x*x f_x = lambda r,x: r - 2.*x x = numpy.linspace(-1.,1.,100) r = numpy.linspace(-1.,1.,100) bifurcation_plot(f,f_x,r,x) ``` ### Example #4 super-critical pitchfork bifurcation $$f(r,x) = rx - x^3$$ ``` f = lambda r,x: r*x - x**3 f_x = lambda r,x: r - 3.*x**2 x = numpy.linspace(-1.,1.,100) r = numpy.linspace(-1.,1.,100) bifurcation_plot(f,f_x,r,x) ``` ##### Example #4 sub-critical pitchfork bifurcation $$f(r,x) = rx + x^3$$ ``` f = lambda r,x: r*x + x**3 f_x = lambda r,x: r + 3.*x**2 x = numpy.linspace(-1.,1.,100) r = numpy.linspace(-1.,1.,100) bifurcation_plot(f,f_x,r,x) ``` ### Example #6 subcritical pitchfork bifurcation with stabilization $$f(r,x) = rx + x^3 - x^5 $$ ``` f = lambda r,x: r*x + x**3 - x**5 f_x = lambda r,x: r + 3.*x**2 -5.*x**4 x = numpy.linspace(-2.,2.,100) r = numpy.linspace(-.5,.5,100) bifurcation_plot(f,f_x,r,x) ``` FIXME: this plot needs to mask out the spurious stable branch which is a plotting error And now you can play with your own function ``` f = lambda r,x: # < your function here > f_x = lambda r,x: # < your derivative here > # Adjust your domain and resolution x = numpy.linspace(-10.,10.,100) r = numpy.linspace(-10.,10.,100) #plot and pray (and watch out for glitches) bifurcation_plot(f,f_x,r,x) ```
github_jupyter
# Prediction de l'accélération et du freinage avec nuScenes ``` %matplotlib inline from nuscenes.nuscenes import NuScenes from nuscenes.can_bus.can_bus_api import NuScenesCanBus import pandas as pd import numpy as np import matplotlib.pyplot as plt # data/sets/nuscenes # D:\Utilisateurs\Alexandre\Repertoire_D\nuscenes\v1 0-trainval01 #nusc = NuScenes(version='v1.0-mini', dataroot='../data/sets/nuscenes') nusc = NuScenes(version='v1.0-trainval', dataroot='D:/Utilisateurs/Alexandre/Repertoire_D/nuscenes/v1.0-trainval01') nusc_can = NuScenesCanBus(dataroot='../data/sets/nuscenes') ``` ## Anticiper la vitesse avec un véhicule en face Principe de base (idée): - le système de pilotage envoie les postions gps à suivre, la vitesse et l'angle recommandés à l'algorithme de gestion - l'algorithme de gestion en fonction de la situation va envoyer sur un modèle pour donner une nouvelle valeur de la vitesse et de l'angle par rapport à l'environnement - plusieurs modèles, mais en premier un basique : s'il y a personne en face on change rien, sinon calcul de la nouvelle vitesse par rapport au véhicule devant. Pour cela, il nous faut plusieurs données pour ce modèle: - position, vitesse, orientation du véhicule égo (nous) et du véhicule en face - à compléter? ### 1/ Recherche de ces données Prenons une scene où on suit une voiture, la scène 61. Cherchons l'instance de la voiture.... ``` scene_test = nusc.scene[58] # 58 avec le dataset normal #0 avec le minidataset scene_test sample = nusc.get('sample',scene_test['last_sample_token']) ann = sample['anns'][1] ann_meta = nusc.get('sample_annotation', ann) #nusc.list_sample(sample['token']) sample liste_vehicle = [] for at in sample['anns']: meta_data = nusc.get('sample_annotation',at) if meta_data['category_name'] == 'vehicle.car': liste_vehicle += [meta_data] nusc.render_annotation("bc3180b07f8e4a728f504ded654df56f") ``` Token de l'instance de la voiture que l'on suit: c1958768d48640948f6053d04cffd35b Maintenant, comparons la position de cette voiture à la notre. `field2token` permet d'accéder à la liste de tout les enregistrements d'une scene. ``` meta_data ann_tokens = set(nusc.field2token('sample_annotation','instance_token',"c1958768d48640948f6053d04cffd35b")) def print_pos_rot(pos,rot): print("{:04.2f} {:04.2f} {:04.2f}".format(pos[0],pos[1],pos[2])) print("{:04.2f} {:04.2f} {:04.2f}".format(rot[0],rot[1],rot[2])) ego_pos = [] voiture_pos = [] ego_rot = [] voiture_rot = [] for at in ann_tokens: meta_data = nusc.get('sample_annotation',at) sample = nusc.get('sample',meta_data['sample_token']) timestamp = sample['timestamp'] lidar = nusc.get('sample_data',sample['data']['LIDAR_TOP']) ego_token = lidar['ego_pose_token'] ego = nusc.get('ego_pose',ego_token) #print_pos_rot(ego['translation'],ego['rotation']) #nt_pos_rot(meta_data['translation'],meta_data['rotation']) #print(meta_data['rotation']) ego_pos += [ego['translation']] ego_rot += [ego['rotation']] voiture_pos += [meta_data['translation']] voiture_rot += [meta_data['rotation']] #print(nusc.ego_pose[:300]) print(nusc.ego_pose[0]) len(nusc.ego_pose) ``` Maintenant qu'on a les données de position de notre véhicule et celui d'en face, on peut essayer de visualiser sur la map ce qu'il en est pour pouvoir déterminer une formule/ fonction pour savoir si une voiture est en face de nous (sur la même voie serait l'idéal. Problème, la rotation est en écriture quaternion (je ne sais pas comment manipuler), donc en attendant je vais essayer de détecter le véhicule en face par rapport à s'il est détecté par la caméra frontale puis en calculant la distance. ``` df_ego_pos = pd.DataFrame(ego_pos,columns=["x","y","z"]) #print(ego_rot) #df_ego_rot = pd.DataFrame(ego_rot,columns=["x","y","z"]) df_voiture_pos = pd.DataFrame(voiture_pos,columns=["x","y","z"]) #df_voiture_rot = pd.DataFrame(voiture_rot,columns=["x","y","z"]) plt.plot(df_ego_pos["x"],df_ego_pos["y"],'bo') plt.plot(df_voiture_pos["x"],df_voiture_pos["y"],'ro') ``` ### 2/ Pretraitement sur les données En regardant le code du sdk j'ai trouvé un bout de code utile qui me permet de savoir quel caméra a détecté l'annotation. Pour faire simple, je vais considérer (actuellement, cela va peut-être changer), qu'une voiture est en face de la notre si elle est détectée seulement par la caméra frontale et qu'elle respecte une certaine distance. Je vais maintenant regrouper toute ces données où on a une voiture en face nous. `get_sample_data` renvoie plusieurs informations dont une liste de boxe de la caméra, si on lui passe un token en paramètre, il renvoie une seul boxe si l'instance est capturé par la caméra, rien sinon. On peut maintenant créer le dataframe contenant toutes les informations: vitesse,distance,timestamp,accélération, token.... Voir `vehicle_data.csv` ``` from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility # renvoie vrai et un un tableau rempli si l'instance est en face d'ego et ego ne tourne pas trop def find_vehicle_in_front(instance_token): instance = nusc.get('instance',instance_token) last_token = instance["last_annotation_token"] curr_token = instance["first_annotation_token"] rows_list = [] i = 0 ann = nusc.get('sample_annotation',instance["first_annotation_token"]) sample = nusc.get('sample',ann['sample_token']) scene = nusc.get('scene',sample['scene_token']) dict_scene = nusc_can.get_messages(scene['name'],'vehicle_monitor') taille = len(dict_scene) # Traitement sur tout les vehicules ou non (a faire) all_camera = False if all_camera: list_cams = [key for key in sample_record['data'].keys() if 'CAM' in key] else: list_cams = ['CAM_FRONT'] # Pour chaque enregistrement de l'annoation on ajoute une ligne avec les elements while curr_token != last_token: curr_ann = nusc.get('sample_annotation',curr_token) curr_sample = nusc.get('sample',curr_ann['sample_token']) cams_check = [] # (abs(dict_scene[i]['utime'] - curr_sample['timestamp']) > 250000 ) and while i < taille - 2 and (dict_scene[i]['utime'] + 250000 < curr_sample['timestamp']): #print("avance: ",i,curr_sample['timestamp']-1532402900000000," ",dict_scene[i]['utime']-1532402900000000) i += 1 #print(curr_sample['timestamp'] - 1532402900000000,dict_scene[i]['utime'] - 1532402900000000 ) # récupérer les caméras qui ont vu l'annotation _, boxes, _ = nusc.get_sample_data(curr_sample['data']['CAM_FRONT'], box_vis_level=BoxVisibility.ANY, selected_anntokens=[curr_token]) #and abs(dict_scene[i]['steering']) < 100 if len(boxes) > 0: #calcul distance entre ego et le vehicule lidar = nusc.get('sample_data',curr_sample['data']['LIDAR_TOP']) ego = nusc.get('ego_pose',lidar['ego_pose_token']) dist = np.linalg.norm(np.array(ego['translation']) - np.array(curr_ann['translation'])) ego_pos = [round(e,3) for e in ego['translation']] object_pos = [round(e,3) for e in curr_ann['translation']] dic = {'scene':scene['name'],'timestamp':curr_sample['timestamp'],'utime':dict_scene[i]['utime'],'inst_token':instance_token, 'ann_token':curr_token,'ego_pos':ego_pos,'object_pos':object_pos, 'distance':round(dist,3),'steering':round(dict_scene[i]['steering'],3),'ego_speed':round(dict_scene[i]['vehicle_speed'],3),'throttle':dict_scene[i]['throttle'], 'brake':dict_scene[i]['brake'],'future_throttle':dict_scene[i+1]['throttle'],'future_brake':dict_scene[i+1]['brake']} rows_list += [dic] curr_token = curr_ann['next'] if i < taille - 2: i += 1 #print(len(rows_list),len(dict_scene)) return len(rows_list)!=0,rows_list # renvoie un tableau rempli pour toute la scene avec les données du véhicule def vehicle_info(scene): #sample = nusc.get('sample',scene['first_sample_token']) curr_token = scene['first_sample_token'] rows_list = [] last_token = scene['last_sample_token'] i = 0 dict_scene = nusc_can.get_messages(scene['name'],'vehicle_monitor') taille = len(dict_scene) # Pour chaque enregistrement de la scene on ajoute une ligne avec les elements while curr_token != last_token: curr_sample = nusc.get('sample',curr_token) while i < taille -2 and (dict_scene[i]['utime'] + 250000 < curr_sample['timestamp']): i += 1 #print(curr_sample['timestamp'] - 1532402900000000,dict_scene[i]['utime'] - 1532402900000000 ) lidar = nusc.get('sample_data',curr_sample['data']['LIDAR_TOP']) ego = nusc.get('ego_pose',lidar['ego_pose_token']) ego_pos = [round(e,3) for e in ego['translation']] dic = {'scene':scene['name'],'timestamp':curr_sample['timestamp'],'utime':dict_scene[i]['utime'],'inst_token':"vehicle_info", 'ann_token':curr_token,'ego_pos':ego_pos,'object_pos':ego_pos, 'distance':99,'steering':round(dict_scene[i]['steering'],3),'ego_speed':round(dict_scene[i]['vehicle_speed'],3),'throttle':dict_scene[i]['throttle'], 'brake':dict_scene[i]['brake'],'future_throttle':dict_scene[i+1]['throttle'],'future_brake':dict_scene[i+1]['brake']} rows_list += [dic] curr_token = curr_sample['next'] if i < taille - 2: i += 1 #print(len(rows_list),len(dict_scene)) return rows_list _ ,dic = find_vehicle_in_front("c1958768d48640948f6053d04cffd35b") #print(dic) df = pd.DataFrame.from_dict(dic).sort_values(by='timestamp').reset_index(drop=True) with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also display(df) #nusc_can.list_misaligned_routes() blackint = nusc_can.can_blacklist blacklist = [ "scene-0"+ str(i) for i in blackint] blacklist blackint = nusc_can.can_blacklist blacklist = [ "scene-0"+ str(i) for i in blackint] # 1532402936198962 1532402936699359 1532402937198682 # Liste toutes les instances d'une scene def get_instances_scene(scene): sample = nusc.get('sample',scene['first_sample_token']) list_instances = [] while sample['token'] != scene['last_sample_token']: anns = sample['anns'] for ann_token in anns: ann = nusc.get('sample_annotation',ann_token) instance = nusc.get('instance',ann['instance_token']) category = nusc.get('category',instance['category_token']) if not instance in list_instances and "vehicle" in category['name']: list_instances += [instance] sample = nusc.get('sample',sample['next']) return list_instances # Renvoie un dataframe contenant les données de toutes les instances de la scene def build_dataframe_for_one_scene(s,affichage): list_rows = vehicle_info(s) list_instances = get_instances_scene(s) for inst in list_instances: ok, res = find_vehicle_in_front(inst['token']) if affichage: print(len(res)," echantillons") if ok: list_rows += res return pd.DataFrame.from_dict(list_rows).sort_values(by='timestamp').reset_index(drop=True) # Explore chaque scene, puis chaque instance de cette scene qui est un vehicle en mouvement (devant) # Cree un dataframe avec pour entree distance au vehicle, ego_vitesse, ego_accel, ego_brake # et vehicle_vitesse (pas mtn) def build_dataframe_for_vehicle_in_front(): scenes = nusc.scene list_rows = [] first = True i = 0 for s in scenes[:20]: if s['name'] not in blacklist and s['name'] not in ["scene-0003","scene-0419"]: #print(s['name']) if i % 100 == 0: print("#",end='') if first: dataframe = build_dataframe_for_one_scene(s,False) first = False else: datatemp = build_dataframe_for_one_scene(s,False) dataframe = dataframe.append(datatemp,ignore_index=True) i += 1 print(dataframe) print(dataframe.describe()) return dataframe #find_vehicle_in_front("c1958768d48640948f6053d04cffd35b") # 15k ligne sans contrainte sur steering (100 scenes) df_vehicle = build_dataframe_for_vehicle_in_front() df_vehicle = df_vehicle.sort_values(by=['timestamp']) #df_vehicle.to_csv(path_or_buf="./data/vehicle_data_30juin_full.csv",index=False) df_brake = df_vehicle[['scene','brake']] #df_brake.to_csv('./data/vehicle_brake_25j.csv') scene_name = 'scene-0061' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') df = build_dataframe_for_one_scene(scene,False) #with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also display(df) ``` On faisant une matrice de corrélation, on aperçoit que la distance entre les deux véhicules et un influencer par la vitesse principalement, le frein agit un peu dessus. De plus, la vitesse est trés corrélée avec le frein. L'accélération a un peu d'effet sur la vitesse, voir aucun sur la distance, cela est un peu étonnant. ``` print(df_vehicle.shape) df_vehicle.corr() ``` Scène intéressante pour prédire le frein: 14 Scène avec piéton: 25,29,43 Il pourrait être intéressant de pouvoir afficher la scène avec les résultats de la prédiction ``` scene_name = 'scene-0067' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') def sort_distance(dataframe): pass import cv2 from typing import Tuple, List import os.path as osp from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix import operator # parametres pour cv2 font = cv2.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = (0,500) fontScale = 1 fontColor = (255,255,255) color = (255,0,0) lineType = 2 pas = (0,50) def get_color(category_name: str) -> Tuple[int, int, int]: """ Provides the default colors based on the category names. This method works for the general nuScenes categories, as well as the nuScenes detection categories. """ if 'bicycle' in category_name or 'motorcycle' in category_name: return 255, 61, 99 # Red elif 'vehicle' in category_name or category_name in ['bus', 'car', 'construction_vehicle', 'trailer', 'truck']: return 255, 158, 0 # Orange elif 'pedestrian' in category_name: return 0, 0, 230 # Blue elif 'cone' in category_name or 'barrier' in category_name: return 0, 0, 0 # Black else: return 255, 0, 255 # Magenta def affichage(im,df_curr): cv2.putText(im, 'Vitesse:'+ str(df_curr.iat[0,9]), bottomLeftCornerOfText, font, fontScale, fontColor, lineType) cv2.putText(im, 'Angle volant:'+ str(df_curr.iat[0,8]), tuple(map(operator.add, bottomLeftCornerOfText,(0,50))), font, fontScale, fontColor, lineType) cv2.putText(im, 'Acceleration:'+ str(df_curr.iat[0,10]), tuple(map(operator.add, bottomLeftCornerOfText,(0,100))), font, fontScale, fontColor, lineType) cv2.putText(im, 'Frein:'+ str(df_curr.iat[0,11]), tuple(map(operator.add, bottomLeftCornerOfText,(0,150))), font, fontScale, fontColor, lineType) cv2.putText(im, 'Acceleration (Pred):'+ str(df_curr.iat[0,12]), tuple(map(operator.add, bottomLeftCornerOfText,(0,200))), font, fontScale, fontColor, lineType) cv2.putText(im, 'Frein (Pred):'+ str(df_curr.iat[0,11]), tuple(map(operator.add, bottomLeftCornerOfText,(0,250))), font, fontScale, fontColor, lineType) if df_curr.shape[0] > 1: cv2.putText(im, 'Distance:'+ str(df_curr.iloc[1]['distance']), tuple(map(operator.add, bottomLeftCornerOfText,(0,300))), font, fontScale, color, lineType) def draw_rect(im,selected_corners, color): prev = selected_corners[-1] for corner in selected_corners: cv2.line(im, (int(prev[0]), int(prev[1])), (int(corner[0]), int(corner[1])), color, 2) prev = corner def render_scene_channel_with_predict(nusc, scene_token: str, dataframe, channel: str = 'CAM_FRONT', freq: float = 10, imsize: Tuple[float, float] = (960, 540), out_path: str = None) -> None: """ Renders a full scene for a particular camera channel. :param scene_token: Unique identifier of scene to render. :param channel: Channel to render. :param freq: Display frequency (Hz). :param imsize: Size of image to render. The larger the slower this will run. :param out_path: Optional path to write a video file of the rendered frames. Reprise de la fonction render_scene_channel du sdk nuscenes mais avec beaucoup de changements Renvoie un dataframe avec un objet par timestamp """ valid_channels = ['CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BACK_LEFT', 'CAM_BACK', 'CAM_BACK_RIGHT'] assert imsize[0] / imsize[1] == 16 / 9, "Aspect ratio should be 16/9." assert channel in valid_channels, 'Input channel {} not valid.'.format(channel) if out_path is not None: assert osp.splitext(out_path)[-1] == '.avi' # Get records from DB scene_rec = nusc.get('scene', scene_token) sample_rec = nusc.get('sample', scene_rec['first_sample_token']) sd_rec = nusc.get('sample_data', sample_rec['data'][channel]) # Open CV init name = '{}: {} (Space to pause, ESC to exit)'.format(scene_rec['name'], channel) cv2.namedWindow(name) cv2.moveWindow(name, 0, 0) if out_path is not None: fourcc = cv2.VideoWriter_fourcc(*'MJPG') out = cv2.VideoWriter(out_path, fourcc, freq, imsize) else: out = None # parametres pour cv2 font = cv2.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = (10,500) fontScale = 1 fontColor = (255,255,255) color = (255,0,0) lineType = 2 pas = (0,50) # parametres pour afficher infos i = 0 taille = dataframe.shape[0] scene_token = nusc.field2token('scene', 'name', dataframe.at[0,'scene'])[0] scene = nusc.get('scene',scene_token) sample = nusc.get('sample',scene['first_sample_token']) df_curr = dataframe[dataframe['timestamp'] == sample['timestamp']] df_curr = df_curr.sort_values(by='distance').reset_index(drop=True) #print(df_curr) has_more_frames = True angle = df_curr.iat[0,8] xmin = 10 xmax = - 10 colors: Tuple = ((0, 0, 255), (255, 0, 0), (155, 155, 155)) borne_a = 600 borne_b = 1000 new_df = pd.DataFrame(columns=df_curr.columns) while has_more_frames: ann = df_curr[df_curr["inst_token"]=="98300b9c4acb4da9a7aecd0084650265"] ann_tok = ann['ann_token'] #print(df_curr['inst_token']) # selected_anntokens=[ann_tok.iat[0]] # Get data from DB impath, boxes, camera_intrinsic = nusc.get_sample_data(sd_rec['token'], box_vis_level=BoxVisibility.ANY) # Load and render if not osp.exists(impath): raise Exception('Error: Missing image %s' % impath) im = cv2.imread(impath) dmin = 999 minbox = None df_wv = df_curr[df_curr["inst_token"]!="vehicle_info"] liste = [] annmin = "none" for j in range(df_wv.shape[0]): ann = df_wv.iloc[j]['ann_token'] impath, boxes, camera_intrinsic = nusc.get_sample_data(sd_rec['token'], box_vis_level=BoxVisibility.ANY, selected_anntokens=[ann]) if len(boxes) != 0: liste += [(ann,boxes[0])] # Pour chaque couple annotation/box on cherche le plus prés d'ego en face for (a,box) in liste: corners = view_points(box.corners(), camera_intrinsic, normalize=True)[:2, :] if (box.center[2] < dmin and corners.T[4][0] < borne_b-angle and corners.T[6][0] > borne_a-angle and "vehicle" in box.name): dmin = box.center[2] annmin = a minbox = box if dmin != 999: c = get_color(minbox.name) corners = view_points(minbox.corners(), camera_intrinsic, normalize=True)[:2, :] draw_rect(im,corners.T[4:], colors[1][::-1]) if i%6 == 0 and i != 0: if dmin != 999: new_df = new_df.append(df_curr[df_curr['ann_token']==annmin]) else: new_df = new_df.append(df_curr[df_curr['inst_token']=="vehicle_info"]) # Affichage informations if sample['token'] != scene['last_sample_token']: if not df_curr.empty: if dmin != 999: cv2.line(im, (int((corners.T[4][0]+corners.T[6][0])/2), 400), (int((corners.T[4][0]+corners.T[6][0])/2), 600), (255, 255, 0), thickness=2) cv2.putText(im, 'Center:'+ str(round(minbox.center[0],3))+"\n "+str(round(minbox.center[2],2)), (int(800+minbox.center[0]*10),250), font, fontScale, (255, 0, 255), lineType) cv2.line(im, (int(borne_b-angle), 400), (int(borne_b-angle), 600), (255, 0, 0), thickness=2) cv2.line(im, (int(borne_a-angle), 400), (int(borne_a-angle), 600), (255, 0, 0), thickness=2) affichage(im,df_curr) else: print(sample['timestamp']) if i%6 == 0 and i != 0: sample = nusc.get('sample',sample['next']) df_curr = dataframe[dataframe['timestamp'] == sample['timestamp']] df_curr = df_curr.sort_values(by='distance').reset_index(drop=True) if not df_curr.empty: angle = df_curr.iat[0,8] #angle = 0 else: print("fin des données ",i) # Render im = cv2.resize(im, imsize) cv2.imshow(name, im) if out_path is not None: out.write(im) key = cv2.waitKey(1) # Images stored at approx 10 Hz, so wait 10 ms. if key == 32: # If space is pressed, pause. key = cv2.waitKey() if key == 27: # if ESC is pressed, exit cv2.destroyAllWindows() break if not sd_rec['next'] == "": sd_rec = nusc.get('sample_data', sd_rec['next']) else: has_more_frames = False i += 1 print("nombre de frame: ",i) new_df = new_df.reset_index(drop=True) #print(new_df) cv2.destroyAllWindows() if out_path is not None: out.release() return new_df scene_name = 'scene-0120' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) df = build_dataframe_for_one_scene(scene,False) render_scene_channel_with_predict(nusc,my_scene_token,df,'CAM_FRONT') print() scene_name = 'scene-0160' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') #df = build_dataframe_for_one_scene(scene,False) #print(df) #df.to_csv(scene_name+".csv") liste_scene = ['scene-0061','scene-0010','scene-0041','scene-0009','scene-0100', 'scene-0101','scene-0190','scene-0194'] #liste_scene = ['scene-0108'] # render_scene_channel_with_predict(nusc,my_scene_token,df, 'CAM_FRONT') df_for_predict = pd.DataFrame(columns=df.columns) for s in liste_scene: s_token = nusc.field2token('scene', 'name', s)[0] scene = nusc.get('scene',s_token) df = build_dataframe_for_one_scene(scene,False) temp = render_scene_channel_with_predict(nusc,s_token,df, 'CAM_FRONT',imsize=(256,144)) df_for_predict = df_for_predict.append(temp) df_for_predict.to_csv("./data/df_predict_throttle_brake.csv") ``` ### 3/ Apprentissage ``` from sklearn.model_selection import train_test_split from sklearn import svm, neighbors from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn import linear_model import random df_for_predict = df_for_predict.reset_index(drop=True) # ["distance","ego_speed","throttle","brake"] features = ["distance","ego_speed","throttle","brake"] features = ["distance","ego_speed"] X = df_vehicle[features] y_throttle = df_vehicle["future_throttle"] y_brake = df_vehicle["future_brake"] Xt_train, Xt_test, yt_train, yt_test = train_test_split(X,y_throttle, test_size = 0.2, random_state = 1) Xb_train, Xb_test, yb_train, yb_test = train_test_split(X,y_brake, test_size = 0.2, random_state = 1) #with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also # display(Xt_train) # temp features = ["distance","ego_speed"] #features = [col for col in train_data.columns.to_list() if ('distance' in col or'ego_speed' in col)] print(features) y_throttle = df_for_predict["throttle"] y_brake = df_for_predict["brake"] X = df_for_predict[features] Xt_train, Xt_test, yt_train, yt_test = train_test_split(X,y_throttle, test_size = 0.2, random_state = 1) Xb_train, Xb_test, yb_train, yb_test = train_test_split(X,y_brake, test_size = 0.2, random_state = 1) model_t = svm.SVR() model_t.fit(Xt_train,yt_train) print(model_t.score(Xt_test,yt_test)) model_b = svm.SVR() model_b.fit(Xb_train,yb_train) print(model_b.score(Xb_test,yb_test)) model_b = RandomForestRegressor(n_estimators=100,random_state=0) model_b.fit(Xb_train,yb_train) print(model_b.score(Xb_test,yb_test)) df_full = pd.read_csv("./data/vehicle_data_30juin_full.csv") %matplotlib inline plt.plot(df_for_predict['distance'],df_for_predict['brake'],'bo') #plt.plot(df_full['distance'],df_full['brake'],'bo') plt.xlim(0, 50) plt.show() from mpl_toolkits.mplot3d import Axes3D %matplotlib qt def randrange(n, vmin, vmax): ''' Helper function to make an array of random numbers having shape (n, ) with each number distributed Uniform(vmin, vmax). ''' return (vmax - vmin)*np.random.rand(n) + vmin fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 ax.scatter(df_vehicle['ego_speed'],df_vehicle['brake'],df_vehicle['distance'],marker='o') ax.set_xlabel('V') ax.set_ylabel('Brake') ax.set_zlabel('Distance') plt.show() ``` 67,185,130,155 piéton traverse, 6 camion au milieu (pas mal), 41 on s'arrete devant une voiture a un feu (genial), 190 9,10 il se passe rien 14 arret puis démarrage car bus avance 45 à exclure Prédire trajectoire en entier... ``` df_ego = df[df['inst_token'] == "vehicle_info"] #df_ego list_vec = [(df_ego.iloc[i+1]['ego_pos'][0] - df_ego.iloc[i]['ego_pos'][0], df_ego.iloc[i+1]['ego_pos'][1] - df_ego.iloc[i]['ego_pos'][1]) for i in range(df_ego.shape[0]-1) ] list_vitesse = [df_ego.iloc[i]['ego_speed'] for i in range(df_ego.shape[0]-1)] list_vec_norm = [ (v[0]/np.sqrt((v[0]*v[0] + v[1]*v[1])),v[1]/np.sqrt((v[0]*v[0] + v[1]*v[1]))) for v in list_vec ] #print(list_vec) list_vec_norm for i in range(df_ego.shape[0]-1): # tuple(map(operator.add, df_ego.iloc[i]['ego_pos'], r = [e * list_vitesse[i]/3.6*0.5 for e in list_vec_norm[i]] #print(list_vec_norm[i]) new_pos = list(map(operator.add, df_ego.iloc[i]['ego_pos'],r)) new_pos = [round(e,3) for e in new_pos] #print(new_pos,df_ego.iloc[i+1]['ego_pos']) # Premiere version , ne marche pas def compute_distance(pos,ABn,dataframe): #dist = np.linalg.norm(np.array(ego['translation']) - np.array(curr_ann['translation'])) dataframe = dataframe.drop(columns=['distance']) taille = dataframe.shape[0] dmin = 99 mini = 0 if ABn[0] == 0: a = 0 else: a = ABn[1]/ABn[0] c = - pos[0] * a + pos[1] for i in range(taille): row = dataframe.iloc[i] if row["inst_token"] != "vehicle_info": distance_ego = round(np.linalg.norm(np.array(pos) - np.array(row['object_pos'][:2])),3) distance_vecteur_vitesse = np.absolute(row['object_pos'][1] - a * row['object_pos'][0] - c)/ np.sqrt(a*a + 1) if distance_ego < dmin and distance_vecteur_vitesse < 5: dmin = distance_ego mini = i #print("Distance:",dmin," ",dataframe.iloc[mini]['inst_token']," ",dataframe.iloc[mini]['object_pos']) return dmin #ego_pos = [round(e,3) for e in ego['translation']] #object_pos = [round(e,3) for e in curr_ann['translation']] # version simplifie pour pouvoir tester def compute_distance_cheat(pos,ABn,dataframe): df = dataframe[dataframe['inst_token']=="98300b9c4acb4da9a7aecd0084650265"] if df.shape[0] == 0: return 99 return round(np.linalg.norm(np.array(pos) - np.array(df.iloc[0]['object_pos'][:2])),3) # Fonction qui déroule une scene en se basant sur les predictions faites, # Point de départ = pos initial puis après calcul à chaque tour de boucle par rapport aux retours des modèles def predict_scene_v2(scene_name,k_past_data): my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') df = build_dataframe_for_one_scene(scene,False) df_ego = df[df['inst_token'] == "vehicle_info"] # Initialisation des paramètres speed = df_ego.iloc[0]['ego_speed'] A = df_ego.iloc[0]['ego_pos'][:2] B = df_ego.iloc[1]['ego_pos'][:2] AB = [round(B[0] - A[0],3),round(B[1] - A[1],3)] ABn = round(AB[0]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3),round(AB[1]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3) #print(A,B,AB,ABn) log = [] features = ["distance","ego_speed","throttle","brake"] sample = nusc.get('sample',scene['first_sample_token']) last = scene['last_sample_token'] i = 0 throttle = [0] brake = [0] past_data = [0]*k_past_data*2 print("Position Predite, Position Reel, Distance, vitesse, accélération, freinage") # Boucle while i != 30 and sample['token'] != last: speed = round(speed,3) distance = compute_distance(A,ABn,df[df['timestamp']==sample['timestamp']]) data = [[distance,speed]] #data = [[distance,speed]+past_data] #print(data) throttle = model_t.predict(data) brake = model_b.predict(data) #throttle = [0] #brake = [0] if throttle[0] < 0: throttle[0] = 0.0 if brake[0] < 0: brake[0] = 0.0 #throttle = 0 #brake = 0 speed = speed - 0.5 if speed < 0: speed = 0 # Calcul nouveau point A = B deplacement = [e * speed/3.6*0.5 for e in ABn] #B = list(map(operator.add, B,deplacement)) i += 1 B = df_ego.iloc[i]['ego_pos'][:2] B = [round(b,3) for b in B] sample = nusc.get('sample',sample['next']) AB = [round(B[0] - A[0],3),round(B[1] - A[1],3)] if AB[0]*AB[0] + AB[1]*AB[1] != 0: ABn = round(AB[0]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3),round(AB[1]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3) else: ABn = (0,0) log += [ABn] past_data.append(distance) past_data.append(speed) past_data.pop(0) past_data.pop(0) print(B,df_ego.iloc[i]['ego_pos'][:2],distance,speed,throttle,brake) #print(past_data) return log scene_name = 'scene-0006' log = predict_scene_v2(scene_name,0) #37efe5932d7f4084ac8ed3bbb5ed6220 56a9802dbe824219992d60debdea6646 23e14d768eab400099c816a3ac0ff041 98300b9c4acb4da9a7aecd0084650265 #nusc.render_instance("98300b9c4acb4da9a7aecd0084650265") print(len(log)) print(log) ``` # Brouillon / animation / recherche de données ``` #test import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation %matplotlib qt TWOPI = 2*np.pi #init scene_name = 'scene-0006' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') df = build_dataframe_for_one_scene(scene,False) df_ego = df[df['inst_token'] == "vehicle_info"] fig, ax = plt.subplots() plt.xlim(0, 2000) plt.ylim(0,2000) t = np.arange(0.0, TWOPI, 0.001) s = np.sin(t) #l = plt.plot(t, s) pos = df_ego[['ego_pos','ego_speed']] #ax = plt.axis([0,TWOPI,-1,1]) v = df[df['inst_token']=="98300b9c4acb4da9a7aecd0084650265"]['object_pos'] print(pos.shape,v.shape) print(pos) #print(v) ax.set_xlim([600,800]) ax.set_ylim([1400,1600]) ego, = plt.plot(0, 0, 'bo') near_vehicle, = plt.plot(0,0,'ro') print(ego) text = plt.text(100,100,"oo") vec_vitesse, = plt.plot(0,0,'k-') def animate(i): ego.set_data(pos.iloc[i,0][0], pos.iloc[i,0][1]) if i < 22: near_vehicle.set_data(v.iloc[i][0],v.iloc[i][1]) text.set_text(pos.iloc[i,1]) text.set_x(pos.iloc[i,0][0]) text.set_y(pos.iloc[i,0][1]) vec_vitesse.set_data([pos.iloc[i,0][0], pos.iloc[i,0][0]+log[i][0]*10], [pos.iloc[i,0][1],pos.iloc[i,0][1]+log[i][1]*10]) #vec_vitesse.set_data([100, 100+log[i][0]*100], [100,100+log[i][1]*100]) #print(i) return ego,text,near_vehicle,vec_vitesse, # create animation using the animate() function myAnimation = animation.FuncAnimation(fig, animate, frames=39, interval=100, blit=True, repeat=True) plt.show() # scene_name = 'scene-0006' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) df_scene = build_dataframe_for_one_scene(scene,False) df = df_scene #display(df_scene) liste_temps = sorted(set(df_scene['timestamp'].to_list())) #liste_temps = np.sort(np.unique(df_scene['timestamp'].to_numpy())) print(liste_temps) list_pos = df[df['timestamp']==1531884156948944]['object_pos'].to_list() print(list_pos) a = np.transpose(np.asarray(list_pos)) df[(df['timestamp']==1531884156948944) & (df['inst_token']!='vehicle_info')] %matplotlib qt import matplotlib as mpl mpl.rcParams.update(mpl.rcParamsDefault) #init scene_name = 'scene-0006' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') df = build_dataframe_for_one_scene(scene,False) df_ego = df[df['inst_token'] == "vehicle_info"] liste_temps = sorted(set(df['timestamp'].to_list())) #plt.style.use(['dark_background']) fig, ax = plt.subplots() mini = df['ego_pos'].min() maxi = df['ego_pos'].max() plt.xlim(mini[0]-50, maxi[0]+50) plt.ylim(mini[1]-50, maxi[1]+50) t = np.arange(0.0, TWOPI, 0.001) pos = df_ego[['timestamp','ego_pos','ego_speed']] #Param ego, = plt.plot(0, 0, 'o') near_vehicle, = plt.plot(0,0,'o') text_ego = plt.text(100,100,"") text_dist = plt.text(100,100,"_ego") vec_vitesse, = plt.plot(0,0,'-') pmin, = plt.plot(440,1100,'o') fct, = plt.plot(0,0,'-') def init(): return [] def animate(frame,arg): i = arg[frame] ego_pos = pos[pos['timestamp']==i]['ego_pos'].iloc[0] ego.set_data(ego_pos[0],ego_pos[1]) list_pos = df[(df['timestamp']==i)&(df['inst_token']!='vehicle_info')]['object_pos'].to_list() if len(list_pos)!=0 : #print(list_pos) a = np.transpose(np.asarray(list_pos)) near_vehicle.set_data(a[0],a[1]) text_ego.set_text(pos[pos['timestamp']==i].iloc[0,2]) text_ego.set_x(pos[pos['timestamp']==i].iloc[0,1][0]) text_ego.set_y(pos[pos['timestamp']==i].iloc[0,1][1]) if frame < len(arg) - 2: j = arg[frame+1] A = pos[pos['timestamp']==i].iloc[0,1] B = pos[pos['timestamp']==j].iloc[0,1] AB = [round(B[0] - A[0],3),round(B[1] - A[1],3)] ABn = round(AB[0]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3),round(AB[1]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3) vec_vitesse.set_data([A[0], A[0]+ABn[0]*10], [A[1],A[1]+ABn[1]*10]) #vec_vitesse.set_data([100, 100+log[i][0]*100], [100,100+log[i][1]*100]) if len(list_pos)!=0 : a = ABn[1]/ABn[0] c = - A[0] * a + A[1] dmin = 50 posmin = [] for p in list_pos: d = np.absolute(p[1] - a * p[0] - c)/ np.sqrt(a*a + 1) distance_ego = round(np.linalg.norm(np.array(A) - np.array(p)),3) if distance_ego < dmin and d < 5: dmin = distance_ego posmin = p if posmin != []: pmin.set_data(posmin[0],posmin[1]) text_dist.set_text(dmin) text_dist.set_x(posmin[0]) text_dist.set_y(posmin[1]) #print(dmin,posmin) x = np.linspace(mini[0]-50, maxi[0]+50) y = a*x + c fct.set_data(x,y) #print(i) return ego,text_ego,text_dist,near_vehicle,vec_vitesse,pmin,fct, # create animation using the animate() function myAnimation = animation.FuncAnimation(fig, animate, frames=len(liste_temps),fargs=([liste_temps]), interval=100, blit=True, repeat=True) plt.show() blackint = nusc_can.can_blacklist blacklist = [ "scene-0"+ str(i) for i in blackint] def compute_near_vehicle_dataframe_one_scene(df): liste_temps = sorted(set(df['timestamp'].to_list())) new_df = pd.DataFrame(columns=df.columns) def compute_one_sample(frame): tstp = liste_temps[frame] #ego_pos = df[(df['timestamp']==tstp)&(df['inst_token']=='vehicle_info')]['ego_pos'].iloc[0] df_curr = df[(df['timestamp']==tstp)&(df['inst_token']!='vehicle_info')] if len(list_pos)!=0 : a = np.transpose(np.asarray(list_pos)) if frame < len(liste_temps) - 2: tstp2 = liste_temps[frame+1] A = df[(df['timestamp']==tstp)&(df['inst_token']=='vehicle_info')]['ego_pos'].iloc[0] B = df[(df['timestamp']==tstp2)&(df['inst_token']=='vehicle_info')]['ego_pos'].iloc[0] AB = [round(B[0] - A[0],3),round(B[1] - A[1],3)] ABn = round(AB[0]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3),round(AB[1]/np.sqrt((AB[0]*AB[0] + AB[1]*AB[1])),3) if len(list_pos)!=0 : a = ABn[1]/ABn[0] c = - A[0] * a + A[1] dmin = 50 posmin = [] row = None for j in range(df_curr.shape[0]): p = df_curr.iloc[j]['object_pos'] d = np.absolute(p[1] - a * p[0] - c)/ np.sqrt(a*a + 1) distance_ego = round(np.linalg.norm(np.array(A) - np.array(p)),3) if distance_ego < dmin and d < 5: dmin = distance_ego posmin = p row = df_curr.iloc[j] if posmin != []: return row for i in range(len(liste_temps)): row = compute_one_sample(i) new_df = new_df.append(row) #print(new_df.shape) #display(new_df) return new_df def compute_near_vehicle_dataframe_all_scene(): scenes = nusc.scene list_rows = [] first = True i = 0 for s in scenes: if s['name'] not in blacklist and s['name'] not in ["scene-0003","scene-0419"]: #scene_token = nusc.field2token('scene', 'name', s['name'])[0] #scene = nusc.get('scene',scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') df = build_dataframe_for_one_scene(s,False) if first: new_df = compute_near_vehicle_dataframe_one_scene(df) first = False else: return_df = compute_near_vehicle_dataframe_one_scene(df) new_df = new_df.append(return_df) return new_df #init scene_name = 'scene-0061' my_scene_token = nusc.field2token('scene', 'name', scene_name)[0] scene = nusc.get('scene',my_scene_token) #nusc.render_scene_channel(my_scene_token, 'CAM_FRONT') pos = df_ego[['timestamp','ego_pos','ego_speed']] #test = comput e_near_vehicle_dataframe_one_scene(df) print(test.shape) near_df = compute_near_vehicle_dataframe_all_scene() print(near_df.shape) near_df.to_csv("./data/near_dataframe_full.csv") from mpl_toolkits.mplot3d import Axes3D %matplotlib qt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 ax.scatter(near_df['ego_speed'],near_df['brake'],near_df['distance'],marker='o') ax.set_xlabel('V') ax.set_ylabel('Brake') ax.set_zlabel('Distance') ax.set_ylim([0, 20]) plt.show() display(near_df) ``` Cette façon de faire avec distance et vitesse à l'instant t seulement n'est pas bonne. Je vais essayer mtn de rajouter ces informations du passé (t-1,-2...) pour avoir plus de paramètres, et j'espère avoir un résultat concret. ``` near_df = pd.read_csv('./data/near_dataframe_full.csv') near_df.shape # Pas opti (copy, à améliorer) # Ajout de colonnes dans le dataframe pour les informations antérieurs (distance + vitesse) def add_past_data_to_dataframe(dataframe,k_past_data): clmns = dataframe.columns.to_list() for j in range(1,k_past_data+1): clmns += ['distance_'+str(j)] + ['ego_speed_'+str(j)] new_df = pd.DataFrame(columns=clmns) set_scene = sorted(set(dataframe['scene'].to_list())) for s in set_scene: df_curr = dataframe[dataframe['scene']==s] for i in range(k_past_data,df_curr.shape[0]): row = df_curr.iloc[i].copy() for j in range(1,k_past_data+1): row['distance_'+str(j)] = df_curr.iloc[i-j]['distance'] row['ego_speed_'+str(j)] = df_curr.iloc[i-j]['ego_speed'] new_df = new_df.append(row) #display(new_df) print(new_df.shape) return new_df train_data = add_past_data_to_dataframe(near_df,5) features = [col for col in train_data.columns.to_list() if ('distance' in col or'ego_speed' in col)] print(train_data.columns,features) [0] * 5 ```
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W2D1_ConvnetsAndRecurrentNeuralNetworks/student/W2D1_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> &nbsp; <a href="https://kaggle.com/kernels/welcome?src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W2D1_ConvnetsAndRecurrentNeuralNetworks/student/W2D1_Tutorial2.ipynb" target="_parent"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open in Kaggle"/></a> # Tutorial 2: Introduction to RNNs **Week 2, Day 1: Convnets And Recurrent Neural Networks** **By Neuromatch Academy** __Content creators:__ Dawn McKnight, Richard Gerum, Cassidy Pirlot, Rohan Saha, Liam Peet-Pare, Saeed Najafi, Alona Fyshe __Content reviewers:__ Saeed Salehi, Lily Cheng, Yu-Fang Yang, Polina Turishcheva, Nina Kudryashova, Kelson Shilling-Scrivo __Content editors:__ Nina Kudryashova __Production editors:__ Anmol Gupta, Spiros Chavlis *Based on material from:* Konrad Kording, Hmrishav Bandyopadhyay, Rahul Shekhar, Tejas Srivastava **Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs** <p align='center'><img src='https://github.com/NeuromatchAcademy/widgets/blob/master/sponsors.png?raw=True'/></p> --- # Tutorial Objectives At the end of this tutorial, we will be able to: - Understand the structure of a Recurrent Neural Network (RNN) - Build a simple RNN model ``` # @title Tutorial slides # @markdown These are the slides for the videos in this tutorial # @markdown If you want to download locally the slides, click [here](https://osf.io/5asx2/download) from IPython.display import IFrame IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/5asx2/?direct%26mode=render%26action=download%26mode=render", width=854, height=480) ``` --- # Setup ``` # @title Install dependencies !pip install livelossplot --quiet !pip install unidecode !pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet from evaltools.airtable import AirtableForm # generate airtable form atform = AirtableForm('appn7VdPRseSoMXEG','W2D1_T2','https://portal.neuromatchacademy.org/api/redirect/to/351ca652-13d8-4e31-be28-30153d03e639') # Imports import time import math import torch import string import random import unidecode import numpy as np import matplotlib.pyplot as plt import torch.nn as nn from tqdm.notebook import tqdm # @title Figure settings import ipywidgets as widgets # interactive display %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle") plt.rcParams["mpl_toolkits.legacy_colorbar"] = False import warnings warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib") # @title Helper functions # https://github.com/spro/char-rnn.pytorch def read_file(filename): file = unidecode.unidecode(open(filename).read()) return file, len(file) # Turning a string into a tensor def char_tensor(string): tensor = torch.zeros(len(string)).long() for c in range(len(string)): try: tensor[c] = all_characters.index(string[c]) except: continue return tensor # Readable time elapsed def time_since(since): s = time.time() - since m = math.floor(s / 60) s -= m * 60 out = f"{m}min {s}sec" return out def generate(decoder, prime_str='A', predict_len=100, temperature=0.8, device='cpu'): hidden = decoder.init_hidden(1) prime_input = char_tensor(prime_str).unsqueeze(0) hidden = hidden.to(device) prime_input = prime_input.to(device) predicted = prime_str # Use priming string to "build up" hidden state for p in range(len(prime_str) - 1): _, hidden = decoder(prime_input[:,p], hidden) inp = prime_input[:,-1] for p in range(predict_len): output, hidden = decoder(inp, hidden) # Sample from the network as a multinomial distribution output_dist = output.data.view(-1).div(temperature).exp() top_i = torch.multinomial(output_dist, 1)[0] # Add predicted character to string and use as next input predicted_char = all_characters[top_i] predicted += predicted_char inp = char_tensor(predicted_char).unsqueeze(0) inp = inp.to(device) return predicted # @title Set random seed # @markdown Executing `set_seed(seed=seed)` you are setting the seed # for DL its critical to set the random seed so that students can have a # baseline to compare their results to expected results. # Read more here: https://pytorch.org/docs/stable/notes/randomness.html # Call `set_seed` function in the exercises to ensure reproducibility. import random import torch def set_seed(seed=None, seed_torch=True): if seed is None: seed = np.random.choice(2 ** 32) random.seed(seed) np.random.seed(seed) if seed_torch: torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True print(f'Random seed {seed} has been set.') # In case that `DataLoader` is used def seed_worker(worker_id): worker_seed = torch.initial_seed() % 2**32 np.random.seed(worker_seed) random.seed(worker_seed) #@title Set device (GPU or CPU). Execute `set_device()` # especially if torch modules used. # inform the user if the notebook uses GPU or CPU. def set_device(): device = "cuda" if torch.cuda.is_available() else "cpu" if device != "cuda": print("WARNING: For this notebook to perform best, " "if possible, in the menu under `Runtime` -> " "`Change runtime type.` select `GPU` ") else: print("GPU is enabled in this notebook.") return device SEED = 2021 set_seed(seed=SEED) DEVICE = set_device() ``` --- # Section 1: Recurrent Neural Networks (RNNs) *Time estimate: ~20mins* ``` # @title Video 1: RNNs from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id=f"BV1L44y1m7PP", width=854, height=480, fs=1) print("Video available at https://www.bilibili.com/video/{0}".format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id=f"PsZjS125lLs", width=854, height=480, fs=1, rel=0) print("Video available at https://youtube.com/watch?v=" + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') # add event to airtable atform.add_event('Video 1: RNNs') display(out) ``` RNNs are compact models that operate over timeseries, and have the ability to remember past input. They also save parameters by using the same weights at every time step. If you've heard of Transformers, those models don't have this kind of temporal weight sharing, and so they are *much* larger. The code below is adapted from [this github repository](https://github.com/spro/char-rnn.pytorch). ``` # RNN # https://github.com/spro/char-rnn.pytorch class CharRNN(nn.Module): def __init__(self, input_size, hidden_size, output_size, model="gru", n_layers=1): """ input_size: int Size of the input layer. hidden_size: int Size of the hidden layers. output_size: int Size of the output layer. model: string `model` can take the values "gru", "rnn", "lstm". Default is "gru". n_layers: int Number of layers """ super(CharRNN, self).__init__() self.model = model.lower() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.encoder = nn.Embedding(input_size, hidden_size) if self.model == "gru": self.rnn = nn.GRU(hidden_size, hidden_size, n_layers) elif self.model == "lstm": self.rnn = nn.LSTM(hidden_size, hidden_size, n_layers) elif self.model == "rnn": self.rnn = nn.RNN(hidden_size, hidden_size, n_layers) self.decoder = nn.Linear(hidden_size, output_size) def forward(self, input, hidden): batch_size = input.size(0) encoded = self.encoder(input) output, hidden = self.rnn(encoded.reshape(1, batch_size, -1), hidden) output = self.decoder(output.reshape(batch_size, -1)) return output, hidden def init_hidden(self, batch_size): if self.model == "lstm": return (torch.zeros(self.n_layers, batch_size, self.hidden_size), torch.zeros(self.n_layers, batch_size, self.hidden_size)) return torch.zeros(self.n_layers, batch_size, self.hidden_size) ``` This next section of code takes care of training the RNN on several of Mark Twain's books. In this short section, we won't dive into the code, but you'll get to learn a lot more about RNNs in a few days! For now, we are just going to observe the training process. ``` # @title Run Me to get the data import requests url = 'https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W2D1_ConvnetsAndRecurrentNeuralNetworks/static/twain.txt' r = requests.get(url, stream=True) with open('twain.txt', 'wb') as fd: fd.write(r.content) ``` One cool thing about RNNs is that they can be used to _generate_ language based on what the network sees during training. As the network makes predictions, instead of confirming of those predictions are correct against some training text, we just feed them back into the model as the next observed token. Starting from a random vector for the hidden state, we can generate many original sentences! And what the network generates will reflect the text it was trained on. ``` # https://github.com/spro/char-rnn.pytorch def random_training_set(file, file_len, chunk_len, batch_size, device='cpu', seed=0): random.seed(seed) inp = torch.LongTensor(batch_size, chunk_len).to(device) target = torch.LongTensor(batch_size, chunk_len).to(device) for bi in range(batch_size): start_index = random.randint(0, file_len - chunk_len - 1) end_index = start_index + chunk_len + 1 chunk = file[start_index:end_index] inp[bi] = char_tensor(chunk[:-1]) target[bi] = char_tensor(chunk[1:]) return inp, target, chunk_len, batch_size, device def train(decoder, criterion, inp, target, chunk_len, batch_size, device): hidden = decoder.init_hidden(batch_size) decoder.zero_grad() loss = 0 for c in range(chunk_len): output, hidden = decoder(inp[:, c].to(device), hidden.to(device)) loss += criterion(output.reshape(batch_size, -1), target[:,c]) loss.backward() decoder_optimizer.step() return loss.item() / chunk_len ``` First, let's load the text file, and define the model and its hyperparameters. ``` # Reading and un-unicode-encoding data all_characters = string.printable n_characters = len(all_characters) # load the text file file, file_len = read_file('twain.txt') # Hyperparams batch_size = 50 chunk_len = 200 model = "rnn" # other options: `lstm`, `gru` n_layers = 2 hidden_size = 200 learning_rate = 0.01 # Define the model, optimizer, and the loss criterion decoder = CharRNN(n_characters, hidden_size, n_characters, model=model, n_layers=n_layers) decoder.to(DEVICE) decoder_optimizer = torch.optim.Adagrad(decoder.parameters(), lr=learning_rate) criterion = nn.CrossEntropyLoss() ``` Let's try it! Run the code below. As the network trains, it will output samples of generated text every 25 epochs. Notice that as the training progresses, the model learns to spell short words, then learns to string some words together, and eventually can produce meaningful sentences (sometimes)! Keep in mind that this is a relatively small network, and doesn't employ some of the cool things you'll learn about later in the week (e.g., LSTMs, though you can change that in the code below by changing the value of the `model` variable if you wish!) After running the model, and observing the output, get together with your pod, and talk about what you noticed during training. Did your network produce anything interesting? Did it produce anything characteristic of Twain? **Note:** training for the full 2000 epochs is likely to take a while, so you may need to stop it before it finishes. If you have time left, set `n_epochs` to 2000 below. ``` n_epochs = 1000 # initial was set to 2000 print_every = 50 # frequency of printing the outputs start = time.time() all_losses = [] loss_avg = 0 print(f"Training for {n_epochs} epochs...\n") for epoch in tqdm(range(1, n_epochs + 1), position=0, leave=True): loss = train(decoder, criterion, *random_training_set(file, file_len, chunk_len, batch_size, device=DEVICE, seed=epoch)) loss_avg += loss if epoch % print_every == 0: print(f"[{time_since(start)} {epoch/n_epochs * 100}%) {loss:.4f}]") print(f"{generate(decoder, prime_str='Wh', predict_len=150, device=DEVICE)}") ``` Now you can generate more examples using a trained model. Recall that `generate` takes the mentioned below arguments to work: ```python generate(decoder, prime_str='A', predict_len=100, temperature=0.8, device='cpu') ``` Try it by yourself ``` print(f"{generate(decoder, prime_str='Wh', predict_len=100, device=DEVICE)}\n") ``` --- # Section 2: Power consumption in Deep Learning *Time estimate: ~20mins* Training NN models can be incredibly costly, both in actual money but also in power consumption. ``` # @title Video 2: Carbon Footprint of AI from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id=f"BV1My4y1j7HJ", width=854, height=480, fs=1) print("Video available at https://www.bilibili.com/video/{0}".format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id=f"as6C334LmRs", width=854, height=480, fs=1, rel=0) print("Video available at https://youtube.com/watch?v=" + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') # add event to airtable atform.add_event('Video 2: Carbon Footprint of AI') display(out) ``` Take a few moments to chat with your pod about the following points: * Which societal costs of training do you find most compelling? * When is training an AI model worth the cost? Who should make that decision? * Should there be additional taxes on energy costs for compute centers? ## Exercise 2: Calculate the carbon footprint that your pod generated today. You can use this [online calculator](https://mlco2.github.io/impact/#compute). ``` # @title Student Response from ipywidgets import widgets text=widgets.Textarea( value='Type your answer here and click on `Submit!`', placeholder='Type something', description='', disabled=False ) button = widgets.Button(description="Submit!") display(text,button) def on_button_clicked(b): atform.add_answer('q1', text.value) print("Submission successful!") button.on_click(on_button_clicked) ``` --- # Summary What a day! We've learned a lot! The basics of CNNs and RNNs, and how changes to architecture that allow models to parameter share can greatly reduce the size of the model. We learned about convolution and pooling, as well as the basic idea behind RNNs. To wrap up we thought about the impact of training large NN models. ``` # @title Airtable Submission Link from IPython import display as IPydisplay IPydisplay.HTML( f""" <div> <a href= "{atform.url()}" target="_blank"> <img src="https://github.com/NeuromatchAcademy/course-content-dl/blob/main/tutorials/static/SurveyButton.png?raw=1" alt="button link end of day Survey" style="width:410px"></a> </div>""" ) ```
github_jupyter
``` import numpy as np import pandas as pd patients = pd.read_csv('internacoes_charlson_zero.csv.gz', compression='gzip', nrows=None, usecols=['target']) target = np.asarray(patients['target'].values) print(target.shape) import nltk nltk.download('rslp') nltk.download('stopwords') import gzip, pickle from sklearn.feature_extraction.text import TfidfVectorizer from nltk.corpus import stopwords import nltk.stem portuguese_stemmer = nltk.stem.RSLPStemmer() class StemmedTfidfVectorizer(TfidfVectorizer): def build_analyzer(self): analyzer = super(TfidfVectorizer,self).build_analyzer() return lambda doc: (portuguese_stemmer.stem(w) for w in analyzer(doc)) with gzip.open('model_10k_multigram.pkl.gz', 'rb') as rpk: tfidf_model = pickle.load(rpk) rpk.close() with gzip.open('data_10k_multigram.npy.gz', 'rb') as rpk: data = pickle.load(rpk) rpk.close() print(data.shape) from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import StratifiedKFold from sklearn.metrics import mean_absolute_error import warnings warnings.filterwarnings('ignore') split_kfold = StratifiedKFold(n_splits=20) for trash, used in split_kfold.split(patients.index.values, target): break target_set = target data_set = data kfold = StratifiedKFold(n_splits=6) values = [] prediction = [] models = [] maes = [] for train, test in kfold.split(data_set, target_set): model = RandomForestRegressor(n_jobs=16) model.fit(data_set[train], target_set[train]) target_pred = model.predict(data_set[test]) mae = mean_absolute_error(target_set[test], target_pred) values.extend(target_set[test]) prediction.extend(target_pred) maes.append(mae) models.append(model) print('mean_absolute_error: ', mae) print(np.mean(maes)) tuples = np.stack((values,np.round(prediction,1)), axis=-1) ## ROUND TUPLES frequencies = {} for x,y in tuples: key = (x, y) if key in frequencies: frequencies[key] += 1 else: frequencies[key] = 1 size = [] x = [] y = [] for key in frequencies.keys(): size.append(frequencies[key]) x.append(key[0]) y.append(key[1]) np.max(values), np.max(x), np.max(y) # https://matplotlib.org/gallery/shapes_and_collections/scatter.html %matplotlib inline import matplotlib.pyplot as plt maxX = np.max(x) plt.figure(figsize=(8, 4), dpi= 300) plt.xlabel('Charlson Value', fontsize=10) plt.ylabel('Prediction Value', fontsize=10) plt.xticks(range(int(maxX)+1)) plt.yticks(range(int(maxX)+1)) plt.scatter(x,y,s=size) plt.show() import operator import sys features = {} ridx = {idx:term for term,idx in tfidf_model.vocabulary_.items()} for model in models: for i,v in enumerate(model.feature_importances_): if not ridx[i] in features.keys(): features[ridx[i]] = v else: features[ridx[i]] += v if (i % 1000) == 0: sys.stdout.write(str(i) + ', ') sys.stdout.flush() sorted(features.items(), key=operator.itemgetter(1), reverse=True)[:20] ```
github_jupyter
``` import torch import torch.nn as nn from torch.nn import init from torch.autograd import Variable import argparse import os import numpy as np import time import random from sklearn.metrics import f1_score from collections import defaultdict import networkx as nx from encoders import Encoder from aggregators import MeanAggregator from model import SupervisedGraphSage from dataset_utils import DataLoader from utils import * parser = argparse.ArgumentParser() parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.') parser.add_argument('--fastmode', action='store_true', default=False, help='Validate during training pass.') parser.add_argument('--seed', type=int, default=42, help='Random seed.') parser.add_argument('--epochs', type=int, default=200, help='Number of epochs to train.') parser.add_argument('--lr', type=float, default=0.015, help='Initial learning rate.') parser.add_argument('--weight_decay', type=float, default=9e-4, help='Weight decay (L2 loss on parameters).') parser.add_argument('--hidden', type=int, default=64, help='Number of hidden units.') parser.add_argument('--num_samples', type=int, default=25, help='Number of samples.') parser.add_argument('--dataset', default='cora', help='Dataset name.') args = parser.parse_args("") np.random.seed(args.seed) torch.manual_seed(args.seed) random.seed(args.seed) dname = args.dataset dataset = DataLoader(dname) data = dataset[0] A_norm, A, X, labels, idx_train, idx_val, idx_test = load_citation_data(data) G = nx.from_numpy_matrix(A) feature_dictionary = {} for i in np.arange(len(labels)): feature_dictionary[i] = labels[i] nx.set_node_attributes(G, feature_dictionary, "attr_name") sub_graphs = [] for i in np.arange(len(A)): s_indexes = [] for j in np.arange(len(A)): s_indexes.append(i) if(A[i][j]==1): s_indexes.append(j) sub_graphs.append(G.subgraph(s_indexes)) subgraph_nodes_list = [] for i in np.arange(len(sub_graphs)): subgraph_nodes_list.append(list(sub_graphs[i].nodes)) sub_graphs_adj = [] for index in np.arange(len(sub_graphs)): sub_graphs_adj.append(nx.adjacency_matrix(sub_graphs[index]).toarray()) new_adj = torch.zeros(A.shape[0], A.shape[0]) for node in np.arange(len(subgraph_nodes_list)): sub_adj = sub_graphs_adj[node] for neighbors in np.arange(len(subgraph_nodes_list[node])): index = subgraph_nodes_list[node][neighbors] count = torch.tensor(0).float() if(index==node): continue else: c_neighbors = set(subgraph_nodes_list[node]).intersection(subgraph_nodes_list[index]) if index in c_neighbors: nodes_list = subgraph_nodes_list[node] sub_graph_index = nodes_list.index(index) c_neighbors_list = list(c_neighbors) for i, item1 in enumerate(nodes_list): if(item1 in c_neighbors): for item2 in c_neighbors_list: j = nodes_list.index(item2) count += sub_adj[i][j] new_adj[node][index] = count/2 new_adj[node][index] = new_adj[node][index]/(len(c_neighbors)*(len(c_neighbors)-1)) new_adj[node][index] = new_adj[node][index] * (len(c_neighbors)**1) weight = torch.FloatTensor(new_adj) weight = weight / weight.sum(1, keepdim=True) weight = weight + torch.FloatTensor(A) coeff = weight.sum(1, keepdim=True) coeff = torch.diag((coeff.T)[0]) weight = weight + coeff weight = weight.detach().numpy() adj = np.nan_to_num(weight, nan=0) feat_data = np.array(X) adj_lists = defaultdict(set) for i in np.arange(len(sub_graphs)): adj_lists[i]=set(subgraph_nodes_list[i]) labels = labels.reshape(A.shape[0], 1) full_nodes = torch.LongTensor(np.arange(A.shape[0])) num_nodes = A.shape[0] num_features = feat_data.shape[1] features = nn.Embedding(num_nodes, num_features) features.weight = nn.Parameter(torch.FloatTensor(feat_data), requires_grad=False) feat_data = torch.FloatTensor(feat_data) agg1 = MeanAggregator(features, cuda=False) enc1 = Encoder(features, num_features, args.hidden, adj_lists, adj, feat_data, agg1, cuda=False) agg2 = MeanAggregator(lambda nodes : enc1(nodes, full_nodes).t(), cuda=False) enc2 = Encoder(lambda nodes : enc1(nodes, full_nodes).t(), enc1.embed_dim, args.hidden, adj_lists, adj, feat_data, agg2, base_model=enc1, cuda=False) enc1.num_samples = args.num_samples enc2.num_samples = args.num_samples num_classes = np.unique(labels).shape[0] graphsage = SupervisedGraphSage(num_classes, enc2) test_size = torch.count_nonzero(idx_test).item() val_size = torch.count_nonzero(idx_val).item() train_size = torch.count_nonzero(idx_train).item() test = np.array(range(train_size+val_size, train_size+val_size+test_size)) val = np.array(range(train_size, train_size+val_size)) train = np.array(range(train_size)) optimizer = torch.optim.Adam(graphsage.parameters(), lr=args.lr, weight_decay=args.weight_decay) times = [] for batch in range(args.epochs): batch_nodes = train[:train_size] random.shuffle(train) start_time = time.time() optimizer.zero_grad() loss = graphsage.loss(batch_nodes, full_nodes, Variable(torch.LongTensor(labels[np.array(batch_nodes)]))) loss.backward() optimizer.step() end_time = time.time() times.append(end_time-start_time) val_output = graphsage.forward(val, full_nodes) print("Validation Accuracy:", 100*f1_score(labels[val], val_output.data.numpy().argmax(axis=1), average="micro")) test_output = graphsage.forward(test, full_nodes) print("Test Accuracy:", 100*f1_score(labels[test], test_output.data.numpy().argmax(axis=1), average="micro")) ```
github_jupyter
<!--NAVIGATION--> < [OPTIONAL - More about interact](02.01-OPTIONAL-More-About-Interact.ipynb) | [Contents](00.00-index.ipynb) | [Widgets in the core ipywidgets package](04.00-widget-list.ipynb) > # Simple Widget Introduction ## O que são widgets? Widgets são objetos python que têm uma representação no navegador, geralmente como um controle como `slider`, `textbox`, etc. ## Para que eles podem ser usados? Você pode usar widgets para construir **interactive GUIs** para seus notebooks. Você também pode usar widgets para **sincronizar informações com e sem estado** entre Python e JavaScript. ## Usando widgets Para usar o framework de widget, você precisa importar `ipywidgets`. ``` import ipywidgets as widgets ``` ### repr Os widgets têm seu próprio display `repr`, o que permite que eles sejam exibidos usando a estrutura de exibição do IPython. Construindo e retornando um `IntSlider` que exibe automaticamente o widget (como visto abaixo). Os widgets são exibidos dentro da área de saída abaixo da célula de código. Limpar a saída da célula também removerá o widget. ``` widgets.IntSlider() ``` ### display() Você também pode exibir explicitamente o widget usando `display(...)`. ``` from IPython.display import display w = widgets.IntSlider() display(w) ``` ### Múltiplas chamadas `display()` Se você exibir o mesmo widget duas vezes, as instâncias exibidas no frontend permanecerão sincronizadas entre si. Tente arrastar o `slider` abaixo e observe o controle deslizante acima. ``` display(w) ``` ## Por que exibir o mesmo widget duas vezes funciona? Os widgets são representados no back-end por um único objeto. Cada vez que um widget é exibido, uma nova representação desse mesmo objeto é criada no frontend. Essas representações são chamadas de `views`. ![Kernel & front-end diagram](images/WidgetModelView.png) ## Propriedades Widget Todos os widgets IPython compartilham um esquema de nomenclatura semelhante. Para ler o valor de um widget, você pode consultar a propriedade `value`. ``` w = widgets.IntSlider() display(w) w.value ``` Da mesma forma, para definir o valor de um widget, você pode definir sua propriedade `value`. ``` w.value = 100 ``` ### keys Além de `valor`, a maioria dos widgets compartilham` keys`, `description` e` disabled`. Para ver toda a lista de propriedades sincronizadas e com estado de qualquer widget específico, você pode consultar a propriedade `keys`. Geralmente, você não deve interagir com propriedades que começam com um sublinhado. ``` w.keys ``` ### Abreviação para definir os valores iniciais das propriedades do widget Ao criar um widget, você pode definir alguns ou todos os valores iniciais desse widget, definindo-os como argumentos de palavra-chave no construtor do widget (conforme visto abaixo). ``` widgets.Text(value='Hello World!', disabled=True) ``` ## Linkar dois widgets semelhantes Se você precisar exibir o mesmo valor de duas maneiras diferentes, terá que usar dois widgets diferentes. Em vez de tentar sincronizar manualmente os valores dos dois widgets, você pode usar a função `link` ou` jslink` para vincular duas propriedades (a diferença entre elas é discutida no [Widget Events](08.00-Widget_Events.ipynb)). Veja abaixo, os valores de dois widgets estão vinculados. ``` slider = widgets.FloatSlider( value=7.5, min=5.0, max=10.0, step=0.1, description='Input:', ) # Criar `text box` para ter o valor do `slider` text = widgets.FloatText(description='Value') # Linkar o valor do `slider` com o valor do `text box` widgets.link((slider, 'value'), (text, 'value')) # Colocar eles em uma caixa vertical widgets.VBox([slider, text]) ``` ### Desvincular widgets Desvincular os widgets é simples. Tudo que você precisa fazer é chamar `.unlink` no objeto de link. Tente alterar um dos widgets acima após desvincular para ver se eles podem ser alterados de forma independente. ``` # mylink.unlink() ``` ## `observe` mudanças no valor de um widget Quase todos os widgets podem ser observados quanto a mudanças em seu valor que acionam uma chamada para uma função. O exemplo abaixo é o `slider` do primeiro bloco de notas do tutorial. O widget `HTML` abaixo do `slider` exibe o quadrado do número. ``` slider = widgets.FloatSlider( value=7.5, min=5.0, max=10.0, step=0.1, description='Input:', ) # Cria uma área de texto não editável para exibir o quadrado de valor square_display = widgets.HTML(description="Square: ", value='{}'.format(slider.value**2)) # Crie uma função para atualizar o valor do square_display quando o `slider` mudar def update_square_display(change): square_display.value = '{}'.format(change.new**2) slider.observe(update_square_display, names='value') # Coloque-os em uma caixa vertical widgets.VBox([slider, square_display]) ``` <!--NAVIGATION--> < [OPTIONAL - More about interact](02.01-OPTIONAL-More-About-Interact.ipynb) | [Contents](00.00-index.ipynb) | [Widgets in the core ipywidgets package](04.00-widget-list.ipynb) >
github_jupyter
``` %pylab inline import pandas as pd import numpy as np import seaborn as sns from matplotlib import patches ``` # Read spreadsheet ``` df = pd.read_excel("../tests/test_data.xlsx") df.keys() ``` ## Select data ``` ts = df.timestamp.unique()[0] dfs = df[df.timestamp==ts] ``` # Tracking ``` sns.lineplot(data=dfs, x="x_px", y="y_px", hue="id_obj", legend=False) ``` ## Plot with bounding boxes ``` sns.palplot(sns.color_palette(None, 20)) fig = plt.figure() pal= sns.color_palette(None, len(dfs.id_obj.unique())) ax = sns.lineplot(data=dfs, x="x_px", y="y_px", hue="id_obj", legend=False, palette=pal) dflast = dfs.groupby("id_obj").last() for i in range(len(dflast)): dflast.bbox_0_x_px[i] dflast.bbox_0_y_px[i] rect = patches.Rectangle( (dflast.bbox_0_x_px[i], dflast.bbox_0_y_px[i]), dflast.bbox_1_x_px[i] - dflast.bbox_0_x_px[i], dflast.bbox_1_y_px[i] - dflast.bbox_0_y_px[i], linewidth=1,edgecolor=pal[i],facecolor='none' ) ax.add_patch(rect) len(df) len(df.keys()) ``` # Intensity evaluation ## In each channel ``` sns.lineplot(data=dfs, x="t_frame", y="intensity mean in channel 0", hue="id_obj", palette=pal, legend=False) sns.lineplot(data=dfs, x="t_frame", y="intensity mean in channel 1", hue="id_obj", palette=pal, legend=False) ``` ## Relative intensity ``` dfs["relative intensity"] = dfs["intensity mean in channel 1"] / dfs["intensity mean in channel 0"] sns.lineplot(data=dfs, x="t_frame", y="relative intensity", hue="id_obj", palette=pal, legend=False) ``` ## All channels together ``` dfsm = pd.melt(dfs.reset_index(), id_vars=['id_obj', "t_frame"],value_vars=['intensity mean in channel 0', 'intensity mean in channel 1']) dfsm sns.lineplot(data=dfsm, x="t_frame", y="value", hue="id_obj", palette=pal, legend=False) # g = sns.PairGrid(data=dfsm, x=) # g = g.map_diag(plt.hist) # g = g.map_offdiag(plt.scatter) ``` # Calculate mean of coords ``` dfsg = dfs.groupby("t_frame").mean() dfsg["x_px_mean"] = dfsg["x_px"] dfsg["y_px_mean"] = dfsg["y_px"] dfsg = dfsg.reset_index() dfsg_small = dfsg[["t_frame", "x_px_mean", "y_px_mean"]] dfsm = dfs.merge(dfsg_small, left_on="t_frame", right_on="t_frame") fg = sns.lmplot(data=dfsg, x="x_px_mean", y="y_px_mean") fg.ax dfsm.keys() dfsm ``` ## Dist from actual center ``` dfsm["distance"] = ((dfsm.y_px-dfsm.y_px_mean)**2 + (dfsm.x_px-dfsm.x_px_mean)**2)**0.5 sns.lineplot(data=dfsm, x="distance", y="relative intensity", hue="id_obj", palette=pal, legend=False) ```
github_jupyter
``` ''' 基于菜鸟教程中的 [NumPy 教程](https://www.runoob.com/numpy/numpy-tutorial.html) ''' import numpy as np np.eye(4) a = np.array([1,2,3]) print (a) a = np.array([[1, 2], [3, 4]]) print (a) a = np.array([1, 2, 3,4,5], ndmin = 2) print (a) a = np.array([1, 2, 3], dtype = complex) print (a) dt = np.dtype(np.int32) print(dt) dt = np.dtype('i4') print(dt) dt = np.dtype('<i4') print(dt) dt = np.dtype([('age',np.int8)]) a = np.array([10,20,30], dtype = dt) print(a['age']) student = np.dtype([('age',np.int8),('class','S10'),('score','f4')]) a = np.array([(12,'asdfasfd',12.5),(13,'zzzzzzzz',12.9)],dtype = student) print(a['score']) a = np.arange(24) print (a,a.ndim) # a 现只有一个维度 # 现在调整其大小 b = a.reshape(2,4,3) # b 现在拥有三个维度 print (b,b.ndim,b.shape) b.shape=(3,4,2) print(b) # 数组的 dtype 为 int8(一个字节) x = np.array([1,2,3,4,5], dtype = np.int8) print (x.itemsize) # 数组的 dtype 现在为 float64(八个字节) y = np.array([1,3,4,5], dtype = np.float64) print (y.itemsize) x = np.array([1,2,3,4,5]) print (x.flags) x = np.empty([3,2], dtype = int) print (x) # 默认为浮点数 x = np.zeros(5) print(x) # 设置类型为整数 y = np.zeros((5,), dtype = np.int) print(y) # 自定义类型 z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print(z) x = [1,2,3] a = np.asarray(x) print (a) x = (1,2,3) a = np.asarray(x) print (a) x = [(1,2,3),(4,5)] a = np.asarray(x) print (a) x = [1,2,3] a = np.asarray(x, dtype = float) print (a) s = b'Hello World' a = np.asarray(s, dtype = 'S1') print (a) x = np.arange(5) print (x) a = np.linspace(1,10,10,retstep=True) print(a) a = np.linspace(1,1,3,dtype=np.int8) print(a) a = np.arange(10) s = slice(2,7,2) # 从索引 2 开始到索引 7 停止,间隔为2 print (a[s]) a = np.arange(10) s = a[2:7:2] print(s) a = np.arange(6).reshape(2,3) for x in np.nditer(a.T): print (x, end=", " ) print ('\n') for x in np.nditer(a.T.copy(order='C')): print (x, end=", " ) print ('\n') a = np.arange(0,60,5) a = a.reshape(3,4) print ('原始数组是:') print (a) print ('\n') for x in np.nditer(a, op_flags=['readwrite']): x[...] = 2*x print ('修改后的数组是:') print (a) ... from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y) plt.show() x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y,"ob") plt.show() # 计算正弦曲线上点的 x 和 y 坐标 x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("sine wave form") # 使用 matplotlib 来绘制点 plt.plot(x, y) plt.show() x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = 'center') plt.bar(x2, y2, color = 'g', align = 'center') plt.title('Bar graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show() ```
github_jupyter
# Stereo Images ``` import matplotlib.pyplot as plt imA = plt.imread("StereoLeft.jpg") imB = plt.imread("StereoRight.jpg") ``` ## Setting up ``` import cameratransform as ct cam1 = ct.Camera(ct.RectilinearProjection(focallength_px=3863.64, image=[4608, 2592])) cam2 = ct.Camera(cam1.projection) cam_group = ct.CameraGroup(cam1.projection, (cam1.orientation, cam2.orientation)) ``` ``` baseline = 0.87 ``` ``` cam1.tilt_deg = 90 cam1.heading_deg = 35 cam1.roll_deg = 0 cam1.pos_x_m = 0 cam1.pos_y_m = 0 cam1.elevation_m = 0 cam2.tilt_deg = 90 cam2.heading_deg = -18 cam2.roll_deg = 0 cam2.pos_x_m = baseline cam2.pos_y_m = 0 cam2.elevation_m = 0 ``` ## Fitting ``` import numpy as np corresponding1 = np.array([[1035.19720133, 1752.47539918], [1191.16681219, 1674.08229634], [1342.64515152, 1595.28089609], [1487.18243488, 1525.87033629], [1623.55377003, 1456.86807389], [1753.39234661, 1391.94878561], [1881.18943613, 1331.92906624], [2002.45376709, 1275.17572617], [2119.63512393, 1220.46387315], [2229.46712739, 1167.79350718], [1132.21312835, 1106.84930585], [ 902.38609626, 1016.70756572], [1594.61961207, 628.61640974], [1794.85813404, 704.30794726], [1791.41760961, 663.70975895], [1956.56278237, 634.80935372], [2121.70795513, 600.40410939], [2288.22933766, 571.50370416], [2439.61241269, 544.66761359], [2583.42633397, 517.14341813], [2736.18561877, 488.93111778], [2876.55901561, 462.7831321 ], [3010.05136359, 437.3232513 ], [3144.23181646, 413.92768515], [3270.84311557, 393.28453856], [3393.32578537, 369.88897242], [2688.73357512, 1033.7464922 ], [2885.97789523, 1144.56386559], [3068.37586866, 1053.89510554], [2870.60132189, 952.09158548], [3237.51817542, 641.90898531], [3288.95016212, 879.98075878], [4105.49922925, 943.60795881], [3965.51938917, 692.28051867], [4037.41700677, 1135.08413333], [3253.6366414 , 1071.87603935], [3769.95210584, 1204.30954628], [4207.84687809, 1265.15387253], [3808.67122255, 1451.37438621], [3587.10046207, 1264.66938952], [3639.1604923 , 1353.23128002]]) corresponding2 = np.array([[ 352.50914077, 801.67993473], [ 460.08683446, 810.68133359], [ 570.95772285, 820.12182507], [ 682.48725018, 829.56231656], [ 797.35908021, 838.80579923], [ 908.18086062, 848.66284585], [1020.80811952, 858.76197628], [1135.19174893, 870.61747721], [1249.57537835, 882.03388552], [1365.71537827, 893.45029383], [ 911.70331034, 537.73870329], [ 956.46082091, 454.7508191 ], [1718.73717286, 432.37206381], [1706.61534708, 518.62351648], [2062.64027012, 573.54205381], [2203.84185338, 600.78475058], [2355.65939432, 631.55257909], [2518.58129093, 665.72644033], [2673.15840747, 699.10556061], [2837.669786 , 733.27942185], [3018.47335419, 768.64539453], [3202.45588621, 807.58770152], [3386.83578872, 844.9405266 ], [3584.72628753, 889.04864983], [3786.59049113, 932.3620321 ], [3991.63365858, 976.47015533], [2525.23601839, 1218.44516641], [2474.07408151, 1366.28811638], [2773.14569785, 1406.5405226 ], [2806.62667125, 1256.44042836], [3392.99303531, 1137.69520116], [2908.10263735, 1298.38150822], [3615.97183145, 1832.82274977], [4128.46912797, 1593.56296216], [3558.36872853, 2064.51618063], [2885.45082314, 1509.32652806], [3106.67717295, 1903.49557987], [3439.6617577 , 2276.44773767], [2628.22670423, 2051.78724561], [2789.70873377, 1806.36653735], [2665.39954766, 1885.90842814]]) cam_group.addPointCorrespondenceInformation(corresponding1, corresponding2) ``` ``` trace = cam_group.metropolis([ ct.FitParameter("C0_heading_deg", lower=0, upper=45, value=15), ct.FitParameter("C0_roll_deg", lower=-5, upper=5, value=0), ct.FitParameter("C1_tilt_deg", lower=45, upper=135, value=85), ct.FitParameter("C1_heading_deg", lower=-45, upper=0, value=-15), ct.FitParameter("C1_roll_deg", lower=-5, upper=5, value=0) ], iterations=1e6) ``` ``` trace[::100].to_csv("trace_stereo.csv", index=False) ``` ``` import pandas as pd trace = pd.read_csv("trace_stereo.csv") cam_group.set_trace(trace) ``` ``` cam_group.plotTrace() ``` ## Measuring ``` points1_start = np.array([[4186.75025841, 1275.33146571], [2331.92641872, 1019.27786453], [2001.20914719, 644.51861935], [1133.13081198, 1109.00803712], [ 900.20742144, 1016.83613865], [3287.47982902, 882.47189246], [3965.52607095, 693.78282123], [2689.04269923, 1033.94065467], [2889.82546079, 1144.44899631]]) points1_end = np.array([[3833.11271185, 1441.03505624], [2234.96105241, 1095.94815417], [2141.25664041, 614.81157533], [1797.43541128, 705.61811479], [1594.1321895 , 630.02825115], [4107.48373669, 942.87002974], [3238.54411195, 640.438481 ], [2868.55390207, 951.44851233], [3070.37430064, 1053.65575788]]) points2_start = np.array([[3390.15132692, 2262.6779465 ], [2312.57037143, 1067.65991742], [2112.03817032, 583.67614881], [ 910.64487701, 538.92782709], [ 955.7855831 , 454.96068822], [2907.87901391, 1297.11142789], [4125.81321176, 1596.76190514], [2524.07911816, 1219.84947435], [2472.59638039, 1365.81424465]]) points2_end = np.array([[2674.06029559, 2066.93032418], [2136.89506898, 1071.98893465], [2200.59552941, 598.28354825], [1706.9610645 , 517.94260225], [1718.87393798, 432.45627336], [3612.29928906, 1832.37417555], [3393.60277139, 1137.62004484], [2807.91089842, 1255.11024902], [2773.34835691, 1405.2303788 ]]) ``` ``` points_start_3D = cam_group.spaceFromImages(points1_start, points2_start) points_end_3D = cam_group.spaceFromImages(points1_end, points2_end) distances = np.linalg.norm(points_end_3D-points_start_3D, axis=-1) print(distances) ``` ``` # the first distance is known to be 14cm scale = 0.14/distances[0] # we use this ratio to scale the space cam_group.scaleSpace(scale) ```
github_jupyter
<a href="https://colab.research.google.com/github/cxbxmxcx/EvolutionaryDeepLearning/blob/main/EDL_6_5_Keras_GA.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Original source https://github.com/zinsmatt/Neural-Network-Numpy/blob/master/neural-network.py """ Created on Thu Nov 15 20:42:52 2018 @author: matthieu """ ``` #@title Install DEAP !pip install deap --quiet #@title Imports import tensorflow as tf import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib.pyplot as plt from IPython.display import clear_output #DEAP from deap import algorithms from deap import base from deap import benchmarks from deap import creator from deap import tools import random #@title Dataset Parameters { run: "auto" } mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() X, Y = x_train / 255.0, y_train plt.imshow(X[0]) print(Y[0]) #@title Define Keras Model middle_layer = 128 #@param {type:"slider", min:16, max:128, step:2} model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(middle_layer, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) optimizer = tf.keras.optimizers.Adam(learning_rate=.001) model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() trainableParams = np.sum([np.prod(v.get_shape()) for v in model.trainable_weights]) print(f"Trainable parameters: {trainableParams}") def score_model(): y_hat = model.predict(x_test) acc = [np.argmax(y)==y_test[i] for i,y in enumerate(y_hat)] return sum(acc)/len(acc) def print_parameters(): for layer in model.layers: for na in layer.get_weights(): print(na) def set_parameters(individual): idx = 0 tensors=[] for layer in model.layers: for na in layer.get_weights(): size = na.size sh = na.shape t = individual[idx:idx+size] t = np.array(t) t = np.reshape(t, sh) idx += size tensors.append(t) model.set_weights(tensors) individual = np.random.rand(trainableParams) set_parameters(individual) print(score_model()) print_parameters() #@title Setting up the Creator creator.create("FitnessMax", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) #@title Create Individual and Population def uniform(low, up, size=None): try: return [random.uniform(a, b) for a, b in zip(low, up)] except TypeError: return [random.uniform(a, b) for a, b in zip([low] * size, [up] * size)] toolbox = base.Toolbox() toolbox.register("attr_float", uniform, -1, 1, trainableParams) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.attr_float) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("select", tools.selTournament, tournsize=5) def customBlend(ind1, ind2): for i, (x1, x2) in enumerate(zip(ind1, ind2)): ind1[i] = (x1 + x2) / 2 ind2[i] = (x1 + x2) / 2 return ind1, ind2 #toolbox.register("mate", tools.cxBlend, alpha=.5) toolbox.register("mate", customBlend) toolbox.register("mutate", tools.mutGaussian, mu=0.0, sigma=.1, indpb=.25) def evaluate(individual): set_parameters(individual) print('.', end='') return 1./score_model(), toolbox.register("evaluate", evaluate) #@title Optimize the Weights { run: "auto" } MU = 25 #@param {type:"slider", min:5, max:1000, step:5} NGEN = 1000 #@param {type:"slider", min:100, max:1000, step:10} RGEN = 10 #@param {type:"slider", min:1, max:100, step:1} CXPB = .6 MUTPB = .3 random.seed(64) pop = toolbox.population(n=MU) hof = tools.HallOfFame(1) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("std", np.std) stats.register("min", np.min) stats.register("max", np.max) from sklearn.metrics import classification_report best = None history = [] for g in range(NGEN): pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=CXPB, mutpb=MUTPB, ngen=RGEN, stats=stats, halloffame=hof, verbose=False) best = hof[0] clear_output() print(f"Gen ({(g+1)*RGEN})") history.extend([1/l["min"] for l in logbook]) plt.plot(history) plt.show() set_parameters(best) accuracy = score_model() print("Best Neural Network accuracy : ", accuracy) if accuracy > .99999: #stop condition break y_pred = model.predict(x_test) y_pred = np.argmax(y_pred, axis=1) print(classification_report(y_test, y_pred)) ```
github_jupyter
# Predicting prices with a single-asset regression model ## Preparing the independent and target variables ``` from alpha_vantage.timeseries import TimeSeries # Update your Alpha Vantage API key here... ALPHA_VANTAGE_API_KEY = 'PZ2ISG9CYY379KLI' ts = TimeSeries(key=ALPHA_VANTAGE_API_KEY, output_format='pandas') df_jpm, meta_data = ts.get_daily_adjusted( symbol='JPM', outputsize='full') df_gs, meta_data = ts.get_daily_adjusted( symbol='GS', outputsize='full') import pandas as pd df_x = pd.DataFrame({'GS': df_gs['5. adjusted close']}) jpm_prices = df_jpm['5. adjusted close'] ``` ## Writing the linear regression model ``` from sklearn.linear_model import LinearRegression class LinearRegressionModel(object): def __init__(self): self.df_result = pd.DataFrame(columns=['Actual', 'Predicted']) def get_model(self): return LinearRegression(fit_intercept=False) def learn(self, df, ys, start_date, end_date, lookback_period=20): model = self.get_model() for date in df[start_date:end_date].index: # Fit the model x = self.get_prices_since(df, date, lookback_period) y = self.get_prices_since(ys, date, lookback_period) model.fit(x, y.ravel()) # Predict the current period x_current = df.loc[date].values [y_pred] = model.predict([x_current]) # Store predictions new_index = pd.to_datetime(date, format='%Y-%m-%d') y_actual = ys.loc[date] self.df_result.loc[new_index] = [y_actual, y_pred] def get_prices_since(self, df, date_since, lookback): index = df.index.get_loc(date_since) return df.iloc[index-lookback:index] linear_reg_model = LinearRegressionModel() linear_reg_model.learn(df_x, jpm_prices, start_date='2018', end_date='2019', lookback_period=20) %matplotlib inline linear_reg_model.df_result.plot( title='JPM prediction by OLS', style=['-', '--'], figsize=(12,8)); ``` ## Risk metrics for measuring prediction performance ### Mean absolute error (MAE) as a risk metric ``` from sklearn.metrics import mean_absolute_error actual = linear_reg_model.df_result['Actual'] predicted = linear_reg_model.df_result['Predicted'] mae = mean_absolute_error(actual, predicted) print('mean absolute error:', mae) ``` #### Mean squared error (MSE) as a risk metric ``` from sklearn.metrics import mean_squared_error mse = mean_squared_error(actual, predicted) print('mean squared error:', mse) ``` ### Explained variance score as a risk metric ``` from sklearn.metrics import explained_variance_score eva = explained_variance_score(actual, predicted) print('explained variance score:', eva) ``` ### R<sup>2</sup> as a risk metric ``` from sklearn.metrics import r2_score r2 = r2_score(actual, predicted) print('r2 score:', r2) ``` ## Ridge regression ``` from sklearn.linear_model import Ridge class RidgeRegressionModel(LinearRegressionModel): def get_model(self): return Ridge(alpha=.5) ridge_reg_model = RidgeRegressionModel() ridge_reg_model.learn(df_x, jpm_prices, start_date='2018', end_date='2019', lookback_period=20) from sklearn.metrics import ( accuracy_score, mean_absolute_error, explained_variance_score, r2_score ) def print_regression_metrics(df_result): actual = list(df_result['Actual']) predicted = list(df_result['Predicted']) print('mean_absolute_error:', mean_absolute_error(actual, predicted)) print('mean_squared_error:', mean_squared_error(actual, predicted)) print('explained_variance_score:', explained_variance_score(actual, predicted)) print('r2_score:', r2_score(actual, predicted)) print_regression_metrics(ridge_reg_model.df_result) ``` # Predicting returns with a cross-asset momentum model ## Preparing the independent variables ``` df_spx, meta_data = ts.get_daily_adjusted( symbol='SPX', outputsize='full') df_gld, meta_data = ts.get_daily_adjusted( symbol='GLD', outputsize='full') df_dxy, dxy_meta_data = ts.get_daily_adjusted( symbol='UUP', outputsize='full') df_ief, meta_data = ts.get_daily_adjusted( symbol='IEF', outputsize='full') import pandas as pd df_assets = pd.DataFrame({ 'SPX': df_spx['5. adjusted close'], 'GLD': df_gld['5. adjusted close'], 'UUP': df_dxy['5. adjusted close'], 'IEF': df_ief['5. adjusted close'], }).dropna() df_assets_1m = df_assets.pct_change(periods=20) df_assets_1m.columns = ['%s_1m'%col for col in df_assets.columns] df_assets_3m = df_assets.pct_change(periods=60) df_assets_3m.columns = ['%s_3m'%col for col in df_assets.columns] df_assets_6m = df_assets.pct_change(periods=120) df_assets_6m.columns = ['%s_6m'%col for col in df_assets.columns] df_assets_12m = df_assets.pct_change(periods=240) df_assets_12m.columns = ['%s_12m'%col for col in df_assets.columns] df_lagged = df_assets_1m.join(df_assets_3m)\ .join(df_assets_6m)\ .join(df_assets_12m)\ .dropna() df_lagged.info() ``` ## Preparing the target variables ``` y = jpm_prices.pct_change().dropna() multi_linear_model = LinearRegressionModel() multi_linear_model.learn(df_lagged, y, start_date='2018', end_date='2019', lookback_period=10) multi_linear_model.df_result.plot( title='JPM actual versus predicted percentage returns', style=['-', '--'], figsize=(12,8)); print_regression_metrics(multi_linear_model.df_result) ``` ## An ensemble of decision trees ### Bagging regressor ``` from sklearn.ensemble import BaggingRegressor class BaggingRegressorModel(LinearRegressionModel): def get_model(self): return BaggingRegressor(n_estimators=20, random_state=0) bagging = BaggingRegressorModel() bagging.learn(df_lagged, y, start_date='2018', end_date='2019', lookback_period=10) print_regression_metrics(bagging.df_result) ``` # Predicting trends with classification-based machine learning ## Preparing the target variables ``` import numpy as np y_direction = y >= 0 y_direction.head(3) flags = list(y_direction.unique()) flags.sort() print(flags) ``` ## Preparing the dataset of multiple assets as input variables ``` df_input = df_assets_1m.join(df_assets_3m).dropna() df_input.info() ``` ## Logistic regression ``` from sklearn.linear_model import LogisticRegression class LogisticRegressionModel(LinearRegressionModel): def get_model(self): return LogisticRegression(solver='lbfgs') logistic_reg_model = LogisticRegressionModel() logistic_reg_model.learn(df_input, y_direction, start_date='2018', end_date='2019', lookback_period=100) logistic_reg_model.df_result.head() ``` ### Risk metrics for measuring classification-based predictions ### Confusion matrix ``` from sklearn.metrics import confusion_matrix df_result = logistic_reg_model.df_result actual = list(df_result['Actual']) predicted = list(df_result['Predicted']) matrix = confusion_matrix(actual, predicted) print(matrix) %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt plt.subplots(figsize=(12,8)) sns.heatmap(matrix.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=flags, yticklabels=flags) plt.xlabel('Actual') plt.ylabel('Predicted') plt.title('JPM percentage returns 2018'); ``` ### Accuracy score ``` from sklearn.metrics import accuracy_score print('accuracy_score:', accuracy_score(actual, predicted)) ``` ### Precision score ``` from sklearn.metrics import precision_score print('precision_score:', precision_score(actual, predicted)) ``` ### Recall score ``` from sklearn.metrics import recall_score print('recall_score:', recall_score(actual, predicted)) ``` ### F1 Score ``` from sklearn.metrics import f1_score print('f1_score:', f1_score(actual, predicted)) ``` ## Support Vector Classifier ``` from sklearn.svm import SVC class SVCModel(LogisticRegressionModel): def get_model(self): return SVC(C=1000, gamma='auto') svc_model = SVCModel() svc_model.learn(df_input, y_direction, start_date='2018', end_date='2019', lookback_period=100) df_result = svc_model.df_result actual = list(df_result['Actual']) predicted = list(df_result['Predicted']) print('accuracy_score:', accuracy_score(actual, predicted)) print('precision_score:', precision_score(actual, predicted)) print('recall_score:', recall_score(actual, predicted)) print('f1_score:', f1_score(actual, predicted)) ```
github_jupyter
# Training Neural Networks The network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten digits to class probabilities. The power of neural networks is that we can train them to approximate this function, and basically any function given enough data and compute time. <img src="assets/function_approx.png" width=500px> At first the network is naive, it doesn't know the function mapping the inputs to the outputs. We train the network by showing it examples of real data, then adjusting the network parameters such that it approximates this function. To find these parameters, we need to know how poorly the network is predicting the real outputs. For this we calculate a **loss function** (also called the cost), a measure of our prediction error. For example, the mean squared loss is often used in regression and binary classification problems $$ \large \ell = \frac{1}{2n}\sum_i^n{\left(y_i - \hat{y}_i\right)^2} $$ where $n$ is the number of training examples, $y_i$ are the true labels, and $\hat{y}_i$ are the predicted labels. By minimizing this loss with respect to the network parameters, we can find configurations where the loss is at a minimum and the network is able to predict the correct labels with high accuracy. We find this minimum using a process called **gradient descent**. The gradient is the slope of the loss function and points in the direction of fastest change. To get to the minimum in the least amount of time, we then want to follow the gradient (downwards). You can think of this like descending a mountain by following the steepest slope to the base. <img src='assets/gradient_descent.png' width=350px> ## Backpropagation For single layer networks, gradient descent is straightforward to implement. However, it's more complicated for deeper, multilayer neural networks like the one we've built. Complicated enough that it took about 30 years before researchers figured out how to train multilayer networks. Training multilayer networks is done through **backpropagation** which is really just an application of the chain rule from calculus. It's easiest to understand if we convert a two layer network into a graph representation. <img src='assets/backprop_diagram.png' width=550px> In the forward pass through the network, our data and operations go from bottom to top here. We pass the input $x$ through a linear transformation $L_1$ with weights $W_1$ and biases $b_1$. The output then goes through the sigmoid operation $S$ and another linear transformation $L_2$. Finally we calculate the loss $\ell$. We use the loss as a measure of how bad the network's predictions are. The goal then is to adjust the weights and biases to minimize the loss. To train the weights with gradient descent, we propagate the gradient of the loss backwards through the network. Each operation has some gradient between the inputs and outputs. As we send the gradients backwards, we multiply the incoming gradient with the gradient for the operation. Mathematically, this is really just calculating the gradient of the loss with respect to the weights using the chain rule. $$ \large \frac{\partial \ell}{\partial W_1} = \frac{\partial L_1}{\partial W_1} \frac{\partial S}{\partial L_1} \frac{\partial L_2}{\partial S} \frac{\partial \ell}{\partial L_2} $$ **Note:** I'm glossing over a few details here that require some knowledge of vector calculus, but they aren't necessary to understand what's going on. We update our weights using this gradient with some learning rate $\alpha$. $$ \large W^\prime_1 = W_1 - \alpha \frac{\partial \ell}{\partial W_1} $$ The learning rate $\alpha$ is set such that the weight update steps are small enough that the iterative method settles in a minimum. ## Losses in PyTorch Let's start by seeing how we calculate the loss with PyTorch. Through the `nn` module, PyTorch provides losses such as the cross-entropy loss (`nn.CrossEntropyLoss`). You'll usually see the loss assigned to `criterion`. As noted in the last part, with a classification problem such as MNIST, we're using the softmax function to predict class probabilities. With a softmax output, you want to use cross-entropy as the loss. To actually calculate the loss, you first define the criterion then pass in the output of your network and the correct labels. Something really important to note here. Looking at [the documentation for `nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss), > This criterion combines `nn.LogSoftmax()` and `nn.NLLLoss()` in one single class. > > The input is expected to contain scores for each class. This means we need to pass in the raw output of our network into the loss, not the output of the softmax function. This raw output is usually called the *logits* or *scores*. We use the logits because softmax gives you probabilities which will often be very close to zero or one but floating-point numbers can't accurately represent values near zero or one ([read more here](https://docs.python.org/3/tutorial/floatingpoint.html)). It's usually best to avoid doing calculations with probabilities, typically we use log-probabilities. ``` # The MNIST datasets are hosted on yann.lecun.com that has moved under CloudFlare protection # Run this script to enable the datasets download # Reference: https://github.com/pytorch/vision/issues/1938 from six.moves import urllib opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib.request.install_opener(opener) import torch from torch import nn import torch.nn.functional as F from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)), ]) # Download and load the training data trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) ``` ### Note If you haven't seen `nn.Sequential` yet, please finish the end of the Part 2 notebook. ``` # Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10)) # Define the loss criterion = nn.CrossEntropyLoss() # Get our data dataiter = iter(trainloader) images, labels = next(dataiter) # Flatten images images = images.view(images.shape[0], -1) # Forward pass, get our logits logits = model(images) # Calculate the loss with the logits and the labels loss = criterion(logits, labels) print(loss) ``` In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, you want to use the negative log likelihood loss, `nn.NLLLoss` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss)). >**Exercise:** Build a model that returns the log-softmax as the output and calculate the loss using the negative log likelihood loss. Note that for `nn.LogSoftmax` and `F.log_softmax` you'll need to set the `dim` keyword argument appropriately. `dim=0` calculates softmax across the rows, so each column sums to 1, while `dim=1` calculates across the columns so each row sums to 1. Think about what you want the output to be and choose `dim` appropriately. ``` # TODO: Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) # TODO: Define the loss criterion = nn.NLLLoss() ### Run this to check your work # Get our data dataiter = iter(trainloader) images, labels = next(dataiter) # Flatten images images = images.view(images.shape[0], -1) # Forward pass, get our logits logits = model(images) # Calculate the loss with the logits and the labels loss = criterion(logits, labels) print(loss) ``` ## Autograd Now that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operations performed on tensors, then going backwards through those operations, calculating gradients along the way. To make sure PyTorch keeps track of operations on a tensor and calculates the gradients, you need to set `requires_grad = True` on a tensor. You can do this at creation with the `requires_grad` keyword, or at any time with `x.requires_grad_(True)`. You can turn off gradients for a block of code with the `torch.no_grad()` content: ```python x = torch.zeros(1, requires_grad=True) >>> with torch.no_grad(): ... y = x * 2 >>> y.requires_grad False ``` Also, you can turn on or off gradients altogether with `torch.set_grad_enabled(True|False)`. The gradients are computed with respect to some variable `z` with `z.backward()`. This does a backward pass through the operations that created `z`. ``` x = torch.randn(2,2, requires_grad=True) print(x) y = x**2 print(y) ``` Below we can see the operation that created `y`, a power operation `PowBackward0`. ``` ## grad_fn shows the function that generated this variable print(y.grad_fn) ``` The autograd module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean. ``` z = y.mean() print(z) ``` You can check the gradients for `x` and `y` but they are empty currently. ``` print(x.grad) ``` To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x` $$ \frac{\partial z}{\partial x} = \frac{\partial}{\partial x}\left[\frac{1}{n}\sum_i^n x_i^2\right] = \frac{x}{2} $$ ``` z.backward() print(x.grad) print(x/2) ``` These gradients calculations are particularly useful for neural networks. For training we need the gradients of the cost with respect to the weights. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the gradients we can make a gradient descent step. ## Loss and Autograd together When we create a network with PyTorch, all of the parameters are initialized with `requires_grad = True`. This means that when we calculate the loss and call `loss.backward()`, the gradients for the parameters are calculated. These gradients are used to update the weights with gradient descent. Below you can see an example of calculating the gradients using a backwards pass. ``` # Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() dataiter = iter(trainloader) images, labels = next(dataiter) images = images.view(images.shape[0], -1) logits = model(images) loss = criterion(logits, labels) print('Before backward pass: \n', model[0].weight.grad) loss.backward() print('After backward pass: \n', model[0].weight.grad) ``` ## Training the network! There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to define an optimizer below. ``` from torch import optim # Optimizers require the parameters to optimize and a learning rate optimizer = optim.SGD(model.parameters(), lr=0.01) ``` Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch: * Make a forward pass through the network * Use the network output to calculate the loss * Perform a backward pass through the network with `loss.backward()` to calculate the gradients * Take a step with the optimizer to update the weights Below I'll go through one training step and print out the weights and gradients so you can see how it changes. Note that I have a line of code `optimizer.zero_grad()`. When you do multiple backwards passes with the same parameters, the gradients are accumulated. This means that you need to zero the gradients on each training pass or you'll retain gradients from previous training batches. ``` print('Initial weights - ', model[0].weight) dataiter = iter(trainloader) images, labels = next(dataiter) images.resize_(64, 784) # Clear the gradients, do this because gradients are accumulated optimizer.zero_grad() # Forward pass, then backward pass, then update weights output = model(images) loss = criterion(output, labels) loss.backward() print('Gradient -', model[0].weight.grad) # Take an update step and view the new weights optimizer.step() print('Updated weights - ', model[0].weight) ``` ### Training for real Now we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll be doing a training pass where we calculate the loss, do a backwards pass, and update the weights. >**Exercise:** Implement the training pass for our network. If you implemented it correctly, you should see the training loss drop with each epoch. ``` ## Your solution here model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.003) epochs = 5 for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten MNIST images into a 784 long vector images = images.view(images.shape[0], -1) # TODO: Training pass optimizer.zero_grad() output = model(images) loss = criterion(output, labels) loss.backward() optimizer.step() running_loss += loss.item() else: print(f"Training loss: {running_loss/len(trainloader)}") ``` With the network trained, we can check out it's predictions. ``` %matplotlib inline import helper dataiter = iter(trainloader) images, labels = next(dataiter) img = images[0].view(1, 784) # Turn off gradients to speed up this part with torch.no_grad(): logps = model(img) # Output of the network are log-probabilities, need to take exponential for probabilities ps = torch.exp(logps) helper.view_classify(img.view(1, 28, 28), ps) ``` Now our network is brilliant. It can accurately predict the digits in our images. Next up you'll write the code for training a neural network on a more complex dataset.
github_jupyter
**6장 – 결정 트리** _이 노트북은 6장에 있는 모든 샘플 코드와 연습문제 해답을 가지고 있습니다._ <table align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/rickiepark/handson-ml2/blob/master/06_decision_trees.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />구글 코랩에서 실행하기</a> </td> </table> # 설정 먼저 몇 개의 모듈을 임포트합니다. 맷플롯립 그래프를 인라인으로 출력하도록 만들고 그림을 저장하는 함수를 준비합니다. 또한 파이썬 버전이 3.5 이상인지 확인합니다(파이썬 2.x에서도 동작하지만 곧 지원이 중단되므로 파이썬 3을 사용하는 것이 좋습니다). 사이킷런 버전이 0.20 이상인지도 확인합니다. ``` # 파이썬 ≥3.5 필수 import sys assert sys.version_info >= (3, 5) # 사이킷런 ≥0.20 필수 import sklearn assert sklearn.__version__ >= "0.20" # 공통 모듈 임포트 import numpy as np import os # 노트북 실행 결과를 동일하게 유지하기 위해 np.random.seed(42) # 깔끔한 그래프 출력을 위해 %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt mpl.rc('axes', labelsize=14) mpl.rc('xtick', labelsize=12) mpl.rc('ytick', labelsize=12) # 그림을 저장할 위치 PROJECT_ROOT_DIR = "." CHAPTER_ID = "decision_trees" IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID) os.makedirs(IMAGES_PATH, exist_ok=True) def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300): path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension) print("그림 저장:", fig_id) if tight_layout: plt.tight_layout() plt.savefig(path, format=fig_extension, dpi=resolution) ``` # 훈련과 시각화 ``` from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier iris = load_iris() X = iris.data[:, 2:] # 꽃잎 길이와 너비 y = iris.target tree_clf = DecisionTreeClassifier(max_depth=2, random_state=42) tree_clf.fit(X, y) from graphviz import Source from sklearn.tree import export_graphviz export_graphviz( tree_clf, out_file=os.path.join(IMAGES_PATH, "iris_tree.dot"), feature_names=iris.feature_names[2:], class_names=iris.target_names, rounded=True, filled=True ) Source.from_file(os.path.join(IMAGES_PATH, "iris_tree.dot")) ``` **식 6-1: 지니 불순도** $ G_i = 1 - \sum\limits_{k=1}^{n}{{p_{i,k}}^2} $ **식 6-3: 엔트로피 불순도** $ H_i = -\sum\limits_{k=1 \atop p_{i,k} \ne 0}^{n}{{p_{i,k}}\log_2(p_{i,k})} $ **식 6-2: 분류에 대한 CART 비용 함수** $ \begin{split} &J(k, t_k) = \dfrac{m_{\text{left}}}{m}G_\text{left} + \dfrac{m_{\text{right}}}{m}G_{\text{right}}\\ &\text{여기에서 }\begin{cases} G_\text{left/right} \text{는 왼쪽/오른쪽 서브셋의 불순도}\\ m_\text{left/right} \text{는 왼쪽/오른쪽 서브셋의 샘플 수} \end{cases} \end{split} $ ``` from matplotlib.colors import ListedColormap def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True): x1s = np.linspace(axes[0], axes[1], 100) x2s = np.linspace(axes[2], axes[3], 100) x1, x2 = np.meshgrid(x1s, x2s) X_new = np.c_[x1.ravel(), x2.ravel()] y_pred = clf.predict(X_new).reshape(x1.shape) custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) if not iris: custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) if plot_training: plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris setosa") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris versicolor") plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris virginica") plt.axis(axes) if iris: plt.xlabel("Petal length", fontsize=14) plt.ylabel("Petal width", fontsize=14) else: plt.xlabel(r"$x_1$", fontsize=18) plt.ylabel(r"$x_2$", fontsize=18, rotation=0) if legend: plt.legend(loc="lower right", fontsize=14) plt.figure(figsize=(8, 4)) plot_decision_boundary(tree_clf, X, y) plt.plot([2.45, 2.45], [0, 3], "k-", linewidth=2) plt.plot([2.45, 7.5], [1.75, 1.75], "k--", linewidth=2) plt.plot([4.95, 4.95], [0, 1.75], "k:", linewidth=2) plt.plot([4.85, 4.85], [1.75, 3], "k:", linewidth=2) plt.text(1.40, 1.0, "Depth=0", fontsize=15) plt.text(3.2, 1.80, "Depth=1", fontsize=13) plt.text(4.05, 0.5, "(Depth=2)", fontsize=11) save_fig("decision_tree_decision_boundaries_plot") plt.show() ``` # 클래스와 클래스 확률을 예측하기 ``` tree_clf.predict_proba([[5, 1.5]]) tree_clf.predict([[5, 1.5]]) ``` # 높은 분산 (회전 같은) 데이터셋의 작은 변화가 매우 다른 결정 트리를 만들었습니다. 사이킷런에서 사용하는 CART 훈련 알고리즘은 확률적이기 때문에 동일한 데이터에서 같은 모델을 훈련하여 매번 매우 다른 모델을 만들 수 있습니다. 이를 확인하기 위해 `random_state`를 다른 값으로 지정해 보겠습니다: ``` tree_clf_tweaked = DecisionTreeClassifier(max_depth=2, random_state=40) tree_clf_tweaked.fit(X, y) plt.figure(figsize=(8, 4)) plot_decision_boundary(tree_clf_tweaked, X, y, legend=False) plt.plot([0, 7.5], [0.8, 0.8], "k-", linewidth=2) plt.plot([0, 7.5], [1.75, 1.75], "k--", linewidth=2) plt.text(1.0, 0.9, "Depth=0", fontsize=15) plt.text(1.0, 1.80, "Depth=1", fontsize=13) save_fig("decision_tree_instability_plot") plt.show() from sklearn.datasets import make_moons Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53) deep_tree_clf1 = DecisionTreeClassifier(random_state=42) deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42) deep_tree_clf1.fit(Xm, ym) deep_tree_clf2.fit(Xm, ym) fig, axes = plt.subplots(ncols=2, figsize=(10, 4), sharey=True) plt.sca(axes[0]) plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.4, -1, 1.5], iris=False) plt.title("No restrictions", fontsize=16) plt.sca(axes[1]) plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.4, -1, 1.5], iris=False) plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14) plt.ylabel("") save_fig("min_samples_leaf_plot") plt.show() angle = np.pi / 180 * 20 rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) Xr = X.dot(rotation_matrix) tree_clf_r = DecisionTreeClassifier(random_state=42) tree_clf_r.fit(Xr, y) plt.figure(figsize=(8, 3)) plot_decision_boundary(tree_clf_r, Xr, y, axes=[0.5, 7.5, -1.0, 1], iris=False) plt.show() np.random.seed(6) Xs = np.random.rand(100, 2) - 0.5 ys = (Xs[:, 0] > 0).astype(np.float32) * 2 angle = np.pi / 4 rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) Xsr = Xs.dot(rotation_matrix) tree_clf_s = DecisionTreeClassifier(random_state=42) tree_clf_s.fit(Xs, ys) tree_clf_sr = DecisionTreeClassifier(random_state=42) tree_clf_sr.fit(Xsr, ys) fig, axes = plt.subplots(ncols=2, figsize=(10, 4), sharey=True) plt.sca(axes[0]) plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) plt.sca(axes[1]) plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) plt.ylabel("") save_fig("sensitivity_to_rotation_plot") plt.show() ``` # 회귀 트리 ``` # 2차식으로 만든 데이터셋 + 잡음 np.random.seed(42) m = 200 X = np.random.rand(m, 1) y = 4 * (X - 0.5) ** 2 y = y + np.random.randn(m, 1) / 10 from sklearn.tree import DecisionTreeRegressor tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) tree_reg.fit(X, y) from sklearn.tree import DecisionTreeRegressor tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) tree_reg1.fit(X, y) tree_reg2.fit(X, y) def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) y_pred = tree_reg.predict(x1) plt.axis(axes) plt.xlabel("$x_1$", fontsize=18) if ylabel: plt.ylabel(ylabel, fontsize=18, rotation=0) plt.plot(X, y, "b.") plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") fig, axes = plt.subplots(ncols=2, figsize=(10, 4), sharey=True) plt.sca(axes[0]) plot_regression_predictions(tree_reg1, X, y) for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): plt.plot([split, split], [-0.2, 1], style, linewidth=2) plt.text(0.21, 0.65, "Depth=0", fontsize=15) plt.text(0.01, 0.2, "Depth=1", fontsize=13) plt.text(0.65, 0.8, "Depth=1", fontsize=13) plt.legend(loc="upper center", fontsize=18) plt.title("max_depth=2", fontsize=14) plt.sca(axes[1]) plot_regression_predictions(tree_reg2, X, y, ylabel=None) for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): plt.plot([split, split], [-0.2, 1], style, linewidth=2) for split in (0.0458, 0.1298, 0.2873, 0.9040): plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) plt.text(0.3, 0.5, "Depth=2", fontsize=13) plt.title("max_depth=3", fontsize=14) save_fig("tree_regression_plot") plt.show() export_graphviz( tree_reg1, out_file=os.path.join(IMAGES_PATH, "regression_tree.dot"), feature_names=["x1"], rounded=True, filled=True ) Source.from_file(os.path.join(IMAGES_PATH, "regression_tree.dot")) tree_reg1 = DecisionTreeRegressor(random_state=42) tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) tree_reg1.fit(X, y) tree_reg2.fit(X, y) x1 = np.linspace(0, 1, 500).reshape(-1, 1) y_pred1 = tree_reg1.predict(x1) y_pred2 = tree_reg2.predict(x1) fig, axes = plt.subplots(ncols=2, figsize=(10, 4), sharey=True) plt.sca(axes[0]) plt.plot(X, y, "b.") plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") plt.axis([0, 1, -0.2, 1.1]) plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", fontsize=18, rotation=0) plt.legend(loc="upper center", fontsize=18) plt.title("No restrictions", fontsize=14) plt.sca(axes[1]) plt.plot(X, y, "b.") plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") plt.axis([0, 1, -0.2, 1.1]) plt.xlabel("$x_1$", fontsize=18) plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) save_fig("tree_regression_regularization_plot") plt.show() ``` # 연습문제 해답 ## 1. to 6. 부록 A 참조. ## 7. _문제: moons 데이터셋에 결정 트리를 훈련시키고 세밀하게 튜닝해보세요._ a. `make_moons(n_samples=1000, noise=0.4)`를 사용해 데이터셋을 생성합니다. `random_state=42`를 지정하여 결과를 일정하게 만듭니다: ``` from sklearn.datasets import make_moons X, y = make_moons(n_samples=10000, noise=0.4, random_state=42) ``` b. 이를 `train_test_split()`을 사용해 훈련 세트와 테스트 세트로 나눕니다 ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` c. `DecisionTreeClassifier`의 최적의 매개변수를 찾기 위해 교차 검증과 함께 그리드 탐색을 수행합니다(`GridSearchCV`를 사용하면 됩니다). 힌트: 여러 가지 `max_leaf_nodes` 값을 시도해보세요. ``` from sklearn.model_selection import GridSearchCV params = {'max_leaf_nodes': list(range(2, 100)), 'min_samples_split': [2, 3, 4]} grid_search_cv = GridSearchCV(DecisionTreeClassifier(random_state=42), params, verbose=1, cv=3) grid_search_cv.fit(X_train, y_train) grid_search_cv.best_estimator_ ``` d. 찾은 매개변수를 사용해 전체 훈련 세트에 대해 모델을 훈련시키고 테스트 세트에서 성능을 측정합니다. 대략 85~87%의 정확도가 나올 것입니다. 기본적으로 `GridSearchCV`는 전체 훈련 세트로 찾은 최적의 모델을 다시 훈련시킵니다(`refit=False`로 지정해서 바꿀 수 있습니다). 그래서 별도로 작업할 필요가 없습니다. 모델의 정확도를 바로 평가할 수 있습니다: ``` from sklearn.metrics import accuracy_score y_pred = grid_search_cv.predict(X_test) accuracy_score(y_test, y_pred) ``` ## 8. _문제: 랜덤 포레스트를 만들어보세요._ a. 이전 연습문제에 이어서, 훈련 세트의 서브셋을 1,000개 생성합니다. 각각은 무작위로 선택된 100개의 샘플을 담고 있습니다. 힌트: 사이킷런의 `ShuffleSplit`을 사용할 수 있습니다. ``` from sklearn.model_selection import ShuffleSplit n_trees = 1000 n_instances = 100 mini_sets = [] rs = ShuffleSplit(n_splits=n_trees, test_size=len(X_train) - n_instances, random_state=42) for mini_train_index, mini_test_index in rs.split(X_train): X_mini_train = X_train[mini_train_index] y_mini_train = y_train[mini_train_index] mini_sets.append((X_mini_train, y_mini_train)) ``` b. 앞에서 찾은 최적의 매개변수를 사용해 각 서브셋에 결정 트리를 훈련시킵니다. 테스트 세트로 이 1,000개의 결정 트리를 평가합니다. 더 작은 데이터셋에서 훈련되었기 때문에 이 결정 트리는 앞서 만든 결정 트리보다 성능이 떨어져 약 80%의 정확도를 냅니다. ``` from sklearn.base import clone forest = [clone(grid_search_cv.best_estimator_) for _ in range(n_trees)] accuracy_scores = [] for tree, (X_mini_train, y_mini_train) in zip(forest, mini_sets): tree.fit(X_mini_train, y_mini_train) y_pred = tree.predict(X_test) accuracy_scores.append(accuracy_score(y_test, y_pred)) np.mean(accuracy_scores) ``` c. 이제 마술을 부릴 차례입니다. 각 테스트 세트 샘플에 대해 1,000개의 결정 트리 예측을 만들고 다수로 나온 예측만 취합니다(사이파이의 `mode()` 함수를 사용할 수 있습니다). 그러면 테스트 세트에 대한 _다수결 예측_이 만들어집니다. ``` Y_pred = np.empty([n_trees, len(X_test)], dtype=np.uint8) for tree_index, tree in enumerate(forest): Y_pred[tree_index] = tree.predict(X_test) from scipy.stats import mode y_pred_majority_votes, n_votes = mode(Y_pred, axis=0) ``` d. 테스트 세트에서 이 예측을 평가합니다. 앞서 만든 모델보다 조금 높은(약 0.5~1.5% 정도) 정확도를 얻게 될 것입니다. 축하합니다. 랜덤 포레스트 분류기를 훈련시켰습니다! ``` accuracy_score(y_test, y_pred_majority_votes.reshape([-1])) ```
github_jupyter
``` import requests import json URL="http://localhost:1234/v1/swagger.json" r = requests.get(url = URL) r res=json.loads(r.content) res["paths"].keys() res["paths"]['/cyndex2/v1/networks/current'] res["paths"] res["paths"]['/diffusion']["get"] paths=res["paths"] url_path='/v1/networks/{networkId}/groups/{groupNodeId}/collapse' #url_path='/cyndex2/v1/networks' url_path='/v1/networks/{networkId}/views/{viewId}/network/{visualProperty}/bypass' url_path="/v1/networks/{networkId}/tables/{tableType}" def write_function(url_path=url_path,paths=paths): function=paths[url_path] all_text="" for request_type in function.keys(): if request_type not in ["get","post","put", "delete"]: print request_type, url_path, "\n\n" else: url_=url_path python_function=function[request_type] f_name=python_function['operationId'] f_desc=python_function['description'] f_desc=f_desc.rstrip("\n") f_desc=f_desc.replace("\n","\n ") parameters=python_function['parameters'] f_para=[] f_para_end=[] f_para_desc=[] f_para_desc_end=[] f_para_not_in_url=[] for p in parameters: pname=p["name"] required=p['required'] if "{"+pname+"}" in url_: url_=url_.replace("{"+pname+"}","'+str(%s)+'" %pname) else: f_para_not_in_url.append(pname) #if not required: #if pname != "body": # print "\n\n!!", request_type, url_path, python_function,"\n\n", pname #f_para.append(pname+"=None") #else: if "description" in p.keys(): pdesc=" :param "+pname+": "+p["description"] if not required: pdesc=pdesc+" -- Not required, can be None" f_para.append(pname) f_para_desc.append(pdesc) else: pdesc=" :param "+pname+": None" if not required: pdesc=pdesc+" -- Not required, can be None" f_para_end.append(pname) f_para_desc_end.append(pdesc) for p in f_para_end: f_para.append(p) for p in f_para_desc_end: f_para_desc.append(p) f_para.append("verbose=None") f_para=", ".join(f_para) f_para_desc.append(" :param verbose: print more") f_para_desc="\n".join(f_para_desc) rets=python_function['responses'] f_returns=[] for r in rets.keys(): r_=r+": "+rets[r]['description'] f_returns.append(r_) # if len(f_returns) > 0: # f_returns="; ".join(f_returns) # else: # f_returns="Nothing" if url_[-1] != ")" : url_=url_ + "'" f_text="def "+f_name+"("+f_para+'):\n """\n '+f_desc+"\n\n"+f_para_desc+'\n' if len(f_returns) > 0: f_text=f_text+ '\n :returns: '+"; ".join(f_returns) f_text=f_text+'\n """\n' if url_.split("/")[1] == "v1": url_=url_.split("/v1/")[1] if url_[:4] != 'str(': url_="'"+url_ url_='self.url+'+url_ else: f_text=f_text+"\n surl=self.url\n sv=surl.split('/')[-1]\n surl=surl.rstrip(sv+'/')" url_=url_.replace('/v1/',"/'+sv+'/") if url_[:4] != 'str(': url_="'"+url_ url_='surl+'+url_ if request_type == "get": if len(f_para_not_in_url) > 0 : PARAMS_GET=[] for p in f_para_not_in_url: PARAMS_GET.append("'"+p+"':"+p) PARAMS_GET=", PARAMS={"+", ".join(PARAMS_GET)+"}" else: PARAMS_GET=", PARAMS=None" f_text=f_text+'\n response=api(url='+url_+PARAMS_GET+', method="GET", verbose=verbose, parse_params=False)\n\treturn response' elif request_type == "delete": f_text=f_text+'\n response=api(url='+url_+', method="DELETE", verbose=verbose)\n\treturn response' elif request_type == "put": if "body" in f_para: f_text=f_text+'\n response=api(url='+url_+', method="PUT", body=body, verbose=verbose)\n\treturn response' else: f_text=f_text+'\n response=api(url='+url_+', method="PUT", verbose=verbose)\n\treturn response' elif request_type == "post": f_para=f_para.split(", ") f_para_=[ s for s in f_para if s != "verbose=None" ] #f_para_=[ s for s in ] PARAMS="PARAMS=set_param([" plabels=[] for p in f_para_: plabels.append("'"+p+"'") plabels=",".join(plabels) PARAMS=PARAMS+plabels+"],["+",".join(f_para_)+"])" f_text=f_text+'\n\t'+PARAMS f_text=f_text+'\n\tresponse=api(url='+url_+', PARAMS=PARAMS, method="POST", verbose=verbose)\n\treturn response' all_text=all_text+"\n"+f_text+"\n\n" return all_text print write_function(url_path=url_path,paths=paths) for p in res["paths"].keys() : ns=p.split("/") print ns if ns[1]=="v1": ns=ns[0] else: ns=ns[1] print ns tmp_out_folder="/Users/jboucas/tmp_out_cytoscape/" for p in res["paths"].keys() : ns=p.split("/") try: if ns[1]=="v1": ns=ns[2] else: ns=ns[1] except: ns="" if ns not in ["enrichmentmap","diffusion","cyndex2","reactomefiviz"]: print ns, p if p not in ["/v1/commands/{namespace}"]: if ns in [""]: #print p #print "*******************" a=write_function(url_path=p,paths=paths) if ns == "": print "py" with open(tmp_out_folder+ns+".py", "a") as fout: try: fout.write( str(a) ) except: print "\n\n********",p,"***********" print a #try: # print p.split("/")[2], "\t", p #except: # print "!!!", p import requests help(requests.put) help(requests.get) - [x] non required parameters to the end of the function - [x] non required parameters in GET are done as params - [x] api( parse_params=True) and False for these special get - [ ] put non required parameters get instructions that they need to go on the body (body needs to be present) ```
github_jupyter
# Analyzing the UncertaintyForest Class by Reproducing Posterior Estimates This set of four tutorials (`uncertaintyforest_running_example.ipynb`, `uncertaintyforest_posteriorestimates.ipynb`, `uncertaintyforest_conditionalentropyestimates.ipynb`, and `uncertaintyforest_mutualinformationestimates.ipynb`) will explain the UncertaintyForest class. After following these tutorials, you should have the ability to run UncertaintyForest on your own machine and generate Figures 1, 2, and 3 from [this paper](https://arxiv.org/pdf/1907.00325.pdf), which help you to visualize a comparison of the estimated posteriors and conditional entropy values for several different algorithms. If you haven't seen it already, take a look at other tutorials to setup and install the ProgLearn package: `installation_guide.ipynb`. *Goal: Run the UncertaintyForest class to produce a figure that compares estimated posteriors for the UncertaintyForest, CART, and IRF algorithms, as in Figure 1 from [this paper](https://arxiv.org/pdf/1907.00325.pdf)* ## Import Required Packages ``` import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.calibration import CalibratedClassifierCV from proglearn.forest import UncertaintyForest from functions.unc_forest_tutorials_functions import estimate_posterior, plot_fig1 ``` ## Specify Parameters ``` # The following are two sets of parameters. # The first are those that were actually used to produce Figure 1. # These take a long time to actually run since there are 6000 data points. # Below those, you'll find some scaled-down parameters so that you can see the results more quickly. # Here are the paper reproduction parameters #n = 6000 #mean = 1 #var = 1 #num_trials = 100 #X_eval = np.linspace(-2, 2, num = 30).reshape(-1, 1) #n_estimators = 300 #num_plotted_trials = 10 # Here are the scaled-down tutorial parameters n = 300 # number of data points mean = 1 # mean of the data var = 1 # variance of the data num_trials = 3 # number of trials to run X_eval = np.linspace(-2, 2, num = 10).reshape(-1, 1) # the evaluation span (over X) for the plot n_estimators = 200 # the number of estimators num_plotted_trials = 2 # the number of "fainter" lines to be displayed on the figure ``` ## Specify Learners Now, we'll specify which learners we'll compare. Figure 1 uses three different learners. ``` # Algorithms used to produce Figure 1 algos = [ { 'instance': RandomForestClassifier(n_estimators = n_estimators), 'label': 'CART', 'title': 'CART Forest', 'color': "#1b9e77", }, { 'instance': CalibratedClassifierCV(base_estimator=RandomForestClassifier(n_estimators = n_estimators // 5), method='isotonic', cv = 5), 'label': 'IRF', 'title': 'Isotonic Reg. Forest', 'color': "#fdae61", }, { 'instance': UncertaintyForest(n_estimators = n_estimators, tree_construction_proportion = 0.4, kappa = 3.0), 'label': 'UF', 'title': 'Uncertainty Forest', 'color': "#F41711", }, ] # Plotting parameters parallel = False ``` ## Generate predicted posteriors Now, we'll run the code to obtain the results that will be displayed in Figure 1. ``` # This is the code that actually generates data and predictions. for algo in algos: algo['predicted_posterior'] = estimate_posterior(algo, n, mean, var, num_trials, X_eval, parallel = parallel) ``` ## Create Figure 1 ``` plot_fig1(algos, num_plotted_trials, X_eval, n, mean, var) ```
github_jupyter
# Quantitative Exercise The goal of this notebook is to practice quantitative data analysis using Numenta Anomaly Benchmark (NAB) dataset on Streaming Outlier Detection algorithm, in particular on SPOT (add reference). We will use three different datasets comprising of data retrieved from real world. ``` import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns from sklearn import preprocessing ``` ## Load Data We load the data directly from the csv files in pandas DataFrames, we check if there are some missing values and finally print a sample of the data ``` df = pd.read_csv('./data/temp_sys_failure.csv') print("Missing values: ", df.isnull().values.any()) df.head() ``` ## Exploratory Data Analysis In this section we will explore the data in more detail. Firstly, we will plot data with different view to understand our dataset. Secondly, we will run our dataset over the SPOT algorithm to find outliers and derive more insights A time series is a sequence of data samples taken in time order with equal time intervals. Time series include many kinds of real experimental data taken from various domains such as finance, medicine and others. Given a time series dataset, data exploration and processing are required to analyze them. ### Descriptive Plotting Basics dataset statistics ``` df.describe() ``` The dataset contains temperature data for a time period of 10 months ``` print(df['timestamp'].min()) print(df['timestamp'].max()) ``` Convert data in the right format, DateTime type and values in Celsius ``` df['timestamp'] = pd.to_datetime(df['timestamp']) df['value'] = (df['value'] - 32) * 5/9 ``` The plot below shows that the average temperature is around the range of [15, 30] but most of points are around 20 ``` df.plot(x='timestamp', y='value', figsize=(10,7), title='Temperature over time', grid=True) ``` Each data sample in a time series must be associated with a unique point in time. This can be achieved by using values of DatetimeIndex type as its index values. ``` df = df.set_index('timestamp') df.index df.sort_index(inplace=True) ``` A time series can be decomposed into components for further analysis, in this case we decide to model it as an additive of base level, trend, seasonality and error. ``` from statsmodels.tsa.seasonal import seasonal_decompose additive = seasonal_decompose(df, model='additive', freq=5) additive_df = pd.concat([additive.seasonal, additive.trend, additive.resid, additive.observed], axis=1) additive_df.columns = ['seasonal', 'trend', 'resid', 'actual_values'] additive_df.head() plt.rcParams.update({'figure.figsize': (10,10)}) additive.plot().suptitle('Additive Decompose') df.reset_index(inplace=True) df.head() df['year'] = df['timestamp'].apply(lambda x : x.year) df['month'] = df['timestamp'].apply(lambda x : x.month) df['day'] = df['timestamp'].apply(lambda x : x.day) df['hour'] = df['timestamp'].apply(lambda x : x.hour) df['minute'] = df['timestamp'].apply(lambda x : x.minute) df.index = df['timestamp'] df.drop(['timestamp'], axis=1, inplace=True) df.head(3) ``` Here, we decided to resample our time series. This means changing the frequency of time series observation. We resampled them by day, week and month. ``` weekly = df['value'].resample('W').mean() monthly = df['value'].resample('M').mean() daily = df['value'].resample('D').mean() daily.plot() weekly.plot() monthly.plot() plt.legend(["daily", "weekly", "monthly"]) df_2 = pd.read_csv('./data/temp_sys_failure.csv') df_2['value'] = (df_2['value'] - 32) * 5/9 mon = df_2['timestamp'] temp = pd.DatetimeIndex(mon) months = pd.Series(temp.month) to_plot = df_2.drop(['timestamp'], axis=1) to_plot = to_plot.join(months) to_plot.plot.scatter(x='value',y='timestamp', figsize=(16,8)) plt.show() ``` ### Outlier detection with SPOT The next step of this quantitative exercise is the research and the study of the outliers. We decided to find the outliers through SPOT algorithm, so after having imported the common libraries, we imported the spot class. In our dataset the indipendent variable is the timestamp in which the temperature is measured. The value of the temperature is our dependent variable because it changes over time. Other two dependent variables are the lower and the upper thresholds. They depend not only on the time, but also on the previous values of the temperature. Our expectation in this part of the analysis is to find some outliers that are caused by sudden increments or decrements of the temperature. ``` import scipy as sp import numpy as np import pandas as pd import matplotlib as mpl import tqdm as tqdm import matplotlib.pyplot as plt from model import spot ``` After having loaded the original dataset, we splitted the timestamp column in date and time in order to have the possibility of creating intervals based on the date. Due to the fact that the 1st January 2014 is in the middle of the dataset, we decided to split the data around this date. The data before the 1st January 2014 are used as initial batch, while the data after are used as streaming data. ``` f = 'https://raw.githubusercontent.com/numenta/NAB/master/data/realKnownCause/ambient_temperature_system_failure.csv' P = pd.read_csv(f) P[['date', 'time']] = P['timestamp'].str.split(' ', 1, expand=True) P['date'] = pd.to_datetime(P['date']) # stream u_data = (P['date'] >= '2014-01-01')# & (P['date'] < '2014-05-21') data = P['value'][u_data].values # initial batch u_init_data = (P['date'] < '2014-01-01') init_data = P['value'][u_init_data].values ``` We set the parameters, initialize the SPOT algorithm and run it. The results are shown in a temporal graph, in which we can see the lower and the upper thresholds in orange, the time series data in blue and the outliers as red points. ``` q = 1e-5 # risk parameter d = 10 # depth s = spot.bidSPOT(q,d) # bidSPOT object s.fit(init_data,data) # data import s.initialize() # initialization step results = s.run() # run s.plot(results) # plot ``` We are intersted only in the data that had been streamed and in particular in the outliers that has been found. So we select only the streamed data and we describe them. We also compute the mean of the thresholds and of the time series. ``` df = P[u_data] df.describe() from statistics import mean print("mean of lower threshold : "+ str(mean(results['lower_thresholds']))) print("mean of temperature : "+ str(mean(df['value']))) print("mean of upper threshold : "+ str(mean(results['upper_thresholds']))) ``` After that, we take only the outliers and we visualize and describe them. ``` out = df.iloc[results['alarms']] display(out) out.describe() ``` We are interested only in outliers, so we create a column in the dataframe that is equal to 1 if the row represents an outlier, 0 otherwise. ``` df['outlier'] = 0 for a in results['alarms']: df['outlier'].iloc[a] = 1 display(df[df['outlier']==1]) ``` In order to better visualize the outliers, we do not show anymore the thresolds so that it is possible to focus our attention on the red points. ``` fig, ax = plt.subplots() a = df.loc[df['outlier'] == 1, ['timestamp', 'value']] #anomaly ax.plot(df['timestamp'], df['value'], color='blue') ax.scatter(a['timestamp'],a['value'], color='red') plt.show() ``` As we have seen when we have shown the oulier rows, most of the outliers happened on 19th and 20th May 2014, so now a focus on that week is shown. During these days, the temperature is decread rapidly, overcoming the lower threshold, and so they resulted as outliers. Our initial expectation has been satisfied. ``` fig, ax = plt.subplots() df2 = df[(df['date'] >= '2014-05-16') & (df['date']<'2014-05-22')] a = df2.loc[df2['outlier'] == 1, ['timestamp', 'value']] #anomaly ax.plot(df2['timestamp'], df2['value'], color='blue') ax.scatter(a['timestamp'],a['value'], color='red') plt.show() ``` Finally, we want to visualize the frequence of outliers based on the value of the temperature. ``` a = df.loc[df['outlier'] == 0, 'value'] b = df.loc[df['outlier'] == 1, 'value'] fig, axs = plt.subplots() axs.hist([a,b], bins=32, stacked=True, color=['blue', 'red'], label=['normal', 'anomaly']) plt.legend() plt.show() ```
github_jupyter
``` from google.colab import drive drive.mount('/content/gdrive') import os os.chdir('/content/gdrive/My Drive/finch/tensorflow2/text_matching/ant/main') %tensorflow_version 2.x !pip install tensorflow-addons from sklearn.metrics import classification_report import json import tensorflow as tf import tensorflow_addons as tfa import numpy as np import pprint import logging import time import math print("TensorFlow Version", tf.__version__) print('GPU Enabled:', tf.test.is_gpu_available()) def get_vocab(f_path): k2v = {} with open(f_path) as f: for i, line in enumerate(f): line = line.rstrip() k2v[line] = i return k2v # stream data from text files def data_generator(f_path, char2idx): with open(f_path) as f: print('Reading', f_path) for line in f: line = json.loads(line.rstrip()) text1, text2, label = line['sentence1'], line['sentence2'], line['label'] text1 = [char2idx.get(c, len(char2idx)) for c in list(text1)] text2 = [char2idx.get(c, len(char2idx)) for c in list(text2)] yield ((text1, text2), int(label)) def dataset(is_training, params): _shapes = (([None], [None]), ()) _types = ((tf.int32, tf.int32), tf.int32) _pads = ((0, 0), -1) if is_training: ds = tf.data.Dataset.from_generator( lambda: data_generator(params['train_path'], params['char2idx']), output_shapes = _shapes, output_types = _types,) ds = ds.shuffle(params['buffer_size']) ds = ds.padded_batch(params['batch_size'], _shapes, _pads) ds = ds.prefetch(tf.data.experimental.AUTOTUNE) else: ds = tf.data.Dataset.from_generator( lambda: data_generator(params['test_path'], params['char2idx']), output_shapes = _shapes, output_types = _types,) ds = ds.padded_batch(params['batch_size'], _shapes, _pads) ds = ds.prefetch(tf.data.experimental.AUTOTUNE) return ds class RE2(tf.keras.Model): def __init__(self, params: dict): super().__init__() self.pretrained_embedding = tf.Variable(np.load(params['embedding_path']), name='pretrained_embedding', dtype=tf.float32) self.embed_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.birnn = [tf.keras.layers.Bidirectional(tf.keras.layers.LSTM( params['hidden_size'], return_sequences=True, zero_output_for_mask=True), name='birnn_%d'%(i+1)) for i in range(params['num_blocks'])] self.enc_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.align_t = self.add_weight(name='temperature', shape=(), trainable=True, initializer=tf.initializers.constant(math.sqrt(1/params['hidden_size']))) self.align_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.align_fc1 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='align_fc1_%d'%(i+1)) for i in range(params['num_blocks'])] self.align_fc2 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='align_fc2_%d'%(i+1)) for i in range(params['num_blocks'])] self.fusion_fc1 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='fusion_fc1_%d'%(i+1)) for i in range(params['num_blocks'])] self.fusion_fc2 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='fusion_fc2_%d'%(i+1)) for i in range(params['num_blocks'])] self.fusion_fc3 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='fusion_fc3_%d'%(i+1)) for i in range(params['num_blocks'])] self.fusion_fc4 = [tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='fusion_fc4_%d'%(i+1)) for i in range(params['num_blocks'])] self.fusion_dropout = tf.keras.layers.Dropout(params['dropout_rate']) self.out_drop1 = tf.keras.layers.Dropout(params['dropout_rate']) self.out_fc = tf.keras.layers.Dense(params['hidden_size'], params['activation'], name='out_fc') self.out_drop2 = tf.keras.layers.Dropout(params['dropout_rate']) self.out_linear = tf.keras.layers.Dense(1, name='out_linear') def call(self, inputs, training=False): x1, x2 = inputs if x1.dtype != tf.int32: x1 = tf.cast(x1, tf.int32) if x2.dtype != tf.int32: x2 = tf.cast(x2, tf.int32) batch_sz = tf.shape(x1)[0] mask1 = tf.sign(x1) mask2 = tf.sign(x2) x1 = self.embedding(x1, training=training) x2 = self.embedding(x2, training=training) res_x1, res_x2 = x1, x2 for i in range(params['num_blocks']): if i > 0: x1 = self.connection(x1, res_x1, i) x2 = self.connection(x2, res_x2, i) res_x1, res_x2 = x1, x2 x1_enc = self.encoding(x1, mask1, i, training=training) x2_enc = self.encoding(x2, mask2, i, training=training) x1 = tf.concat((x1, x1_enc), -1) x2 = tf.concat((x2, x2_enc), -1) align_1, align_2 = self.alignment(x1, x2, mask1, mask2, i, training=training) x1 = self.fusion(x1, align_1, i, training=training) x2 = self.fusion(x2, align_2, i, training=training) x1 = self.pooling(x1, mask1) x2 = self.pooling(x2, mask2) x = self.prediction(x1, x2, training=training) return x def embedding(self, x, training): x = tf.nn.embedding_lookup(self.pretrained_embedding, x) x = self.embed_dropout(x, training=training) return x def connection(self, x, res, i): if i == 1: x = tf.concat((res, x), -1) elif i > 1: hidden_size = x.shape[-1] x = (res[:, :, -hidden_size:] + x) * tf.math.sqrt(0.5) x = tf.concat((res[:, :, :-hidden_size], x), -1) return x def encoding(self, x, mask, i, training): x = self.birnn[i](x, mask=tf.cast(mask, tf.bool)) x = self.enc_dropout(x, training=training) return x def alignment(self, x1, x2, mask1, mask2, i, training): mask1 = tf.cast(tf.expand_dims(mask1, -1), tf.float32) mask2 = tf.cast(tf.expand_dims(mask2, -1), tf.float32) x1_ = self.align_fc1[i](self.align_dropout(x1, training=training)) x2_ = self.align_fc2[i](self.align_dropout(x2, training=training)) align = tf.matmul(x1_, x2_, transpose_b=True) * self.align_t mask = tf.matmul(mask1, mask2, transpose_b=True) align = mask * align + (1 - mask) * tf.float32.min align_1 = tf.nn.softmax(align, 1) align_2 = tf.nn.softmax(align, 2) x2 = tf.matmul(align_1, x1, transpose_a=True) x1 = tf.matmul(align_2, x2) return x1, x2 def fusion(self, x, align, i, training): x = tf.concat([self.fusion_fc1[i](tf.concat((x, align), -1)), self.fusion_fc2[i](tf.concat((x, x - align), -1)), self.fusion_fc3[i](tf.concat((x, x * align), -1))], -1) x = self.fusion_dropout(x, training=training) x = self.fusion_fc4[i](x) return x def pooling(self, x, mask): mask = tf.cast(tf.expand_dims(mask, -1), tf.float32) return tf.reduce_max(x * mask, 1) def prediction(self, x1, x2, training): x = tf.concat((x1, x2, x1 * x2, x1 - x2), -1) x = self.out_drop1(x, training=training) x = self.out_fc(x) x = self.out_drop2(x, training=training) x = self.out_linear(x) x = tf.squeeze(x, 1) return x params = { 'train_path': '../data/train.json', 'test_path': '../data/dev.json', 'vocab_path': '../vocab/char.txt', 'embedding_path': '../vocab/char.npy', 'batch_size': 32, 'buffer_size': 34334, 'num_blocks': 2, 'dropout_rate': .2, 'hidden_size': 300, 'activation': tf.nn.relu, 'init_lr': 1e-4, 'max_lr': 8e-4, 'label_smooth': .0, 'clip_norm': .1, 'num_patience': 10, } def label_smoothing(label, smooth): if smooth > 0.: return label * (1 - smooth) + 0.5 * smooth else: return label params['char2idx'] = get_vocab(params['vocab_path']) params['vocab_size'] = len(params['char2idx']) + 1 # input stream ids check (text1, text2), _ = next(data_generator(params['train_path'], params['char2idx'])) print(text1) print(text2) model = RE2(params) model.build([[None, None], [None, None]]) pprint.pprint([(v.name, v.shape) for v in model.trainable_variables]) decay_lr = tfa.optimizers.Triangular2CyclicalLearningRate( initial_learning_rate = params['init_lr'], maximal_learning_rate = params['max_lr'], step_size = 8 * params['buffer_size'] // params['batch_size'],) optim = tf.optimizers.Adam(params['init_lr']) global_step = 0 best_acc = .0 count = 0 t0 = time.time() logger = logging.getLogger('tensorflow') logger.setLevel(logging.INFO) while True: # TRAINING for ((text1, text2), labels) in dataset(is_training=True, params=params): with tf.GradientTape() as tape: logits = model((text1, text2), training=True) labels = tf.cast(labels, tf.float32) num_neg = tf.reduce_sum(tf.cast(tf.equal(labels, 0.), tf.float32)).numpy() num_pos = tf.reduce_sum(labels).numpy() if num_pos == 0.: pos_weight = 1. else: pos_weight = num_neg / num_pos loss = tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits( labels = label_smoothing(labels, params['label_smooth']), logits = logits, pos_weight = pos_weight)) optim.lr.assign(decay_lr(global_step)) grads = tape.gradient(loss, model.trainable_variables) grads, _ = tf.clip_by_global_norm(grads, params['clip_norm']) optim.apply_gradients(zip(grads, model.trainable_variables)) if global_step % 100 == 0: logger.info("Step {} | Loss: {:.4f} | Spent: {:.1f} secs | LR: {:.6f}".format( global_step, loss.numpy().item(), time.time()-t0, optim.lr.numpy().item())) t0 = time.time() global_step += 1 # EVALUATION m = tf.keras.metrics.Accuracy() intent_true = [] intent_pred = [] for ((text1, text2), labels) in dataset(is_training=False, params=params): logits = tf.sigmoid(model((text1, text2), training=False)) y_pred = tf.cast(tf.math.greater_equal(logits, .5), tf.int32) m.update_state(y_true=labels, y_pred=y_pred) intent_true += labels.numpy().flatten().tolist() intent_pred += y_pred.numpy().flatten().tolist() acc = m.result().numpy() logger.info("Evaluation: Testing Accuracy: {:.3f}".format(acc)) logger.info('\n'+classification_report(y_true = intent_true, y_pred = intent_pred, labels = [0, 1], target_names = ['Not Matched', 'Matched'], digits = 3)) if acc > best_acc: best_acc = acc # you can save model here count = 0 else: count += 1 logger.info("Best Accuracy: {:.3f}".format(best_acc)) if count == params['num_patience']: print(params['num_patience'], "times not improve the best result, therefore stop training") break ```
github_jupyter
``` %matplotlib inline import tensorflow as tf import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn import metrics from sklearn.model_selection import train_test_split MAX_DOCUMENT_LENGTH = 100 VOCAB_SIZE = 20000 EMBEDDING_SIZE = 50 N_FILTERS = 10 N_CLASSES = 8 WINDOW_SIZE=20 FILTER_SHAPE1 = [WINDOW_SIZE,EMBEDDING_SIZE] FILTER_SHAPE2 = [WINDOW_SIZE,N_FILTERS] POOLING_WINDOW = 4 POOLING_STRIDE = 2 LEARNING_RATE = 0.05 STEPS = 200 df = pd.read_csv('../data/CS503/labeled_news.csv', header=None) X, y = df[1], df[0] y = y.apply(lambda x: x-1) print (y.unique()) x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=VOCAB_SIZE) tokenizer.fit_on_texts(x_train) x_train = tokenizer.texts_to_sequences(x_train) x_test = tokenizer.texts_to_sequences(x_test) x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=MAX_DOCUMENT_LENGTH) x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=MAX_DOCUMENT_LENGTH) def cnn2_model(features, target): target = tf.one_hot(target, N_CLASSES, 1, 0) word_vectors = tf.contrib.layers.embed_sequence(features, vocab_size=VOCAB_SIZE, embed_dim=EMBEDDING_SIZE, scope='words') word_vectors = tf.expand_dims(word_vectors, 3) conv1 = tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID') pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME') pool1 = tf.transpose(pool1, [0, 1, 3, 2]) conv2 = tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID') pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1]) logits = tf.contrib.layers.fully_connected(pool2, N_CLASSES, activation_fn=None) loss = tf.contrib.losses.softmax_cross_entropy(logits, target) train_op = tf.contrib.layers.optimize_loss( loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE) return ({ 'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits) }, loss, train_op) classifier = tf.contrib.learn.Estimator(model_fn=cnn2_model) # Train and predict classifier.fit(x_train, y_train, steps=STEPS) # Evaluate model y_predicted = [p['class'] for p in classifier.predict(x_test, as_iterable=True)] print(y_predicted) # compare the predict label and true label score = metrics.accuracy_score(y_test, y_predicted) print('Accuracy: {0:f}'.format(score)) keras = tf.keras model = keras.Sequential() model.add(keras.layers.Embedding(VOCAB_SIZE, EMBEDDING_SIZE, input_length=MAX_DOCUMENT_LENGTH)) model.add(keras.layers.Conv1D(64, EMBEDDING_SIZE, activation='relu')) model.add(keras.layers.MaxPooling1D(pool_size=4)) model.add(keras.layers.LSTM(100, dropout=0.2, recurrent_dropout=0.2)) model.add(keras.layers.Dense(8, activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() model.fit(x_train, y_train, epochs=3) accr = model.evaluate(x_test,y_test) print('Test set\n Loss: {:0.3f}\n Accuracy: {:0.3f}'.format(accr[0],accr[1])) data_directory = '../data/glove.6B' file_name = 'glove.6B.{}d.txt' def create_embed_dict(embed_file): embed_dict = dict() with open(embed_file) as file: for line in file.readlines(): row = line.strip().split() word = row[0] embed_vect = [float(i) for i in row[1:]] embed_dict[word] = embed_vect return embed_dict def create_embed_matrix(embed_dict): embed_matrix = np.zeros((VOCAB_SIZE, EMBEDDING_SIZE)) for word, index in tokenizer.word_index.items(): embed_vect = embed_dict.get(word, None) if embed_vect is not None: embed_matrix[index] = embed_vect else: print ('Not found:', word, embed_matrix[index]) embed_matrix[0] = embed_dict['unk'] return embed_matrix def glove50d_cnn_model(features, target): target = tf.one_hot(target, N_CLASSES, 1, 0) embed_dict = create_embed_dict(data_directory + '/' + file_name.format(EMBEDDING_SIZE)) embed_matrix = create_embed_matrix(embed_dict) embed_matrix = tf.cast(embed_matrix, tf.float32) word_vectors = tf.nn.embedding_lookup(embed_matrix, features) word_vectors = tf.expand_dims(word_vectors, 3) conv1 = tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID') pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME') pool1 = tf.transpose(pool1, [0, 1, 3, 2]) conv2 = tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID') pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1]) logits = tf.contrib.layers.fully_connected(pool2, N_CLASSES, activation_fn=None) loss = tf.contrib.losses.softmax_cross_entropy(logits, target) train_op = tf.contrib.layers.optimize_loss( loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE) return ({ 'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits) }, loss, train_op) classifier = tf.contrib.learn.Estimator(model_fn=glove50d_cnn_model) # Train and predict classifier.fit(x_train, y_train, steps=STEPS) # Evaluate model y_predicted = [p['class'] for p in classifier.predict(x_test, as_iterable=True)] print(y_predicted) # compare the predict label and true label score = metrics.accuracy_score(y_test, y_predicted) print('Accuracy: {0:f}'.format(score)) ```
github_jupyter
# Classification *Supervised* machine learning techniques involve training a model to operate on a set of *features* and predict a *label* using a dataset that includes some already-known label values. You can think of this function like this, in which ***y*** represents the label we want to predict and ***X*** represents the vector of features the model uses to predict it. $$y = f([x_1, x_2, x_3, ...])$$ *Classification* is a form of supervised machine learning in which you train a model to use the features (the ***x*** values in our function) to predict a label (***y***) that calculates the probability of the observed case belonging to each of a number of possible classes, and predicting an appropriate label. The simplest form of classification is *binary* classification, in which the label is 0 or 1, representing one of two classes; for example, "True" or "False"; "Internal" or "External"; "Profitable" or "Non-Profitable"; and so on. ## Binary Classification Let's start by looking at an example of *binary classification*, where the model must predict a label that belongs to one of two classes. In this exercsie, we'll train a binary classifier to predict whether or not a patient should be tested for diabetes based on some medical data. ### Explore the data Run the following cell to load a CSV file of patent data into a **Pandas** dataframe: > **Citation**: The diabetes dataset used in this exercise is based on data originally collected by the National Institute of Diabetes and Digestive and Kidney Diseases. ``` import pandas as pd # load the training dataset diabetes = pd.read_csv('data/diabetes.csv') diabetes.head() ``` This data consists of diagnostic information about some patients who have been tested for diabetes. Scroll to the right if necessary, and note that the final column in the dataset (**Diabetic**) contains the value ***0*** for patients who tested negative for diabetes, and ***1*** for patients who tested positive. This is the label that we will train our mode to predict; most of the other columns (**Pregnancies**,**PlasmaGlucose**,**DiastolicBloodPressure**, and so on) are the features we will use to predict the **Diabetic** label. Let's separate the features from the labels - we'll call the features ***X*** and the label ***y***: ``` # Separate features and labels features = ['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age'] label = 'Diabetic' X, y = diabetes[features].values, diabetes[label].values for n in range(0,4): print("Patient", str(n+1), "\n Features:",list(X[n]), "\n Label:", y[n]) ``` Now let's compare the feature distributions for each label value. ``` from matplotlib import pyplot as plt %matplotlib inline features = ['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age'] for col in features: diabetes.boxplot(column=col, by='Diabetic', figsize=(6,6)) plt.title(col) plt.show() ``` For some of the features, there's a noticable difference in the distribution for each label value. In particular, **Pregnancies** and **Age** show markedly different distributions for diabetic patients than for non-diabetic patients. These features may help predict whether or not a patient is diabetic. ### Split the data Our dataset includes known values for the label, so we can use this to train a classifier so that it finds a statistical relationship between the features and the label value; but how will we know if our model is any good? How do we know it will predict correctly when we use it with new data that it wasn't trained with? Well, we can take advantage of the fact we have a large dataset with known label values, use only some of it to train the model, and hold back some to test the trained model - enabling us to compare the predicted labels with the already known labels in the test set. In Python, the **scikit-learn** package contains a large number of functions we can use to build a machine learning model - including a **train_test_split** function that ensures we get a statistically random split of training and test data. We'll use that to split the data into 70% for training and hold back 30% for testing. ``` from sklearn.model_selection import train_test_split # Split data 70%-30% into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0) print ('Training cases: %d\nTest cases: %d' % (X_train.size, X_test.size)) ``` ### Train and Evaluate a Binary Classification Model OK, now we're ready to train our model by fitting the training features (**X_train**) to the training labels (**y_train**). There are various algorithms we can use to train the model. In this example, we'll use *Logistic Regression*, which (despite its name) is a well-established algorithm for classification. In addition to the training features and labels, we'll need to set a *regularization* parameter. This is used to counteract any bias in the sample, and help the model generalize well by avoiding *overfitting* the model to the training data. > **Note**: Parameters for machine learning algorithms are generally referred to as *hyperparameters* (to a data scientist, *parameters* are values in the data itself - *hyperparameters* are defined externally from the data!) ``` # Train the model from sklearn.linear_model import LogisticRegression # Set regularization rate reg = 0.01 # train a logistic regression model on the training set model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train) print (model) ``` Now we've trained the model using the training data, we can use the test data we held back to evaluate how well it predicts. Again, **scikit-learn** can help us do this. Let's start by using the model to predict labels for our test set, and compare the predicted labels to the known labels: ``` predictions = model.predict(X_test) print('Predicted labels: ', predictions) print('Actual labels: ' ,y_test) ``` The arrays of labels are too long to be displayed in the notebook output, so we can only compare a few values. Even if we printed out all of the predicted and actual labels, there are too many of them to make this a sensible way to evaluate the model. Fortunately, **scikit-learn** has a few more tricks up its sleeve, and it provides some metrics that we can use to evaluate the model. The most obvious thing you might want to do is to check the *accuracy* of the predictions - in simple terms, what proportion of the labels did the model predict correctly? ``` from sklearn.metrics import accuracy_score print('Accuracy: ', accuracy_score(y_test, predictions)) ``` The accuracy is returned as a decimal value - a value of 1.0 would mean that the model got 100% of the predictions right; while an accuracy of 0.0 is, well, pretty useless! Accuracy seems like a sensible metric to evaluate (and to a certain extent it is), but you need to be careful about drawing too many conclusions from the accuracy of a classifier. Remember that it's simply a measure of how many cases were predicted correctly. Suppose only 3% of the population is diabetic. You could create a classifier that always just predicts 0, and it would be 97% accurate - but not terribly helpful in identifying patients with diabetes! Fortunately, there are some other metrics that reveal a little more about how our model is performing. Scikit-Learn includes the ability to create a *classification report* that provides more insight than raw accuracy alone. ``` from sklearn. metrics import classification_report print(classification_report(y_test, predictions)) ``` The classification report includes the following metrics for each class (0 and 1) > note that the header row may not line up with the values! * *Precision*: Of the predictons the model made for this class, what proportion were correct? * *Recall*: Out of all of the instances of this class in the test dataset, how many did the model identify? * *F1-Score*: An average metric that takes both precision and recall into account. * *Support*: How many instances of this class are there in the test dataset? The classification report also includes averages for these metrics, including a weighted average that allows for the imbalance in the number of cases of each class. Because this is a *binary* classification problem, the ***1*** class is considered *positive* and its precision and recall are particularly interesting - these in effect answer the questions: - Of all the patients the model predicted are diabetic, how many are actually diabetic? - Of all the patients that are actually diabetic, how many did the model identify? You can retrieve these values on their own by using the **precision_score** and **recall_score** metrics in scikit-learn (which by default assume a binary classification model). ``` from sklearn.metrics import precision_score, recall_score print("Overall Precision:",precision_score(y_test, predictions)) print("Overall Recall:",recall_score(y_test, predictions)) ``` The precision and recall metrics are derived from four possible prediction outcomes: * *True Positives*: The predicted label and the actual label are both 1. * *False Positives*: The predicted label is 1, but the actual label is 0. * *False Negatives*: The predicted label is 0, but the actual label is 1. * *True Negatives*: The predicted label and the actual label are both 0. These metrics are generally tabulated for the test set and shown together as a *confusion matrix*, which takes the following form: <table style="border: 1px solid black;"> <tr style="border: 1px solid black;"> <td style="border: 1px solid black;color: black;" bgcolor="lightgray">TN</td><td style="border: 1px solid black;color: black;" bgcolor="white">FP</td> </tr> <tr style="border: 1px solid black;"> <td style="border: 1px solid black;color: black;" bgcolor="white">FN</td><td style="border: 1px solid black;color: black;" bgcolor="lightgray">TP</td> </tr> </table> Note that the correct (*true*) predictions form a diagonal line from top left to bottom right - these figures should be significantly higher than the *false* predictions if the model is any good. In Python, you can use the **sklearn.metrics.confusion_matrix** function to find these values for a trained classifier: ``` from sklearn.metrics import confusion_matrix # Print the confusion matrix cm = confusion_matrix(y_test, predictions) print (cm) ``` Until now, we've considered the predictions from the model as being either 1 or 0 class labels. Actually, things are a little more complex than that. Statistical machine learning algorithms, like logistic regression, are based on *probability*; so what actually gets predicted by a binary classifier is the probability that the label is true (**P(y)**) and the probability that the label is false (1 - **P(y)**). A threshold value of 0.5 is used to decide whether the predicted label is a 1 (*P(y) > 0.5*) or a 0 (*P(y) <= 0.5*). You can use the **predict_proba** method to see the probability pairs for each case: ``` y_scores = model.predict_proba(X_test) print(y_scores) ``` The decision to score a prediction as a 1 or a 0 depends on the threshold to which the predicted probabilties are compared. If we were to change the threshold, it would affect the predictions; and therefore change the metrics in the confusion matrix. A common way to evaluate a classifier is to examine the *true positive rate* (which is another name for recall) and the *false positive rate* for a range of possible thresholds. These rates are then plotted against all possible thresholds to form a chart known as a *received operator characteristic (ROC) chart*, like this: ``` from sklearn.metrics import roc_curve from sklearn.metrics import confusion_matrix import matplotlib import matplotlib.pyplot as plt %matplotlib inline # calculate ROC curve fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1]) # plot ROC curve fig = plt.figure(figsize=(6, 6)) # Plot the diagonal 50% line plt.plot([0, 1], [0, 1], 'k--') # Plot the FPR and TPR achieved by our model plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show() ``` The ROC chart shows the curve of the true and false positive rates for different threshold values between 0 and 1. A perfect classifier would have a curve that goes straight up the left side and straight across the top. The diagonal line across the chart represents the probability of predicting correctly with a 50/50 random prediction; so you obviously want the curve to be higher than that (or your model is no better than simply guessing!). The area under the curve (AUC) is a value between 0 and 1 that quantifies the overall performance of the model. The closer to 1 this value is, the better the model. Once again, scikit-Learn includes a function to calculate this metric. ``` from sklearn.metrics import roc_auc_score auc = roc_auc_score(y_test,y_scores[:,1]) print('AUC: ' + str(auc)) ``` ### Perform preprocessing in a pipeline In this case, the ROC curve and its AUC indicate that the model performs better than a random guess which is not bad considering we performed very little preprocessing of the data. In practice, it's common to perform some preprocessing of the data to make it easier for the algorithm to fit a model to it. There's a huge range of preprocessing transformations you can perform to get your data ready for modeling, but we'll limit ourselves to a few common techniques: - Scaling numeric features so they're on the same scale. This prevents feaures with large values from producing coefficients that disproportionately affect the predictions. - Encoding categorical variables. For example, by using a *one hot encoding* technique you can create individual binary (true/false) features for each possible category value. To apply these preprocessing transformations, we'll make use of a Scikit-Learn feature named *pipelines*. These enable us to define a set of preprocessing steps that end with an algorithm. You can then fit the entire pipeline to the data, so that the model encapsulates all of the preprocessing steps as well as the regression algorithm. This is useful, because when we want to use the model to predict values from new data, we need to apply the same transformations (based on the same statistical distributions and catagory encodings used with the training data). >**Note**: The term *pipeline* is used extensively in machine learning, often to mean very different things! In this context, we're using it to refer to pipeline objects in Scikit-Learn, but you may see it used elsewhere to mean something else. ``` # Train the model from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.linear_model import LogisticRegression import numpy as np # Define preprocessing for numeric columns (normalize them so they're on the same scale) numeric_features = [0,1,2,3,4,5,6] numeric_transformer = Pipeline(steps=[ ('scaler', StandardScaler())]) # Define preprocessing for categorical features (encode the Age column) categorical_features = [7] categorical_transformer = Pipeline(steps=[ ('onehot', OneHotEncoder(handle_unknown='ignore'))]) # Combine preprocessing steps preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features)]) # Create preprocessing and training pipeline pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('logregressor', LogisticRegression(C=1/reg, solver="liblinear"))]) # fit the pipeline to train a logistic regression model on the training set model = pipeline.fit(X_train, (y_train)) print (model) ``` The pipeline encapsulates the preprocessing steps as well as model training. Let's use the model trained by this pipeline to predict labels for our test set, and compare the performance metrics with the basic model we created previously. ``` # Get predictions from test data predictions = model.predict(X_test) # Get evaluation metrics cm = confusion_matrix(y_test, predictions) print ('Confusion Matrix:\n',cm, '\n') print('Accuracy:', accuracy_score(y_test, predictions)) print("Overall Precision:",precision_score(y_test, predictions)) print("Overall Recall:",recall_score(y_test, predictions)) auc = roc_auc_score(y_test,y_scores[:,1]) print('AUC: ' + str(auc)) # calculate ROC curve y_scores = model.predict_proba(X_test) fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1]) # plot ROC curve fig = plt.figure(figsize=(6, 6)) # Plot the diagonal 50% line plt.plot([0, 1], [0, 1], 'k--') # Plot the FPR and TPR achieved by our model plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show() ``` The results look a little better, so clearly preprocessing the data has made a difference. ### Try a different algorithm Now let's try a different algorithm. Previously we used a logistic regression algorithm, which is a *linear* algorithm. There are many kinds of classification algorithm we could try, including: - **Support Vector Machine algorithms**: Algorithms that define a *hyperplane* that separates classes. - **Tree-based algorithms**: Algorithms that build a decision tree to reach a prediction - **Ensemble algorithms**: Algorithms that combine the outputs of multiple base algorithms to improve generalizability. This time, We'll use the same preprocessing steps as before, but we'll train the model using an *ensemble* algorithm named *Random Forest* that combines the outputs of multiple random decision trees (for more details, see the [Scikit-Learn documentation](https://scikit-learn.org/stable/modules/ensemble.html#forests-of-randomized-trees)). ``` from sklearn.ensemble import RandomForestClassifier # Create preprocessing and training pipeline pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('logregressor', RandomForestClassifier(n_estimators=100))]) # fit the pipeline to train a random forest model on the training set model = pipeline.fit(X_train, (y_train)) print (model) ``` Let's look at the performance metrics for the new model. ``` predictions = model.predict(X_test) cm = confusion_matrix(y_test, predictions) print ('Confusion Matrix:\n',cm, '\n') print('Accuracy:', accuracy_score(y_test, predictions)) print("Overall Precision:",precision_score(y_test, predictions)) print("Overall Recall:",recall_score(y_test, predictions)) auc = roc_auc_score(y_test,y_scores[:,1]) print('\nAUC: ' + str(auc)) # calculate ROC curve y_scores = model.predict_proba(X_test) fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1]) # plot ROC curve fig = plt.figure(figsize=(6, 6)) # Plot the diagonal 50% line plt.plot([0, 1], [0, 1], 'k--') # Plot the FPR and TPR achieved by our model plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show() ``` That looks better! ### Use the Model for Inferencing Now that we have a reasonably useful trained model, we can save it for use later to predict labels for new data: ``` import joblib # Save the model as a pickle file filename = './models/diabetes_model.pkl' joblib.dump(model, filename) ``` When we have some new observations for which the label is unknown, we can load the model and use it to predict values for the unknown label: ``` # Load the model from the file model = joblib.load(filename) # predict on a new sample # The model accepts an array of feature arrays (so you can predict the classes of multiple patients in a single call) # We'll create an array with a single array of features, representing one patient X_new = np.array([[2,180,74,24,21,23.9091702,1.488172308,22]]) print ('New sample: {}'.format(list(X_new[0]))) # Get a prediction pred = model.predict(X_new) # The model returns an array of predictions - one for each set of features submitted # In our case, we only submitted one patient, so our prediction is the first one in the resulting array. print('Predicted class is {}'.format(pred[0])) ``` ## Multiclass Classification Binary classification techniques work well when the data observations belong to one of two classes or categories, such as "True" or "False". When the data can be categorized into more than two classes, you must use a multiclass classification algorithm. Fortunately, in most machine learning frameworks, including scikit-learn, implementing a multiclass classifier is not significantly more complex than binary classification - and in many cases, the classification algorithm classes used for binary classification implicitly support multiclass classification. ### Explore the data Let's start by examining a dataset that contains observations of multiple classes. We'll use a dataset that contains observations of three different species of penguin. > **Citation**: The penguins dataset used in the this exercise is a subset of data collected and made available by [Dr. Kristen Gorman](https://www.uaf.edu/cfos/people/faculty/detail/kristen-gorman.php) and the [Palmer Station, Antarctica LTER](https://pal.lternet.edu/), a member of the [Long Term Ecological Research Network](https://lternet.edu/). ``` import pandas as pd # load the training dataset penguins = pd.read_csv('data/penguins.csv') # Display a random sample of 10 observations sample = penguins.sample(10) sample ``` The dataset contains the following columns: * **CulmenLength**: The length in mm of the penguin's culmen (bill). * **CulmenDepth**: The depth in mm of the penguin's culmen. * **FlipperLength**: The length in mm of the penguin's flipper. * **BodyMass**: The body mass of the penguin in grams. * **Species**: An integer value that represents the species of the penguin. The **Species** column is the label we want to train a model to predict. The dataset includes three possible species, which are encoded as 0, 1, and 2. The actual species names are revealed by the code below: ``` penguin_classes = ['Amelie', 'Gentoo', 'Chinstrap'] print(sample.columns[0:5].values, 'SpeciesName') for index, row in penguins.sample(10).iterrows(): print('[',row[0], row[1], row[2], row[3], int(row[4]),']',penguin_classes[int(row[4])]) ``` Now that we know what the feaures and labels in the data represent, let's explore the dataset. First, let's see if there are any missing (*null*) values. ``` # Count the number of null values for each column penguins.isnull().sum() ``` It looks like there are some missing feature values, but no missing labels. Let's dig a little deeper and see the rows that contain nulls. ``` # Show rows containing nulls penguins[penguins.isnull().any(axis=1)] ``` There are two rows that contain no feature values at all (*NaN* stands for "not a number"), so these won't be useful in training a model. Let's discard them from the dataset. ``` # Drop rows containing NaN values penguins=penguins.dropna() #Confirm there are now no nulls penguins.isnull().sum() ``` Now that we've dealt with the missing values, let's explore how the features relate to the label by creating some box charts. ``` from matplotlib import pyplot as plt %matplotlib inline penguin_features = ['CulmenLength','CulmenDepth','FlipperLength','BodyMass'] penguin_label = 'Species' for col in penguin_features: penguins.boxplot(column=col, by=penguin_label, figsize=(6,6)) plt.title(col) plt.show() ``` From the box plots, it looks like species 0 and 2 (Amelie and Chinstrap) have similar data profiles for culmen depth, flipper length, and body mass, but Chinstraps tend to have longer culmens. Species 1 (Gentoo) tends to have fairly clearly differentiated features from the others; which should help us train a good classification model. ### Prepare the data Just as for binary classification, before training the model, we need to separate the features and label, and then split the data into subsets for training and validation. We'll also apply a *stratification* technique when splitting the data to maintain the proportion of each label value in the training and validation datasets. ``` from sklearn.model_selection import train_test_split # Separate features and labels penguins_X, penguins_y = penguins[penguin_features].values, penguins[penguin_label].values # Split data 70%-30% into training set and test set x_penguin_train, x_penguin_test, y_penguin_train, y_penguin_test = train_test_split(penguins_X, penguins_y, test_size=0.30, random_state=0, stratify=penguins_y) print ('Training Set: %d, Test Set: %d \n' % (x_penguin_train.size, x_penguin_test.size)) ``` ### Train and evaluate a multiclass classifier Now that we have a set of training features and corresponding training labels, we can fit a multiclass classification algorithm to the data to create a model. Most scikit-learn classification algorithms inherently supports multiclass classification. We'll try a logistic regression algorithm. ``` from sklearn.linear_model import LogisticRegression # Set regularization rate reg = 0.1 # train a logistic regression model on the training set multi_model = LogisticRegression(C=1/reg, solver='lbfgs', multi_class='auto', max_iter=10000).fit(x_penguin_train, y_penguin_train) print (multi_model) ``` Now we can use the trained model to predict the labels for the test features, and compare the predicted labels to the actual labels: ``` penguin_predictions = multi_model.predict(x_penguin_test) print('Predicted labels: ', penguin_predictions[:15]) print('Actual labels : ' ,y_penguin_test[:15]) ``` Let's look at a classification report. ``` from sklearn. metrics import classification_report print(classification_report(y_penguin_test, penguin_predictions)) ``` As with binary classification, the report includes *precision* and *recall* metrics for each class. However, while with binary classification we could focus on the scores for the *positive* class; in this case, there are multiple classes so we need to look at an overall metric (either the macro or weighted average) to get a sense of how well the model performs across all three classes. You can get the overall metrics separately from the report using the scikit-learn metrics score classes, but with multiclass results you must specify which average metric you want to use for precision and recall. ``` from sklearn.metrics import accuracy_score, precision_score, recall_score print("Overall Accuracy:",accuracy_score(y_penguin_test, penguin_predictions)) print("Overall Precision:",precision_score(y_penguin_test, penguin_predictions, average='macro')) print("Overall Recall:",recall_score(y_penguin_test, penguin_predictions, average='macro')) ``` Now let's look at the confusion matrix for our model: ``` from sklearn.metrics import confusion_matrix # Print the confusion matrix mcm = confusion_matrix(y_penguin_test, penguin_predictions) print(mcm) ``` The confusion matrix shows the intersection of predicted and actual label values for each class - in simple terms, the diagonal intersections from top-left to bottom-right indicate the number of correct predictions. When dealing with multiple classes, it's generally more intuitive to visualize this as a heat map, like this: ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.imshow(mcm, interpolation="nearest", cmap=plt.cm.Blues) plt.colorbar() tick_marks = np.arange(len(penguin_classes)) plt.xticks(tick_marks, penguin_classes, rotation=45) plt.yticks(tick_marks, penguin_classes) plt.xlabel("Actual Species") plt.ylabel("Predicted Species") plt.show() ``` The darker squares in the confusion matrix plot indicate high numbers of cases, and you can hopefully see a diagonal line of darker squares indicating cases where the predicted and actual label are the same. ### Preprocess data in a pipeline Again, just like with binary classification, you can use a pipeline to apply preprocessing steps to the data before fitting it to an algorithm to train a model. Let's see if we can improve the penguin predictor by scaling the numeric features in a transformation steps before training. We'll also try a different algorithm (a support vector machine), just to show that we can! ``` from sklearn.preprocessing import StandardScaler from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.svm import SVC # Define preprocessing for numeric columns (scale them) feature_columns = [0,1,2,3] feature_transformer = Pipeline(steps=[ ('scaler', StandardScaler()) ]) # Create preprocessing steps preprocessor = ColumnTransformer( transformers=[ ('preprocess', feature_transformer, feature_columns)]) # Create training pipeline pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('regressor', SVC())]) # fit the pipeline to train a linear regression model on the training set multi_model = pipeline.fit(x_penguin_train, y_penguin_train) print (multi_model) ``` Now we can evaluate the new model. ``` # Get predictions from test data penguin_predictions = multi_model.predict(x_penguin_test) # Overall metrics print("Overall Accuracy:",accuracy_score(y_penguin_test, penguin_predictions)) print("Overall Precision:",precision_score(y_penguin_test, penguin_predictions, average='macro')) print("Overall Recall:",recall_score(y_penguin_test, penguin_predictions, average='macro')) # Confusion matrix plt.imshow(mcm, interpolation="nearest", cmap=plt.cm.Blues) plt.colorbar() tick_marks = np.arange(len(penguin_classes)) plt.xticks(tick_marks, penguin_classes, rotation=45) plt.yticks(tick_marks, penguin_classes) plt.xlabel("Actual Species") plt.ylabel("Predicted Species") plt.show() ``` ### Use the model with new data observations Now let's save our trained model so we can use it again later. ``` import joblib # Save the model as a pickle file filename = './models/penguin_model.pkl' joblib.dump(multi_model, filename) ``` OK, so now we have a trained model. Let's use it to predict the class of a new penguin observation: ``` # Load the model from the file multi_model = joblib.load(filename) # The model accepts an array of feature arrays (so you can predict the classes of multiple penguin observations in a single call) # We'll create an array with a single array of features, representing one penguin x_new = np.array([[50.4,15.3,224,5550]]) print ('New sample: {}'.format(x_new[0])) # The model returns an array of predictions - one for each set of features submitted # In our case, we only submitted one penguin, so our prediction is the first one in the resulting array. penguin_pred = multi_model.predict(x_new)[0] print('Predicted class is', penguin_classes[penguin_pred]) ``` You can also submit a batch of penguin observations to the model, and get back a prediction for each one. ``` # This time our input is an array of two feature arrays x_new = np.array([[49.5,18.4,195, 3600], [38.2,20.1,190,3900]]) print ('New samples:\n{}'.format(x_new)) # Call the web service, passing the input data predictions = multi_model.predict(x_new) # Get the predicted classes. for prediction in predictions: print(prediction, '(' + penguin_classes[prediction] +')') ``` ## Learn More Classification is one of the most common forms of machine learning, and by following the basic principles we've discussed in this notebook you should be able to train and evaluate classification models with scikit-learn. It's worth spending some time investigating classification algorithms in more depth, and a good starting point is the [Scikit-Learn documentation](https://scikit-learn.org/stable/user_guide.html).
github_jupyter
# Preprocessing This notebook does the preprocessing for the dataset. 1. The bounding boxes and labels are extracted from the annotation files 2. The image, bounding box and label are grouped and accumulated in a list 3. For training, a train-validation split of 80/20 is done by shuffling the extracted training data and splitting 4. These split data is saved into a CSV file for a `CSVGenerator` in the training section to consume ``` import glob import csv import numpy as np import os import matplotlib.pyplot as plt def extract_box(path): """extract_box Extract annotation box positions for each labels from VIVA hand dataset. output is a list of tuples. :param path: text file path """ with open(path) as temp: output = [] for i, line in enumerate(temp): if i != 0 and line: label, x_1, y_1, x_off, y_off, *_ = line.split() pt_1 = (int(x_1), int(y_1)) pt_2 = (pt_1[0] + int(x_off), (pt_1[1] + int(y_off))) output.append((label, pt_1, pt_2)) return output def create_csv(image_dir, annotation_dir, csv_out_path, val_out_path=None, val_split=None): image_paths = sorted(glob.glob(image_dir + '*')) annotations_paths = sorted(glob.glob(annotation_dir + '*')) # each image can have up to 4 hand bboxes rows = [] for image_path, annotations_path in zip(image_paths, annotations_paths): annotations = extract_box(annotations_path) for annotation in annotations: # annotation [label, (x1, y1), (x2, y2)] # save as image,x1,y2,x2,y2,label if not os.path.isabs(image_path): image_path = '../' + image_path rows.append([image_path, annotation[1][0], annotation[1][1], annotation[2][0], annotation[2][1], annotation[0]]) if val_split: # shuffle and split np.random.shuffle(rows) val_size = int(len(rows) * val_split) val_rows = rows[:val_size] with open('./data/validation.csv' if val_out_path is None else val_out_path, 'w') as csv_file: writer = csv.writer(csv_file) for row in val_rows: writer.writerow(row) rows = rows[val_size:] with open(csv_out_path, 'w') as csv_file: writer = csv.writer(csv_file) for row in rows: writer.writerow(row) # this is the root directory where the training data is extracted data_dir = '../data/' # training data path train_dir = data_dir + 'detectiondata/train/' train_image_dir = train_dir + 'pos/' train_annotation_dir = train_dir + 'posGt/' out_path = './data/train.csv' create_csv(train_image_dir, train_annotation_dir, out_path, val_split=0.2) # the test data images are in the same root dir as training test_image_dir = data_dir + 'detectiondata/test/pos/' # but the annotations are downloaded separately and extracted into data_dir/evaluation/ test_annotation_dir = data_dir + 'detectiondata/test/posGt/' test_out_path = './data/test.csv' create_csv(test_image_dir, test_annotation_dir, test_out_path) ``` ## Visualization Some visualization of the training data. ``` train_annotations_paths = sorted(glob.glob(train_annotation_dir + '*')) #class names lh_d_label = 'leftHand_driver' rh_d_label = 'rightHand_driver' lh_p_label = 'leftHand_passenger' rh_p_label = 'rightHand_passenger' # each image can have up to 4 hand bboxes lh_d_count = 0 rh_d_count = 0 lh_p_count = 0 rh_p_count = 0 for annotations_path in train_annotations_paths: anns = extract_box(annotations_path) viewpoint = os.path.splitext(os.path.split(annotations_path)[1])[0].split('_')[-1] for ann in anns: if ann[0] == lh_d_label: lh_d_count += 1 elif ann[0] == rh_d_label: rh_d_count += 1 elif ann[0] == lh_p_label: lh_p_count += 1 elif ann[0] == rh_p_label: rh_p_count += 1 print('Left Hand Driver Bounding Boxes: {}'.format(lh_d_count)) print('Right Hand Driver Bounding Boxes: {}'.format(rh_d_count)) print('Left Hand Passenger Bounding Boxes: {}'.format(lh_p_count)) print('Right Hand Passenger Bounding Boxes: {}'.format(rh_p_count)) #plot plt.bar([0, 1, 2, 3], [lh_d_count, rh_d_count, lh_p_count, rh_p_count], tick_label=['Left Hand\nDriver', 'Right Hand\nDriver', 'Left Hand\nPassenger', 'Right Hand\nPassenger']) plt.savefig('./charts/classes_count.png') plt.show() ``` The challenge evaluates on two different levels: Level-1 (L1): hand instances with minimum height of 70 pixels, only over the shoulder (back) camera view. - Check height from annotation >= 70 - From image name format `videoID_framenumber_vehicletype_driversubjectID_passengersubjectID_viewpoint.png` viewpoint is 3. Level-2 (L2): hand instances with minimum height of 25 pixels, all camera views. - Check height from annotation >= 25 ``` test_annotations_paths = sorted(glob.glob(test_annotation_dir + '*')) L1 = 0 L2 = 0 for annotations_path in test_annotations_paths: anns = extract_box(annotations_path) viewpoint = os.path.splitext(os.path.split(annotations_path)[1])[0].split('_')[-1] for ann in anns: height = ann[2][1] - ann[1][1] if viewpoint == '3' and height >= 70: L1 += 1 if height >= 25: L2 += 1 print('L1: {}'.format(L1)) print('L2: {}'.format(L2)) ```
github_jupyter
# Two modifications of mean-variance portfolio theory #### Daniel Csaba, Thomas J. Sargent and Balint Szoke #### December 2016 ### Remarks about estimating means and variances The famous **Black-Litterman** (1992) portfolio choice model that we describe in this notebook is motivated by the finding that with high or moderate frequency data, means are more difficult to estimate than variances. A model of **robust portfolio choice** that we'll describe also begins from the same starting point. To begin, we'll take for granted that means are more difficult to estimate that covariances and will focus on how Black and Litterman, on the one hand, an robust control theorists, on the other, would recommend modifying the **mean-variance portfolio choice model** to take that into account. At the end of this notebook, we shall use some rates of convergence results and some simulations to verify how means are more difficult to estimate than variances. Among the ideas in play in this notebook will be * mean-variance portfolio theory * Bayesian approaches to estimating linear regressions * A risk-sensitivity operator and its connection to robust control theory ``` %matplotlib inline import numpy as np import scipy as sp import scipy.stats as stat import matplotlib.pyplot as plt from ipywidgets import interact, FloatSlider ``` ## Adjusting mean-variance portfolio choice theory for distrust of mean excess returns This notebook describes two lines of thought that modify the classic mean-variance portfolio choice model in ways designed to make its recommendations more plausible. As we mentioned above, the two approaches build on a common hunch -- that because it is much easier statistically to estimate covariances of excess returns than it is to estimate their means, it makes sense to contemplated the consequences of adjusting investors' subjective beliefs about mean returns in order to render more sensible decisions. Both of the adjustments that we describe are designed to confront a widely recognized embarassment to mean-variance portfolio theory, namely, that it usually implies taking very extreme long-short portfolio positions. ##### Mean-variance portfolio choice A risk free security earns one-period net return $r_f$. An $n \times 1$ vector of risky securities earns an $n \times 1$ vector $\vec r - r_f {\bf 1}$ of *excess returns*, where ${\bf 1}$ is an $n \times 1$ vector of ones. The excess return vector is multivariate normal with mean $\mu$ and covariance matrix $\Sigma$, which we express either as $$ \vec r - r_f {\bf 1} \sim {\mathcal N}(\mu, \Sigma) $$ or $$ \vec r - r_f {\bf 1} = \mu + C \epsilon $$ where $\epsilon \sim {\mathcal N}(0, I)$ is an $n \times 1 $ random vector. Let $w $ be an $n\times 1$ vector of portfolio weights. A portfolio consisting $w$ earns returns $$ w' (\vec r - r_f {\bf 1}) \sim {\mathcal N}(w' \mu, w' \Sigma w ) $$ The **mean-variance portfolio choice problem** is to choose $w$ to maximize $$ U(\mu,\Sigma;w) = w'\mu - \frac{\delta}{2} w' \Sigma w , \quad (1) $$ where $\delta > 0 $ is a risk-aversion parameter. The first-order condition for maximizing (1) with respect to the vector $w$ is $$ \mu = \delta \Sigma w , \quad (2) $$ which implies the following design of a risky portfolio: $$ w = (\delta \Sigma)^{-1} \mu , \quad (3) $$ ##### Estimating $\mu$ and $\Sigma$ The key inputs into the portfolio choice model (3) are * estimates of the parameters $\mu, \Sigma$ of the random excess return vector $(\vec r - r_f {\bf 1})$ * the risk-aversion parameter $\delta$ A standard way of estimating $\mu$ is maximum-likelihood or least squares; that amounts to estimating $\mu$ by a sample mean of excess returns and estimating $\Sigma$ by a sample covariance matrix. ###### The Black-Litterman starting point When estimates of $\mu$ and $\Sigma$ from historical sample means and covariances have been combined with ``reasonable'' values of the risk-aversion parameter $\delta$ to compute an optimal portfolio from formula (3), a typical outcome has been $w$'s with **extreme long and short positions**. A common reaction to these outcomes is that they are so unreasonable that a portfolio manager cannot recommend them to a customer. ``` #======================================== # Primitives of the laboratory #======================================== np.random.seed(12) N = 10 # number of assets T = 200 # sample size # random market portfolio (sum is normalized to 1) w_m = np.random.rand(N) w_m = w_m/(w_m.sum()) # True risk premia and variance of excess return # (constructed so that the Sharpe ratio is 1) Mu = (np.random.randn(N) + 5)/100 # mean excess return (risk premium) S = np.random.randn(N, N) # random matrix for the covariance matrix V = S @ S.T # turn the random matrix into symmetric psd Sigma = V * (w_m @ Mu)**2 / (w_m @ V @ w_m) # make sure that the Sharpe ratio is one # Risk aversion of market portfolio holder delta = 1 / np.sqrt(w_m @ Sigma @ w_m) # Generate a sample of excess returns excess_return = stat.multivariate_normal(Mu, Sigma) sample = excess_return.rvs(T) #================================== # Mean-variance portfolio #================================== # Estimate mu and sigma Mu_est = sample.mean(0).reshape(N, 1) Sigma_est = np.cov(sample.T) # Solve the constrained problem for the weights (with iota @ w = 1) #iota = np.ones((N, 1)) # column vector of ones #def lamb(mu, sigma, delta): # aux_vector = iota.T @ np.linalg.inv(delta * sigma) # save memory # return ((1 - aux_vector @ mu) / (aux_vector @ iota))[0] # lagrange multiplier on the const #w = np.linalg.solve(d_m * sigma_hat, mu_hat) + lamb(mu_hat, sigma_hat, delta) * iota) w = np.linalg.solve(delta * Sigma_est, Mu_est) fig, ax = plt.subplots(figsize = (8, 5)) ax.set_title('Mean-variance portfolio weights recommendation and the market portfolio ', fontsize = 12) ax.plot(np.arange(N) + 1, w, 'o', color = 'k', label = '$w$ (mean-variance)') ax.plot(np.arange(N) + 1, w_m, 'o', color = 'r', label = '$w_m$ (market portfolio)') ax.vlines(np.arange(N) + 1, 0, w, lw = 1) ax.vlines(np.arange(N) + 1, 0, w_m, lw = 1) ax.axhline(0, color = 'k') ax.axhline(-1, color = 'k', linestyle = '--') ax.axhline(1, color = 'k', linestyle = '--') ax.set_xlim([0, N+1]) ax.set_xlabel('Assets', fontsize = 11) ax.xaxis.set_ticks(np.arange(1, N + 1, 1)) plt.legend(numpoints = 1, loc = 'best', fontsize = 11) plt.show() ``` Black and Litterman's responded to this situation in the following way: * They continue to accept (3) as a good model for choosing an optimal portfolio $w$ * They want to continue to allow the customer to express his or her risk tolerance by setting $\delta$ * Leaving $\Sigma$ at its maximum-likelihood value, they push $\mu$ away from its maximum value in a way designed to make portfolio choices that are more plausible in terms of conforming to what most people actually do. In particular, given $\Sigma$ and a reasonable value of $\delta$, Black and Litterman reverse engineered a vector $\mu_{BL}$ of mean excess returns that makes the $w$ implied by formula (3) equal the **actual** market portfolio $w_m$, so that $$ w_m = (\delta \Sigma)^{-1} \mu_{BL} \quad (4) $$ ##### Details Let's define $$ w_m' \mu \equiv ( r_m - r_f) $$ as the (scalar) excess return on the market portfolio $w_m$. Define $$ \sigma^2 = w_m' \Sigma w_m $$ as the variance of the excess return on the market portfolio $w_m$. Define $$ {\bf SR}_m = \frac{ r_m - r_f}{\sigma} $$ as the **Sharpe-ratio** on the market portfolio $w_m$. Let $\delta_m$ be the value of the risk aversion parameter that induces an investor to hold the market portfolio in light of the optimal portfolio choice rule (3). Evidently, portfolio rule (3) then implies that $ r_m - r_f = \delta_m \sigma^2 $ or $$ \delta_m = \frac{r_m - r_f}{\sigma^2} $$ or $$ \delta_m = \frac{\bf SR}{\sigma}, \quad (5) $$ Following the Black-Litterman philosophy, our first step will be to back a value of $\delta_m$ from * an estimate of the Sharpe-ratio, and * our maximum likelihood estimate of $\sigma$ drawn from our estimates or $w_m$ and $\Sigma$ The second key Black-Litterman step is then to use this value of $\delta$ together with the maximum likelihood estimate of $\Sigma$ to deduce a $\mu_{\bf BL}$ that verifies portfolio rule (3) at the market portfolio $w = w_m$: $$ \mu_m = \delta_m \Sigma w_m $$ The starting point of the Black-Litterman portfolio choice model is thus a pair $(\delta_m, \mu_m) $ that tells the customer to hold the market portfolio. ``` # ===================================================== # Derivation of Black-Litterman pair (\delta_m, \mu_m) # ===================================================== # Observed mean excess market return r_m = w_m @ Mu_est # Estimated variance of market portfolio sigma_m = w_m @ Sigma_est @ w_m # Sharpe-ratio SR_m = r_m/np.sqrt(sigma_m) # Risk aversion of market portfolio holder d_m = r_m/sigma_m # Derive "view" which would induce market portfolio mu_m = (d_m * Sigma_est @ w_m).reshape(N, 1) fig, ax = plt.subplots(figsize = (8, 5)) ax.set_title(r'Difference between $\hat{\mu}$ (estimate) and $\mu_{BL}$ (market implied)', fontsize = 12) ax.plot(np.arange(N) + 1, Mu_est, 'o', color = 'k', label = '$\hat{\mu}$') ax.plot(np.arange(N) + 1, mu_m, 'o', color = 'r', label = '$\mu_{BL}$') ax.vlines(np.arange(N) + 1, mu_m, Mu_est, lw = 1) ax.axhline(0, color = 'k', linestyle = '--') ax.set_xlim([0, N + 1]) ax.set_xlabel('Assets', fontsize = 11) ax.xaxis.set_ticks(np.arange(1, N + 1, 1)) plt.legend(numpoints = 1, loc = 'best', fontsize = 11) plt.show() ``` ##### Adding ``views'' Black and Litterman start with a baseline customer who asserts that he or she shares the ``market's views'', which means that his or her believes that excess returns are governed by $$ \vec r - r_f {\bf 1} \sim {\mathcal N}( \mu_{BL}, \Sigma) , \quad (6) $$ Black and Litterman would advise that customer to hold the market portfolio of risky securities. Black and Litterman then imagine a consumer who would like to express a view that differs from the market's. The consumer wants appropriately to mix his view with the market's before using (3) to choose a portfolio. Suppose that the customer's view is expressed by a hunch that rather than (6), excess returns are governed by $$ \vec r - r_f {\bf 1} \sim {\mathcal N}( \hat \mu, \tau \Sigma) , \quad (7) $$ where $\tau > 0$ is a scalar parameter that determines how the decision maker wants to mix his view $\hat \mu$ with the market's view $\mu_{\bf BL}$. Black and Litterman would then use a formula like the following one to mix the views $\hat \mu$ and $\mu_{\bf BL}$: $$\tilde \mu = (\Sigma^{-1} + (\tau \Sigma)^{-1})^{-1} (\Sigma^{-1} \mu_{BL} + (\tau \Sigma)^{-1} \hat \mu) , \quad (8) $$ Black and Litterman would then advice the customer to hold the portfolio associated with these views implied by rule (3): $$ \tilde w = (\delta \Sigma)^{-1} \tilde \mu , \quad (9) $$ This portfolio $\tilde w$ will deviate from the portfolio $w_{BL}$ in amounts that depend on the mixing parameter $\tau$. If $\hat \mu$ is the maximum likelihood estimator and $\tau$ is chosen heavily to weight this view, then the customer's portfolio will involve big short-long positions. ``` def Black_Litterman(lamb, mu_1, mu_2, Sigma_1, Sigma_2): """ This function calculates the Black-Litterman mixture mean excess return and covariance matrix """ sigma1_inv = np.linalg.inv(Sigma_1) sigma2_inv = np.linalg.inv(Sigma_2) mu_tilde = np.linalg.solve(sigma1_inv + lamb * sigma2_inv, sigma1_inv @ mu_1 + lamb * sigma2_inv @ mu_2) return mu_tilde #=================================== # Example cont' # mean : MLE mean # cov : scaled MLE cov matrix #=================================== tau = 1 mu_tilde = Black_Litterman(1, mu_m, Mu_est, Sigma_est, tau * Sigma_est) # The Black-Litterman recommendation for the portfolio weights w_tilde = np.linalg.solve(delta * Sigma_est, mu_tilde) tau_slider = FloatSlider(min = 0.05, max = 10, step = 0.5, value = tau) @interact(tau = tau_slider) def BL_plot(tau): mu_tilde = Black_Litterman(1, mu_m, Mu_est, Sigma_est, tau * Sigma_est) w_tilde = np.linalg.solve(delta * Sigma_est, mu_tilde) fig, ax = plt.subplots(1, 2, figsize = (16, 6)) ax[0].set_title(r'Relationship between $\hat{\mu}$, $\mu_{BL}$ and $\tilde{\mu}$', fontsize = 15) ax[0].plot(np.arange(N) + 1, Mu_est, 'o', color = 'k', label = r'$\hat{\mu}$ (subj view)') ax[0].plot(np.arange(N) + 1, mu_m, 'o', color = 'r', label = r'$\mu_{BL}$ (market)') ax[0].plot(np.arange(N) + 1, mu_tilde, 'o', color = 'y', label = r'$\tilde{\mu}$ (mixture)') ax[0].vlines(np.arange(N) + 1, mu_m, Mu_est, lw = 1) ax[0].axhline(0, color = 'k', linestyle = '--') ax[0].set_xlim([0, N + 1]) ax[0].xaxis.set_ticks(np.arange(1, N + 1, 1)) ax[0].set_xlabel('Assets', fontsize = 14) ax[0].legend(numpoints = 1, loc = 'best', fontsize = 13) ax[1].set_title('Black-Litterman portfolio weight recommendation', fontsize = 15) ax[1].plot(np.arange(N) + 1, w, 'o', color = 'k', label = r'$w$ (mean-variance)') ax[1].plot(np.arange(N) + 1, w_m, 'o', color = 'r', label = r'$w_{m}$ (market, BL)') ax[1].plot(np.arange(N) + 1, w_tilde, 'o', color = 'y', label = r'$\tilde{w}$ (mixture)') ax[1].vlines(np.arange(N) + 1, 0, w, lw = 1) ax[1].vlines(np.arange(N) + 1, 0, w_m, lw = 1) ax[1].axhline(0, color = 'k') ax[1].axhline(-1, color = 'k', linestyle = '--') ax[1].axhline(1, color = 'k', linestyle = '--') ax[1].set_xlim([0, N + 1]) ax[1].set_xlabel('Assets', fontsize = 14) ax[1].xaxis.set_ticks(np.arange(1, N + 1, 1)) ax[1].legend(numpoints = 1, loc = 'best', fontsize = 13) plt.show() ``` ### Bayes interpretation of the Black-Litterman recommendation Consider the following Bayesian interpretation of the Black-Litterman recommendation. The prior belief over the mean excess returns is consistent with the market porfolio and is given by $$ \mu \sim \mathcal{N}(\mu_{BL}, \Sigma).$$ Given a particular realization of the mean excess returns $\mu$ one observes the average excess returns $\hat \mu$ on the market according to the distribution $$\hat \mu \mid \mu, \Sigma \sim \mathcal{N}(\mu, \tau\Sigma).$$ where $\tau$ is typically small capturing the idea that the variation in the mean is smaller than the variation of the individual random variable. Given the realized excess returns one should then update the prior over the mean excess returns according to Bayes rule. The corresponding posterior over mean excess returns is normally distributed with mean $$ (\Sigma^{-1} + (\tau \Sigma)^{-1})^{-1} (\Sigma^{-1}\mu_{BL} + (\tau \Sigma)^{-1} \hat \mu)$$ The covariance matrix is $$ (\Sigma^{-1} + (\tau \Sigma)^{-1})^{-1}.$$ Hence, the Black-Litterman recommendation is consistent with the Bayes update of the prior over the mean excess returns in light of the realized average excess returns on the market. ### Curve Decolletage Consider two independent "competing" views on the excess market returns. $$ \vec r_e \sim {\mathcal N}( \mu_{BL}, \Sigma) $$ and $$ \vec r_e \sim {\mathcal N}( \hat{\mu}, \tau\Sigma). $$ A special feature of the multivariate normal random variable $Z$ is that its density function depends only on the (Euclidiean) length of its realization $z$. Formally, let the $k$-dimensional random vector be $Z\sim \mathcal{N}(\mu, \Sigma)$, then $\bar{Z} \equiv \Sigma(Z-\mu)\sim \mathcal{N}(\mathbf{0}, I)$ and so the points where the density takes the same value can be described by the ellipse $$\bar z \cdot \bar z = (z - \mu)'\Sigma^{-1}(z - \mu) = \bar d \quad \quad (10)$$ where $\bar d\in\mathbb{R}_+$ denotes the (transformation) of a particular density value. The curves defined by equation (10) can be labelled as iso-likelihood ellipses. > **Remark:** More generally there is a class of density functions that possesses this feature, i.e. > $$\exists g: \mathbb{R}_+ \mapsto \mathbb{R}_+ \ \ \text{ and } \ \ c \geq 0, \ \ \text{s.t. the density } \ \ f \ \ \text{of} \ \ Z \ \ \text{ has the form } \quad f(z) = c g(z\cdot z)$$ > This property is called **spherical symmetry** (see p 81. in Leamer (1978)). In our specific example, we can use the pair $(\bar d_1, \bar d_2)$ as being two "likelihood" values for which the corresponding isolikelihood ellipses in the excess return space are given by \begin{align} (\vec r_e - \mu_{BL})'\Sigma^{-1}(\vec r_e - \mu_{BL}) &= \bar d_1 \\ (\vec r_e - \hat \mu)'\left(\tau \Sigma\right)^{-1}(\vec r_e - \hat \mu) &= \bar d_2 \end{align} Notice that for particular $\bar d_1$ and $\bar d_2$ values the two ellipses have a tangency point. These tangency points, indexed by the pairs $(\bar d_1, \bar d_2)$, characterize points $\vec r_e$ from which there exists no deviation where one can increase the likelihood of one view without decreasing the likelihood of the other view. The pairs $(\bar d_1, \bar d_2)$ for which there is such a point outlines a curve in the excess return space. This curve is reminiscent of the Pareto curve in an Edgeworth-box setting. Leamer (1978) calls this curve *information contract curve* and describes it by the following program: maximize the likelihood of one view, say the Black-Litterman recommendation, while keeping the likelihood of the other view at least at a prespecified constant $\bar d_2$. \begin{align*} \bar d_1(\bar d_2) &\equiv \max_{\vec r_e} \ \ (\vec r_e - \mu_{BL})'\Sigma^{-1}(\vec r_e - \mu_{BL}) \\ \text{subject to } \quad &(\vec r_e - \hat\mu)'(\tau\Sigma)^{-1}(\vec r_e - \hat \mu) \geq \bar d_2 \end{align*} Denoting the multiplier on the constraint by $\lambda$, the first-order condition is $$ 2(\vec r_e - \mu_{BL} )'\Sigma^{-1} + \lambda 2(\vec r_e - \hat\mu)'(\tau\Sigma)^{-1} = \mathbf{0} $$ which defines the *information contract curve* between $\mu_{BL}$ and $\hat \mu$ $$ \vec r_e = (\Sigma^{-1} + \lambda (\tau \Sigma)^{-1})^{-1} (\Sigma^{-1} \mu_{BL} + \lambda (\tau \Sigma)^{-1}\hat \mu ) \quad \quad (11)$$ Note that if $\lambda = 1$, (11) is equivalent with (8) and it identifies one point on the information contract curve. Furthermore, because $\lambda$ is a function of the minimum likelihood $\bar d_2$ on the RHS of the constraint, by varying $\bar d_2$ (or $\lambda$), we can trace out the whole curve as the figure below illustrates. ``` #======================================== # Draw a new sample for two assets #======================================== np.random.seed(1987102) N_new = 2 # number of assets T_new = 200 # sample size tau_new = .8 # random market portfolio (sum is normalized to 1) w_m_new = np.random.rand(N_new) w_m_new = w_m_new/(w_m_new.sum()) Mu_new = (np.random.randn(N_new) + 5)/100 S_new = np.random.randn(N_new, N_new) V_new = S_new @ S_new.T Sigma_new = V_new * (w_m_new @ Mu_new)**2 / (w_m_new @ V_new @ w_m_new) excess_return_new = stat.multivariate_normal(Mu_new, Sigma_new) sample_new = excess_return_new.rvs(T_new) Mu_est_new = sample_new.mean(0).reshape(N_new, 1) Sigma_est_new = np.cov(sample_new.T) sigma_m_new = w_m_new @ Sigma_est_new @ w_m_new d_m_new = (w_m_new @ Mu_est_new)/sigma_m_new mu_m_new = (d_m_new * Sigma_est_new @ w_m_new).reshape(N_new, 1) N_r1, N_r2 = 100, 100 r1 = np.linspace(-0.04, .1, N_r1) r2 = np.linspace(-0.02, .15, N_r2) lamb_grid = np.linspace(.001, 20, 100) curve = np.asarray([Black_Litterman(l, mu_m_new, Mu_est_new, Sigma_est_new, tau_new*Sigma_est_new).flatten() for l in lamb_grid]) lamb_slider = FloatSlider(min = .1, max = 7, step = .5, value = 1) @interact(lamb = lamb_slider) def decolletage(lamb): dist_r_BL = stat.multivariate_normal(mu_m_new.squeeze(), Sigma_est_new) dist_r_hat = stat.multivariate_normal(Mu_est_new.squeeze(), tau_new * Sigma_est_new) X, Y = np.meshgrid(r1, r2) Z_BL = np.zeros((N_r1, N_r2)) Z_hat = np.zeros((N_r1, N_r2)) for i in range(N_r1): for j in range(N_r2): Z_BL[i, j] = dist_r_BL.pdf(np.hstack([X[i, j], Y[i, j]])) Z_hat[i, j] = dist_r_hat.pdf(np.hstack([X[i, j], Y[i, j]])) mu_tilde_new = Black_Litterman(lamb, mu_m_new, Mu_est_new, Sigma_est_new, tau_new * Sigma_est_new).flatten() fig, ax = plt.subplots(figsize = (10, 6)) ax.contourf(X, Y, Z_hat, cmap = 'viridis', alpha =.4) ax.contourf(X, Y, Z_BL, cmap = 'viridis', alpha =.4) ax.contour(X, Y, Z_BL, [dist_r_BL.pdf(mu_tilde_new)], cmap = 'viridis', alpha = .9) ax.contour(X, Y, Z_hat, [dist_r_hat.pdf(mu_tilde_new)], cmap = 'viridis', alpha = .9) ax.scatter(Mu_est_new[0], Mu_est_new[1]) ax.scatter(mu_m_new[0], mu_m_new[1]) ax.scatter(mu_tilde_new[0], mu_tilde_new[1], color = 'k', s = 20*3) ax.plot(curve[:, 0], curve[:, 1], color = 'k') ax.axhline(0, color = 'k', alpha = .8) ax.axvline(0, color = 'k', alpha = .8) ax.set_xlabel(r'Excess return on the first asset, $r_{e, 1}$', fontsize = 12) ax.set_ylabel(r'Excess return on the second asset, $r_{e, 2}$', fontsize = 12) ax.text(Mu_est_new[0] + 0.003, Mu_est_new[1], r'$\hat{\mu}$', fontsize = 20) ax.text(mu_m_new[0] + 0.003, mu_m_new[1] + 0.005, r'$\mu_{BL}$', fontsize = 20) ``` Note that the line that connects the two points $\hat \mu$ and $\mu_{BL}$ is linear, which comes from the fact that the covariance matrices of the two competing distributions (views) are proportional to each other. To illustrate the fact that this is not necessarily the case, consider another example using the same parameter values, except that the "second view" constituting the constraint has covariance matrix $\tau I$ instead of $\tau \Sigma$. This leads to the following figure, on which the curve connecting $\hat \mu$ and $\mu_{BL}$ are bending. ``` lamb_grid2 = np.linspace(.001, 20000, 1000) curve2 = np.asarray([Black_Litterman(l, mu_m_new, Mu_est_new, Sigma_est_new, tau_new*np.eye(N_new)).flatten() for l in lamb_grid2]) lamb_slider2 = FloatSlider(min = 5, max = 1500, step = 100, value = 200) @interact(lamb = lamb_slider2) def decolletage(lamb): dist_r_BL = stat.multivariate_normal(mu_m_new.squeeze(), Sigma_est_new) dist_r_hat = stat.multivariate_normal(Mu_est_new.squeeze(), tau_new * np.eye(N_new)) X, Y = np.meshgrid(r1, r2) Z_BL = np.zeros((N_r1, N_r2)) Z_hat = np.zeros((N_r1, N_r2)) for i in range(N_r1): for j in range(N_r2): Z_BL[i, j] = dist_r_BL.pdf(np.hstack([X[i, j], Y[i, j]])) Z_hat[i, j] = dist_r_hat.pdf(np.hstack([X[i, j], Y[i, j]])) mu_tilde_new = Black_Litterman(lamb, mu_m_new, Mu_est_new, Sigma_est_new, tau_new * np.eye(N_new)).flatten() fig, ax = plt.subplots(figsize = (10, 6)) ax.contourf(X, Y, Z_hat, cmap = 'viridis', alpha = .4) ax.contourf(X, Y, Z_BL, cmap = 'viridis', alpha = .4) ax.contour(X, Y, Z_BL, [dist_r_BL.pdf(mu_tilde_new)], cmap='viridis', alpha =.9) ax.contour(X, Y, Z_hat, [dist_r_hat.pdf(mu_tilde_new)], cmap='viridis', alpha =.9) ax.scatter(Mu_est_new[0], Mu_est_new[1]) ax.scatter(mu_m_new[0], mu_m_new[1]) ax.scatter(mu_tilde_new[0], mu_tilde_new[1], color = 'k', s = 20*3) ax.plot(curve2[:, 0], curve2[:, 1], color = 'k') ax.axhline(0, color = 'k', alpha = .8) ax.axvline(0, color = 'k', alpha = .8) ax.set_xlabel(r'Excess return on the first asset, $r_{e, 1}$', fontsize = 12) ax.set_ylabel(r'Excess return on the second asset, $r_{e, 2}$', fontsize = 12) ax.text(Mu_est_new[0] + 0.003, Mu_est_new[1], r'$\hat{\mu}$', fontsize = 20) ax.text(mu_m_new[0] + 0.003, mu_m_new[1] + 0.005, r'$\mu_{BL}$', fontsize = 20) ``` ### Black-Litterman recommendation as regularization First, consider the OLS regression. $$\min_{\beta} \Vert X\beta - y \Vert^2 $$ which yields the solution $$ \hat{\beta}_{OLS} = (X'X)^{-1}X'y.$$ A common performance measure of estimators is the *mean squared error (MSE)*. An estimator is "good" if its MSE is realtively small. Suppose that $\beta_0$ is the "true" value of the coefficent, then the MSE of the OLS estimator is $$\text{mse}(\hat \beta_{OLS}, \beta_0) := \mathbb E \Vert \hat \beta_{OLS} - \beta_0\Vert^2 = \underbrace{\mathbb E \Vert \hat \beta_{OLS} - \mathbb E \beta_{OLS}\Vert^2}_{\text{variance}} + \underbrace{\Vert \mathbb E \hat\beta_{OLS} - \beta_0\Vert^2}_{\text{bias}}$$ From this decomposition one can see that in order for the MSE to be small, both the bias and the variance terms must be small. For example, consider the case when $X$ is a $T$-vector of ones (where $T$ is the sample size), so $\hat\beta_{OLS}$ is simply the sample average, while $\beta_0\in \mathbb{R}$ is defined by the true mean of $y$. In this example the MSE is $$ \text{mse}(\hat \beta_{OLS}, \beta_0) = \underbrace{\frac{1}{T^2} \mathbb E \left(\sum_{t=1}^{T} (y_{t}- \beta_0)\right)^2 }_{\text{variance}} + \underbrace{0}_{\text{bias}}$$ However, because there is a trade-off between the estimator's bias and variance, there are cases when by permitting a small bias we can substantially reduce the variance so overall the MSE gets smaller. A typical scenario when this proves to be useful is when the number of coefficients to be estimated is large relative to the sample size. In these cases one approach to handle the bias-variance trade-off is the so called *Tikhonov regularization*. A general form with regularization matrix $\Gamma$ can be written as $$\min_{\beta} \Big\{ \Vert X\beta - y \Vert^2 + \Vert \Gamma (\beta - \tilde \beta) \Vert^2 \Big\}$$ which yields the solution $$ \hat{\beta}_{Reg} = (X'X + \Gamma'\Gamma)^{-1}(X'y + \Gamma'\Gamma\tilde \beta).$$ Substituting the value of $\hat{\beta}_{OLS}$ yields $$ \hat{\beta}_{Reg} = (X'X + \Gamma'\Gamma)^{-1}(X'X\hat{\beta}_{OLS} + \Gamma'\Gamma\tilde \beta).$$ Often, the regularization matrix takes the form $\Gamma = \lambda I$ with $\lambda>0$ and $\tilde \beta = \mathbf{0}$. Then the Tikhonov regularization is equivalent to what is called *ridge regression* in statistics. To illustrate how this estimator addresses the bias-variance trade-off, we compute the MSE of the ridge estimator $$ \text{mse}(\hat \beta_{\text{ridge}}, \beta_0) = \underbrace{\frac{1}{(T+\lambda)^2} \mathbb E \left(\sum_{t=1}^{T} (y_{t}- \beta_0)\right)^2 }_{\text{variance}} + \underbrace{\left(\frac{\lambda}{T+\lambda}\right)^2 \beta_0^2}_{\text{bias}}$$ The ridge regression shrinks the coefficients of the estimated vector towards zero relative to the OLS estimates thus reducing the variance term at the cost of introducing a "small" bias. However, there is nothing special about the zero vector. When $\tilde \beta \neq \mathbf{0}$ shrinkage occurs in the direction of $\tilde \beta$. Now, we can give a regularization interpretation of the Black-Litterman portfolio recommendation. To this end, simplify first the equation (8) characterizing the Black-Litterman recommendation \begin{align*} \tilde \mu &= (\Sigma^{-1} + (\tau \Sigma)^{-1})^{-1} (\Sigma^{-1}\mu_{BL} + (\tau \Sigma)^{-1}\hat \mu) \\ &= (1 + \tau^{-1})^{-1}\Sigma \Sigma^{-1} (\mu_{BL} + \tau ^{-1}\hat \mu) \\ &= (1 + \tau^{-1})^{-1} ( \mu_{BL} + \tau ^{-1}\hat \mu) \end{align*} In our case, $\hat \mu$ is the estimated mean excess returns of securities. This could be written as a vector autoregression where * $y$ is the stacked vector of observed excess returns of size $(N T\times 1)$ -- $N$ securities and $T$ observations * $X = \sqrt{T^{-1}}(I_{N} \otimes \iota_T)$ where $I_N$ is the identity matrix and $\iota_T$ is a column vector of ones. Correspondingly, the OLS regression of $y$ on $X$ would yield the mean excess returns as coefficients. With $\Gamma = \sqrt{\tau T^{-1}}(I_{N} \otimes \iota_T)$ we can write the regularized version of the mean excess return estimation. \begin{align*} \hat{\beta}_{Reg} &= (X'X + \Gamma'\Gamma)^{-1}(X'X\hat{\beta}_{OLS} + \Gamma'\Gamma\tilde \beta) \\ &= (1 + \tau)^{-1}X'X (X'X)^{-1} (\hat \beta_{OLS} + \tau \tilde \beta) \\ &= (1 + \tau)^{-1} (\hat \beta_{OLS} + \tau \tilde \beta) \\ &= (1 + \tau^{-1})^{-1} ( \tau^{-1}\hat \beta_{OLS} + \tilde \beta) \end{align*} Given that $\hat \beta_{OLS} = \hat \mu$ and $\tilde \beta = \mu_{BL}$ in the Black-Litterman model we have the following interpretation of the model's recommendation. The estimated (personal) view of the mean excess returns, $\hat{\mu}$ that would lead to extreme short-long positions are "shrunk" towards the conservative market view, $\mu_{BL}$. that leads to the more conservative market portfolio. So the Black-Litterman procedure results in a recommendation that is a compromise between the conservative market portfolio and the more extreme portfolio that is implied by estimated "personal" views. ### Digression on ${\sf T}$ operator The Black-Litterman approach is partly inspired by the econometric insight that it is easier to estimate covariances of excess returns than the means. That is what gave Black and Litterman license to adjust investors' perception of mean excess returns while not tampering with the covariance matrix of excess returns. The robust control theory is another approach that also hinges on adjusting mean excess returns but not covariances. Associated with a robust control problem is what Hansen and Sargent call a ${\sf T}$ operator. Let's define the ${\sf T}$ operator as it applies to the problem at hand. Let $x$ be an $n \times 1$ Gaussian random vector with mean vector $\mu$ and covariance matrix $\Sigma = C C'$. This means that $x$ can be represented as $$ x = \mu + C \epsilon $$ where $\epsilon \sim {\mathcal N}(0,I)$. Let $\phi(\epsilon)$ denote the associated standardized Gaussian density. Let $m(\epsilon,\mu)$ be a **likelihood ratio**, meaning that it satisfies * $m(\epsilon, \mu) > 0 $ * $ \int m(\epsilon,\mu) \phi(\epsilon) d \epsilon =1 $ That is, $m(\epsilon, \mu)$ is a nonnegative random variable with mean 1. Multiplying $\phi(\epsilon) $ by the likelihood ratio $m(\epsilon, \mu)$ produces a distorted distribution for $\epsilon$, namely, $$ \tilde \phi(\epsilon) = m(\epsilon,\mu) \phi(\epsilon) $$ The next concept that we need is the **entropy** of the distorted distribution $\tilde \phi$ with respect to $\phi$. **Entropy** is defined as $$ {\rm ent} = \int \log m(\epsilon,\mu) m(\epsilon,\mu) \phi(\epsilon) d \epsilon $$ or $$ {\rm ent} = \int \log m(\epsilon,\mu) \tilde \phi(\epsilon) d \epsilon $$ That is, relative entropy is the expected value of the likelihood ratio $m$ where the expectation is taken with respect to the twisted density $\tilde \phi$. Relative entropy is nonnegative. It is a measure of the discrepancy between two probability distributions. As such, it plays an important role in governing the behavior of statistical tests designed to discriminate one probability distribution from another. We are ready to define the ${\sf T}$ operator. Let $V(x)$ be a value function. Define $$ \eqalign{ {\sf T}\left(V(x)\right) & = \min_{m(\epsilon,\mu)} \int m(\epsilon,\mu)[V(\mu + C \epsilon) + \theta \log m(\epsilon,\mu) ] \phi(\epsilon) d \epsilon \cr & = - \log \theta \int \exp \left( \frac{- V(\mu + C \epsilon)}{\theta} \right) \phi(\epsilon) d \epsilon } $$ This asserts that ${\sf T}$ is an indirect utility function for a minimization problem in which an ``evil agent'' chooses a distorted probablity distribution $\tilde \phi$ to lower expected utility, subject to a penalty term that gets bigger the larger is relative entropy. Here the penalty parameter $\theta \in [\underline \theta, +\infty] $ is a robustness parameter; when it is $+\infty$, there is no scope for the minimizing agent to distort the distribution, so no robustness to alternative distributions is acquired. As $\theta$ is lowered, more robustness is achieved. **Note:** The ${\sf T}$ operator is sometimes called a *risk-sensitivity* operator. We shall apply ${\sf T}$ to the special case of a linear value function $w' (\vec r - r_f {\bf 1}) $ where $\vec r - r_f {\bf 1} \sim \mathcal N(\mu , \Sigma)$ or $\vec r - r_f {\bf 1} = \mu + C \epsilon$ and $\epsilon \sim {\mathcal N}(0,I)$. The associated worst-case distribution of $\epsilon$ is Gaussian with mean $v =-\theta^{-1} C' w$ and covariance matrix $I$. (When the value function is affine, the worst-case distribution distorts the mean vector of $\epsilon$ but not the covariance matrix of $\epsilon$.) For utility function argument $w' (\vec r - r_f {\bf 1}) $, $$ {\sf T} (\vec r - r_f {\bf 1}) = w' \mu + \zeta - \frac{1}{2\theta} w' \Sigma w $$ and entropy is $$ \frac{v'v}{2} = \frac{1}{2\theta^2} w' C C' w. $$ #### A robust mean-variance portfolio model According to criterion (1), the mean-variance portfolio choice problem chooses $w$ to maximize $$ E [w ( \vec r - r_f {\bf 1})]] - {\rm var} [ w ( \vec r - r_f {\bf 1}) ] \quad (10) $$ which equals $$ w'\mu - \frac{\delta}{2} w' \Sigma w $$ A robust decision maker can be modelled as replacing the mean return $ E [w ( \vec r - r_f {\bf 1})]$ with the risk-sensitive $$ {\sf T} [w ( \vec r - r_f {\bf 1})] = w' \mu - \frac{1}{2 \theta} w' \Sigma w $$ that comes from replacing the mean $\mu$ of $ \vec r - r_f {\bf 1} $ with the worst-case mean $$ \mu - \theta^{-1} \Sigma w $$ Notice how the worst-case mean vector depends on the portfolio $w$. The operator ${\sf T}$ is the indirect utility function that emerges from solving a problem in which an agent who chooses probabilities does so in order to minimize the expected utility of a maximizing agent (in our case, the maximizing agent chooses portfolio weights $w$). The robust version of the mean-variance portfolio choice problem is then to choose a portfolio $w$ that maximizes $$ {\sf T} [w ( \vec r - r_f {\bf 1})] - \frac{\delta}{2} w' \Sigma w , \quad (11) $$ or $$ w' (\mu - \theta^{-1} \Sigma w ) - \frac{\delta}{2} w' \Sigma w, \quad (12) $$ The minimizer of (12) is $$ w_{\rm rob} = \frac{1}{\delta + \gamma } \Sigma^{-1} \mu , \quad (13) $$ where $\gamma \equiv \theta^{-1}$ is sometimes called the risk-sensitivity parameter. An increase in the risk-sensitivity paramter $\gamma$ shrinks the portfolio weights toward zero in the same way that an increase in risk aversion does. ---------------------------------------- # Appendix We want to illustrate the "folk theorem" that with high or moderate frequency data, it is more difficult to esimate means than variances. In order to operationalize this statement, we take two analog estimators: - sample average: $\bar X_N = \frac{1}{N}\sum_{i=1}^{N} X_i$ - sample variance: $S_N = \frac{1}{N-1}\sum_{t=1}^{N} (X_i - \bar X_N)^2$ to estimate the unconditional mean and unconditional variance of the random variable $X$, respectively. To measure the "difficulty of estimation", we use *mean squared error* (MSE), that is the average squared difference between the estimator and the true value. Assuming that the process $\{X_i\}$ is ergodic, both analog estimators are known to converge to their true values as the sample size $N$ goes to infinity. More precisely, for all $\varepsilon > 0$, \begin{align} \lim_{N\to \infty} \ \ P\left\{ \left |\bar X_N - \mathbb E X \right| > \varepsilon \right\} = 0 \quad \quad \text{and}\quad \quad \lim_{N\to \infty} \ \ P \left\{ \left| S_N - \mathbb V X \right| > \varepsilon \right\} = 0 \end{align} A necessary condition for these convergence results is that the associated MSEs vanish as $N$ goes to infintiy, or in other words, $$\text{MSE}(\bar X_N, \mathbb E X) = o(1) \quad \quad \text{and} \quad \quad \text{MSE}(S_N, \mathbb V X) = o(1)$$ Even if the MSEs converge to zero, the associated rates might be different. Looking at the limit of the *relative MSE* (as the sample size grows to infinity) $$ \frac{\text{MSE}(S_N, \mathbb V X)}{\text{MSE}(\bar X_N, \mathbb E X)} = \frac{o(1)}{o(1)} \underset{N \to \infty}{\to} B $$ can inform us about the relative (asymptotic) rates. We will show that in general, with dependent data, the limit $B$ depends on the sampling frequency. In particular, we find that the rate of convergence of the variance estimator is less sensitive to increased sampling frequency than the rate of convergence of the mean estimator. Hence, we can expect the relative asymptotic rate, $B$, to get smaller with higher frequency data, illustrating that "it is more difficult to estimate means than variances". That is, we need significantly more data to obtain a given precision of the mean estimate than for our variance estimate. ### A special case -- i.i.d. sample We start our analysis with the benchmark case of iid data. Consider a sample of size $N$ generated by the following iid process, $$X_i \sim \mathcal{N}(\mu, \sigma^2).$$ Taking $\bar X_N$ to estimate the mean, the MSE is $$ \text{MSE}(\bar X_N, \mu) = \frac{\sigma^2}{N} .$$ Taking $S_N$ to estimate the variance, the MSE is $$ \text{MSE}(S_N, \sigma^2) = \frac{2\sigma^4}{N-1} .$$ Both estimators are unbiased and hence the MSEs reflect the corresponding variances of the estimators. Furthermore, both MSEs are $o(1)$ with a (multiplicative) factor of difference in their rates of convergence: $$ \frac{\text{MSE}(S_N, \sigma^2)}{\text{MSE}(\bar X_N, \mu)} = \frac{N2\sigma^2}{N-1} \quad \underset{N \to \infty}{\to} \quad 2\sigma^2$$ We are interested in how this (asymptotic) relative rate of convergence changes as increasing sampling frequency puts dependence into the data. ### Dependence and sampling frequency To investigate how sampling frequency affects relative rates of convergence, we assume that the data are generated by a mean-reverting continuous time process of the form $$dX_t = -\kappa (X_t -\mu)dt + \sigma dW_t\quad\quad $$ where $\mu$ is the unconditional mean, $\kappa > 0$ is a persistence parameter, and $\{W_t\}$ is a standardized Brownian motion. Observations arising from this system in particular discrete periods $\mathcal T(h) \equiv \{nh : n \in \mathbb Z \}$ with $h>0$ can be described by the following process $$X_{t+1} = (1 - \exp(-\kappa h))\mu + \exp(-\kappa h)X_t + \epsilon_{t, h}$$ where $$\epsilon_{t, h} \sim \mathcal{N}(0, \Sigma_h) \quad \text{with}\quad \Sigma_h = \frac{\sigma^2(1-\exp(-2\kappa h))}{2\kappa}$$ We call $h$ the *frequency* parameter, whereas $n$ represents the number of *lags* between observations. Hence, the effective distance between two observations $X_t$ and $X_{t+n}$ in the discrete time notation is equal to $h\cdot n$ in terms of the underlying continuous time process. Straightforward calculations show that the autocorrelation function for the stochastic process $\{X_{t}\}_{t\in \mathcal T(h)}$ is $$\Gamma_h(n) \equiv \text{corr}(X_{t + h n}, X_t) = \exp(-\kappa h n)$$ and the autocovariance function is $$\gamma_h(n) \equiv \text{cov}(X_{t + h n}, X_t) = \frac{\exp(-\kappa h n)\sigma^2}{2\kappa} .$$ It follows that if $n=0$, the unconditional variance is given by $\gamma_h(0) = \frac{\sigma^2}{2\kappa}$ irrespective of the sampling frequency. The following figure illustrates how the dependence between the observations is related to sampling frequency. - For any given $h$, the autocorrelation converges to zero as we increase the distance -- $n$ -- between the observations. This represents the "weak dependence" of the $X$ process. - Moreover, for a fixed lag length, $n$, the dependence vanishes as the sampling frequency goes to infinity. In fact, letting $h$ go to $\infty$ gives back the case of i.i.d. data. ``` mu = .0 kappa = .1 sigma = .5 var_uncond = sigma**2 / (2 * kappa) n_grid = np.linspace(0, 40, 100) autocorr_h1 = np.exp(- kappa * n_grid * 1) autocorr_h2 = np.exp(- kappa * n_grid * 2) autocorr_h5 = np.exp(- kappa * n_grid * 5) autocorr_h1000 = np.exp(- kappa * n_grid * 1e8) fig, ax = plt.subplots(figsize = (8, 4)) ax.plot(n_grid, autocorr_h1, label = r'$h = 1$', color = 'darkblue', lw = 2) ax.plot(n_grid, autocorr_h2, label = r'$h = 2$', color = 'darkred', lw = 2) ax.plot(n_grid, autocorr_h5, label = r'$h = 5$', color = 'orange', lw = 2) ax.plot(n_grid, autocorr_h1000, label = r'"$h = \infty$"', color = 'darkgreen', lw = 2) ax.legend(loc = 'best', fontsize = 13) ax.grid() ax.set_title(r'Autocorrelation functions, $\Gamma_h(n)$', fontsize = 13) ax.set_xlabel(r'Lags between observations, $n$', fontsize = 11) plt.show() ``` ### Frequency and the mean estimator Consider again the AR(1) process generated by discrete sampling with frequency $h$. Assume that we have a sample of size $N$ and we would like to estimate the unconditional mean -- in our case the true mean is $\mu$. Again, the sample average is an unbiased estimator of the unconditional mean. $$ \mathbb{E}[\bar X_N] = \frac{1}{N}\sum_{i = 1}^N \mathbb{E}[X_i] = \mathbb{E}[X_0] = \mu $$ The variance of the sample mean is given by \begin{align} \mathbb{V}\left(\bar X_N\right) &= \mathbb{V}\left(\frac{1}{N}\sum_{i = 1}^N X_i\right) \\ &= \frac{1}{N^2} \left(\sum_{i = 1}^N \mathbb{V}(X_i) + 2 \sum_{i = 1}^{N-1} \sum_{s = i+1}^N \text{cov}(X_i, X_s) \right) \\ &= \frac{1}{N^2} \left( N \gamma(0) + 2 \sum_{i=1}^{N-1} i \cdot \gamma\left(h\cdot (N - i)\right) \right) \\ &= \frac{1}{N^2} \left( N \frac{\sigma^2}{2\kappa} + 2 \sum_{i=1}^{N-1} i \cdot \exp(-\kappa h (N - i)) \frac{\sigma^2}{2\kappa} \right) \end{align} It is explicit in the above equation that time dependence in the data inflates the variance of the mean estimator through the covariance terms. Moreover, as we can see, a higher sampling frequency---smaller $h$---makes all the covariance terms larger everything else being fixed. This implies a relatively slower rate of convergence of the sample average for high frequency data. Intuitively, the stronger dependence across observations for high frequency data reduces the "information content" of each observation relative to the iid case. We can upper bound the variance term in the following way. \begin{align} \mathbb{V}(\bar X_N) &= \frac{1}{N^2} \left( N \sigma^2 + 2 \sum_{i=1}^{N-1} i \cdot \exp(-\kappa h (N - i)) \sigma^2 \right) \\ &\leq \frac{\sigma^2}{2\kappa N} \left(1 + 2 \sum_{i=1}^{N-1} \cdot \exp(-\kappa h (i)) \right) \\ &= \underbrace{\frac{\sigma^2}{2\kappa N}}_{\text{i.i.d. case}} \left(1 + 2 \frac{1 - \exp(-\kappa h)^{N-1}}{1 - \exp(-\kappa h)} \right) \end{align} Asymptotically the $\exp(-\kappa h)^{N-1}$ vanishes and the dependence in the data inflates the benchmark iid variance by a factor of $\left(1 + 2 \frac{1}{1 - \exp(-\kappa h)} \right)$. This long run factor is larger the higher is the frequency (the smaller is $h$). Therefore, we expect the asymptotic relative MSEs, $B$, to change with time dependent data. We just saw that the mean estimator's rate is roughly changing by a factor of $\left(1 + 2 \frac{1}{1 - \exp(-\kappa h)} \right)$. Unfortunately, the variance estimator's MSE is harder to derive. Nonetheless, we can approximate it by using (large sample) simulations, thus getting an idea about how the asymptotic relative MSEs changes in the sampling frequency $h$ relative to the iid case that we compute in closed form. ``` def sample_generator(h, N, M): phi = (1 - np.exp(- kappa * h)) * mu rho = np.exp(- kappa * h) s = sigma**2 * (1 - np.exp(-2 * kappa * h)) / (2 * kappa) mean_uncond = mu std_uncond = np.sqrt(sigma**2 / (2 * kappa)) eps_path = stat.norm(0, np.sqrt(s)).rvs((M, N)) y_path = np.zeros((M, N + 1)) y_path[:, 0] = stat.norm(mean_uncond, std_uncond).rvs(M) for i in range(N): y_path[:, i + 1] = phi + rho*y_path[:, i] + eps_path[:, i] return y_path # generate large sample for different frequencies N_app, M_app = 1000, 30000 # sample size, number of simulations h_grid = np.linspace(.1, 80, 30) var_est_store = [] mean_est_store = [] labels = [] for h in h_grid: labels.append(h) sample = sample_generator(h, N_app, M_app) mean_est_store.append(np.mean(sample, 1)) var_est_store.append(np.var(sample, 1)) var_est_store = np.array(var_est_store) mean_est_store = np.array(mean_est_store) # save mse of estimators mse_mean = np.var(mean_est_store, 1) + (np.mean(mean_est_store, 1) - mu)**2 mse_var = np.var(var_est_store, 1) + (np.mean(var_est_store, 1) - var_uncond)**2 benchmark_rate = 2*var_uncond # iid case #relative MSE for large samples rate_h = mse_var/mse_mean fig, ax = plt.subplots(figsize = (8, 5)) ax.plot(h_grid, rate_h, color = 'darkblue', lw = 2, label = r'large sample relative MSE, $B(h)$') ax.axhline(benchmark_rate, color = 'k', linestyle = '--', label = r'iid benchmark') ax.set_title('Relative MSE for large samples as a function of sampling frequency \n MSE($S_N$) relative to MSE($\\bar X_N$)', fontsize = 12) ax.set_xlabel('Sampling frequency, $h$', fontsize = 11) ax.set_ylim([1, 2.9]) ax.legend(loc = 'best', fontsize = 10) plt.show() ``` The above figure illustrates the relationship between the asymptotic relative MSEs and the sampling frequency. * We can see that with low frequency data -- large values of $h$ -- the ratio of asymptotic rates approaches the iid case. * As $h$ gets smaller -- the higher the frequency -- the relative performance of the variance estimator is better in the sense that the ratio of asymptotic rates gets smaller. That is, as the time dependence gets more pronounced, the rate of convergence of the mean estimator's MSE deteriorates more than that of the variance estimator. ----------------------------------------------------------- #### References Black, F. and Litterman, R., 1992. "Global portfolio optimization". Financial analysts journal, 48(5), pp.28-43. Dickey, J. 1975. "Bayesian alternatives to the F-test and least-squares estimate in the normal linear model", in: S.E. Fienberg and A. Zellner, eds., "Studies in Bayesian econometrics and statistics" (North-Holland, Amsterdam) 515-554. Hansen, Lars Peter and Thomas J. Sargent. 2001. "Robust Control and Model Uncertainty." American Economic Review, 91(2): 60-66. Leamer, E.E., 1978. **Specification searches: Ad hoc inference with nonexperimental data**, (Vol. 53). John Wiley & Sons Incorporated.
github_jupyter
``` from __future__ import absolute_import, division, print_function, unicode_literals try: %tensorflow_version 2.x except Exception: pass import tensorflow as tf from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import numpy as np from IPython.display import Image # in order to always get the same result tf.random.set_seed(1) np.random.seed(1) ``` # Auto Encoder Using Dense layer, we will compress MNIST to 3d vector so we can visualize it. This is called Auto Encoder design. ``` Image(url= "https://raw.githubusercontent.com/captainchargers/deeplearning/master/img/autoencoder1.png", width=500, height=250) ``` # Get MNIST Data ``` (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() ``` # MNIST Preprocess ``` # we will use train data for auto encoder training x_train = x_train.reshape(60000, 784) # select only 300 test data for visualization x_test = x_test[:300] y_test = y_test[:300] x_test = x_test.reshape(300, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') # normalize data gray_scale = 255 x_train /= gray_scale x_test /= gray_scale ``` # Auto Encoder diagram ``` Image(url= "https://raw.githubusercontent.com/captainchargers/deeplearning/master/img/autoencoder2.png", width=500, height=250) ``` # Modeling ``` # MNIST input 28 rows * 28 columns = 784 pixels input_img = Input(shape=(784,)) # encoder encoder1 = Dense(128, activation='sigmoid')(input_img) encoder2 = Dense(3, activation='sigmoid')(encoder1) # decoder decoder1 = Dense(128, activation='sigmoid')(encoder2) decoder2 = Dense(784, activation='sigmoid')(decoder1) # this model maps an input to its reconstruction autoencoder = Model(inputs=input_img, outputs=decoder2) autoencoder.compile(optimizer='adam', loss='binary_crossentropy') # GPU %time autoencoder.fit(x_train, x_train, epochs=1, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # GPU %time autoencoder.fit(x_train, x_train, epochs=10, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # GPU %time autoencoder.fit(x_train, x_train, epochs=20, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # GPU %time autoencoder.fit(x_train, x_train, epochs=5, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # CPU # %time autoencoder.fit(x_train, x_train, epochs=5, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # TPU # %time autoencoder.fit(x_train, x_train, epochs=5, batch_size=32, shuffle=True, validation_data=(x_test, x_test)) # create encoder model encoder = Model(inputs=input_img, outputs=encoder2) # create decoder model encoded_input = Input(shape=(3,)) decoder_layer1 = autoencoder.layers[-2] decoder_layer2 = autoencoder.layers[-1] decoder = Model(inputs=encoded_input, outputs=decoder_layer2(decoder_layer1(encoded_input))) # get latent vector for visualization latent_vector = encoder.predict(x_test) # get decoder output to visualize reconstructed image reconstructed_imgs = decoder.predict(latent_vector) ``` # MNIST 3D Visualization ``` # epoch is 1 # visualize in 3D plot from pylab import rcParams rcParams['figure.figsize'] = 10, 8 fig = plt.figure(1) ax = Axes3D(fig) xs = latent_vector[:, 0] ys = latent_vector[:, 1] zs = latent_vector[:, 2] color=['red','green','blue','lime','white','pink','aqua','violet','gold','coral'] for x, y, z, label in zip(xs, ys, zs, y_test): c = color[int(label)] ax.text(x, y, z, label, backgroundcolor=c) ax.set_xlim(xs.min(), xs.max()) ax.set_ylim(ys.min(), ys.max()) ax.set_zlim(zs.min(), zs.max()) plt.show() # epoch is 10 # visualize in 3D plot from pylab import rcParams rcParams['figure.figsize'] = 10, 8 fig = plt.figure(1) ax = Axes3D(fig) xs = latent_vector[:, 0] ys = latent_vector[:, 1] zs = latent_vector[:, 2] color=['red','green','blue','lime','white','pink','aqua','violet','gold','coral'] for x, y, z, label in zip(xs, ys, zs, y_test): c = color[int(label)] ax.text(x, y, z, label, backgroundcolor=c) ax.set_xlim(xs.min(), xs.max()) ax.set_ylim(ys.min(), ys.max()) ax.set_zlim(zs.min(), zs.max()) plt.show() ``` # Visualize Reconstructed Images ``` #epoc is 1 n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstructed image ax = plt.subplot(2, n, i + 1 + n) plt.imshow(reconstructed_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() #epoc is 10 n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstructed image ax = plt.subplot(2, n, i + 1 + n) plt.imshow(reconstructed_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() # this epoch is 20 n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstructed image ax = plt.subplot(2, n, i + 1 + n) plt.imshow(reconstructed_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() ```
github_jupyter
<a href='https://ai.meng.duke.edu'> = <img align="left" style="padding-top:10px;" src=https://storage.googleapis.com/aipi_datasets/Duke-AIPI-Logo.png> # Boilerplate for running projects in Google Colab ``` # Run this cell only if working in Colab # Connects to any needed files from GitHub and Google Drive import os import getpass # Remove Colab default sample_data !rm -r ./sample_data # Clone GitHub files to colab workspace git_user = "AIPI540" # Enter user or organization name git_email = "jon.reifschneider@gmail.com" # Enter your email repo_name = "AIPI540-Deep-Learning-Applications" # Enter repo name # Use the below if repo is private, or is public and you want to push to it # Otherwise comment next two lines out git_token = getpass.getpass("enter git token") # Enter your github token git_path = f"https://{git_token}@github.com/{git_user}/{repo_name}.git" # Use the below instead if repo is public and you do not need to push to it #git_path = 'https://github.com/AIPI540/AIPI540-Deep-Learning-Applications.git' #Enter repo url !git clone "{git_path}" # Install dependencies from requirements.txt file notebook_dir = '0_infra_setup/colab_example' !pip install -r "{os.path.join(repo_name,notebook_dir,'requirements.txt')}" # Change working directory to location of notebook path_to_notebook = os.path.join(repo_name,notebook_dir) %cd "{path_to_notebook}" %ls # Mount Google drive to access files there # from google.colab import drive # drive.mount('/content/gdrive') # # Path to files in Google Drive # path_to_gdrive_files = '../../gdrive/MyDrive/AIPI540/class_demos/colab_example' # # Display contents # print('Contents of gdrive directory:') # print(os.listdir(path_to_gdrive_files)) import numpy as np import pandas as pd # Import a user-defined class from jonsmodule import Student # Demonstrate use of imported class Student name = 'jon reifschneider' email = 'jon.reifschneider@duke.edu' jon = Student(name,email) print(jon.name) print(f'Current grades: {jon.grades}') course='AIPI520' new_grade = 85 jon.add_grade(course,new_grade) print(f'New grades: {jon.get_grades()}') course='AIPI510' new_grade = 95 jon.add_grade(course,new_grade) # Demonstrate saving data to a file # You can then push your data file back to github course='AIPI510' new_grade = 95 jon.add_grade(course,new_grade) grades = pd.DataFrame(jon.grades.items(),columns=['Course','Grade']) grades.to_csv('grades.csv',index=False) grades # To edit a python script in Colab, double click on it in left side file explorer # Make edits, then be sure to push your edited file back to github # Execute a python script from Colab !python jonsmodule.py # Run this cell only if working in Colab and you want to push new/changed files to GitHub # Note: you will need to manually save your current notebook to GitHub after running this cell !git config --global user.email "{git_email}" !git config --global user.name "{git_user}" !git add --all #List files here that you have added or changed, other than this notebook !git commit -m "updated from colab" !git push ```
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML %matplotlib inline ``` #Configurable parameters for pure pursuit + How fast do you want the robot to move? It is fixed at $v_{max}$ in this exercise + When can we declare the goal has been reached? + What is the lookahead distance? Determines the next position on the reference path that we want the vehicle to catch up to ``` vmax = 0.75 goal_threshold = 0.05 lookahead = 3.0 # Unicycle model def simulate_unicycle(pose, v,w, dt=0.1): x, y, t = pose return x + v*np.cos(t)*dt, y + v*np.sin(t)*dt, t+w*dt class PurePursuitTracker(object): def __init__(self, x, y, v, lookahead = 3.0): """ Tracks the path defined by x, y at velocity v x and y must be numpy arrays v and lookahead are floats """ self.length = len(x) self.ref_idx = 0 #index on the path that tracker is to track self.lookahead = lookahead self.x, self.y = x, y self.v, self.w = v, 0 # For starting def update(self, xc, yc, theta): """ Input: xc, yc, theta - current pose of the robot Update v, w based on current pose Returns True if trajectory is over. """ #Calculate ref_x, ref_y using current ref_idx #Check if we reached the end of path, then return TRUE #Two conditions must satisfy #1. ref_idx exceeds length of traj #2. ref_x, ref_y must be within goal_threshold # Write your code to check end condition ref_x, ref_y = self.x[self.ref_idx], self.y[self.ref_idx] goal_x, goal_y = self.x[-1], self.y[-1] if (self.ref_idx > self.length) and \ (np.linalg.norm([ref_x-goal_x, ref_y-goal_y])) < goal_threshold: # Ended, within goal return True #End of path has not been reached #update ref_idx using np.hypot([ref_x-xc, ref_y-yc]) < lookahead while np.hypot(ref_x-xc, ref_y-yc) < lookahead: self.ref_idx += 1 # Reached the current index, next if self.ref_idx < self.length: ref_x, ref_y = self.x[self.ref_idx], self.y[self.ref_idx] else: return True #Find the anchor point # this is the line we drew between (0, 0) and (x, y) anchor = np.asarray([ref_x - xc, ref_y - yc]) #Remember right now this is drawn from current robot pose #we have to rotate the anchor to (0, 0, pi/2) #code is given below for this theta = np.pi/2 - theta rot = np.asarray([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) anchor = np.dot(rot, anchor) Lsq = (anchor[0] ** 2 + anchor[1] **2) # dist to reference path^2 X = anchor[0] #cross-track error #from the derivation in notes, plug in the formula for omega self.w = -2*self.v*X/Lsq return False ``` ## Visualize given trajectory ``` x = np.arange(0, 50, 0.5) y = [np.sin(idx / 5.0) * idx / 2.0 for idx in x] #write code here plt.figure() plt.plot(x,y) plt.show() ``` ## Run the tracker simulation 1. Instantiate the tracker class 2. Initialize some starting pose 3. Simulate robot motion 1 step at a time - get $v$, $\omega$ from tracker, predict new pose using $v$, $\omega$, current pose in simulate_unicycle() 4. Stop simulation if tracker declares that end-of-path is reached 5. Record all parameters ``` #write code to instantiate the tracker class tracker = PurePursuitTracker(x, y, vmax) pose = -1, 0, np.pi/2 #arbitrary initial pose x0,y0,t0 = pose # record it for plotting traj =[] while True: #write the usual code to obtain successive poses pose = simulate_unicycle(pose, tracker.v, tracker.w) if tracker.update(*pose): print("ARRIVED!!") break traj.append([*pose, tracker.w, tracker.ref_idx]) xs,ys,ts,ws,ids = zip(*traj) plt.figure(figsize=(12,12)) plt.plot(x,y,label='Reference') plt.quiver(x0,y0, np.cos(t0), np.sin(t0),scale=12) plt.plot(xs,ys,label='Tracked') xf,yf,tf = pose plt.quiver(xf,yf, np.cos(tf), np.sin(tf),scale=12) plt.title('Pure Pursuit trajectory') plt.legend() plt.grid() ``` # Visualize curvature ``` plt.figure(figsize=(12,12)) plt.title('Curvature') plt.plot(np.abs(ws)) plt.grid() ``` ## Animate Make a video to plot the current pose of the robot and reference pose it is trying to track. You can use funcAnimation in matplotlib. A reference can be found [here](http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/) ``` # Convert trajectory to Numpy array np_traj = np.array(traj) # N, 5 shape && float64 # Create figure and axis fig, ax = plt.subplots() fig.set_dpi(200) ax.set_xlim((-5, 52)) ax.set_ylim((-17, 21)) # Get lines (to modify) line_tracked, = ax.plot([], [], label="Tracked", lw=2.0) line_ref = ax.plot(x,y,label='Reference') ax.legend() # Initialize everything def init_func(): line_tracked.set_data([], []) # Clear tracking data return (line_tracked, ) # Animation function def animate(fnum): line_tracked.set_data(np_traj[:fnum, 0], np_traj[:fnum, 1]) return (line_tracked, ) # Animation object anim = animation.FuncAnimation(fig, animate, init_func=init_func, frames=np_traj.shape[0], interval=20, blit=True) HTML(anim.to_html5_video()) ``` ## Effect of noise in simulations What happens if you add a bit of Gaussian noise to the simulate_unicycle() output? Is the tracker still robust? The noise signifies that $v$, $\omega$ commands did not get realized exactly ``` # Unicycle model def simulate_unicycle(pose, v,w, dt=0.1): x, y, t = pose t += np.random.normal(0.0, np.deg2rad(5)) # Localization orientation error x += np.random.normal(0.0, 0.1) y += np.random.normal(0.0, 0.1) return x + v*np.cos(t)*dt, y + v*np.sin(t)*dt, t+w*dt ``` Rest everything is the same as before ``` # Do the simulation tracker = PurePursuitTracker(x, y, vmax) pose_noisy = -1, 0, np.pi/2 #arbitrary initial pose x0,y0,t0 = pose_noisy # record it for plotting traj_noisy =[] while True: #write the usual code to obtain successive poses pose_noisy = simulate_unicycle(pose_noisy, tracker.v, tracker.w) if tracker.update(*pose_noisy): print("ARRIVED!!") break traj_noisy.append([*pose_noisy, tracker.w, tracker.ref_idx]) # Visualize everything xs,ys,ts,ws,ids = zip(*traj_noisy) xsc, ysc, tsc, wsc, idsc = zip(*traj) # Clean trajectory plt.figure(figsize=(12,12)) # Reference plt.plot(x,y,label='Reference') plt.plot(xs,ys,label='Tracked (noisy)', lw=2.0) plt.plot(xsc, ysc, label='Tracked (clean)') plt.quiver(x0,y0, np.cos(t0), np.sin(t0),scale=12) xf,yf,tf = pose_noisy plt.quiver(xf,yf, np.cos(tf), np.sin(tf),scale=12) plt.title('Pure Pursuit trajectory') plt.legend() plt.grid() ```
github_jupyter
<div style="width: 100%; overflow: hidden;"> <div style="width: 150px; float: left;"> <img src="data/D4Sci_logo_ball.png" alt="Data For Science, Inc" align="left" border="0" width=160px> </div> <div style="float: left; margin-left: 10px;"> <h1>Epidemiology 201</h1> <h1>Social Networks</h1> <p>Bruno Gonçalves<br/> <a href="http://www.data4sci.com/">www.data4sci.com</a><br/> @bgoncalves, @data4sci</p></div> </div> ``` from collections import Counter from pprint import pprint import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import networkx as nx import watermark from NetworkEpiModel import * %load_ext watermark %matplotlib inline ``` We start by print out the versions of the libraries we're using for future reference ``` %watermark -n -v -m -g -iv ``` Load default figure style ``` plt.style.use('./d4sci.mplstyle') colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] ``` ## A toy network ``` G = nx.Graph() G.add_edges_from([ (1, 3), (3, 4), (4, 5), (4, 6), (4, 7), (4, 8), (8, 7), (8, 6), (6, 5), (6, 0), (6, 9), (5, 0), (5, 2) ]) ``` The degree of each node is given by: ``` G.degree() ``` And we can easily add attributes to each node ``` nx.set_node_attributes(G, dict(zip(range(10), ('M', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'F', 'F'))), 'Gender') nx.set_node_attributes(G, dict(G.degree()), 'Degree') ``` And extract the attributes of each node into a DataFrame ``` nodes = pd.DataFrame.from_dict(dict(G.nodes(data=True)), orient='index') nodes.index.name='Node' nodes.sort_index(inplace=True) nodes ``` ## Hubs Let's define a hub as being the node with the largest degree of a network. We can find the largest degree of the network with ``` kmax = max([deg for node, deg in G.degree()]) kmax ``` And the nodes with that degree are: ``` hubs = [node for node, deg in G.degree() if deg == kmax] hubs ``` As expected. ## Contact tracing If we assume that node 6 becomes infected, we can find who is at risk by checking his contacts: ``` contacts = list(G.neighbors(6)) contacts ``` And if we want to take the contact tracing a step further, we can also get the contacts of these nodes: ``` full_contacts = set(contacts) for node in contacts: full_contacts |= set(G.neighbors(node)) contacts full_contacts ``` This also illustrates the fact that <div style="width: 100%; overflow: hidden;"> <img src="data/D4Sci_logo_full.png" alt="Data For Science, Inc" align="center" border="0" width=300px> </div>
github_jupyter
# Setting Up Git ## Overview - **Teaching:** 5 min - **Exercises:** 0 min **Questions** - How do I get set up to use Git? **Objectives** - Configure git the first time it is used on a computer. - Understand the meaning of the --global configuration flag. First you will need to launch a terminal, e.g. see setup. For the purposes of this lesson, if you are running on notebooks.azure.com we will work in the library folder, so before doing anything else we need to change directory: ```bash % cd library ``` If you using git on another platform then this is **not** necessary. ## Configure your git When we use Git on a new computer for the first time, we need to configure a few things. Below are a few examples of configurations we will set as we get started with Git: - our name and email address, - to colorize our output, - what our preferred text editor is, - and that we want to use these settings globally (i.e. for every project) On a command line, Git commands are written as git verb, where verb is what we actually want to do. So here is how Dracula sets up his new laptop: ```bash % git config --global user.name "Vlad Dracula" % git config --global user.email "vlad@tran.sylvan.ia" % git config --global color.ui "auto" ``` Please use your own name and email address instead of Dracula’s. This user name and email will be associated with your subsequent Git activity, which means that any changes pushed to GitHub, BitBucket, GitLab or another Git host server in a later lesson will include this information. ## Pin: Line Endings As with other keys, when you hit the ‘return’ key on your keyboard, your computer encodes this input. For reasons that are long to explain, different operating systems use different character(s) to represent the end of a line. (You may also hear these referred to as newlines or line breaks.) Because git uses these characters to compare files, it may cause unexpected issues when editing a file on different machines. You can change the way git recognizes and encodes line endings using the core.autocrlf command to git config. The following settings are recommended: On OS X and Linux: ```bash % git config --global core.autocrlf input ``` And on Windows: ```bash % git config --global core.autocrlf true ``` You can read more about this issue on this [GitHub page](https://help.github.com/articles/dealing-with-line-endings/). For these lessons, we will be interacting with [GitHub](https://github.com/) and so the email address used should be the same as the one used when setting up your GitHub account. If you are concerned about privacy, please review [GitHub’s instructions for keeping your email address private](https://help.github.com/articles/keeping-your-email-address-private/). If you elect to use a private email address with GitHub, then use that same email address for the `user.email` value, e.g. `username@users.noreply.github.com` replacing `username` with your GitHub one. You can change the email address later on by using the git config command again. Dracula also has to set his favorite text editor, following this table: | **Editor** | **Configuration command** | |---|---| | Atom | % git config --global core.editor "atom --wait" | | **nano** | **% git config --global core.editor "nano -w"** | | BBEdit (Mac, with command line tools) | % git config --global core.editor "bbedit -w" | | Sublime Text (Mac) | % git config --global core.editor "subl -n -w" | | Sublime Text (Win, 32-bit install) | % git config --global core.editor "'c:/program files (x86)/sublime text 3/sublime_text.exe' -w" | | Sublime Text (Win, 64-bit install) | % git config --global core.editor "'c:/program files/sublime text 3/sublime_text.exe' -w" | | Notepad++ (Win, 32-bit install) | % git config --global core.editor "'c:/program files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin" | | Notepad++ (Win, 64-bit install) | % git config --global core.editor "'c:/program files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin" | | Kate (Linux) | % git config --global core.editor "kate" | | Gedit (Linux) | % git config --global core.editor "gedit --wait --new-window" | | Scratch (Linux) | % git config --global core.editor "scratch-text-editor" | | emacs | % git config --global core.editor "emacs" | | vim | % git config --global core.editor "vim" | It is possible to reconfigure the text editor for Git whenever you want to change it. The four commands we just ran above only need to be run once: the flag --global tells Git to use the settings for every project, in your user account, on this computer. You can check your settings at any time: ``` %%bash2 --dir ~ git config --list ``` ## Pin: Git Help and Manual Always remember that if you forget a `git` command, you can access the list of commands by using `-h` and access the Git manual by using `--help`: ```bash % git config -h % git config --help ``` Additionally [online manual pages](https://git-scm.com) or [Stack Overflow](https://stackoverflow.com) are excellent resources. ## Key Points - Use `git config` to configure a user name, email address, editor, and other preferences once per machine.
github_jupyter
``` # %matplotlib # !git reset master --hard && git pull # !wget http://www.openslr.org/resources/12/dev-clean.tar.gz # !tar -zxf dev-clean.tar.gz # !wget https://raw.githubusercontent.com/pyannote/pyannote-audio/develop/tutorials/data_preparation/download_ami.sh # !mkdir ami # !bash download_ami.sh ami # !wget https://raw.githubusercontent.com/pyannote/pyannote-audio/develop/tutorials/data_preparation/AMI/MixHeadset.development.rttm # !wget https://raw.githubusercontent.com/pyannote/pyannote-audio/develop/tutorials/data_preparation/AMI/MixHeadset.test.rttm # !wget https://raw.githubusercontent.com/pyannote/pyannote-audio/develop/tutorials/data_preparation/AMI/MixHeadset.train.rttm import malaya_speech.train as train import numpy as np import malaya_speech from tqdm import tqdm import random np.seterr(divide='raise', invalid='raise') import librosa def random_stretch(samples, low = 0.5, high = 1.3): input_length = len(samples) stretching = samples.copy() random_stretch = np.random.uniform(low = low, high = high) stretching = librosa.effects.time_stretch( stretching.astype('float'), random_stretch ) return stretching def random_pitch(samples, low = 0.5, high = 1.0): y_pitch_speed = samples.copy() length_change = np.random.uniform(low = low, high = high) speed_fac = 1.0 / length_change tmp = np.interp( np.arange(0, len(y_pitch_speed), speed_fac), np.arange(0, len(y_pitch_speed)), y_pitch_speed, ) minlen = min(y_pitch_speed.shape[0], tmp.shape[0]) y_pitch_speed *= 0 y_pitch_speed[:minlen] = tmp[:minlen] return y_pitch_speed import pandas as pd import random from tqdm import tqdm from glob import glob maxlen = 0.3 selected_frames = [30, 90] functions = [random_pitch, random_stretch] noises_files = glob('../noise/noise/*.wav') noises = [malaya_speech.astype.int_to_float(malaya_speech.utils.read.wav(n)[0]) for n in tqdm(noises_files)] noises = [n for n in noises] len(noises) def generator(sr = 16000): for i in tqdm(range(len(noises))): print(noises_files[i]) x, y = [], [] fs = malaya_speech.utils.generator.frames(noises[i], int(maxlen * 100), sr, False) x.extend([f.array for f in fs]) y.extend([0] * len(fs)) for s in selected_frames: fs = malaya_speech.utils.generator.frames(noises[i], s, sr, False) x.extend([f.array for f in fs]) y.extend([0] * len(fs)) print(len(x)) # for k in range(len(x)): # for _ in range(random.randint(0, 3)): # for f in functions: # x.append(f(x[k])) # y.append(y[k]) # print(len(x)) for k in range(len(x)): yield { 'waveforms': x[k].tolist(), 'targets': [int(y[k])], } generator = generator() import os import tensorflow as tf os.system('rm noise/data/*') DATA_DIR = os.path.expanduser('noise/data') tf.gfile.MakeDirs(DATA_DIR) shards = [{'split': 'train', 'shards': 200}, {'split': 'dev', 'shards': 1}] train.prepare_dataset(generator, DATA_DIR, shards, prefix = 'vad') ```
github_jupyter
# Convert CIF to JCPDS * This notebook shows how to calculate a theoretical diffraction pattern using `pymatgen`. * This also aims to show how to read `CIF` files, convert them to `JCPDS`. * Some `jcpds` files can be downloaded from: https://github.com/SHDShim/JCPDS ``` %matplotlib inline ``` ## What is CIF file https://en.wikipedia.org/wiki/Crystallographic_Information_File ``` %ls ./cif/*.cif %cat ./cif/MgSiO3_bm.cif ``` ## What is a JCPDS file What is lacking in cif? ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` ## What is `pymatgen`? https://pymatgen.org ``` import pymatgen as mg from pymatgen import Lattice, Structure from pymatgen.analysis.diffraction.xrd import XRDCalculator from pymatgen.symmetry.analyzer import SpacegroupAnalyzer mg.__version__ ``` This works with `pymatgen` version `2019.4.11` or later. `ds_jcpds` is written by Dan Shim for making a jcpds file. ``` import sys sys.path.append('../../peakpo/') sys.path.append('../local_modules/') import ds_jcpds import quick_plots as quick ``` ## Input parameters ``` %ls ./cif/ fn_cif = "./cif/MgSiO3_bm.cif" fn_jcpds = './jcpds/MgSiO3-bm.jcpds' comments_jcpds = "Bridgmanite" ``` Parameters for the equation of state of bridgmanite. ``` k0 = 260. # 200. k0p = 4.00 # 4. alpha = 3.16e-5 # 1.e-5 wl_xray = 0.3344 xrange = (0,40) ``` ## Read CIF The `cif` file below was downloaded from American mineralogist crystal structure database. ``` material = mg.Structure.from_file(fn_cif) ``` ## Get some parameters in CIF ``` print('Unit-cell volume = ', material.volume) print('Density = ', material.density) print('Chemical formula = ', material.formula) lattice = material.lattice print('Lattice parameters = ', lattice.a, lattice.b, lattice.c, \ lattice.alpha, lattice.beta, lattice.gamma) crystal_system = SpacegroupAnalyzer(material).get_crystal_system() print(crystal_system) ``` ## Get diffraction pattern ``` c = XRDCalculator(wavelength=wl_xray) pattern = c.get_pattern(material, two_theta_range = xrange) ``` ## Extract twotheta, d-sp, int, hkl ``` pattern.hkls[0][0]['hkl'] pattern.hkls.__len__() h = []; k = []; l = [] for i in range(pattern.hkls.__len__()): h.append(pattern.hkls[i][0]['hkl'][0]) k.append(pattern.hkls[i][0]['hkl'][1]) l.append(pattern.hkls[i][0]['hkl'][2]) d_lines = [pattern.x, pattern.d_hkls, pattern.y, h, k, l ] diff_lines = np.transpose(np.asarray(d_lines)) print(diff_lines[1,:]) ``` ## Table output We can make a nice looking table using the `pandas` package. `pandas` is more than looking-good table producer. It is a powerful statistics package popular in data science. ``` table = pd.DataFrame(data = diff_lines, # values columns=['Two Theta', 'd-spacing', 'intensity', 'h', 'k', 'l']) # 1st row as the column names table.head() ``` ## Plot peak positions generated from pymatgen ``` f, ax = plt.subplots(figsize=(8,3)) ax.vlines(diff_lines[:,0], 0., diff_lines[:,2], color='b'); ``` ## Convert to JCPDS Setup an `jcpds` object from a `cif` file ``` material_jcpds = ds_jcpds.JCPDS() material_jcpds.set_from_cif(fn_cif, k0, k0p, \ thermal_expansion=alpha, two_theta_range=xrange) ``` Calculate diffraction pattern at a pressure. ``` material_jcpds.cal_dsp(pressure = 100.) dl = material_jcpds.get_DiffractionLines() tth, inten = material_jcpds.get_tthVSint(wl_xray) f, ax = plt.subplots(2, 1, figsize=(7,3), sharex=True) ax[0].vlines(diff_lines[:,0], 0., diff_lines[:,2], color='b') ax[1].vlines(tth, 0., inten, color = 'r') ax[0].set_xlim(7.5,9) ``` ## Save to a JCPDS file ``` material_jcpds.write_to_file(fn_jcpds, comments=comments_jcpds) %cat {fn_jcpds} ``` # Read back the written JCPDS for test ``` material_test = ds_jcpds.JCPDS(filename = fn_jcpds) ``` Calculate a pattern at a pressure ``` material_test.cal_dsp(pressure = 100.) material_test.get_DiffractionLines() tth, inten = material_test.get_tthVSint(wl_xray) f = plt.figure(figsize=(8,3)) plt.vlines(diff_lines[:,0], 0., diff_lines[:,2], color='b', label='0 GPa') plt.vlines(tth, 0., inten, color = 'r', label='100 GPa') plt.legend(); ```
github_jupyter
# Continuous training with TFX and Google Cloud AI Platform ## Learning Objectives 1. Use the TFX CLI to build a TFX pipeline. 2. Deploy a TFX pipeline version with tuning enabled to a hosted AI Platform Pipelines instance. 3. Create and monitor a TFX pipeline run using the TFX CLI and KFP UI. In this lab, you use utilize the following tools and services to deploy and run a TFX pipeline on Google Cloud that automates the development and deployment of a TensorFlow 2.3 WideDeep Classifer to predict forest cover from cartographic data: * The [**TFX CLI**](https://www.tensorflow.org/tfx/guide/cli) utility to build and deploy a TFX pipeline. * A hosted [**AI Platform Pipeline instance (Kubeflow Pipelines)**](https://www.tensorflow.org/tfx/guide/kubeflow) for TFX pipeline orchestration. * [**Dataflow**](https://cloud.google.com/dataflow) jobs for scalable, distributed data processing for TFX components. * A [**AI Platform Training**](https://cloud.google.com/ai-platform/) job for model training and flock management of tuning trials. * [**AI Platform Prediction**](https://cloud.google.com/ai-platform/), a model server destination for blessed pipeline model versions. * [**CloudTuner**](https://www.tensorflow.org/tfx/guide/tuner#tuning_on_google_cloud_platform_gcp) (KerasTuner implementation) and [**AI Platform Vizier**](https://cloud.google.com/ai-platform/optimizer/docs/overview) for advanced model hyperparameter tuning. You will then create and monitor pipeline runs using the TFX CLI as well as the KFP UI. ### Setup #### Update lab environment PATH to include TFX CLI and skaffold ``` import yaml # Set `PATH` to include the directory containing TFX CLI and skaffold. PATH=%env PATH %env PATH=/home/jupyter/.local/bin:{PATH} ``` #### Validate lab package version installation ``` !python -c "import tensorflow; print('TF version: {}'.format(tensorflow.__version__))" !python -c "import tfx; print('TFX version: {}'.format(tfx.__version__))" !python -c "import kfp; print('KFP version: {}'.format(kfp.__version__))" ``` **Note**: this lab was built and tested with the following package versions: `TF version: 2.3.2` `TFX version: 0.25.0` `KFP version: 1.4.0` (Optional) If running the above command results in different package versions or you receive an import error, upgrade to the correct versions by running the cell below: ``` %pip install --upgrade --user tensorflow==2.3.2 %pip install --upgrade --user tfx==0.25.0 %pip install --upgrade --user kfp==1.4.0 ``` Note: you may need to restart the kernel to pick up the correct package versions. #### Validate creation of AI Platform Pipelines cluster Navigate to [AI Platform Pipelines](https://console.cloud.google.com/ai-platform/pipelines/clusters) page in the Google Cloud Console. Note you may have already deployed an AI Pipelines instance during the Setup for the lab series. If so, you can proceed using that instance. If not: **Create or select an existing Kubernetes cluster (GKE) and deploy AI Platform**. Make sure to select `"Allow access to the following Cloud APIs https://www.googleapis.com/auth/cloud-platform"` to allow for programmatic access to your pipeline by the Kubeflow SDK for the rest of the lab. Also, provide an `App instance name` such as "tfx" or "mlops". Validate the deployment of your AI Platform Pipelines instance in the console before proceeding. ## Exercise: review the example TFX pipeline design pattern for Google Cloud The pipeline source code can be found in the `pipeline` folder. ``` %cd pipeline !ls -la ``` The `config.py` module configures the default values for the environment specific settings and the default values for the pipeline runtime parameters. The default values can be overwritten at compile time by providing the updated values in a set of environment variables updated in this lab notebook below. The `pipeline.py` module contains the TFX DSL defining the workflow implemented by the pipeline. The `preprocessing.py` module implements the data preprocessing logic the `Transform` component. The `model.py` module implements the training, tuning, and model building logic for the `Trainer` and `Tuner` components. The `runner.py` module configures and executes `KubeflowDagRunner`. At compile time, the `KubeflowDagRunner.run()` method converts the TFX DSL into the pipeline package in the [argo](https://github.com/argoproj/argo-workflows) format for execution on your AI Platform Pipelines instance. The `features.py` module contains feature definitions common across `preprocessing.py` and `model.py`. ## Exercise: build your pipeline package with the TFX CLI You will use TFX CLI to compile and deploy the pipeline. As explained in the previous section, the environment specific settings can be provided through a set of environment variables and embedded into the pipeline package at compile time. ### Configure your environment resource settings Update the below constants with the settings reflecting your lab environment. - `GCP_REGION` - the compute region for AI Platform Training, Vizier, and Prediction. - `ARTIFACT_STORE` - An existing GCS bucket. You can use any bucket or use the GCS bucket created during installation of AI Platform Pipelines. The default bucket name will contain the `kubeflowpipelines-default` prefix. * `CUSTOM_SERVICE_ACCOUNT` - In the gcp console Click on the Navigation Menu. Navigate to `IAM & Admin`, then to `Service Accounts` and use the service account starting with prefix - `'tfx-tuner-caip-service-account'`. This enables CloudTuner and the Google Cloud AI Platform extensions Tuner component to work together and allows for distributed and parallel tuning backed by AI Platform Vizier's hyperparameter search algorithm. - `ENDPOINT` - set the `ENDPOINT` constant to the endpoint to your AI Platform Pipelines instance. The endpoint to the AI Platform Pipelines instance can be found on the [AI Platform Pipelines](https://console.cloud.google.com/ai-platform/pipelines/clusters) page in the Google Cloud Console. Open the *SETTINGS* for your instance and use the value of the `host` variable in the *Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SKD* section of the *SETTINGS* window. The format is `'...pipelines.googleusercontent.com'`. ``` PROJECT_ID = !(gcloud config get-value core/project) PROJECT_ID = PROJECT_ID[0] GCP_REGION = 'us-central1' ARTIFACT_STORE_URI = f'gs://{PROJECT_ID}-kubeflowpipelines-default' CUSTOM_SERVICE_ACCOUNT = f'tfx-tuner-caip-service-account@{PROJECT_ID}.iam.gserviceaccount.com' #TODO: Set your environment resource settings here for ENDPOINT. ENDPOINT = '' # Set your resource settings as Python environment variables. These override the default values in pipeline/config.py. %env GCP_REGION={GCP_REGION} %env ARTIFACT_STORE_URI={ARTIFACT_STORE_URI} %env CUSTOM_SERVICE_ACCOUNT={CUSTOM_SERVICE_ACCOUNT} %env PROJECT_ID={PROJECT_ID} ``` ### Set the pipeline compile time settings Default pipeline runtime environment values are configured in the pipeline folder `config.py`. You will set their values directly below: * `PIPELINE_NAME` - the pipeline's globally unique name. For each subsequent pipeline update, each pipeline version uploaded to KFP will be reflected on the `Pipelines` tab in the `Pipeline name > Version name` dropdown in the format `PIPELINE_NAME_datetime.now()`. * `MODEL_NAME` - the pipeline's unique model output name for AI Platform Prediction. For multiple pipeline runs, each pushed blessed model will create a new version with the format `'v{}'.format(int(time.time()))`. * `DATA_ROOT_URI` - the URI for the raw lab dataset `gs://workshop-datasets/covertype/small`. * `CUSTOM_TFX_IMAGE` - the image name of your pipeline container build by skaffold and published by `Cloud Build` to `Cloud Container Registry` in the format `'gcr.io/{}/{}'.format(PROJECT_ID, PIPELINE_NAME)`. * `RUNTIME_VERSION` - the TensorFlow runtime version. This lab was built and tested using TensorFlow `2.3`. * `PYTHON_VERSION` - the Python runtime version. This lab was built and tested using Python `3.7`. * `USE_KFP_SA` - The pipeline can run using a security context of the GKE default node pool's service account or the service account defined in the `user-gcp-sa` secret of the Kubernetes namespace hosting Kubeflow Pipelines. If you want to use the `user-gcp-sa` service account you change the value of `USE_KFP_SA` to `True`. Note that the default AI Platform Pipelines configuration does not define the `user-gcp-sa` secret. * `ENABLE_TUNING` - boolean value indicating whether to add the `Tuner` component to the pipeline or use hyperparameter defaults. See the `model.py` and `pipeline.py` files for details on how this changes the pipeline topology across pipeline versions. ``` PIPELINE_NAME = 'tfx_covertype_continuous_training' MODEL_NAME = 'tfx_covertype_classifier' DATA_ROOT_URI = 'gs://workshop-datasets/covertype/small' CUSTOM_TFX_IMAGE = 'gcr.io/{}/{}'.format(PROJECT_ID, PIPELINE_NAME) RUNTIME_VERSION = '2.3' PYTHON_VERSION = '3.7' USE_KFP_SA=False ENABLE_TUNING=False %env PIPELINE_NAME={PIPELINE_NAME} %env MODEL_NAME={MODEL_NAME} %env DATA_ROOT_URI={DATA_ROOT_URI} %env KUBEFLOW_TFX_IMAGE={CUSTOM_TFX_IMAGE} %env RUNTIME_VERSION={RUNTIME_VERSION} %env PYTHON_VERIONS={PYTHON_VERSION} %env USE_KFP_SA={USE_KFP_SA} %env ENABLE_TUNING={ENABLE_TUNING} ``` ### Compile your pipeline code You can build and upload the pipeline to the AI Platform Pipelines instance in one step, using the `tfx pipeline create` command. The `tfx pipeline create` goes through the following steps: - (Optional) Builds the custom image to that provides a runtime environment for TFX components or uses the latest image of the installed TFX version. - Compiles the pipeline code into a pipeline package. - Uploads the pipeline package via the `ENDPOINT` to the hosted AI Platform instance. When prototyping with the TFX SDK, you may prefer to first use the `tfx pipeline compile` command, which only executes the compilation step. After the pipeline compiles successfully you can use `tfx pipeline create` to go through all steps. ``` !tfx pipeline compile --engine kubeflow --pipeline_path runner.py ``` Note: you should see a `{PIPELINE_NAME}.tar.gz` file appear in your `/pipeline` directory. ## Exercise: deploy your pipeline container to AI Platform Pipelines with TFX CLI After the pipeline code compiles without any errors you can use the `tfx pipeline create` command to perform the full build and deploy the pipeline. You will deploy your compiled pipeline container hosted on Google Container Registry e.g. `gcr.io/[PROJECT_ID]/[PIPELINE_NAME]` to run on AI Platform Pipelines with the TFX CLI. To learn more about the command below, you can review the [TFX CLI documentation](https://www.tensorflow.org/tfx/guide/cli#create). ``` !tfx pipeline create \ --pipeline_path=runner.py \ --endpoint={ENDPOINT} \ --build_target_image={CUSTOM_TFX_IMAGE} ``` If you make a mistake above and need to redeploy the pipeline you can first delete the previous version using `tfx pipeline delete` or you can update the pipeline in-place using `tfx pipeline update`. To delete the pipeline: `tfx pipeline delete --pipeline_name {PIPELINE_NAME} --endpoint {ENDPOINT}` To update the pipeline: `tfx pipeline update --pipeline_path runner.py --endpoint {ENDPOINT}` ## Exercise: create a pipeline run with the TFX CLI After the pipeline has been deployed, you can trigger and monitor pipeline runs using TFX CLI. For more information on the step below, review the [TFX CLI documentation](https://www.tensorflow.org/tfx/guide/cli#tfx_run) on the "run group". ``` !tfx run create --pipeline_name={PIPELINE_NAME} --endpoint={ENDPOINT} ``` ## Exercise: monitor your pipeline runs with the TFX CLI To view the status of existing pipeline runs: ``` !tfx run list --pipeline_name {PIPELINE_NAME} --endpoint {ENDPOINT} ``` To retrieve the status of a given run retrieved from the command above: ``` RUN_ID='[YOUR RUN ID]' !tfx run status --pipeline_name {PIPELINE_NAME} --run_id {RUN_ID} --endpoint {ENDPOINT} ``` ## Exercise: monitor your pipeline runs with the Kubeflow Pipelines UI On the [AI Platform Pipelines](https://console.cloud.google.com/ai-platform/pipelines/clusters) page, click `OPEN PIPELINES DASHBOARD`. A new browser tab will open. Select the `Pipelines` tab to the left where you see the `PIPELINE_NAME` pipeline you deployed previously. Click on the most recent pipeline version which will open up a window with a visualization of your TFX pipeline directed graph. Pipeline components are represented as named boxes with direct arrows representing artifact dependencies and the execution order of your ML workflow. Next, click the `Experiments` tab. You will see your pipeline name under `Experiment name` with an downward arrow that allows you to view all active and previous runs. Click on the pipeline run that you trigger with the step above. You can follow your pipeline's run progress by viewing your pipeline graph get built on the screen and drill into individual components to view artifacts, ML Metadata, and logs. Click on the `Trainer` component in the KFP UI once it is running and navigate to the `Visualizations` tab. Scroll down to the Tensorboard widget and hit the `Open Tensorboard` button to monitor your training performance. Individual model performance will vary run-to-run but your model will achieve about 70-72% accuracy. On the [AI Platform Jobs](https://console.cloud.google.com/ai-platform/jobs) page, you can also further inspect the Training job logs and graphs on training resource utilization. Tracking your model's performance and resource footprint across runs gives you a systemic way to measure and prioritize actions to improve your model's performance such as hyperparameter tuning, adding additional data, increasing model complexity, or focusing on additional feature engineering. ### Important A full pipeline run with tuning enabled will take about 50 minutes to complete. You can view the run's progress using the TFX CLI commands above and in the KFP UI. While the pipeline run is in progress, there are also optional exercises below to explore your pipeline's artifacts and Google Cloud integrations while the pipeline run is in progress. ### Exercise (optional): review the pipeline code to explore hyperparameter tuning workflow Incorporating automatic model hyperparameter tuning into a continuous training TFX pipeline workflow enables faster experimentation, development, and deployment of a top performing model. However, you might not want to tune the hyperparameters every time you retrain your model due to the computational cost, amount of time to tune, and diminishing performance returns over time. Typically you would want to tune for a large number of trials over a wide search space which is beyond the duration of this lab. The pipeline run you triggered above did not include hyperparameter tuning based on the `ENABLE_TUNING=False` environment variable set above and the model instead used default hyperparameters. Default hyperparameter values in the search space are defined in `_get_hyperparameters()` in the pipeline's `model.py` and these values are used to build a TensorFlow WideDeep Classifier model. Review the pipeline design pattern for conditional model tuning in `pipeline.py`. When `ENABLE_TUNING=True`, the pipeline typology changes to include the `Tuner` component that calls out to the AI Platform Vizier service for hyperparameter tuning. The `Tuner` component `"best_hyperparameters"` artifact will be passed directly to your `Trainer` component to deploy the top performing model. Also, review the tuning function in `model.py` for configuring `CloudTuner`. Once you have used `Tuner` determine a good set of hyperparameters, you can remove `Tuner` from your pipeline and use model hyperparameters defined in your model code or use a `ImporterNode` to import the `Tuner` `"best_hyperparameters"`artifact from a previous `Tuner` run to your model `Trainer`. ### Exercise (optional): review your pipeline's Dataflow jobs for data processing On the [Dataflow](https://console.cloud.google.com/dataflow) page, click on the most recent job and inspect the computation graph for parallelized data processing. It will include details about your job's status, type, SDK version, any errors or warnings, and additional diagnostic graphs. As your pipeline run progresses, you will see jobs kick off for the ExampleGen, StatisticsGen, Transform, and Evaluator pipeline components. Take a look at the job monitoring charts that display metrics over the duration of the pipeline job. They provide I/O metrics to identify bottlenecks, statistical information to surface anomalies, and step-level visibility for debugging pipeline lag or errors. ### Exercise (optional): review your pipeline's artifacts on Cloud Storage On the [Cloud Storage page](https://console.cloud.google.com/storage), review how TFX standardizes the organization of your pipeline run artifacts. You will find them organized by component and versioned in your `gs://{PROJECT_ID}-kubeflowpipelines-default` artifact storage bucket. This standardization brings reproducibility and traceability to your ML workflows and allows for easier reuse of pipeline components and artifacts across use cases. ## License <font size=-1>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](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.</font>
github_jupyter
# 量子编译简介 本文档介绍 *Qubiter* 所用的正余弦分解(CSD, Cosine-Sine decomposition)量子编译器及其性能。 量子编译器指以任意 $N=2^n$ 维的幺正矩阵 $U$ 作为输入,能够输出等价于矩阵 $U$ 的基本操作序列(比如 CNOT 受控反门和单量子比特旋转门)的计算机程序,可以有很多种。通常幺正矩阵 $U$ 的形式为 $U=e^{-itH}$,其中 $t$ 和 $H$ 分别代表时间和哈密顿算符。在物理学和量子化学领域中,$H$ 的具体形式往往可以先验已知,通常的做法是用 Trotter-Suzuki 近似对 $U$ 进行展开。而在人工智能等领域,哈密顿量 $H$ 的具体形式一般不能先验已知,这时候则推荐使用线性代数中正余弦分解(CSD)来处理矩阵。这两种不同的编译方式都可以使用 *Qubiter* 实现,此文档着重介绍正余弦分解编译方法。 使用 *Qubiter* 进行 CSD 量子编译需要调用 'quantum_CSD_compiler' 文件夹中的类文件。这些类的使用除了需要 *Qubiter* 的 Python 文件包和安装了 numpy、scipy 库的 Python 环境(例如 Anaconda )外,还需要[安装由 Artiste-qb.net 提供的二进制库](https://github.com/artiste-qb-net/Python-CS-Decomposition#installation)。此库包括了 Python 封装的进行正余弦分解的 LAPACK 子程序 'cuncsd.f'。复述本文档中的计算需要安装所有必要的文件和库。 在 'quantum_CSD_compiler' 文件夹中的 ['csd-intro.pdf'](https://github.com/artiste-qb-net/qubiter/blob/master/quantum_CSD_compiler/csd-intro.pdf) 文件提供了 CSD(正余弦分解)的介绍。其他参考文献有: 1. [R.R. Tucci,《初级量子编译》(第二版)](https://arxiv.org/abs/quant-ph/9902062) 2. Qubiter 1.11: 基于 C++ 的原始 *Qubiter* 版本。最初一版 *Qubiter 1.11* 和文献1同步发布。在新的 *Qubiter* 版本(基于 Python)的 'quantum_CSD_compiler/LEGACY' 文件夹中包含了 *Qubiter 1.11* 原始程序。 3. R.R. Tucci,[《量子快速傅立叶变换 - 正余弦分解递归应用举例》](https://arxiv.org/abs/quant-ph/0411097) *Qubiter* 通过递归调用 CSD 来建立由节点矩阵构成的树结构。这些节点矩阵通过正确的顺序读取后是和输入矩阵 $U$ 完全等价的。 在这里以三个量子比特的量子傅立叶矩阵 $U$ 为例,用如下方式构建类树的对象: ``` import os import sys print(os.getcwd()) os.chdir('../') print(os.getcwd()) sys.path.insert(0,os.getcwd()) import numpy as np import cuncsd_sq as csd import math from qubiter.FouSEO_writer import * from qubiter.quantum_CSD_compiler.Tree import * from qubiter.quantum_CSD_compiler.DiagUnitarySEO_writer import * from qubiter.quantum_CSD_compiler.MultiplexorSEO_writer import * import pandas as pd num_bits = 3 init_unitary_mat = FouSEO_writer.fourier_trans_mat(1 << num_bits) emb = CktEmbedder(num_bits, num_bits) file_prefix = 'csd_test' t = Tree(True, file_prefix, emb, init_unitary_mat, verbose=False) t.close_files() ``` 上述代码自动将矩阵 $U$ 展开并创建 DIAG 和 MP_Y 线路,其图形化文件(Picture file)为: ``` file = file_prefix + '_3_ZLpic.txt' df = pd.read_csv(file, delim_whitespace=True, header=None) df ``` 相应的,创建的文字化文件(English file)为: ``` file = file_prefix + '_3_eng.txt' df = pd.read_csv(file, delim_whitespace=True, header=None) df ``` 在图形化文件中, 一个 DIAG 线路作为一个百分号链出现,而一个 MP_Y 线路作为百分号链加 Ry 门出现。我们可以看到,相对于较复杂的文字化文件,图形化文件可以很直观地给出 DIAG 和 MP_Y 门的概览。在 *Qubiter* 的诠释文件 [qubiter_rosetta_stone.pdf](https://github.com/artiste-qb-net/qubiter/blob/master/qubiter_rosetta_stone.pdf) 中可以了解更多 DIAG 和 MP_Y 线路的解释和举例。 在这里,每一个 DIAG 线路都代表一个由单位尺度大小的复数构成的对角矩阵,从而保证了矩阵的幺正性。同时每一个 MP_Y 线路代表了具有如下形式的矩阵, $\left[\begin{array}{cc} cc & ss \\ -ss & cc \end{array}\right]$, 其中 $cc$ and $ss$ 是相同大小的实对角矩阵从而满足 $cc^2 + ss^2 = 1$. 对每一个输入的文字化文件,'DiagUnitaryExpander' 类都会生成新的文字化文件和图形化文件,其中: * 所有非 'DIAG' 开始的行都被回显, * 所有以 'DIAG' 开始的行都被其精确或近似的多线路展开所替换。 同样的,'MultiplexorExpander' 也将任一输入的文字化文件输出为新的文字化文件和图形化文件,其中: * 所有非 'MP_Y' 开始的行都被回显, * 所有以 'MP_Y' 开始的行都被其精确或近似的多线路展开所替换。 所有之前的文字化文件都可以被这两个类展开并且构建为新的文字化和图形化文件,最终会得到一个只包含 CNOT 门和单量子比特旋转的文字化文件。而此文件中的逻辑门相乘后和原始矩阵 $U$ 是完全等价的。鉴于最终的文字化文件较长且不适合展示,这里仅以单个 DIAG 和单个 MP_Y 线路的精确展开为例做演示: 首先对于一个四量子比特门 %---%---%---% 我们创建包含其展开的文字化文件和图形化文件。这代表一个幺正对角矩阵,其相位角是随机生成的并存储为变量 'rad_angles'。其图形化文件为: ``` file_prefix = "d_unitary_exact_check" num_bits = 4 num_angles = (1 << num_bits) emb = CktEmbedder(num_bits, num_bits) rad_angles = list(np.random.rand(num_angles)*2*np.pi) wr = DiagUnitarySEO_writer(file_prefix, emb, 'exact', rad_angles) wr.write() wr.close_files() file = file_prefix + '_4_ZLpic.txt' with open(file) as f: print(f.read()) ``` 可以通过如下方式检验此精确展开的正确性:将展开后的门操作用 'SEO_MatrixProduct' 类进行相乘,并存储乘积为 'matpro.prod_arr'。利用 'rad_angles' 中的相位角精确重建对角矩阵并存为 'exact_mat'。将两结果差值(即 matpro.prod_arr - exact_mat)的标准差存储为 'err' 并输出: ``` matpro = SEO_MatrixProduct(file_prefix, num_bits) exact_mat = DiagUnitarySEO_writer.du_mat(rad_angles) err = np.linalg.norm(matpro.prod_arr - exact_mat) print("diag unitary error=", err) ``` 接下来,对另一个四量子比特门 Ry--%---%---% 我们构建展开后的文字化文件和图形化文件。这是一个多路复用器矩阵(multiplexor matrix),其随机相位角存储为变量 'rad_angles'。其图形化文件为: ``` file_prefix = "plexor_exact_check" num_bits = 4 num_angles = (1 << (num_bits-1)) emb = CktEmbedder(num_bits, num_bits) rad_angles = list(np.random.rand(num_angles)*2*np.pi) wr = MultiplexorSEO_writer(file_prefix, emb, 'exact', rad_angles) wr.write() wr.close_files() file = file_prefix + '_4_ZLpic.txt' with open(file) as f: print(f.read()) ``` 同前面一样,可以通过如下方式检验此精确展开的正确性:将展开后的门操作用 'SEO_MatrixProduct' 进行相乘,并存储乘积为 'matpro.prod_arr'。利用 'rad_angles' 中的相位角精确重建对角矩阵并存为 'exact_mat'。将两结果差值(即 matpro.prod_arr - exact_mat)的标准差存储为 'err' 并输出: ``` matpro = SEO_MatrixProduct(file_prefix, num_bits) exact_mat = MultiplexorSEO_writer.mp_mat(rad_angles) err = np.linalg.norm(matpro.prod_arr - exact_mat) print("multiplexor error=", err) ``` 上述计算意味着,对量子傅立叶变换(QFT)盲目使用 CSD 量子编译会得到一个随量子比特数 $n$ 指数增长的操作序列。而我们知道对 QFT 使用 Coppersmith 分解仅得到随着 $n$ 多项式增长的结果。不过由于 CSD 的非惟一性,在文献3中介绍了如何用 CSD 编译以得到优于 Coppersmith 分解的方法。 对于 $n$ 个量子比特,$U$ 是一个 $N = 2^n$ 维的幺正矩阵并且具有 $N^2$ 个自由度(真实自由度)。这是由于 $U$ 具有 $N^2$ 个复数参量(即 $2N^2$ 个实数参量)以及 $N$ 个实约束条件和 $N(N-1)/2$ 个复约束条件(即总共 $N^2$ 个实约束条件)。真实自由度为 $2N^2$ 个实数参量减去 $N^2$ 个实约束条件,即为 $N^2$ 个自由度。 (a) 矩阵 $U$ 的正余弦分解含有 $N$ 个DIAG 和 $N$ 个 MP_Y 线路,而每个 DIAG(或 MP_Y)线路都依赖于 $N$ (或 $N/2$) 个相位角。仅 DIAG 线路就具有足够多的 $N^2$ 自由度来构建 $U$ 的 $N^2$ 个自由度。显然 *Qubiter* 所用的 CSD 会产生冗余量。不过由于正余弦分解的非唯一性,可以通过寻找在 DIAG 和 MP_Y 线路中不产生额外相位角的正余弦分解来解决这个问题。 (b) 此正余弦分解会得到 $N^2 = 2^{2n}$ 量级的 CNOT 门和单量子比特旋转,所以对于 $N$ 比较小的情况比较适合。而当 $N$ 非常大的情况下,此方法不再适用。此时可以通过寻找对单个 MP_Y 和 DIAG 线路的近似来简化问题。 显然,对于问题(a)和(b)还有很大的改进空间。
github_jupyter
# 【課題】高エネルギー実験で生成された荷電粒子の飛跡を見つける この課題では、変分量子固有値ソルバー法を物理実験に応用することを考えてみます。特に高エネルギー物理の実験に着目し、その必須技術である「**荷電粒子飛跡の再構成**」を変分量子固有値ソルバー法を使って実現することを目指します。 ```{contents} 目次 --- local: true --- ``` ## はじめに **変分量子固有値ソルバー法**(*Variational Quantum Eigensolver*, VQE)を紹介した{doc}`ノートブック <vqe>`で、VQEの考え方と変分量子回路の基本的な実装の方法を学びました。ここでは、VQEの高エネルギー物理への応用を考えてみます。 高エネルギー実験では、高いエネルギーに加速した粒子(例えば陽子)を人工的に衝突させ、生成された多数の二次粒子を検出器で測定することで、その生成過程をつかさどる基礎物理反応を理解していきます。そのためには、検出器で測定された信号から生成粒子を同定し、そのエネルギーや運動量を正しく再構成することがとても重要です。この実習では、生成した物理反応を再構成するための最初のステップとして、「**荷電粒子飛跡の再構成**」をVQEで実現する方法について学んでいきます。 (hep)= ## 高エネルギー実験 (hep_LHC)= ### LHC実験の概要 ```{image} figs/LHC_ATLAS.png :alt: LHC_ATLAS :class: bg-primary mb-1 :width: 1000px :align: center ``` LHC(大型ハドロン加速器 Large Hadron Collider)は、スイスとフランスの国境に位置する欧州原子核研究機構(CERN)で運転されている円形の加速器です。地下約100 mに掘られた周長27 kmのトンネルの中に置かれ、6.5 TeVのエネルギーまで陽子を加速することができます(1 TeVは$10^{12}$ eV)。その加速された陽子を正面衝突させることで、世界最高エネルギーである13 TeV での陽子衝突実験を実現しています(左上の写真)。右上の写真は、地下トンネルに設置されたLHCの写真です。 LHCでは4つの実験(ATLAS, CMS, ALICE, LHCb)が進行中ですが、その中でもATLASとCMSは大型の汎用検出器を備えた実験です(左下の写真が実際のATLAS検出器)。陽子衝突で発生した二次粒子を周囲に設置した高精度の検出器で観測することで、さまざまな素粒子反応の観測や新しい現象の探索などを行っています。右下の絵はATLAS検出器で実際に記録した粒子生成反応の一つで、これは2012年にATLASとCMSで発見されたヒッグス粒子の候補を示したものです(ヒッグス粒子は単体で測定されるわけではなく、その崩壊の結果出てきた多数の粒子を観測するのでこのように見えます)。 (hep_detect)= ### 荷電粒子の測定 ATLASやCMS実験の検出器は、異なる性質を持った検出器を内側から外側に階層的に配置しています。最内層の検出器は荷電粒子の再構成や識別に使われる検出器で、実験では最も重要な検出器の一つです。この検出器はそれ自体が約10層程度の層構造を持っており、一つの荷電粒子が通過したとき、複数の検出器信号を作ります。 例えば、左下図にあるように一度の陽子衝突で無数の粒子が生成され、それらが検出器に「ヒット」と呼ばれる信号を作ります(図中の白、黄色、オレンジ等の点に相当)。このヒットの集合から「ある荷電粒子が作ったヒットの組み合わせ」を選び、その粒子の「飛跡」を再構成します。右下図のいろいろな色の曲線が飛跡に対応します。この飛跡の再構成は、ATLASやCMS実験に限らず、高エネルギー実験では最も重要な実験技術の一つと言えます。 ```{image} figs/tracking.png :alt: tracking :class: bg-primary mb-1 :width: 1000px :align: center ``` (tracking)= ## 飛跡の再構成 この実習で目指すのは、高エネルギー粒子の衝突で発生する**荷電粒子の飛跡を再構成する**こと(**Tracking**と呼ぶ)です。ただし、現在の量子コンピュータでは大きなサイズの問題を解くことはまだ難しいため、サイズの小さい問題、つまり少数の生成粒子が生成された場合に絞って検討を行います。 まず、必要なライブラリを最初にインポートします。 ``` # Tested with python 3.7.9, qiskit 0.23.5, numpy 1.20.1、hepqpr-qallse 0.1.0 import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, Aer from qiskit.circuit.library import TwoLocal from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver, NumPyEigensolver from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.aqua.components.optimizers import SPSA, COBYLA from qiskit.aqua import QuantumInstance ``` (ML_challenge)= ### TrackMLチャレンジ データとしては、2018年に行われた[TrackML Particle Trackingチャレンジ](https://www.kaggle.com/c/trackml-particle-identification)で提供されたオープンデータを活用します。CERNでは、将来の加速器計画として「高輝度LHC」(2027年に開始予定)と呼ばれるLHCの増強計画を進めています。高輝度LHCでは陽子の衝突頻度が現在の10倍近くに上がり、発生する2次粒子の数もそれに応じて増えるため、Trackingは非常にチャレンジングになると予想されています。それを克服するために、高輝度LHCでの実験環境を擬似的に作り、そこでの有効なTracking技術の開発を目指して行われたのがTrackMLチャレンジです。 (hamiltonian_form)= ### ハミルトニアンの構成とVQEの実行 課題として考えるのは、**Trackingを実現するためのハミルトニアンを構成し、それをVQEに実装して実行する**ことです。 (pre_processing)= #### 前準備 この課題ではTrackMLチャレンジのデータを用いますが、元のデータは扱いが難しいため、量子計算に用いやすいように前処理を行なったデータを使います。まず下図に示したように、検出器3層に渡って連続するヒットを選び出します(点線で囲まれた3層ヒットのことを、ここでは「セグメント」と呼ぶことにします)。色のついた点がヒットだと考えてください。この時検出器中心から発生した粒子を優先的に選び出せるように、セグメントが検出器中心の方を向いているものを選びます。 ```{image} figs/track_segment.png :alt: track_segment :class: bg-primary mb-1 :width: 350px :align: center ``` こうして選び出したセグメントのリストを作り、そのリストから任意のペアを選んで、その**相互作用の強さ**を考えます。この相互作用は物理的な力ではなく、二つのセグメントが**同一の荷電粒子が作る飛跡とどれぐらい無矛盾なのか**を表す指標だと考えてください。この指標の決め方ですが、セグメントのペアが同一飛跡に近くなるにつれ、相互作用の強さは-1に近づくように設定されています。セグメントを構成する3つのヒットのうちの1つが2つのセグメントに共有されているケース(図中で赤で示した場合に相当)は、飛跡の候補としては適切でないので相互作用は+1になっています。なぜかと言うと、赤で示したような「枝分かれ」あるいは「収束」したような飛跡というのは、今興味がある飛跡(検出器中心で発生した荷電粒子の軌道)とは矛盾しているからです。 また、図中のオレンジのようなケース(途中でヒットが抜けているようなセグメント)や茶色のケース(飛跡がジグザグしているもの)も興味のある飛跡とは言えないため、相互作用の強さは-1より大きな値に設定しています。なぜジグザグした飛跡が好ましくないかですが、一様な磁場に直交する方向に荷電粒子が入射した場合、その入射平面ではローレンツ力のせいで一定の曲率で同じ方向に粒子の軌道が曲がるからです。 以上のような理由から、この相互作用の強さは緑のケースに相当するセグメントのペアが最も-1に近くなるように決められていて、このようなペア(**各セグメントの3つのヒットのうち2つが共有されていて、かつ一定の曲率で同じ方向に軌道が曲がっているペア**)を選び出すことがここでの目標になります。 この段階まで処理されたデータを、`data/QUBO_05pct_input.txt`というファイルで提供しています。ファイルの中を見ると分かりますが、個々のセグメントは"23749_38657_45525"のような名前がついており、セグメントのペアをキーとする辞書型のデータとして格納されています(例えば、最初のデータは"('23749_38657_45525', '23749_38657_45525'): 0.01112655792777395"となっています)。同じセグメントのペアをキーとするデータがなぜこういう値をもっているのかは、前処理に使うモデルの詳細に依るのでここでは説明を省略します(ここでの課題には影響ありません)。 (problem)= #### 問題 以上のデータから、VQEで用いるハミルトニアンを構成してみてください。 **ヒント1**:この形式のデータを以下のコードを使って読み込むとします。 ``` file_r = 'data/QUBO_05pct_input.txt' from ast import literal_eval with open(file_r, "r") as f: line = f.read() Q = literal_eval(line) print("Q size =",len(Q)) n_max = 100 nvar = 0 key_i = [] b_ij = np.zeros((n_max,n_max)) for (k1, k2), v in Q.items(): if k1 == k2: b_ij[nvar][nvar] = v key_i.append(k1) nvar += 1 for (k1, k2), v in Q.items(): if k1 != k2: for i in range(nvar): for j in range(nvar): if k1 == key_i[i] and k2 == key_i[j]: if i < j: b_ij[i][j] = v else: b_ij[j][i] = v b_ij = b_ij[:nvar,:nvar] print("# of segments =",nvar) ``` セグメント数を$N$(上のコードではnvar)とすると、この時b_ijは$N$行$N$列の正方行列になります。実はこのデータは、**QUBO**(*Quadratic Unconstrained Binary Optimization*、2次制約無し2値最適化)と呼ばれる問題として解くことができる形式で与えられています。QUBOは量子ビット$T$がバイナリー値(0か1)を持つ場合に、以下の式で与えられる目的関数$O$を最小化する問題として定義されます。 $$ O(b,T) = \sum_{i=1}^Nb_{ii}T_i + \sum_{i=1}^N\sum_{j=1\:(i<j)}^Nb_{ij}T_iT_j $$ $T^2=T$でもあるため、上式は簡単に $$ O(b,T) = \sum_{i=1}^N\sum_{j=1}^Nb_{ij}T_iT_j $$ と書くこともできます。$T$は{0,1}のバイナリー値を持ちますが、シンプルな計算で{+1,-1}を持つ量子ビットに変換することができます。{+1,-1}はパウリ$Z$演算子の固有値でもあるため、パウリ$Z$演算子を使って目的関数$O$をハミルトニアンとして書くことができれば、そのまま量子回路に実装することができます。 以下のスペースに、どのような変換が可能か等を含め、VQEでTrackingを実行するために必要な量子演算を定義してください。 **ヒント2**:まず、{0,1}のバイナリー値を持つ$T$を{+1,-1}をもつスピン$s$に変換します。$T=0$を$s=1$、$T=1$を$s=-1$に対応させるとします。この関係の下で、目的関数$O$を $$ H(h,J,s) = \sum_{i=1}^Nh_is_i + \sum_{i=1}^N\sum_{j=1\:(i<j)}^NJ_{ij}s_is_j $$ となるような関数$H$に書き換えてみてください。この関数$H$はイジング模型のハミルトニアンと同じ形になっています。 ``` from qiskit.quantum_info import Pauli from qiskit.aqua.operators import PrimitiveOp ################## ### EDIT BELOW ### ################## # ステップ1:{0,1}を取るTに対して定義されているb_ijを、{+1,-1}を取る変数sに対して定義しなおす。 # ステップ2:変数sをパウリZ演算子を使って実装する。 #def get_qubitops(...): # # # return ?? ################## ### EDIT ABOVE ### ################## ``` このコードの部分を課題として提出してください。 **ヒント3**:get_qubitopsは、パウリ$Z$演算子を使って実装した観測量$H$を返す関数です。Qiskitでパウリ$Z$演算子とそのテンソル積を実装するには、qiskit.quantum_info.Pauliクラス([ここ](https://qiskit.org/documentation/stubs/qiskit.quantum_info.Pauli.html)を参照)とqiskit.aqua.operatorsライブラリ([ここ](https://qiskit.org/documentation/apidoc/qiskit.aqua.operators.html)を参照)を使うのが便利です。セグメント間の相互作用の強さを表す$J_{ij}$は、2つのパウリ$Z$演算子のテンソル積に対する係数として導入する必要があります。それをqiskit.quantum_info.Pauliを使ってどのように書くでしょうか?$h_i$は単一パウリ$Z$演算子の係数になります。そして、最終的に測定する観測量$H$は、それらパウリ$Z$演算子の線形結合になりますね。 (tracking_vqe)= ### VQEによる近似解の探索 上で定義したハミルトニアンを元に、VQEを使ってエネルギーの最小固有値(の近似解)を求めていきます。ただその前に、このハミルトニアンの行列を対角化して、エネルギーの最小固有値とその固有ベクトルを厳密に計算した場合の答えを出してみましょう。 ``` # ハミルトニアンオペレータを取得 ################## ### EDIT BELOW ### ################## qubitOp = get_qubitops(...) ################## ### EDIT ABOVE ### ################## print("") print("total number of qubits = ",qubitOp.num_qubits) # ハミルトニアン行列を対角化して、エネルギーの最小固有値と固有ベクトルを求める ee = NumPyMinimumEigensolver(qubitOp) result = ee.run() # 最小エネルギーに対応する量子ビットの組み合わせを表示 print('Eigensolver: objective =', result.eigenvalue.real) x = sample_most_likely(result.eigenstate) print('Eigensolver: x =',x) samples_eigen = {} for i in range(nvar): samples_eigen[key_i[i]] = x[i] ``` xのリストで1になっている量子ビット(セグメント)が、最小エネルギーに対応するものとして選ばれているのが分かります。 次に、同じハミルトニアンモデルをVQEに実装して、最小エネルギーを求めてみます。オプティマイザーとしてSPSAあるいはCOBYLAを使う場合のコードは以下のようになります。 まず最初に、VQE用の量子回路を作ります。 ``` # VQE用の回路を作る:ここではTwoLocalという組み込み関数を使う seed = 10598 spsa = SPSA(maxiter=300) cobyla = COBYLA(maxiter=500) two = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', 'linear', reps=1) print(two) ``` バックエンドしてqasm_simulatorを使い、実行した結果を書き出します。 ``` # VQEの実行 backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=1024, seed_simulator=seed) vqe = VQE(qubitOp, two, spsa) #vqe = VQE(qubitOp, two, cobyla) result = vqe.run(quantum_instance) # 最小エネルギーに対応する量子ビットの組み合わせを表示 print('') print('VQE: objective =', result.eigenvalue.real) x = sample_most_likely(result.eigenstate) print('VQE x =',x) samples_vqe = {} for i in range(nvar): samples_vqe[key_i[i]] = x[i] ``` (omake)= ### おまけ Trackingがうまく行っても、この答えだと0と1が並んでいるだけで面白くないですよね。正しく飛跡が見つかったかどうか目で確認するため、以下のコードを走らせてみましょう。 このコードは、QUBOを定義する時に使った検出器のヒット位置をビーム軸に垂直な平面でプロットして、どのヒットが選ばれたかを分かりやすく可視化したものです。緑の線が実際に見つかった飛跡で、青の線を含めたものが全体の飛跡の候補です。この実習では限られた数の量子ビットしか使っていないため、大部分の飛跡は見つけられていませんが、緑の線から計算に使った3点ヒットからは正しく飛跡が見つかっていることが分かると思います。 ``` from hepqpr.qallse import * input_path = './data/event000001000-hits.csv' dw = DataWrapper.from_path(input_path) # get the results #all_doublets = Qallse.process_sample(samples_eigen) all_doublets = Qallse.process_sample(samples_vqe) final_tracks, final_doublets = TrackRecreaterD().process_results(all_doublets) #print("all_doublets =",all_doublets) #print("final_tracks =",final_tracks) #print("final_doublets =",final_doublets) p, r, ms = dw.compute_score(final_doublets) trackml_score = dw.compute_trackml_score(final_tracks) print(f'SCORE -- precision (%): {p * 100}, recall (%): {r * 100}, missing: {len(ms)}') print(f' tracks found: {len(final_tracks)}, trackml score (%): {trackml_score * 100}') from hepqpr.qallse.plotting import iplot_results, iplot_results_tracks dims = ['x', 'y'] _, missings, _ = diff_rows(final_doublets, dw.get_real_doublets()) dout = 'plot-ising_found_tracks.html' iplot_results(dw, final_doublets, missings, dims=dims, filename=dout) ``` **提出するもの** - ハミルトニアンを実装する部分のコード
github_jupyter
# How to Understand and Manipulate the Periodogram of an Oscillating Star --- ## Learning Goals By the end of this tutorial you will: - Understand the key features of periodograms of oscillating stars. - Understand how these features change depending on the type of star being studied. - Be able to manipulate the periodogram to focus in on areas you're interested in. - Be able to smooth a periodogram. - Be able to remove features such as the convective background in solar-like oscillators. ## Introduction The brightnesses of stars can oscillate — that is, vary over time — for many different reasons. For example, in the companion tutorials we explored light curves that oscillated due to an eclipsing binary pair transiting in front of one another, and we looked at a star that showed variability due to star spots on its surface rotating in and out of view. In this tutorial, we will focus on *intrinsic* oscillators: stars that exhibit variability due to processes inside the stars. For example, one of these internal processes is the presence of standing waves trapped in the interior. When the light curve of a star is transformed into the frequency domain, such waves can be observed as distinct peaks in the frequency spectrum of the star. The branch of astronomy that focuses on studying these signals is called [*asteroseismology*](https://en.wikipedia.org/wiki/Asteroseismology). Asteroseismology is an important tool because it allows intrinsic properties of a star, such as its mass and radius, to be estimated from the light curve alone. The only requirement is that the quality of the light curve — its duration, sampling, and precision — must be good enough to provide a high-resolution view of the star in the frequency domain. *Kepler* data is particularly well-suited for this purpose. In this tutorial, we will explore two types of intrinsic oscillators that are commonly studied by asteroseismologists: 1. **$\delta$ Scuti stars**: a class of oscillating stars typically 1.5 to 2.5 times as massive as the Sun, which oscillate due to fluctuations in the opacity of the outer layers of the star. 2. **Solar-Like Oscillators**: a class that includes all stars that oscillate in the same manner as the Sun, namely due to turbulent motion in the convective outer layers of their atmospheres. This includes both main sequence stars as well as red giant stars. ## Imports This tutorial only requires **[Lightkurve](https://docs.lightkurve.org)**, which in turn uses **[Matplotlib](https://matplotlib.org/)** for plotting. ``` import lightkurve as lk %matplotlib inline ``` --- ## 1. Exploring the Frequency Spectrum of a $\delta$ Scuti Oscillator [$\delta$ Scuti stars](https://en.wikipedia.org/wiki/Delta_Scuti_variable) are stars roughly 1.5 to 2.5 as massive as the Sun, and oscillate due to fluctuations in the opacity of the outer layers of the star ([known as the Kappa mechanism](https://en.wikipedia.org/wiki/Kappa%E2%80%93mechanism)), alternately appearing brighter and fainter. An example star of this type is HD 42608, which was recently observed by the *TESS* space telescope. We can search for these data using Lightkurve: ``` lk.search_lightcurve('HD 42608', mission='TESS') ``` Success! A light curve for the object appears to be available in the data archive. Let's go ahead and download the data and convert it straight to a [`periodogram`](https://docs.lightkurve.org/api/lightkurve.periodogram.Periodogram.html) using the [`to_periodogram()`](https://docs.lightkurve.org/api/lightkurve.lightcurve.KeplerLightCurve.html#lightkurve.lightcurve.KeplerLightCurve.to_periodogram) function. ``` lc = lk.search_lightcurve('HD 42608', sector=6).download() pg = lc.normalize().to_periodogram() pg.plot(); ``` We can see that there is a strong power excess around 50 cycles per day. These indicate stellar oscillations. To study these peaks in more detail, we can zoom in by recreating the periodogram using the [`minimum_frequency`](https://docs.lightkurve.org/api/lightkurve.periodogram.LombScarglePeriodogram.html#lightkurve.periodogram.LombScarglePeriodogram.from_lightcurve) and [`maximum_frequency`](https://docs.lightkurve.org/api/lightkurve.periodogram.LombScarglePeriodogram.html#lightkurve.periodogram.LombScarglePeriodogram.from_lightcurve) keywords: ``` pg = lc.normalize().to_periodogram(minimum_frequency=35, maximum_frequency=60) pg.plot(); ``` This is much clearer! Stars of this type are known to display multiple types of oscillation, including: - **Radial Oscillations**: caused by the star shrinking and expanding radially. Also called a "breathing mode." - **Dipole Oscillations**: caused by the star's hemispheres shrinking and expanding alternately. Both types of oscillations are on display in the figure above. Identifying exactly what type of oscillation a given peak represents is challenging. Fortunately, this star (HD 42608) is part of a set of stars for which the oscillations have been analyzed in detail in a research paper by [Bedding et al. (2020)](https://arxiv.org/pdf/2005.06157.pdf), so you can consult that paper to learn more about the details. Note that the modes of oscillation are very "sharp" in the figure above. This is because $\delta$ Scuti oscillations are *coherent*, which is a term astronomers in the field use for signals that have long lifetimes and are not heavily damped. Because of this, their exact oscillation frequencies can be observed in a fairly straightforward way. This sets $\delta$ Scuti stars apart from solar-like oscillators, which are damped. Let's look at an example of such a star next. ## 2. Exploring the Frequency Spectrum of a Solar-Like Oscillator Solar-like oscillators exhibit variability driven by a different mechanism than $\delta$ Scuti stars. They encompass the class of stars that [oscillate in the same manner as the Sun](https://en.wikipedia.org/wiki/Helioseismology). Because they have lower masses than $\delta$ Scuti stars, solar-like oscillators have convective outer envelopes. The turbulent motion of these envelopes excites standing waves inside the stars which cause brightness changes on the surface. Unlike $\delta$ Scuti stars however, these waves are not coherent. Instead, these waves are stochastic and damped, which means that the lifetimes and amplitudes of the waves are limited and variable. While the name might imply that only stars like the Sun are solar-like oscillators, this is not true. All stars with convective outer layers can exhibit solar-like oscillations, including red giant stars! Let's have a look at the Sun-like star KIC 10963065 ([also known as Rudy](https://arxiv.org/pdf/1612.00436.pdf)), observed with *Kepler*. Because solar-like oscillation amplitudes are low, we will need to combine multiple quarters of data to improve our signal-to-noise. We can list the available data sets as follows: ``` search_result = lk.search_lightcurve('KIC 10963065', mission='Kepler') search_result ``` To create and plot this periodogram, we will apply a few common practices in the field: - We will combine multiple quarters to improve the frequency resolution. - We will [`normalize`](https://docs.lightkurve.org/api/lightkurve.lightcurve.LightCurve.html#lightkurve.lightcurve.LightCurve.normalize) the light curve to parts per million (`ppm`). - We will use the `psd` normalization option when calling [`to_periodogram`](https://docs.lightkurve.org/api/lightkurve.lightcurve.KeplerLightCurve.html#lightkurve.lightcurve.KeplerLightCurve.to_periodogram), which sets the units of frequency to microhertz, and normalizes the power using the spacing between bins of frequency. We'll also plot the resulting figure in log-log space. ``` lc = search_result[0:10].download_all().stitch() pg = lc.normalize(unit='ppm').to_periodogram(normalization='psd') pg.plot(scale='log'); ``` This periodogram looks very different to that of the $\delta$ Scuti star above. There is a lot of power excess at low frequencies: this is what we call the *convective background*, which is additional noise contributed by the convective surface of the star constantly changing. We do not see any clear peaks like we did for the $\delta$ Scuti oscillator however. There is a good reason for this: this main sequence star oscillates at frequencies too large to be seen on this periodogram, lying above the periodogram's [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency). The Nyquist frequency is a property of a time series that describes the maximum frequency that can be reliably determined in a periodogram. It stems from the assumption that you need a minimum of two observations per oscillation period to observe a pattern (one observation on the "up," and one on the "down" oscillation). It is defined as follows: $\nu_{\rm nyq} = \frac{1}{2\Delta t}$ , where $\Delta t$ is the observing cadence. The reason that we can't see Rudy's oscillations in the periodogram above is because we constructed this periodogram using the *Kepler* 30-minute Long Cadence data. Solar-like oscillators on the main sequence typically oscillate on the order of minutes (five minutes for the Sun), at frequencies much higher than will be visible on this periodogram. To see Rudy's oscillations, we will need to use the *Kepler* Short Cadence (SC) observations, which used a time sampling of one minute. We can obtain these data as follows: ``` search_result = lk.search_lightcurve('KIC 10963065', mission='Kepler', cadence='short') lc = search_result[0:10].download_all().stitch() pg = lc.normalize(unit='ppm').to_periodogram(normalization='psd') pg.plot(scale='log'); ``` Now we can see a power excess near $2000\, \mu\rm{Hz}$. This frequency is almost 10 times higher than we could view using the Long Cadence data alone. Let's zoom in on this region so we can look at the signals in more detail, like we did for the $\delta$ Scuti star. ``` zoom_pg = lc.normalize(unit='ppm').to_periodogram(normalization='psd', minimum_frequency=1500, maximum_frequency=2700) zoom_pg.plot(); ``` Compared to the $\delta$ Scuti, the modes of oscillation in the figure above are less sharp, even though we used much more data to create the periodogram. This is because the modes in solar-like oscillators are damped due to the turbulent motion of the convective envelope. This lowers their amplitudes and also causes the lifetimes of the oscillations to be short. The short lifetimes create some uncertainty around the exact oscillation frequency, and so the peaks that appear in the periodogram are a little broader (usually Lorentzian-like in shape). This may not be immediately apparant from these figures, but is much clearer if you zoom in on an individual mode. ## 3. How to Smooth and Detrend a Periodogram ### 3.1. The box kernel filter To further explore the oscillation modes, we will demonstrate some of Lightkurve's smoothing tools. There are two types of smoothing functions we can call through the [`smooth()`](https://docs.lightkurve.org/api/lightkurve.periodogram.Periodogram.html#lightkurve.periodogram.Periodogram.smooth) function. Let's start with a basic "moving median," also known as a 1D box kernel. ``` smooth_pg = zoom_pg.smooth(method='boxkernel', filter_width=0.5) ax = zoom_pg.plot(label='Original') smooth_pg.plot(ax=ax, color='red', label='Smoothed'); ``` In the figure above, the smoothed periodogram is plotted over the top of the original periodogram. In this case we have used the [Astropy `Box1DKernel`](https://docs.astropy.org/en/stable/api/astropy.convolution.Box1DKernel.html) filter, with a filter width of $0.5\, \mu \rm{Hz}$. The filter takes the median value of power in a region $0.5\, \mu \rm{Hz}$ around a data point, and replaces that point with the median value. It then moves on to the next data point. This creates a smoothed periodogram of the same length as the original. Because the power values are now correlated, these smoothed periodograms usually aren't used for computational analysis, but they can aid visual explorations of the location of the oscillation modes. ### 3.2. The log median filter While the [`Box1DKernel`](https://docs.astropy.org/en/stable/api/astropy.convolution.Box1DKernel.html) filter can be used to help identify modes of oscillation in the presence of noise, it is mostly good for smoothing on small scales. For large scales, we can instead use Lightkurve's log median filter. As we saw above, solar-like oscillators exhibit a large power excess at low frequencies due to the turbulent convection visible near the stellar surface. When studying modes of oscillation, we typically aren't interested in the convective background, and prefer to remove it. The log median filter performs a similar operation to the [`Box1DKernel`](https://docs.astropy.org/en/stable/api/astropy.convolution.Box1DKernel.html) filter, but does so in log space. This means that at low frequencies the number of frequency bins of which the median is taken is small, and that at high frequencies many frequency bins are included in the median calculation. As a result, the log median filter smooths over the convection background but ignores the modes of oscillation at high frequencies. The result of applying a log median filter is demonstrated using the red line in the figure below: ``` smooth_pg = pg.smooth(method='logmedian', filter_width=0.1) ax = pg.plot(label='Original') smooth_pg.plot(ax=ax, linewidth=2, color='red', label='Smoothed', scale='log'); ``` ### 3.3. Flattening When studying modes of oscillation, it is typically preferred to remove the convective background. In a detailed analysis this would involve fitting a model to the background. As can be seen in the figure above, however, Lightkurve's log median [`smooth()`](https://docs.lightkurve.org/api/lightkurve.periodogram.LombScarglePeriodogram.html#lightkurve.periodogram.LombScarglePeriodogram.smooth) method provides a useful first-order approximation of the background without the need for a model. To divide the power spectrum by the background, we can use Lightkurve's [`flatten()`](https://docs.lightkurve.org/api/lightkurve.periodogram.LombScarglePeriodogram.html#lightkurve.periodogram.LombScarglePeriodogram.flatten) method. This function uses the log median smoothing method to determine the background, and returns a new [`periodogram`](https://docs.lightkurve.org/api/lightkurve.periodogram.Periodogram.html) object in which the background has been divided out. ``` snrpg = pg.flatten() snrpg ``` The periodogram obtained by dividing by the noise in this way is commonly called a Signal-to-Noise periodogram (`SNRPeriodogram`), because the noise, in the form of the convective background, has been removed. This is a little bit of a misnomer, because there is still noise present in the periodogram. We plot the `SNRPeriodogram` below, and see that the modes of oscillation stick out from the noise much more clearly now that the convective background has been removed. ``` snrpg.plot(); ``` ## 4. Closing Comments In this tutorial, we explored two common types of oscillating stars, and demonstrated how Lightkurve can be used to study their power specta. In the accompanying tutorials, you can learn how to use these tools to extract more detailed information from them, including the radius and mass of a star! For further reading on $\delta$ Scuti stars, solar-like oscillators, and Fourier Transforms, we recommend you consult the following papers: - [Vanderplas (2017)](https://arxiv.org/pdf/1703.09824.pdf) – A detailed paper on Fourier Transforms and Lomb-Scargle Periodograms. - [Bedding et al. (2020)](https://arxiv.org/pdf/2005.06157.pdf) – A demonstration of mode identification in $\delta$ Scuti stars. - [Chaplin & Miglio (2013)](https://arxiv.org/pdf/1303.1957.pdf) – A review paper on asteroseismology of solar-like oscillators with *Kepler*. - [Aerts (2019)](https://arxiv.org/pdf/1912.12300.pdf) – A comprehensive review that covers asteroseismology of a wide range of oscillating stars, including solar-like oscillators and $\delta$ Scutis. ## About this Notebook **Authors**: Oliver Hall (oliver.hall@esa.int), Geert Barentsen **Updated On**: 2020-09-29 # Citing Lightkurve and Astropy If you use `lightkurve` or `astropy` for published research, please cite the authors. Click the buttons below to copy BibTeX entries to your clipboard. ``` lk.show_citation_instructions() ``` <img style="float: right;" src="https://raw.githubusercontent.com/spacetelescope/notebooks/master/assets/stsci_pri_combo_mark_horizonal_white_bkgd.png" alt="Space Telescope Logo" width="200px"/>
github_jupyter
# Iris classification in Keras Author: Michał Słapek Classification example for Iris dataset. ``` import numpy as np import pandas as pd from matplotlib import pyplot as plt import seaborn as sns import keras from keras.models import Sequential from keras.layers import Dense from utils import get_iris_data from plot_iris import plot_contours data = get_iris_data() type(data) data.head(5) sns.set() plt.figure(dpi=100) sns.scatterplot( x='sepal length (cm)', y='sepal width (cm)', hue='family', data=data ) plt.show() ``` ## Model plot ``` plot_x_lim = (4, 9) plot_y_lim = (1.5, 5) plot_X, plot_Y = np.meshgrid( np.arange(*plot_x_lim, step=0.1), np.arange(*plot_y_lim, step=0.1) ) def format_loss(l): return '[' + ', '.join(f'{v:0.2f}' for v in l) + ']' def plot_model(model, name='model'): fig, ax = plt.subplots(dpi=100) a = plot_contours(ax, model, plot_X, plot_Y) fig.colorbar(a) sns.scatterplot( x=X_train[:, 0], y=X_train[:, 1], hue='T' + pd.Series(y_train).astype(str), hue_order=[f'T{i}' for i in range(3)], marker='x', legend=False ) sns.scatterplot( x=X_valid[:, 0], y=X_valid[:, 1], hue='V' + pd.Series(y_valid).astype(str), hue_order=[f'V{i}' for i in range(3)], legend=False ) text = f'train: {format_loss(model.evaluate(X_train, y_train, verbose=False))}\n' \ f'valid: {format_loss(model.evaluate(X_valid, y_valid, verbose=False))}' ax.text(4.5, 4.5, text, color='white') ``` ## Train, test, validation split ``` from sklearn.model_selection import train_test_split X = data[['sepal length (cm)', 'sepal width (cm)']].values y = data['class'].values X_train_valid, X_test, y_train_valid, y_test = train_test_split( X, y, test_size=0.25, random_state=910797 ) X_train, X_valid, y_train, y_valid = train_test_split( X_train_valid, y_train_valid, test_size=1/3, random_state=142385 ) for m in [X_train, X_valid, X_test]: print(type(m)) print(m.shape) ``` ## Model class ~ (sepal width) * (sepal length) ``` models = {} ``` ### Flat model ``` model = Sequential() model.add(Dense(units=3, input_dim=2, activation='softmax')) model.compile( loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True), metrics=['accuracy'] ) model.summary() # model.load_weights('weights/iris_flat.hdf5') model.fit( X_train, y_train, epochs=1_000, batch_size=len(y_train), validation_data=(X_valid, y_valid) ) # model.save_weights('weights/iris_flat.hdf5') models['flat'] = model plot_model(model, 'flat') ``` ## Medium model ``` model = Sequential() model.add(Dense(units=5, input_dim=2, activation='relu')) model.add(Dense(units=3, activation='softmax')) model.compile( loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True), metrics=['accuracy'] ) model.summary() model.load_weights('weights/iris_medium.hdf5') # model.fit( # X_train, y_train, # epochs=10_000, # batch_size=len(y_train), # validation_data=(X_valid, y_valid), # verbose=False # ) # model.save_weights('weights/iris_medium.hdf5') models['medium'] = model plot_model(model) ``` ## Big model ``` model = Sequential() model.add(Dense(units=100, input_dim=2, activation='relu')) model.add(Dense(units=100, activation='relu')) model.add(Dense(units=100, activation='relu')) model.add(Dense(units=3, activation='softmax')) model.compile( loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True), metrics=['accuracy'] ) model.summary() model.load_weights('weights/iris_big.hdf5') # model.fit( # X_train, y_train, # epochs=10_000, # batch_size=len(y_train), # validation_data=(X_valid, y_valid), # verbose=False # ) # model.save_weights('weights/iris_big.hdf5') models['big'] = model plot_model(model) for k, m in models.items(): score = m.evaluate(X_valid, y_valid, verbose=False) print(f'Model {k:10}: {score}') models['????'].evaluate(X_test, y_test) ```
github_jupyter
# Table of Contents * [Intro](#Intro) * [Generative Adversarial Networks (GANs)](#Generative-Adversarial-Networks-%28GANs%29) * [Gaussian Distribution Approximation (Keras)](#Gaussian-Distribution-Approximation-%28Keras%29) * [MNIST GAN (Keras)](#MNIST-GAN-%28Keras%29) * [Generator Model](#Generator-Model) * [Discriminator Model](#Discriminator-Model) * [GAN Model](#GAN-Model) * [Train](#Train) * [Wasserstein GAN](#Wasserstein-GAN) * [Generator Model](#Generator-Model) * [Discriminator Model](#Discriminator-Model) * [GAN Model](#GAN-Model) * [Train](#Train) * [Plot Losses](#Plot-Losses) * [Generate gif](#Generate-gif) # Intro Exploratory notebook related to Generative Adversarial Networks (GANs). Includes toy examples implementation and testing of related techniques or subjects. ## Generative Adversarial Networks (GANs) Architecture that learns by posing two networks in competition with each others. Goal is to learn parameters in order to produce a distribution close to our dataset distribution (true distribution). * Discriminator: detect if an image belongs to a target dataset or not (generated by the generator) * Generator: generate new examples that looks like the training/target data (fool the discriminator) ``` import time from PIL import Image import numpy as np import pdb import os import sys import seaborn as sns import matplotlib import matplotlib.pyplot as plt from matplotlib import animation from keras.models import Sequential from keras.layers.core import Reshape, Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D, UpSampling2D from keras.layers.advanced_activations import LeakyReLU from keras import backend as K from keras import optimizers from keras.layers.normalization import BatchNormalization from keras.datasets import mnist from tqdm import tqdm_notebook as tqdm %matplotlib notebook sns.set_style("dark") sys.path.append(os.path.join(os.getcwd(), os.pardir)) from utils.plot_utils import plot_sample_imgs from utils.generative_utils import NoiseDistribution, set_trainable RES_DIR = os.path.join(*[os.pardir]*2, 'data', 'deep_learning') %load_ext autoreload %autoreload 2 ``` # Gaussian Distribution Approximation (Keras) Example adapted from [Aylien blog](http://blog.aylien.com/introduction-generative-adversarial-networks-code-tensorflow/). Check also [here](https://medium.com/towards-data-science/gan-by-example-using-keras-on-tensorflow-backend-1a6d515a60d0) for Keras code ``` # target 1D gaussian distribution class class GaussianDistribution: def __init__(self, mu=4, sigma=0.5): self.mu = mu self.sigma = sigma def sample(self, N): samples = np.random.normal(self.mu, self.sigma, N) samples.sort() return samples # generator input noise distribution class class GeneratorNoiseDistribution: def __init__(self, vrange): self.vrange = vrange def sample(self, N): return np.linspace(-self.vrange, self.vrange, N) + \ np.random.random(N) * 0.01 def generator(input_dim, hidden_size): g = Sequential() g.add(Dense(hidden_size, input_dim=input_dim, activation=K.softplus)) g.add(Dense(input_dim)) return g def discriminator(input_dim, hidden_size): d = Sequential() d.add(Dense(hidden_size*2, input_dim=input_dim, activation=K.tanh)) d.add(Dense(hidden_size*2, activation=K.tanh)) d.add(Dense(hidden_size*2, activation=K.tanh)) d.add(Dense(1, activation=K.sigmoid)) return d # init distributions gaussian_d = GaussianDistribution() generator_d = GeneratorNoiseDistribution(8) # init GAN components d = discriminator(1, 128) g = generator(1, 128) # discriminator model optimizer = optimizers.RMSprop(lr=0.0008, clipvalue=1.0, decay=6e-8) discriminator_model = d discriminator_model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) # adversarial model optimizer = optimizers.RMSprop(lr=0.0004, clipvalue=1.0, decay=3e-8) adversarial_model = Sequential() adversarial_model.add(g) adversarial_model.add(d) adversarial_model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) batch_size = 64 fig, ax = plt.subplots(dpi=100, figsize=(5, 4)) true_dist = np.reshape(gaussian_d.sample(1000), (1000, 1)) plt.show() def animate(step): #for step in range(100): # generate data # first we sample from the true distribution, then we generate some # "fake" data by feeding noise to the generator true_sample = np.reshape(gaussian_d.sample(batch_size), (batch_size, 1)) noise = generator_d.sample(batch_size) fake_sample = g.predict(noise) #pdb.set_trace() # train discriminator # feed true and fake samples with respective labels (1, 0) to the discriminator x = np.reshape(np.concatenate((true_sample, fake_sample)), (batch_size*2, 1)) y = np.ones([batch_size*2, 1]) y[batch_size:, :] = 0 d_loss = discriminator_model.train_on_batch(x, y) # train GAN # feed noise to the model and expect true (1) response from discriminator, # which is in turn fed with data generated by the generator noise = np.reshape(generator_d.sample(batch_size), (batch_size, 1)) y = np.ones([batch_size, 1]) a_loss = adversarial_model.train_on_batch(noise, y) log_mesg = "%d: [D loss: %f, acc: %f]" % (step, d_loss[0], d_loss[1]) log_mesg = "%s [A loss: %f, acc: %f]" % (log_mesg, a_loss[0], a_loss[1]) # plot fig.clf() fake = sns.distplot(fake_sample) fake.set_xlim([0,8]) fake.set_ylim([0,3]) sns.distplot(true_dist) sns.plt.text(3, 2, "Epoch {}, a_loss {:.3f}".format(step, a_loss[0])) anim = animation.FuncAnimation(fig, animate, 200, repeat=False) noise = generator_d.sample(batch_size) fake_sample = g.predict(noise) sns.distplot(fake_sample) sns.plt.show() ``` # MNIST GAN (Keras) Example adapted from [MNIST Generative Adversarial Model in Keras](http://www.kdnuggets.com/2016/07/mnist-generative-adversarial-model-keras.html) ``` noise_d = NoiseDistribution() input_dim = 100 img_shape = (28,28,1) ``` ## Generator Model ``` # model takes real values vector of size input_dim and via upsampling, # reshaping, and various convolutional filters generates a 28x28 b/w image def generator_model(input_dim, n_channels=128, init_side=7): m = Sequential() m.add(Dense(init_side*init_side*n_channels, input_dim=input_dim, activation=LeakyReLU())) m.add(BatchNormalization(mode=2)) m.add(Reshape((init_side, init_side, n_channels))) m.add(UpSampling2D()) m.add(Convolution2D(n_channels//2, 3, 3, border_mode='same', activation=LeakyReLU())) m.add(BatchNormalization(mode=2)) m.add(UpSampling2D()) m.add(Convolution2D(n_channels//4, 3, 3, border_mode='same', activation=LeakyReLU())) m.add(BatchNormalization(mode=2)) #?? Tanh m.add(Convolution2D(1, 1, 1, border_mode='same', activation='sigmoid')) return m g = generator_model(input_dim=input_dim, n_channels=512) g.summary() # plot random generated image plt.imshow(g.predict(noise_d.sample((1, input_dim)))[0] .reshape(28, 28)) plt.show() ``` ## Discriminator Model ``` # model takes image and after convolution and flattening # outputs a probability value def discriminator_model(input_shape, init_filters=64): m = Sequential() m.add(Convolution2D(init_filters, 5, 5, subsample=(2, 2), input_shape=input_shape, border_mode='same', activation=LeakyReLU(0.2))) #?? maxpooling and dropout? MaxPool2D(pool_size=2) m.add(Convolution2D(init_filters*2, 5, 5, subsample=(2, 2), border_mode='same', activation=LeakyReLU(0.2))) #m.add(Convolution2D(init_filters*4, 3, 5, border_mode='same', # activation=LeakyReLU(0.2))) m.add(Flatten()) m.add(Dense(256, activation=LeakyReLU())) m.add(Dense(1, activation='sigmoid')) return m d = discriminator_model(input_shape=(28,28,1), init_filters=256) d.summary() # print prediction for random image d.predict(g.predict(noise_d.sample((1, input_dim)))) ``` ## GAN Model ``` # init GAN components g = generator_model(input_dim) d = discriminator_model(img_shape) # compile generator #g_optimizer = optimizers.Adam(lr=0.0001) #g.compile(loss='binary_crossentropy', optimizer=g_optimizer) # compile discriminator d_optimizer = optimizers.Adam(lr=0.001) d.compile(loss='binary_crossentropy', optimizer=d_optimizer) # build adversarial model gan = Sequential() gan.add(g) gan.add(d) gan_optimizer = optimizers.Adam(lr=0.0001) gan.compile(loss='binary_crossentropy', optimizer=gan_optimizer) gan.summary() ``` ## Train ``` generator_fun = lambda num_samples : generator.predict(noise_d.sample((num_samples, input_dim))) # load mnist data using Keras (X_train, y_train), (X_test, y_test) = mnist.load_data() # reshape and normalize train data X_train = np.expand_dims(X_train, axis=-1) X_train = X_train.astype('float32')/255 print(X_train.shape) print(y_train.shape) def train_discriminator(d, g, noise_d, input_dim, X_train, batch_size, epoch): # generate data # first we sample from the true distribution (mnist dataset), then we generate some # "fake" images by feeding noise to the generator # generate random indexes for train data batch_idxs = np.random.randint(0, len(X_train), batch_size) # collect images corresponsing to previously generated index, and add a dimension true_sample = X_train[batch_idxs,:,:,:] # generate fake sample fake_sample = g.predict(noise_d.sample((batch_size, input_dim))) # prepare train batch data # concatenativ true and fake samples and adjusting labels accordingly x = np.concatenate((true_sample, fake_sample)) y = np.ones([batch_size*2, 1]) y[batch_size:,:] = 0 # train discriminator # feed true and fake samples with respective labels (1, 0) to the discriminator set_trainable(d, True, None, None) d_loss = d.train_on_batch(x, y) #print("Epoch {}: [D loss: {}]".format(epoch, d_loss)) return d_loss def train(d, g, gan, noise_d, input_dim, X_train, batch_size=32, n_epochs=1, add_epoch=0): losses = {'g':[], 'd':[]} for epoch in range(n_epochs): # train discriminator d_loss = train_discriminator(d, g, noise_d, input_dim, X_train, batch_size, epoch) losses['d'].append(d_loss) set_trainable(d, False, None, None) # train GAN # feed noise to the model and expect true (1) response from discriminator, # which is in turn fed with data generated by the generator noise = noise_d.sample((batch_size, input_dim)) y = np.ones([batch_size, 1]) g_loss = gan.train_on_batch(noise, y) losses['g'].append(g_loss) #print("Epoch {}: [G loss: {}]".format(epoch, g_loss)) if (epoch%10)==0: plot_sample_imgs(generator_fun, img_shape[:2], savepath=os.path.join('data', 'mnist_gan', 'mnist_gen{}.jpg'.format(epoch+add_epoch))) return losses # pretrain discriminator batch_size = 128 n_epochs = 1 for epoch in range(n_epochs): train_discriminator(d, g, noise_d, input_dim, X_train, batch_size, epoch) #plt.ion() plt.ioff() K.set_value(d.optimizer.lr, 1e-3) K.set_value(gan.optimizer.lr, 1e-3) losses = train(d, g, gan, noise_d, input_dim, X_train, batch_size=256, n_epochs=1000, add_epoch=120) # plot random generated image plt.imshow(g.predict(np.random.randn(input_dim).reshape(1, -1)) .reshape(28, 28)) plt.show() plt.imshow(true_sample[2].reshape(28, 28)) plt.show() gan.test_on_batch(noise, y) gan.train_on_batch(noise, y) ``` # Wasserstein GAN [Source](https://myurasov.github.io/2017/09/24/wasserstein-gan-keras.html) ``` from keras.layers import * from keras.models import * from keras.optimizers import * from keras.initializers import * from keras.callbacks import * from keras.utils.generic_utils import Progbar noise_d = NoiseDistribution() input_dim = 100 img_shape = (28,28,1) num_classes = 10 ``` ## Generator Model ``` # utility for the standard deconvolution block used in the generator def generator_deconv_block(filters, block_input, kernel_size=(3, 3), strides=(1, 1)): block = UpSampling2D()(block_input) block = Convolution2D(filters, (3, 3), strides=strides, padding='same')(block) block = LeakyReLU()(block) block = BatchNormalization()(block) return block # different from basic DCGAN, this WGAN model # takes as input both the prior sample (noise) and the image class def generator_model(input_dim, voc_size, init_filters=128, init_side=7, num_deconv_blocks=2): # Input combination part input_class = Input(shape=(1, ), dtype='int32') e = Embedding(voc_size, input_dim)(input_class) embedded_class = Flatten()(e) # noise noise = Input(shape=(input_dim, )) # hadamard product h = multiply([noise, embedded_class]) # CNN part x = Dense(1024)(h) x = LeakyReLU()(x) x = Dense(init_side*init_side*init_filters)(x) x = LeakyReLU()(x) x = BatchNormalization()(x) x = Reshape((init_side, init_side, init_filters))(x) for i in range(num_deconv_blocks): x = generator_deconv_block(init_filters//(2**(i+1)), block_input=x, kernel_size=(5, 5)) x = Convolution2D(1, (2, 2), padding='same', activation='tanh')(x) return Model(inputs=[noise, input_class], outputs=x) # instantiate generate model gen = generator_model(input_dim=input_dim, voc_size=10, init_filters=128) gen.summary() # plot random generated image plt.imshow(gen.predict([noise_d.sample((1, input_dim)), np.array([7])])[0] .reshape(28, 28)) plt.show() ``` ## Discriminator Model ``` # utility for the standard convolution block used in the discriminator def discriminator_conv_block(filters, block_input, kernel_size=(3, 3), strides=(1, 1), pool_size=None): block = Convolution2D(filters, kernel_size, strides=strides, padding='same')(block_input) block = LeakyReLU()(block) block = BatchNormalization()(block) # if given, add max pooling if pool_size: block = MaxPool2D(pool_size=pool_size)(block) return block # different from basic DCGAN, this WGAN discriminator model # takes an image as input, and output both a prediction about image autheticity # as well as one for the image class def discriminator_model(input_shape, num_classes, init_filters=32, num_conv_blocks=3): input_image = Input(shape=input_shape) x = input_image for i in range(num_conv_blocks): x = discriminator_conv_block(init_filters*(2**i), block_input=x, pool_size=None) features = Flatten()(x) out_autheticity = Dense(1, activation='linear')(features) out_class = Dense(num_classes, activation='softmax')(features) return Model(inputs=[input_image], outputs=[out_autheticity, out_class]) # instantiate discriminator model dis = discriminator_model(input_shape=img_shape, num_classes=10, init_filters=32) dis.summary() # print prediction for random image dis.predict(gen.predict([noise_d.sample((1, input_dim)), np.array([3])])) ``` ## GAN Model ``` # loss function for discriminator def d_loss(y_true, y_pred): return K.mean(y_true * y_pred) # init GAN components gen = generator_model(input_dim=input_dim, voc_size=num_classes, init_filters=128) dis = discriminator_model(input_shape=img_shape, num_classes=num_classes, init_filters=32) # compile discriminator dis.compile(loss=[d_loss, 'sparse_categorical_crossentropy'], optimizer=RMSprop(lr=1e-4)) # Build adversarial model noise = Input(shape=(input_dim, )) input_class = Input(shape=(1, ), dtype='int32') out_autheticity, out_class = dis(gen(inputs=[noise, input_class])) gan = Model(inputs=[noise, input_class], outputs=[out_autheticity, out_class]) gan.compile(loss=[d_loss, 'sparse_categorical_crossentropy'], optimizer=RMSprop(lr=1e-4)) gan.summary() ``` ## Train ``` # given that generator uses tanh activation function, # we need to process its output to make it a valid image #deprocess = lambda img : np.transpose((img/2+0.5).clip(0,1), (1,2,0)) deprocess = lambda img : (img/2+0.5).clip(0,1) generator_fun = lambda num_samples : deprocess(gen.predict([noise_d.sample((num_samples, input_dim)), np.random.randint(0, num_classes, num_samples)])) # load mnist data using Keras (X_train, y_train), (X_test, y_test) = mnist.load_data() # normalize to -1..1 range and reshape X_train = (X_train.astype(np.float32) - 127.5) / 127.5 X_train = np.expand_dims(X_train, axis=-1) print(X_train.shape) print(y_train.shape) def train_discriminator(dis, gen, noise_d, input_dim, num_classes, X_train, Y_train, batch_size, epoch): # clip weights for l in dis.layers: weights = l.get_weights() weights = [np.clip(w, -0.01, 0.01) for w in weights] l.set_weights(weights) # generate data # first we sample from the true distribution (mnist dataset), then we generate some # "fake" images by feeding noise to the generator # generate random indexes for train data batch_idxs = np.random.randint(0, len(X_train), batch_size) # collect images corresponsing to previously generated index, and add a dimension true_sample = X_train[batch_idxs] true_sample_classes = y_train[batch_idxs] # train on true samples dis_true_loss = dis.train_on_batch(true_sample, [-np.ones(batch_size), true_sample_classes]) # generate fake sample noise = noise_d.sample((batch_size, input_dim)) generated_classes = np.random.randint(0, num_classes, batch_size) fake_sample = gen.predict([noise, generated_classes.reshape(-1, 1)]) # train on fake samples dis_fake_loss = dis.train_on_batch(fake_sample, [np.ones(batch_size), generated_classes]) #print("Epoch {}: [D loss: {}]".format(epoch, d_loss)) return dis_true_loss, dis_fake_loss def train(dis, gen, gan, noise_d, input_dim, num_classes, X_train, Y_train, batch_size=32, n_epochs=1, add_epochs=0): losses = {'gan':[], 'dis_fake_loss':[], 'dis_true_loss':[]} for epoch in tqdm(range(n_epochs), desc='Training GAN'): if (epoch+add_epochs % 1000) < 15 or epoch+add_epochs % 500 == 0: # 25 times in 1000, every 500th d_iters = 40 else: d_iters = 5#D_ITERS # train discriminator set_trainable(dis, True, None, None) for d_epoch in range(d_iters): dis_true_loss, dis_fake_loss = train_discriminator(dis, gen, noise_d, input_dim, num_classes, X_train, Y_train, batch_size, epoch) losses['dis_fake_loss'].append(dis_fake_loss) losses['dis_true_loss'].append(dis_true_loss) set_trainable(dis, False, None, None) # train GAN # feed noise to the model and expect true (1) response from discriminator, # which is in turn fed with data generated by the generator noise = noise_d.sample((batch_size, input_dim)) generated_classes = np.random.randint(0, num_classes, batch_size) gan_loss = gan.train_on_batch( [noise, generated_classes.reshape((-1, 1))], [-np.ones(batch_size), generated_classes]) losses['gan'].append(gan_loss) #print("Epoch {}: [G loss: {}]".format(epoch, g_loss)) if epoch%10 == 0: plot_sample_imgs(generator_fun, img_shape[:2], savepath=os.path.join(RES_DIR, 'data', 'mnist_wgan', 'mnist_gen{}.jpg'.format(epoch+add_epochs))) return losses add_epochs = 0 #plt.ion() plt.ioff() n_epochs = 500 losses = train(dis, gen, gan, noise_d, input_dim, num_classes, X_train, y_train, batch_size=64, n_epochs=n_epochs, add_epochs=add_epochs) add_epochs += n_epochs ``` ## Plot Losses ``` def plot_losses(losses): f = plt.figure() #plt.plot(losses['dis_fake_loss'], label='dis_fake_loss') #plt.plot(losses['dis_fake_loss'], label='dis_true_loss') plt.plot(np.array(losses['gan'])[:,2], label='gan loss') plt.legend() plt.show() plot_losses(losses) np.array(losses['gan'])[:,0] ``` # Generate gif ``` import imageio import os RES_DIR = os.path.join(os.pardir, os.pardir, 'data', 'deep_learning') dir_path = os.path.join(RES_DIR, 'data', 'mnist_wgan', 'test_2') filenames = [(os.path.join(dir_path, filename), int(filename[9:-4])) for filename in os.listdir(dir_path)] images = [] for filename in sorted(filenames, key=lambda x:x[1]): images.append(imageio.imread(filename[0])) imageio.mimsave(os.path.join(RES_DIR, 'data', 'mnist_wgan', 'wgan.gif'), images) ```
github_jupyter
# Unary Operators ## WHEN X AND +X ARE NOT EQUAL ``` import decimal ctx = decimal.getcontext() ctx.prec = 40 one_third = decimal.Decimal('1') / decimal.Decimal('3') one_third one_third == +one_third ctx.prec = 28 one_third == +one_third +one_third from collections import Counter ct = Counter('abracadabra') ct ct['r'] = -3 ct['d'] = 0 ct +ct ``` # Overloading + for Vector Addition ``` from array import array import reprlib import math import numbers import functools import operator import itertools class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return 'Vector({})'.format(components) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): if isinstance(other, Vector): return (len(self) == len(other) and all(a == b for a, b in zip(self, other))) else: return NotImplemented def __hash__(self): hashes = (hash(x) for x in self._components) return functools.reduce(operator.xor, hashes, 0) def __abs__(self): return math.sqrt(sum(x * x) for x in self) def __neg__(self): return Vector(-x for x in self) def __pos__(self): return Vector(self) def __add__(self, other): try: pairs = itertools.zip_longest(self, other, fillvalue=0.0) return Vector(a + b for a, b in pairs) except TypeError: return NotImplemented def __radd__(self, other): return self + other def __mul__(self, scalar): if isinstance(scalar, numbers.Real): return Vector(n * scalar for n in self) else: return NotImplemented def __rmul__(self, scalar): return self * scalar def __matmul__(self, other): try: return sum(a * b for a, b in zip(self, other)) except TypeError: return NotImplemented def __rmatmul__(self, other): return self @ other def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, index): cls = type(self) if isinstance(index, slice): return cls(self._components[index]) elif isinstance(index, numbers.Integral): return self._components[index] else: msg = '{.__name__} indices must be integers' raise TypeError(msg.format(cls)) shortcut_names = 'xyzt' def __getattr__(self, name): cls = type(self) if len(name) == 1: pos = cls.shortcut_names.find(name) if 0 <= pos < len(self._components): return self._components[pos] msg = '{.__name__!r} object has no atttribute {!r}' raise AttributeError(msg.format(cls, name)) def __setattr__(self, name, value): cls = type(self) if len(name) == 1: if name in cls.shortcut_names: error = 'readonly attribute {attr_name!r}' elif name.islower(): error = "can't set attributes 'a' to 'z' in {cls_name!r}" else: error = '' if error: msg = error.format(cls_name=cls.__name__, attr_name=name) raise AttributeError(msg) super().__setattr__(name, value) def angle(self, n): r = math.sqrt(sum(x * x for x in self[n:])) a = math.atan2(r, self[n-1]) if (n == len(self) - 1) and (self[-1] < 0): return math.pi * 2 - a else: return a def angles(self): return (self.angle(n) for n in range(1, len(self))) def __format__(self, fmt_spec=''): if fmt_spec.endswith('h'): # hyperspherical coordinates fmt_spec = fmt_spec[:-1] coords = itertools.chain([abs(self)], self.angles()) outer_fmt = '<{}>' else: coords = self outer_fmt = '({})' components = (format(c, fmt_spec) for c in coords) return outer_fmt.format(', '.join(components)) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv) v1 = Vector([3, 4, 5]) v2 = Vector([6, 7, 8]) v1 + v2 v1 + v2 == Vector([3+6, 4+7, 5+8]) v1 + (10, 20, 30) from vector2d_v3 import Vector2d v2d = Vector2d(1, 2) v1 + v2d (10, 20, 30) + v1 v2d + v1 v1 + 1 v1 + 'ABC' ``` # Overloading * for Scalar Multiplication ``` v1 = Vector([1, 2, 3]) v1 * 10 v1 = Vector([1.0, 2.0, 3.0]) 14 * v1 v1 * True from fractions import Fraction v1 * Fraction(1, 3) ``` ## THE NEW @ INFIX OPERATOR IN PYTHON 3.5 ``` va = Vector([1, 2, 3]) vz = Vector([5, 6, 7]) va @ vz == 38.0 [10, 20, 30] @ vz va @ 3 ``` # Rich Comparison Operators ``` va = Vector([1.0, 2.0, 3.0]) vb = Vector(range(1, 4)) va == vb vc = Vector([1, 2]) from vector2d_v3 import Vector2d v2d = Vector2d(1, 2) vc == v2d t3 = (1, 2, 3) va == t3 va != vb vc != v2d va != (1, 2, 3) ``` # Augmented Assignment Operators ``` v1 = Vector([1, 2, 3]) v1_alias = v1 id(v1) v1 += Vector([4, 5, 6]) v1 id(v1) v1_alias v1 *= 11 v1 id(v1) import abc class Tombola(abc.ABC): @abc.abstractmethod def load(self, iterable): """Add items from an iterable""" @abc.abstractmethod def pick(self): """Remove item at random, returning it This method should raise 'LookupError' when the instance is empty. """ def loaded(self): """Return 'True' if there's at least 1 item, 'False' otherwise.""" return bool(self.inspect()) def inspect(self): """Return a sorted tuple with the items currently inside.""" items = [] while True: try: items.append(self.pick()) except LookupError: break self.load(items) return tuple(sorted(items)) import random class BingoCage(Tombola): def __init__(self, items): self._randomizer = random.SystemRandom() self._items = [] self.load(items) def load(self, items): self._items.extend(items) self._randomizer.shuffle(self._items) def pick(self): try: return self._items.pop() except IndexError: raise LookupError('pick from empty BingoCage') def __call__(self): self.pick() import itertools class AddableBingoCage(BingoCage): def __add__(self, other): if isinstance(other, Tombola): return AddableBingoCage(self.inspect() + other.inspect()) else: return NotImplemented def __iadd__(self, other): if isinstance(other, Tombola): other_iterable = other.inspect() else: try: other_iterable = iter(other) except TypeError: self_cls = type(self).__name__ msg = "right operand in += must be {!r} or an iterable" raise TypeError(msg.format(self_cls)) self.load(other_iterable) return self vowels = 'AEIOU' globe = AddableBingoCage(vowels) globe.inspect() globe.pick() in vowels len(globe.inspect()) globe2 = AddableBingoCage('XYZ') globe3 = globe + globe2 len(globe3.inspect()) void = globe + [10, 20] globe_orig = globe len(globe.inspect()) globe += globe2 len(globe.inspect()) globe += ['M','N'] len(globe.inspect()) globe is globe_orig globe += 1 ```
github_jupyter
> Texto fornecido sob a Creative Commons Attribution license, CC-BY. Todo o código está disponível sob a FSF-approved BSD-3 license.<br> > (c) Original por Lorena A. Barba, Gilbert F. Forsyth em 2017, traduzido por Felipe N. Schuch em 2020.<br> > [@LorenaABarba](https://twitter.com/LorenaABarba) - [@fschuch](https://twitter.com/fschuch) 12 passos para Navier-Stokes ====== *** Esse notebook continua a apresentação dos **12 passos para Navier-Stokes**, um módulo prático aplicado como um curso interativo de Dinâmica dos Fluidos Computacional (CFD, do Inglês *Computational Fluid Dynamics*), por [Prof. Lorena Barba](http://lorenabarba.com). Adaptado e traduzido para português por [Felipe N. Schuch](https://fschuch.github.io/). Você deve completar o [Passo 1](./01_Passo_1.ipynb) antes de continuar, tendo escrito seu próprio script Python ou notebook, e tendo experimentado variar os parâmetros de discretização e observado o que aconteceu. Passo 2: Convecção não Linear ----- *** Aqui iremos implementar a equação de convecção não linear, com os mesmos métodos empregados no passo anterior. A equação convectiva unidimensional é escrita como: $$\frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = 0$$ Perceba que em vez de uma constante $c$ multiplicando o segundo termo, ele é agora multiplicado pela própria solução $u$. Portanto, o segundo termo da equação é agora denominado *não linear*. Vamos usar a mesma discretização do Passo 1: diferença para frente para a derivada temporal e diferença para trás para a derivada espacial. A equação discretizada é dado por: $$\frac{u_i^{n+1}-u_i^n}{\Delta t} + u_i^n \frac{u_i^n-u_{i-1}^n}{\Delta x} = 0$$ Isolando o termo com a única incógnita, $u_i^{n+1}$, temos: $$u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n)$$ Como antes, o código Python começa ao importar as bibliotecas necessárias. Então, declaramos alguns parâmetros que determinam a discretização no espaço e no tempo (você deve experimentar alterar esses valores e ver o que acontece). Finalmente, definimos a condição inicial (CI) ao inicializar o arranjo para a solução usando $u_0 = 2$ onde $ 0,5 \leq x \leq 1 $, senão $u = 1$, no intervalo $0 \le x \le 2$ (i.e., função chapéu). ``` import numpy #Aqui carregamos numpy from matplotlib import pyplot #Aqui carregamos matplotlib %matplotlib inline x = numpy.linspace(0., 2., num = 41) nt = 20 #Número de passos de tempo que queremos calcular dt = .025 #Tamanho de cada passo de tempo nx = x.size dx = x[1] - x[0] u = numpy.ones_like(x) #Como antes, iniciamos o u com todos os valores 1 u[(0.5<=x) & (x<=1)] = 2 #Então definimos u = 2 entre 0,5 e 1, nossa CI un = numpy.ones_like(u) #Inicializar o arranjo temporário, para manter a solução no passo de tempo ``` O código no bloco abaixo está *incompleto*. Nós apenas copiamos as linhas do [Passo 1](./01_Passo_1.ipynb), que executavam o avanço temporal. Será que você pode editar o código para que dessa vez execute a convecção não linear? ``` for n in range(nt): #Laço temporal un = u.copy() ##Cópia dos valores de u para un for i in range(1, nx): ##Laço espacial ###A linha abaixo foi copiada do Passo 1. Edite ela de acordo com a nova equação. ###Então descomente e execute a célula para calcular o resultado do Passo 2. ###u[i] = un[i] - c * dt / dx * (un[i] - un[i-1]) pyplot.plot(x, u) ##Plot the results ``` Quais diferenças você observou para a evolução da função chapéu em comparação com o caso linear? O que acontece se você modificar os parâmetros numéricos e executar o código novamente? Após refletir sobre essas questões, você pode prosseguir para o arquivo complementar [Convergência e condição CFL](./03_Condicao_CFL.ipynb), ou ir direto para o [Passo 3](./04_Passo_3.ipynb). Material Complementar ----- *** Para uma explicação passo à passo sobre a discretização da equaçaõ de convecção linear com diferenças finitas (e também os passos seguintes, até o Passo 4), assista **Video Lesson 4** por Prof. Barba no YouTube. ``` from IPython.display import YouTubeVideo YouTubeVideo('y2WaK7_iMRI') from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling() ``` > A célula acima executa o estilo para esse notebook. Nós modificamos o estilo encontrado no GitHub de [CamDavidsonPilon](https://github.com/CamDavidsonPilon), [@Cmrn_DP](https://twitter.com/cmrn_dp).
github_jupyter
### Deliverable 1: Preprocessing the Data for a Neural Network ``` # Import our dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler,OneHotEncoder import pandas as pd import tensorflow as tf # Import and read the charity_data.csv. import pandas as pd application_df = pd.read_csv("C:/Users/hzlip/Documents/VU_DataAnalytics/Mod_19_Neural_Networks_Machine_Learning/Neural_Network_Charity_Analysis/Resources/charity_data.csv") application_df.head() # Drop the non-beneficial ID columns, 'EIN' and 'NAME'. application_df = application_df.drop(["EIN", "NAME"], axis=1) application_df.head() # Determine the number of unique values in each column. counts = application_df.nunique() counts # Look at APPLICATION_TYPE value counts for binning app_type_value_counts = application_df.APPLICATION_TYPE.value_counts() app_type_value_counts # Visualize the value counts of APPLICATION_TYPE app_type_value_counts.plot.density() # Determine which values to replace if counts are less than ...? replace_application = list(app_type_value_counts[app_type_value_counts < 500].index) # Replace in dataframe for app in replace_application: application_df.APPLICATION_TYPE = application_df.APPLICATION_TYPE.replace(app,"Other") # Check to make sure binning was successful application_df.APPLICATION_TYPE.value_counts() # Look at CLASSIFICATION value counts for binning classification_value_counts = application_df.CLASSIFICATION.value_counts() classification_value_counts # Visualize the value counts of CLASSIFICATION classification_value_counts.plot.density() # Determine which values to replace if counts are less than ..? replace_class = list(classification_value_counts[classification_value_counts < 1800].index) # Replace in dataframe for cls in replace_class: application_df.CLASSIFICATION = application_df.CLASSIFICATION.replace(cls,"Other") # Check to make sure binning was successful application_df.CLASSIFICATION.value_counts() # Generate our categorical variable lists application_cat = application_df.dtypes[application_df.dtypes == "object"].index.tolist() application_cat # Create a OneHotEncoder instance enc = OneHotEncoder(sparse=False) # Fit and transform the OneHotEncoder using the categorical variable list encode_df = pd.DataFrame(enc.fit_transform(application_df[application_cat])) # Add the encoded variable names to the dataframe encode_df.columns = enc.get_feature_names(application_cat) encode_df.head() # Merge one-hot encoded features and drop the originals # Merge one-hot encoded features and drop the originals application_df = application_df.merge(encode_df,left_index=True, right_index=True) application_df = application_df.drop(application_cat,1) application_df.head() # Split our preprocessed data into our features and target arrays y = application_df["IS_SUCCESSFUL"].values X = application_df.drop(["IS_SUCCESSFUL"],1).values # Split the preprocessed data into a training and testing dataset X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) # Create a StandardScaler instances scaler = StandardScaler() # Fit the StandardScaler X_scaler = scaler.fit(X_train) # Scale the data X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) ``` ### Deliverable 2: Compile, Train and Evaluate the Model ``` # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer. number_input_features = len(X_train[0]) hidden_nodes_layer1 = 180 hidden_nodes_layer2 = 90 hidden_nodes_layer3 = 60 nn = tf.keras.models.Sequential() # First hidden layer nn.add(tf.keras.layers.Dense(units=hidden_nodes_layer1, input_dim=number_input_features, activation="relu")) # Second hidden layer nn.add(tf.keras.layers.Dense(units=hidden_nodes_layer2, activation="relu")) # Third hidden layer nn.add(tf.keras.layers.Dense(units=hidden_nodes_layer3, activation="relu")) # Output layer nn.add(tf.keras.layers.Dense(units=1, activation="sigmoid")) # Check the structure of the model nn.summary() # Compile the model nn.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) # Import checkpoint dependencies import os from tensorflow.keras.callbacks import ModelCheckpoint # Define the checkpoint path and filenames os.makedirs("checkpoints/",exist_ok=True) checkpoint_path = "checkpoints/weights.{epoch:02d}.hdf5" # Create a callback that saves the model's weights every 5 epochs cp_callback = ModelCheckpoint( filepath=checkpoint_path, verbose=1, save_weights_only=True, save_freq="epoch", period=5) # Train the model fit_model = nn.fit(X_train_scaled,y_train,epochs=100,callbacks=[cp_callback]) # Evaluate the model using the test data model_loss, model_accuracy = nn.evaluate(X_test_scaled,y_test,verbose=2) print(f"Loss: {model_loss}, Accuracy: {model_accuracy}") # Export our model to HDF5 file nn.save("AlphabetSoupCharity_Optimization2.h5") ```
github_jupyter
# Factor Risk Exposure By Evgenia "Jenny" Nitishinskaya, Delaney Granizo-Mackenzie, and Maxwell Margenot. Part of the Quantopian Lecture Series: * [www.quantopian.com/lectures](https://www.quantopian.com/lectures) * [github.com/quantopian/research_public](https://github.com/quantopian/research_public) --- ##DISCLAIMER: As always, this analysis is based on historical data, and risk exposures estimated on historical data may or may not affect the exposures going forward. As such, computing the risk exposure of to a factor is not enough. You must put confidence bounds on that risk exposure, and determine whether the risk exposure can even be modeled reasonably. For more information on this, please see our other lectures, especially Instability of Parameter Estimates. ##Using Factor Models to Determine Risk Exposure We can use factor models to analyze the sources of risks and returns in portfolios. Recall that a factor model expresses the returns as $$R_i = a_i + b_{i1} F_1 + b_{i2} F_2 + \ldots + b_{iK} F_K + \epsilon_i$$ By modelling the historical returns, we can see how much of them is due to speculation on different factors and how much to asset-specific fluctuations ($\epsilon_p$). We can also examine what sources of risk the portfolio is exposed to. In risk analysis, we often model active returns (returns relative to a benchmark) and active risk (standard deviation of active returns, also known as tracking error or tracking risk). For instance, we can find a factor's marginal contribution to active risk squared (FMCAR). For factor $j$, this is $$ \text{FMCAR}_j = \frac{b_j^a \sum_{i=1}^K b_i^a Cov(F_j, F_i)}{(\text{Active risk})^2} $$ where $b_i^a$ is the portfolio's active exposure to factor $i$. This tells us how much risk we incur by being exposed to factor $j$, given all the other factors we're already exposed to. Fundamental factor models are often used to evaluate portfolios because they correspond directly to investment choices (e.g. whether we invest in small-cap or large-cap stocks, etc.). Below, we construct a model to evaluate a single asset; for more information on the model construction, check out the fundamental factor models notebook. We'll use the canonical Fama-French factors for this example, which are the returns of portfolios constructred based on fundamental factors. ##How many factors do you want? In the Arbitrage Pricing Theory lecture we mention that for predictive models you want fewer parameters. However, this doesn't quite hold for risk exposure. Instead of trying to not overfit a predictive model, you are looking for any possible risk factor that could be influencing your returns. Therefore it's actually safer to estimate exposure to many many risk factors to see if any stick. Anything left over in our $\alpha$ is risk exposure that is currently unexplained by the selected factors. You want your strategy's return stream to be all alpha, and to be unexplained by as many parameters as possible. If you can show that your historical returns have little to no dependence on many factors, this is very positive. Certainly some unrelated risk factors might have spurious relationships over time in a large dataset, but those are not likely to be consistent. ## Setup The first thing we do is compute a year's worth of factor returns. ### NOTE The process for doing this is described in the Fundamental Factor Models lecture and uses pipeline. For more information please see that lecture. ``` import numpy as np import statsmodels.api as sm import scipy.stats as stats from statsmodels import regression import matplotlib.pyplot as plt import pandas as pd import numpy as np from quantopian.pipeline import Pipeline from quantopian.pipeline.data import Fundamentals from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import CustomFactor, Returns # Here's the raw data we need, everything else is derivative. class MarketCap(CustomFactor): # Here's the data we need for this factor inputs = [Fundamentals.shares_outstanding, USEquityPricing.close] # Only need the most recent values for both series window_length = 1 def compute(self, today, assets, out, shares, close_price): # Shares * price/share = total price = market cap out[:] = shares * close_price class BookToPrice(CustomFactor): # pb = price to book, we'll need to take the reciprocal later inputs = [Fundamentals.pb_ratio] window_length = 1 def compute(self, today, assets, out, pb): out[:] = 1 / pb def make_pipeline(): """ Create and return our pipeline. We break this piece of logic out into its own function to make it easier to test and modify in isolation. In particular, this function can be copy/pasted into research and run by itself. """ pipe = Pipeline() # Add our factors to the pipeline market_cap = MarketCap() # Raw market cap and book to price data gets fed in here pipe.add(market_cap, "market_cap") book_to_price = BookToPrice() pipe.add(book_to_price, "book_to_price") # We also get daily returns returns = Returns(inputs=[USEquityPricing.close], window_length=2) pipe.add(returns, "returns") # We compute a daily rank of both factors, this is used in the next step, # which is computing portfolio membership. market_cap_rank = market_cap.rank() pipe.add(market_cap_rank, 'market_cap_rank') book_to_price_rank = book_to_price.rank() pipe.add(book_to_price_rank, 'book_to_price_rank') # Build Filters representing the top and bottom 1000 stocks by our combined ranking system. biggest = market_cap_rank.top(1000) smallest = market_cap_rank.bottom(1000) highpb = book_to_price_rank.top(1000) lowpb = book_to_price_rank.bottom(1000) # Don't return anything not in this set, as we don't need it. pipe.set_screen(biggest | smallest | highpb | lowpb) # Add the boolean flags we computed to the output data pipe.add(biggest, 'biggest') pipe.add(smallest, 'smallest') pipe.add(highpb, 'highpb') pipe.add(lowpb, 'lowpb') return pipe pipe = make_pipeline() start_date = '2014-1-1' end_date = '2015-1-1' from quantopian.research import run_pipeline results = run_pipeline(pipe, start_date, end_date) R_biggest = results[results.biggest]['returns'].groupby(level=0).mean() R_smallest = results[results.smallest]['returns'].groupby(level=0).mean() R_highpb = results[results.highpb]['returns'].groupby(level=0).mean() R_lowpb = results[results.lowpb]['returns'].groupby(level=0).mean() SMB = R_smallest - R_biggest HML = R_highpb - R_lowpb ``` How did each factor do over 2014? ``` SMB_CUM = np.cumprod(SMB+1) HML_CUM = np.cumprod(HML+1) plt.plot(SMB_CUM.index, SMB_CUM.values) plt.plot(HML_CUM.index, HML_CUM.values) plt.ylabel('Cumulative Return') plt.legend(['SMB Portfolio Returns', 'HML Portfolio Returns']); ``` ## Computing Risk Exposure Now we can determine how exposed another return stream is to each of these factors. We can do this by running static or rolling linear regressions between our return stream and the factor portfolio returns. First we'll compute the active returns (returns - benchmark) of some random asset and then model that asset as a linear combination of our two factors. The more a factor contributes to the active returns, the more exposed the active returns are to that factor. ``` # Get returns data for our portfolio portfolio = get_pricing(['MSFT', 'AAPL', 'YHOO', 'FB', 'TSLA'], fields='price', start_date=start_date, end_date=end_date).pct_change()[1:] R = np.mean(portfolio, axis=1) bench = get_pricing('SPY', fields='price', start_date=start_date, end_date=end_date).pct_change()[1:] # The excess returns of our active management, in this case just holding a portfolio of our one asset active = R - bench # Define a constant to compute intercept constant = pd.TimeSeries(np.ones(len(active.index)), index=active.index) df = pd.DataFrame({'R': active, 'F1': SMB, 'F2': HML, 'Constant': constant}) df = df.dropna() # Perform linear regression to get the coefficients in the model b1, b2 = regression.linear_model.OLS(df['R'], df[['F1', 'F2']]).fit().params # Print the coefficients from the linear regression print 'Sensitivities of active returns to factors:\nSMB: %f\nHML: %f' % (b1, b2) ``` Using the formula from the start of the notebook, we can compute the factors' marginal contributions to active risk squared: ``` F1 = df['F1'] F2 = df['F2'] cov = np.cov(F1, F2) ar_squared = (active.std())**2 fmcar1 = (b1*(b2*cov[0,1] + b1*cov[0,0]))/ar_squared fmcar2 = (b2*(b1*cov[0,1] + b2*cov[1,1]))/ar_squared print 'SMB Risk Contribution:', fmcar1 print 'HML Risk Contribution:', fmcar2 ``` The rest of the risk can be attributed to active specific risk, i.e. factors that we did not take into account or the asset's idiosyncratic risk. However, as usual we will look at how the exposure to these factors changes over time. As we lose a tremendous amount of information by just looking at one data point. Let's look at what happens if we run a rolling regression over time. ``` # Compute the rolling betas model = pd.stats.ols.MovingOLS(y = df['R'], x=df[['F1', 'F2']], window_type='rolling', window=100) rolling_parameter_estimates = model.beta rolling_parameter_estimates.plot(); plt.title('Computed Betas'); plt.legend(['F1 Beta', 'F2 Beta', 'Intercept']); ``` Now we'll look at FMCAR as it changes over time. ``` # Remove the first 99, which are all NaN for each case # Compute covariances covariances = pd.rolling_cov(df[['F1', 'F2']], window=100)[99:] # Compute active risk squared active_risk_squared = pd.rolling_std(active, window = 100)[99:]**2 # Compute betas betas = rolling_parameter_estimates[['F1', 'F2']] # Set up empty dataframe FMCAR = pd.DataFrame(index=betas.index, columns=betas.columns) # For each factor for factor in betas.columns: # For each bar in our data for t in betas.index: # Compute the sum of the betas and covariances s = np.sum(betas.loc[t] * covariances[t][factor]) # Get the beta b = betas.loc[t][factor] # Get active risk squared AR = active_risk_squared.loc[t] # Put them all together to estimate FMCAR on that date FMCAR[factor][t] = b * s / AR ``` Let's plot this. ``` plt.plot(FMCAR['F1'].index, FMCAR['F1'].values) plt.plot(FMCAR['F2'].index, FMCAR['F2'].values) plt.ylabel('Marginal Contribution to Active Risk Squared') plt.legend(['F1 FMCAR', 'F2 FMCAR']); ``` ###Problems with using this data Whereas it may be interesting to know how a portfolio was exposed to certain factors historically, it is really only useful if we can make predictions about how it will be exposed to risk factors in the future. It's not always a safe assumption to say that future exposure will be the current exposure. As you saw the exposure varies quite a bit, so taking the average is dangerous. We could put confidence intervals around that average, but that would only work if the distribution of exposures were normal or well behaved. Let's check using our old buddy, the Jarque-Bera test. ``` from statsmodels.stats.stattools import jarque_bera _, pvalue1, _, _ = jarque_bera(FMCAR['F1'].dropna().values) _, pvalue2, _, _ = jarque_bera(FMCAR['F2'].dropna().values) print 'p-value F1_FMCAR is normally distributed', pvalue1 print 'p-value F2_FMCAR is normally distributed', pvalue2 ``` The p-values are below our default cutoff of 0.05. We can't even put good confidence intervals on the risk exposure of the asset without extra effort, so making any statement about exposure in the future is very difficult right now. Any hedge we took out to cancel the exposure to one of the factors might be way over or under hedged. We are trying to predict future exposure, and predicting the future is incredibly difficult. One must be very careful with statistical methods to ensure that false predictions are not made. # Factor and tracking portfolios We can use factor and tracking portfolios to tweak a portfolio's sensitivities to different sources of risk. A <i>factor portfolio</i> has a sensitivity of 1 to a particular factor and 0 to all other factors. In other words, it represents the risk of that one factor. We can add a factor portfolio to a larger portfolio to adjust its exposure to that factor. A similar concept is a <i>tracking portfolio</i>, which is constructed to have the same factor sensitivities as a benchmark or other portfolio. Like a factor portfolio, this allows us to either speculate on or hedge out the risks associated with that benchmark or portfolio. For instance, we regularly hedge out the market, because we care about how our portfolio performs relative to the market, and we don't want to be subject to the market's fluctuations. To construct a factor or tracking portfolio, we need the factor sensitivities of what we want to track. We already know what these are in the former case, but we need to compute them in the latter using usual factor model methods. Then, we pick some $K+1$ assets (where $K$ is the number of factors we're considering) and solve for the weights of the assets in the portfolio. ##Portfolio Exposure The portfolio exposure can be computed directly from the return stream, or as the weighted average of all the assets held. ## Example Say we have two factors $F_1$ and $F_2$, and a benchmark with sensitivities of 1 and 1.1 to the factors, respectively. We identify 3 securities $x_1, x_2, x_3$ that we would like to use in composing a portfolio that tracks the benchmark, whose sensitivities are $b_{11} = 0.7$, $b_{12} = 1.1$, $b_{21} = 0.1$, $b_{22} = 0.5$, $b_{31} = 1.5$, $b_{32} = 1.3$. We would like to compute weights $w_1$, $w_2$, $w_3$ so that our tracking portfolio is $$ P = w_1 x_1 + w_2 x_2 + w_3 x_3 $$ We want our portfolio sensitivities to match the benchmark: $$ w_1 b_{11} + w_2 b_{21} + w_3 b_{31} = 1 $$ $$ w_1 b_{12} + w_2 b_{22} + w_3 b_{32} = 1.1 $$ Also, the weights need to sum to 1: $$ w_1 + w_2 + w_3 = 1 $$ Solving this system of 3 linear equations, we find that $w_1 = 1/3$, $w_2 = 1/6$, and $w_3 = 1/2$. Putting the securities together into a portfolio using these weights, we obtain a portfolio with the same risk profile as the benchmark. ##How to Use Risk Exposure Models Once we know our risk exposures, we can do a few things. We can not enter into positions that have high exposures to certain factors, or we can hedge our positions to try to neutralize the exposure. ###Risk Management Often times funds will have a layer of protection over their traders/algorithms. This layer of protection takes in the trades that the fund wants to make, then computes the exposure of the new portfolio, and checks to make sure they're within pre-defined ranges. If they are not, it does not place the trade and files a warning. ###Hedging Another method of dealing with exposure is to take out hedges. You can determine, for example, your exposure to each sector of the market. You can then take out a hedge if a particular sector seems to affect your returns too much. For more information on hedging, please see our Beta Hedging lecture. Good algorithms will have built-in hedging logic that ensures they are never over-exposed. *This presentation is for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation for any security; nor does it constitute an offer to provide investment advisory or other services by Quantopian, Inc. ("Quantopian"). Nothing contained herein constitutes investment advice or offers any opinion with respect to the suitability of any security, and any views expressed herein should not be taken as advice to buy, sell, or hold any security or as an endorsement of any security or company. In preparing the information contained herein, Quantopian, Inc. has not taken into account the investment needs, objectives, and financial circumstances of any particular investor. Any views expressed and data illustrated herein were prepared based upon information, believed to be reliable, available to Quantopian, Inc. at the time of publication. Quantopian makes no guarantees as to their accuracy or completeness. All information is subject to change and may quickly become unreliable for various reasons, including changes in market conditions or economic circumstances.*
github_jupyter
## Dependencies ``` import json, glob from tweet_utility_scripts import * from tweet_utility_preprocess_roberta_scripts_aux import * from transformers import TFRobertaModel, RobertaConfig from tokenizers import ByteLevelBPETokenizer from tensorflow.keras import layers from tensorflow.keras.models import Model ``` # Load data ``` test = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv') print('Test samples: %s' % len(test)) display(test.head()) ``` # Model parameters ``` input_base_path = '/kaggle/input/290-tweet-train-10fold-roberta-96-onecycle-lr/' with open(input_base_path + 'config.json') as json_file: config = json.load(json_file) config vocab_path = input_base_path + 'vocab.json' merges_path = input_base_path + 'merges.txt' base_path = '/kaggle/input/qa-transformers/roberta/' # vocab_path = base_path + 'roberta-base-vocab.json' # merges_path = base_path + 'roberta-base-merges.txt' config['base_model_path'] = base_path + 'roberta-base-tf_model.h5' config['config_path'] = base_path + 'roberta-base-config.json' model_path_list = glob.glob(input_base_path + '*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep='\n') ``` # Tokenizer ``` tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path, lowercase=True, add_prefix_space=True) ``` # Pre process ``` test['text'].fillna('', inplace=True) test['text'] = test['text'].apply(lambda x: x.lower()) test['text'] = test['text'].apply(lambda x: x.strip()) x_test, x_test_aux, x_test_aux_2 = get_data_test(test, tokenizer, config['MAX_LEN'], preprocess_fn=preprocess_roberta_test) ``` # Model ``` module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False) def model_fn(MAX_LEN): input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids') attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask') base_model = TFRobertaModel.from_pretrained(config['base_model_path'], config=module_config, name='base_model') last_hidden_state, _ = base_model({'input_ids': input_ids, 'attention_mask': attention_mask}) logits = layers.Dense(2, use_bias=False, name='qa_outputs')(last_hidden_state) start_logits, end_logits = tf.split(logits, 2, axis=-1) start_logits = tf.squeeze(start_logits, axis=-1) end_logits = tf.squeeze(end_logits, axis=-1) model = Model(inputs=[input_ids, attention_mask], outputs=[start_logits, end_logits]) return model ``` # Make predictions ``` NUM_TEST_IMAGES = len(test) test_start_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN'])) test_end_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN'])) for model_path in model_path_list: print(model_path) model = model_fn(config['MAX_LEN']) model.load_weights(model_path) test_preds = model.predict(get_test_dataset(x_test, config['BATCH_SIZE'])) test_start_preds += test_preds[0] test_end_preds += test_preds[1] ``` # Post process ``` test['start'] = test_start_preds.argmax(axis=-1) test['end'] = test_end_preds.argmax(axis=-1) test['selected_text'] = test.apply(lambda x: decode(x['start'], x['end'], x['text'], config['question_size'], tokenizer), axis=1) # Post-process test["selected_text"] = test.apply(lambda x: ' '.join([word for word in x['selected_text'].split() if word in x['text'].split()]), axis=1) test['selected_text'] = test.apply(lambda x: x['text'] if (x['selected_text'] == '') else x['selected_text'], axis=1) test['selected_text'].fillna(test['text'], inplace=True) ``` # Visualize predictions ``` test['text_len'] = test['text'].apply(lambda x : len(x)) test['label_len'] = test['selected_text'].apply(lambda x : len(x)) test['text_wordCnt'] = test['text'].apply(lambda x : len(x.split(' '))) test['label_wordCnt'] = test['selected_text'].apply(lambda x : len(x.split(' '))) test['text_tokenCnt'] = test['text'].apply(lambda x : len(tokenizer.encode(x).ids)) test['label_tokenCnt'] = test['selected_text'].apply(lambda x : len(tokenizer.encode(x).ids)) test['jaccard'] = test.apply(lambda x: jaccard(x['text'], x['selected_text']), axis=1) display(test.head(10)) display(test.describe()) ``` # Test set predictions ``` submission = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/sample_submission.csv') submission['selected_text'] = test['selected_text'] submission.to_csv('submission.csv', index=False) submission.head(10) ```
github_jupyter
# sell-short-in-may-and-go-away see: https://en.wikipedia.org/wiki/Sell_in_May The reason for this example is to demonstrate short selling (algo), and short selling using adjust_percent function (algo2). algo - Sell short in May and go away, buy to cover in Nov algo2 - first trading day of the month, adjust position to 50% (Select the one you want to call in the Strategy.run() function ``` import datetime import matplotlib.pyplot as plt import pandas as pd from talib.abstract import * import pinkfish as pf # Format price data pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inline %matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure %matplotlib inline: only draw static images in the notebook ''' plt.rcParams["figure.figsize"] = (10, 7) pf.DEBUG = False ``` Some global data ``` #symbol = '^GSPC' symbol = 'SPY' capital = 10000 start = datetime.datetime(2015, 10, 30) #start = datetime.datetime(*pf.SP500_BEGIN) end = datetime.datetime.now() ``` Define Strategy Class ``` class Strategy: def __init__(self, symbol, capital, start, end): self.symbol = symbol self.capital = capital self.start = start self.end = end self.ts = None self.tlog = None self.dbal = None self.stats = None def _algo(self): pf.TradeLog.cash = self.capital for i, row in enumerate(self.ts.itertuples()): date = row.Index.to_pydatetime() high = row.high; low = row.low; close = row.close; end_flag = pf.is_last_row(self.ts, i) shares = 0 # Buy to cover (at the open on first trading day in Nov) if self.tlog.shares > 0: if (row.month == 11 and row.first_dotm) or end_flag: shares = self.tlog.buy2cover(date, row.open) # Sell short (at the open on first trading day in May) else: if row.month == 5 and row.first_dotm: shares = self.tlog.sell_short(date, row.open) if shares > 0: pf.DBG("{0} SELL SHORT {1} {2} @ {3:.2f}".format( date, shares, self.symbol, row.open)) elif shares < 0: pf.DBG("{0} BUY TO COVER {1} {2} @ {3:.2f}".format( date, -shares, self.symbol, row.open)) # Record daily balance self.dbal.append(date, high, low, close) def _algo2(self): pf.TradeLog.cash = self.capital for i, row in enumerate(self.ts.itertuples()): date = row.Index.to_pydatetime() high = row.high; low = row.low; close = row.close; end_flag = pf.is_last_row(self.ts, i) shares = 0 # On the first day of the month, adjust short position to 50% if (row.first_dotm or end_flag): weight = 0 if end_flag else 0.5 self.tlog.adjust_percent(date, close, weight, pf.Direction.SHORT) # Record daily balance self.dbal.append(date, high, low, close) def run(self): self.ts = pf.fetch_timeseries(self.symbol) self.ts = pf.select_tradeperiod(self.ts, self.start, self.end, use_adj=True) # add calendar columns self.ts = pf.calendar(self.ts) self.tlog = pf.TradeLog(self.symbol) self.dbal = pf.DailyBal() self.ts, self.start = pf.finalize_timeseries(self.ts, self.start) # Pick either algo or algo2 self._algo() #self._algo2() self._get_logs() self._get_stats() def _get_logs(self): self.rlog = self.tlog.get_log_raw() self.tlog = self.tlog.get_log() self.dbal = self.dbal.get_log(self.tlog) def _get_stats(self): self.stats = pf.stats(self.ts, self.tlog, self.dbal, self.capital) ``` Run Strategy ``` s = Strategy(symbol, capital, start, end) s.run() s.rlog.head() s.tlog.head() s.dbal.tail() ``` Run Benchmark, Retrieve benchmark logs, and Generate benchmark stats ``` benchmark = pf.Benchmark(symbol, s.capital, s.start, s.end) benchmark.run() ``` Plot Equity Curves: Strategy vs Benchmark ``` pf.plot_equity_curve(s.dbal, benchmark=benchmark.dbal) ``` Plot Trades ``` pf.plot_trades(s.dbal, benchmark=benchmark.dbal) ``` Bar Graph: Strategy vs Benchmark ``` df = pf.plot_bar_graph(s.stats, benchmark.stats) df ```
github_jupyter
``` from awesome_panel_extensions.awesome_panel.notebook import Header Header(folder="examples/reference/frameworks/fast", notebook="FastTextInput.ipynb") ``` # Fast TextInput - Reference Guide The `FastTextInput` widget is based on the [fast-text-field](https://explore.fast.design/components/fast-text-field) web component and extends the built in [Panel TextInput](https://panel.holoviz.org/reference/widgets/TextInput.html). <table> <tr> <td><img src="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel-extensions/master/assets/images/frameworks/fast/fast-text-input.png"></td> </tr> </table> #### Parameters: ##### Core * **``value``** (str): A string value. ###### Display * **``name``** (str): The label of the TextInput. * **``disabled``** (boolean): Whether or not the TextInput is disabled. Default is False. * **``placeholder``** (string): A placeholder string displayed when no value is entered. ###### Fast * **``apperance``** (string): Determines the appearance of the textinput. One of `outline` or `filled`. Defaults to `outline`. * **``autofocus``** (bool): The autofocus attribute. Defaults to `False`. * **``type_of_text``** (bool): The type of text input. One of `email`, `password`, `tel`, `text`, `url`. Defaults to `text`. * **``readonly``** (bool): Whether or not the TextInput is read only. Defaults to `False`. The `FastTextInput` has the same layout and styling parameters as most other widgets. For example `width` and `sizing_mode`. Please note that you can only use the Fast components inside a custom Panel template that - Loads the [Fast `javascript` library](https://www.fast.design/docs/components/getting-started#from-cdn). - Wraps the content of the `<body>` html tag inside the [fast-design-system-provider](https://www.fast.design/docs/components/getting-started#add-components) tag. We provide the `FastTemplate` for easy usage. You can also develop your own custom [Panel template](https://panel.holoviz.org/user_guide/Templates.html) if you need something special. For example combining it with more [fast.design](https://fast.design/) web components and the [Fluent Design System](https://www.microsoft.com/design/fluent/#/) to create **VS Code** and **Microsoft Office** like experiences. Please note that Fast components will not work in older, legacy browser like Internet Explorer. ___ Let's start by importing the dependencies ``` import param import panel as pn from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput pn.config.sizing_mode = "stretch_width" pn.extension() ``` ## Parameters Let's explore the parameters of the `FastTextInput`. ``` textinput = FastTextInput(name="The label", sizing_mode="fixed", width=300, appearance="outline", placeholder="write something") textinput_parameters = ["name", "value", "disabled", "placeholder", "appearance", "autofocus", "type_of_text", "readonly", "height", "width", "sizing_mode"] app=pn.Row( textinput ) template=FastTemplate(main=[app]) template settings_pane = pn.WidgetBox(pn.Param(textinput, parameters=textinput_parameters, show_name=False)) settings_pane ``` ## pn.Param Let's verify that that `FastTextInput` can be used as a widget by `pn.Param`. ``` WIDGETS = { "some_text": { "type": FastTextInput, "sizing_mode": "fixed", "width": 400, "placeholder": "write some text!" } } class ParameterizedApp(param.Parameterized): some_text = param.String(default="This is some text", label="This is a label") view = param.Parameter() def __init__(self, **params): super().__init__(**params) self.view = pn.Param(self, parameters=["some_text"], widgets=WIDGETS) parameterized_app = ParameterizedApp() paremeterized_template = FastTemplate(main=[parameterized_app.view]) paremeterized_template pn.Param(parameterized_app.param.some_text) ``` ## Resources - [fast.design](https://fast.design/) - [fast-text-field](https://explore.fast.design/components/fast-text-field) ## Known Issues - The `fast-text-field` web component has additional attributes (`max_length`, `min_length`, `pattern`, `size`, `spellcheck`, `required`) that does not seem to work. If you think they are important please upvote [Fast Github Issue 3852](https://github.com/microsoft/fast/issues/3852). <table> <tr> <td><img src="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel-extensions/master/assets/images/frameworks/fast/fast-panel-logo.png"></td> </tr> </table>
github_jupyter
``` # !pip install efficientnet-pytorch sklearn import argparse import os import random import time from collections import OrderedDict import numpy as np import torch import torchvision from PIL import Image from torch import nn from torch import optim from torch.utils.data import DataLoader from torch.utils.data.sampler import WeightedRandomSampler from torchvision import transforms import models from dataset_generator import DatasetGenerator mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] # this is an enhancement to first resize to larger image and then crop image_resize = 256 image_size = 224 class_to_idx = { 'normal': 0, 'pneumonia': 1, 'COVID-19': 2 } print(torch.__version__) print(torchvision.__version__) SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True image_dir = 'data' # we will use train/test split only to get more COVID-19 data train_csv_file = 'train_split.txt' test_csv_file = 'test_split.txt' train_transforms = transforms.Compose([ transforms.RandomOrder([ transforms.ColorJitter(hue=.05, saturation=.05), transforms.RandomHorizontalFlip(), transforms.RandomRotation(15, resample=Image.BILINEAR), transforms.RandomResizedCrop(image_size, scale=(0.9, 1.0)), ]), transforms.ToTensor(), transforms.Normalize(mean=mean, std=std) ]) test_transforms = transforms.Compose([ transforms.Resize(image_resize), transforms.CenterCrop(image_size), transforms.ToTensor(), transforms.Normalize(mean=mean, std=std) ]) train_dir = os.path.join(image_dir, 'train') train_dataset = DatasetGenerator(train_csv_file, train_dir, transform=train_transforms) image, label = next(iter(train_dataset)) test_dir = os.path.join(image_dir, 'test') test_dataset = DatasetGenerator(test_csv_file, test_dir, transform=test_transforms) image, label = next(iter(test_dataset)) def load_pretrained_model(arch): model_func = getattr(models, arch) model = model_func() model.arch = arch return model # convert labels to tensor def labels_to_tensor(labels): label_indices = [class_to_idx[label] for label in labels] label_indices = np.array(label_indices, int) label_indices = torch.LongTensor(label_indices) return label_indices labels_to_tensor(['normal', 'pneumonia', 'COVID-19']) def validate(model, valid_dataloader, loss_func, device): #track accuracy and loss accuracy = 0 test_loss = 0 with torch.no_grad(): #deactivates requires_grad flag, disables tracking of gradients for images, labels in valid_dataloader: #iterate over images and labels in valid dataset labels = labels_to_tensor(labels) images, labels = images.to(device), labels.to(device) #move a tensor to a device log_ps = model.forward(images) #log form of probabilities for each label test_loss += loss_func(log_ps, labels).item() #.item() returns loss value as float, compare prob to actual ps = torch.exp(log_ps) #gets rid of log equality = (labels.data == ps.max(dim=1)[1]) #takes highest probability accuracy += torch.mean(equality.type(torch.FloatTensor)) return test_loss, accuracy # Do validation on the test set def test_model(model, test_loader, device): #track accuracy, move to device, switch on eval mode accuracy = 0 model.to(device) model.eval() with torch.no_grad(): for images, labels in iter(test_loader): labels = labels_to_tensor(labels) images, labels = images.to(device), labels.to(device) #move a tensor to a device log_ps = model.forward(images) ps = torch.exp(log_ps) equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() model_accuracy = accuracy/len(test_loader) model.accuracy = model_accuracy return model.accuracy # Save the checkpoint def save_checkpoint(checkpoint_path, model): checkpoint = { # Save the model arch, accuracy, class_to_idx 'arch':model.arch, 'accuracy':model.accuracy, 'class_to_idx':class_to_idx, 'state_dict':model.state_dict() } torch.save(checkpoint, checkpoint_path) print('Saved the trained model: %s' % checkpoint_path) train_label_cnt = [0, 0, 0] train_labels = [] # TBD shuffle the training data # TBD this is best done inside the DatasetGenerator class # train_dataset.csv_df = train_dataset.csv_df.sample(frac=1) for label in train_dataset.csv_df[2]: train_label_cnt[class_to_idx[label]] += 1 train_labels.append(class_to_idx[label]) train_num_samples = sum(train_label_cnt) train_class_weights = [train_num_samples/train_label_cnt[i] for i in range(len(train_label_cnt))] train_weights = [train_class_weights[train_labels[i]] for i in range(int(train_num_samples))] # TBD create WeightedRandomSampler to balance the training data set train_sampler = WeightedRandomSampler(torch.DoubleTensor(train_weights), int(train_num_samples)) #train_dataset.csv_df.head(20) train_class_weights # Using the image datasets and the transforms, define the dataloaders batch_size = 64 train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=16, shuffle=False, sampler=train_sampler) dataloaders = {"train": train_loader, "test": DataLoader(test_dataset, batch_size=batch_size, num_workers=16, shuffle=True)} device = 'cpu' cuda = torch.cuda.is_available() if cuda: device = 'cuda' device available_models = [m for m in dir(models) if 'Net' in m and 'Model' not in m] available_models arch = 'DenseNet169' pretrained_model = load_pretrained_model(arch) # !ls -ltrh ../pretrain def convert_prior_weights(pretrained_model, state_dict, prefix='module.'): old_state_dict = pretrained_model.state_dict() new_state_dict = state_dict if prefix is not None: new_state_dict = OrderedDict() # make sure the keys of the state dict match those of old_state_dict for k in state_dict: short_key = k.replace(prefix, '') # make sure the shape of the weight tensors matches if state_dict[k].shape != old_state_dict[short_key].shape: print('Unmatched key {} in state_dict: {} vs. {}'.format(short_key, state_dict[k].shape, old_state_dict[short_key].shape)) else: new_state_dict[short_key] = state_dict[k] for k in new_state_dict: if k not in old_state_dict: print('Unexpected key %s in new_state_dict' % k) for k in old_state_dict: if k not in new_state_dict: print('Missing key %s in old_state_dict' % k) return new_state_dict ``` ```python # TBD this is to load previously saved checkpoints from pretraining ckp_path = '../pretrain/DenseNet169-17082020-063151.pth.tar' model_checkpoint = torch.load(ckp_path, map_location=torch.device(device)) state_dict = model_checkpoint['state_dict'] # TBD this step is for converting the variable names from pretraining # TBD so it is not necessary when loading saved checkpoints from previous txfer learning new_state_dict = convert_prior_weights(pretrained_model, state_dict) pretrained_model.load_state_dict(new_state_dict, strict=False) ``` ``` optimizer = optim.Adam(pretrained_model.get_optimizer_parameters(), lr=0.00001, betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5) criterion = nn.NLLLoss() def train(model, loss_func, optimizer, dataloaders, device, epochs, checkpoint_prefix, print_every=20): device = torch.device(device) model.to(device) train_loader = dataloaders['train'] test_loader = dataloaders['test'] epoch_start = time.time() max_acc = 0.0 # loop to train for number of epochs for e in range(epochs): running_loss = 0 batch_start = time.time() steps = 0 for images, labels in train_loader: # within each loop, iterate train_loader, and print loss label_indices = labels_to_tensor(labels) images, labels = images.to(device), label_indices.to(device) optimizer.zero_grad() log_ps = model.forward(images) loss = loss_func(log_ps, labels) loss.backward() optimizer.step() running_loss += loss.item() steps += 1 if steps % print_every == 0: model.eval() valid_loss, valid_accuracy = validate(model, test_loader, loss_func, device) model.train() batch_time = time.time() - batch_start print( "Epoch: {}/{}..".format(e + 1, epochs), "Step: {}..".format(steps), "Training Loss: {:.3f}..".format(running_loss / len(train_loader)), "Test Loss: {:.3f}..".format(valid_loss / len(test_loader)), "Test Accuracy: {:.3f}..".format(valid_accuracy / len(test_loader)), "Batch Time: {:.3f}, avg: {:.3f}".format(batch_time, batch_time / steps) ) model.eval() test_accuracy = test_model(model, test_loader, device) model.train() epoch_time = time.time() - epoch_start if test_accuracy > max_acc: max_acc = test_accuracy model.accuracy = test_accuracy save_checkpoint('%s.pth.tar' % checkpoint_prefix, model) print ('Epoch [{}] [save] Accuracy={:.3f} time: {:.3f}, avg: {:.3f}' .format(e + 1, test_accuracy, epoch_time, epoch_time / (e + 1))) else: print ('Epoch [{}] [----] Accuracy={:.3f} time: {:.3f}, avg: {:.3f}' .format(e + 1, test_accuracy, epoch_time, epoch_time / (e + 1))) return model #device = 'cpu' epochs = 2 training_start = time.time() checkpoint_prefix = os.path.join('checkpoints','%s-%d'%(arch, training_start)) trained_model = train(pretrained_model, criterion, optimizer, dataloaders, device, epochs, checkpoint_prefix, print_every=20) print('%.2f seconds taken for model training' % (time.time() - training_start)) test_loader = dataloaders['test'] test_accuracy = test_model(trained_model, test_loader, device) print(test_accuracy) ```
github_jupyter
# Vehicle's Market Price - EDA This is the **E**xploratory **D**ata **A**nalysis for the vehicle's market price dataset. In this analysis, we are going to analyze the different variables of the model in relation to the vehicle's prices for a better understanding of the dataset. Here are the steps of the analysis: ### Step 1 - Packages ``` import pandas as pd import altair as alt import pandas_profiling from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from vega_datasets import data alt.data_transformers.disable_max_rows() ``` ### Step 2 - Data loading For this model we are using a dataset of vehicle prices downloaded from Austin Reese's public repository in [kaggle](https://www.kaggle.com/austinreese/craigslist-carstrucks-data). This dataset contains 509,577 used cars listings with their market price. ``` vehicles = pd.read_csv("../data/vehicles_train.csv") vehicles_test = pd.read_csv("../data/vehicles_test.csv") print(len(vehicles)) print(len(vehicles_test)) vehicles = vehicles.rename(columns = {"lat": "latitude", "long": "longitude"}) ``` ### Step 3 - Dataset head ``` vehicles.head() ``` ### Step 4 - Data Description In this dataset we have 17 categorical variables and 7 numerical variables, with the following description: **Categorical variables:** - `URL`: The url of the listing on Craiglist - `Region`: Region where the listing was posted - `region_url`: Craiglist's Region URL - `manufacturer`: Vehicle manufacturer - `model`: Vehicle model - `condition`: Vehicle condition according to the user (eg. 'excellent', 'like new') - `cylinders`: Number of cylinders of the vehicle - `fuel`: Vehicle fuel type - `title_status`: Status of the vehicle (eg. 'rebuilt', 'clean') - `transmission`: Transmission of the vehicle - `vin`: VIN number of the vehicle - `drive`: type of drive of the vehicle (eg. '4wd', 'fwd') - `size`: Size of the vehicle - `type`: Type of the vehicle (eg. 'SUV', 'pickup', 'sedan') - `paint_color`: Color of the paint of the vehicle - `image_url`: URL of the picture of the vehicle - `state`: State where the listing is posted **Numerical variables:** - `id`: id of the listing - `year`: vehicle's manufacturing year - `price`: **Response**, price of the vehicle - `odometer`: Mileage of the vehicle at the moment the listing was posted - `latitude`: Latitude of the state - `longitude`: Longitude of the state The following code shows the variables and their non-null count ``` vehicles.info() ``` In order to explore the numerical variables, we used the pd.describe() function. ``` vehicles.describe() ``` In addition, we analyzed the frequency of the levels of the categorical variables ``` numeric_features = ['year', 'odometer'] categorical_features = ['state','manufacturer','model', 'condition', 'cylinders', 'fuel', 'title_status', 'transmission', 'size', 'type', 'paint_color'] for feat in categorical_features: print('Feature: %s' %(feat)) print('------------') print(f'This feature has {len(vehicles[feat].unique())} levels') print('------------') print(vehicles[feat].value_counts()) print('\n\n') ``` ### Step 5 - Data Visualizations #### Correlations ``` vehicles_corr = vehicles.corr().reset_index().rename(columns = {'index':'Var1'}).melt(id_vars = ['Var1'], value_name = 'Correlation', var_name = 'Var2') base = alt.Chart(vehicles_corr).encode( alt.Y('Var1:N'), alt.X('Var2:N') ) heatmap = base.mark_rect().encode( alt.Color('Correlation:Q', scale=alt.Scale(scheme='viridis')) ) text = base.mark_text(baseline='middle').encode( text=alt.Text('Correlation:Q', format='.2'), color=alt.condition( alt.datum.Correlation >= 0.95, alt.value('black'), alt.value('white') ) ) (heatmap + text).properties( width = 400, height = 400, title = "Pearson's correlation" ) ``` #### Frequency map ``` vehicles['state'] = vehicles['state'].str.upper() vehicles_position = vehicles.dropna(subset = ['latitude', 'longitude'])[['state','latitude', 'longitude','price', 'id']] vehicles_position = vehicles_position.groupby(by = "state")\ .agg({'price': 'mean', 'longitude' : 'mean', 'latitude' : 'mean', 'id': 'count'})\ .reset_index() states = alt.topo_feature(data.us_10m.url, feature='states') # US states background background = alt.Chart(states).mark_geoshape( fill='lightgray', stroke='white' ).properties( width=500, height=300 ).project('albersUsa') points = alt.Chart(vehicles_position).transform_aggregate( latitude='mean(latitude)', longitude='mean(longitude)', count='sum(id)', groupby=['state'] ).mark_circle().encode( longitude='longitude:Q', latitude='latitude:Q', size=alt.Size('count:Q', title='Number of vehicles per state'), color=alt.value('steelblue'), tooltip=[alt.Tooltip('state:N', title='state'), alt.Tooltip('count:Q', title='Price', format=',.2f')] ).properties( title='Number of vehicles per state' ) background + points states = alt.topo_feature(data.us_10m.url, feature='states') # US states background background = alt.Chart(states).mark_geoshape( fill='lightgray', stroke='white' ).properties( width=500, height=300 ).project('albersUsa') points = alt.Chart(vehicles_position).transform_aggregate( latitude='mean(latitude)', longitude='mean(longitude)', count='mean(price)', groupby=['state'] ).mark_circle().encode( longitude='longitude:Q', latitude='latitude:Q', size=alt.Size('count:Q', title='Average market price per state'), color=alt.value('steelblue'), tooltip=[alt.Tooltip('state:N', title='state'), alt.Tooltip('count:Q', title='Price', format='$,.2f')] ).properties( title='Average market price per state' ) background + points ``` #### Market Price by Categorical Variables ``` categorical_features = ['manufacturer', 'condition', 'cylinders', 'fuel', 'title_status', 'transmission', 'size', 'type', 'paint_color'] categorical_encodings = ['manufacturer', 'condition', 'cylinders', 'fuel', 'title_status', 'transmission', 'size', 'type', 'paint_color'] base = alt.Chart().mark_bar().encode( alt.Y('mean(price):Q') ).properties( width=400, height=400 ) chart = alt.vconcat() for i in range(len(categorical_features)): vehicles_graph = vehicles[['price', categorical_features[i]]].groupby(by = categorical_features[i])\ .mean()\ .reset_index() row = alt.hconcat(data = vehicles_graph) row |= base.encode( x = alt.X(categorical_encodings[i])).properties(title = f'Mean market price by {categorical_features[i]}') chart &= row chart ```
github_jupyter
If we have smaller data it can be useful to benefit from k-fold cross-validation to maximize our ability to evaluate the neural network's performance. This is possible in Keras because we can "wrap" any neural network such that it can use the evaluation features available in scikit-learn, including k-fold cross-validation. To accomplish this, we first have to create a function that returns a compiled neural network. Next we use `KerasClassifier` (if we have a classifier, if we have a regressor we can use `KerasRegressor`) to wrap the model so it can be used by scikit-learn. After this, we can use our neural network like any other scikit-learn learning algorithm (e.g. random forests, logistic regression). In our solution, we used `cross_val_score` to run a 3-fold cross-validation on our neural network. ## Preliminaries ``` # Load libraries import numpy as np from keras import models from keras import layers from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from sklearn.datasets import make_classification # Set random seed np.random.seed(0) ``` ## Create Feature And Target Data ``` # Number of features number_of_features = 100 # Generate features matrix and target vector features, target = make_classification(n_samples = 10000, n_features = number_of_features, n_informative = 3, n_redundant = 0, n_classes = 2, weights = [.5, .5], random_state = 0) ``` ## Create Function That Constructs Neural Network ``` # Create function returning a compiled network def create_network(): # Start neural network network = models.Sequential() # Add fully connected layer with a ReLU activation function network.add(layers.Dense(units=16, activation='relu', input_shape=(number_of_features,))) # Add fully connected layer with a ReLU activation function network.add(layers.Dense(units=16, activation='relu')) # Add fully connected layer with a sigmoid activation function network.add(layers.Dense(units=1, activation='sigmoid')) # Compile neural network network.compile(loss='binary_crossentropy', # Cross-entropy optimizer='rmsprop', # Root Mean Square Propagation metrics=['accuracy']) # Accuracy performance metric # Return compiled network return network ``` ## Wrap Function In KerasClassifier ``` # Wrap Keras model so it can be used by scikit-learn neural_network = KerasClassifier(build_fn=create_network, epochs=10, batch_size=100, verbose=0) ``` ## Conduct k-Fold Cross-Validation Using scikit-learn ``` # Evaluate neural network using three-fold cross-validation cross_val_score(neural_network, features, target, cv=3) ```
github_jupyter
``` import astropy.units as u import numpy as np from matplotlib import pyplot as plt from astroduet.bbmag import bb_abmag_fluence, bb_abmag import astroduet.config as config from astroduet.background import background_pixel_rate from astroduet.utils import duet_abmag_to_fluence %load_ext autoreload %autoreload 2 from astropy.visualization import quantity_support import matplotlib font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) # Account for the fact that you're co-adding the two frames here: duet = config.Telescope(config='minimum_mass_requirement') # From Marianne: # Using the median surface brightnesses from Bai: # Elliptical, D1: 0.56 ph/s/pixel # Elliptical, D2: 0.64 ph/s/pixel # Spiral, D1: 2.09 ph/s/pixel # Spiral, D2: 1.68 ph/s/pixel pixel_area = duet.pixel * duet.pixel mean_elliptical_duet1 = 24.94535864867936 * u.ABmag mean_elliptical_duet2 = 24.730938046220277 * u.ABmag mean_spiral_duet1 = 23.684754905932877 * u.ABmag mean_spiral_duet2 = 23.827616937816682 * u.ABmag rate1 = pixel_area.value * duet.fluence_to_rate(duet_abmag_to_fluence(mean_elliptical_duet1, 1)) rate1 = pixel_area.value * duet.fluence_to_rate(duet_abmag_to_fluence(mean_spiral_duet1, 1)) print(rate1) rate2 = pixel_area.value * duet.fluence_to_rate(duet_abmag_to_fluence(mean_elliptical_duet2, 2)) rate2 = pixel_area.value * duet.fluence_to_rate(duet_abmag_to_fluence(mean_spiral_duet2, 2)) print(rate2) # Band1 # 5-sigma limiting magnitude in 1 and 5 stacked frames. # Account for the fact that you're co-adding the two frames here: duet = config.Telescope(config='minimum_mass_requirement') bandone = duet.bandpass1 bandtwo = duet.bandpass2 surf_scale = 1.0 exposure = 300*u.s print() siglimit=5 dmag = 0.01 print() [bgd_band1, bgd_band2] = background_pixel_rate(duet, med_zodi=True) tot_bgd_rate = bgd_band1 + rate1 * surf_scale for nframes in [8]: snr = 100 swiftmag = 20.5 while snr > siglimit: swiftmag += dmag band1_fluence, band2_fluence = bb_abmag_fluence(duet =duet, swiftmag=swiftmag*u.ABmag, bbtemp=12e3*u.K) band1_rate = duet.fluence_to_rate(band1_fluence) band2_rate = duet.fluence_to_rate(band2_fluence) src_rate = band1_rate snr = duet.calc_snr(exposure, src_rate, tot_bgd_rate, nint=nframes) bbmag1, bbmag2 = bb_abmag(swiftmag=swiftmag*u.ABmag, bbtemp=12e3*u.K, bandone = bandone, bandtwo=bandtwo) print('Band1 {} {}-σ magnitude limit: {}'.format(nframes*exposure, siglimit, bbmag1)) print(snr) duet1_limit = bbmag1 tot_bgd_rate = bgd_band2 + rate2*surf_scale for nframes in [8]: snr = 100 swiftmag = 20.8 while snr > siglimit: swiftmag += dmag band1_fluence, band2_fluence = bb_abmag_fluence(duet =duet, swiftmag=swiftmag*u.ABmag, bbtemp=12e3*u.K) band1_rate = duet.fluence_to_rate(band1_fluence) band2_rate = duet.fluence_to_rate(band2_fluence) src_rate = band2_rate snr = duet.calc_snr(exposure, src_rate, tot_bgd_rate, nint=nframes) bbmag1, bbmag2 = bb_abmag(swiftmag=swiftmag*u.ABmag, bbtemp=12e3*u.K, bandone = bandone, bandtwo=bandtwo) print('Band2 {} {}-σ magnitude limit: {}'.format(nframes*exposure, siglimit, bbmag2)) print(snr) print() duet2_limit = bbmag2 from astroduet import models sims = models.Simulations() sims.emgw_simulations target = 0.2 *u.day lc = models.load_model_ABmag('kilonova_0.02.dat', dist = 10*u.pc) duet1_abmag_at_5hr = np.interp(target.to(u.s).value, lc[0].to(u.s).value, lc[1]) duet2_abmag_at_5hr = np.interp(target.to(u.s).value, lc[0].to(u.s).value, lc[2]) hrs = lc[0].to(u.hr) plt.figure() plt.plot(hrs, lc[1]) plt.plot(hrs, lc[2]) plt.ylim([-12, -15]) plt.xlim([0, 10]) plt.xlabel('Hours') plt.figure() dist1 = 10 * 10**((duet1_limit.value - duet1_abmag_at_5hr) / 5)*u.pc print(dist1.to(u.Mpc)) dist2 = 10 * 10**((duet2_limit.value - duet2_abmag_at_5hr) / 5)*u.pc print(dist2.to(u.Mpc)) lc1 = models.load_model_ABmag('kilonova_0.02.dat', dist = dist1) plt.plot(hrs, lc1[1]) lc2 = models.load_model_ABmag('kilonova_0.02.dat', dist = dist2) plt.plot(hrs, lc2[2]) plt.axhline(duet1_limit.value, linestyle = ':') plt.axhline(duet2_limit.value, linestyle = ':') plt.axvline(target.to(u.hr).value, linestyle=':') plt.ylim([24, 17]) plt.xlim([0, 10]) plt.xlabel('Hours') plt.show() lc = models.load_model_ABmag('shock_5e10.dat', dist = 10*u.pc) duet1_abmag_at_5hr = np.interp(target.to(u.s).value, lc[0].to(u.s).value, lc[1]) duet2_abmag_at_5hr = np.interp(target.to(u.s).value, lc[0].to(u.s).value, lc[2]) hrs = lc[0].to(u.hr) plt.figure() plt.plot(hrs, lc[1]) plt.plot(hrs, lc[2]) plt.ylim([-12, -18]) plt.xlim([0, 10]) plt.xlabel('Hours') plt.figure() dist1 = 10 * 10**((duet1_limit.value - duet1_abmag_at_5hr) / 5)*u.pc print(dist1.to(u.Mpc)) dist2 = 10 * 10**((duet2_limit.value - duet2_abmag_at_5hr) / 5)*u.pc print(dist2.to(u.Mpc)) lc1 = models.load_model_ABmag('shock_5e10.dat', dist = dist1) plt.plot(hrs, lc1[1]) lc2 = models.load_model_ABmag('shock_5e10.dat', dist = dist2) plt.plot(hrs, lc2[2]) plt.axhline(duet1_limit.value, linestyle = ':') plt.axhline(duet2_limit.value, linestyle = ':') plt.axvline(target.to(u.hr).value, linestyle=':') plt.ylim([24, 17]) plt.xlim([0, 10]) plt.xlabel('Hours') plt.show() ```
github_jupyter
``` import sys; sys.path.append(_dh[0].split("knowknow")[0]) from knowknow import * wos_base = "G:/My Drive/projects/qualitative analysis of literature/pre 5-12-2020/009 get everything from WOS" basedir = Path(wos_base) from csv import DictReader # This cell ensures there are not overflow errors while importing large CSVs import sys import csv maxInt = sys.maxsize while True: # decrease the maxInt value by factor 10 # as long as the OverflowError occurs. try: csv.field_size_limit(maxInt) break except OverflowError: maxInt = int(maxInt/10) journal_keep = ["ETHNIC AND RACIAL STUDIES", "LAW & SOCIETY REVIEW", "DISCOURSE & SOCIETY", "SOCIOLOGICAL INQUIRY", "CONTRIBUTIONS TO INDIAN SOCIOLOGY", "SOCIETY & NATURAL RESOURCES", "RATIONALITY AND SOCIETY", "DEVIANT BEHAVIOR", "ACTA SOCIOLOGICA", "SOCIOLOGY-THE JOURNAL OF THE BRITISH SOCIOLOGICAL ASSOCIATION", "WORK EMPLOYMENT AND SOCIETY", "SOCIOLOGICAL METHODS & RESEARCH", "SOCIOLOGICAL PERSPECTIVES", "JOURNAL OF MARRIAGE AND FAMILY", "WORK AND OCCUPATIONS", "JOURNAL OF CONTEMPORARY ETHNOGRAPHY", "THEORY AND SOCIETY", "POLITICS & SOCIETY", "SOCIOLOGICAL SPECTRUM", "RACE & CLASS", "ANTHROZOOS", "LEISURE SCIENCES", "COMPARATIVE STUDIES IN SOCIETY AND HISTORY", "SOCIAL SCIENCE QUARTERLY", "MEDIA CULTURE & SOCIETY", "SOCIOLOGY OF HEALTH & ILLNESS", "SOCIOLOGIA RURALIS", "SOCIOLOGICAL REVIEW", "TEACHING SOCIOLOGY", "BRITISH JOURNAL OF SOCIOLOGY", "JOURNAL OF THE HISTORY OF SEXUALITY", "SOCIOLOGY OF EDUCATION", "SOCIAL NETWORKS", "ARMED FORCES & SOCIETY", "YOUTH & SOCIETY", "POPULATION AND DEVELOPMENT REVIEW", "SOCIETY", "JOURNAL OF HISTORICAL SOCIOLOGY", "HUMAN ECOLOGY", "INTERNATIONAL SOCIOLOGY", "SOCIAL FORCES", "EUROPEAN SOCIOLOGICAL REVIEW", "JOURNAL OF HEALTH AND SOCIAL BEHAVIOR", "SOCIOLOGICAL THEORY", "SOCIAL INDICATORS RESEARCH", "POETICS", "HUMAN STUDIES", "SOCIOLOGICAL FORUM", "AMERICAN SOCIOLOGICAL REVIEW", "SOCIOLOGY OF SPORT JOURNAL", "SOCIOLOGY OF RELIGION", "JOURNAL OF LAW AND SOCIETY", "GENDER & SOCIETY", "BRITISH JOURNAL OF SOCIOLOGY OF EDUCATION", "LANGUAGE IN SOCIETY", "AMERICAN JOURNAL OF ECONOMICS AND SOCIOLOGY", "ANNALS OF TOURISM RESEARCH", "SOCIAL PROBLEMS", "INTERNATIONAL JOURNAL OF INTERCULTURAL RELATIONS", "SOCIAL SCIENCE RESEARCH", "SYMBOLIC INTERACTION", "JOURNAL OF LEISURE RESEARCH", "ECONOMY AND SOCIETY", "INTERNATIONAL JOURNAL OF COMPARATIVE SOCIOLOGY", "SOCIAL COMPASS", "SOCIOLOGICAL QUARTERLY", "JOURNAL OF MATHEMATICAL SOCIOLOGY", "AMERICAN JOURNAL OF SOCIOLOGY", "REVIEW OF RELIGIOUS RESEARCH", "RURAL SOCIOLOGY", "JOURNAL FOR THE SCIENTIFIC STUDY OF RELIGION", "ARCHIVES EUROPEENNES DE SOCIOLOGIE", "CANADIAN JOURNAL OF SOCIOLOGY-CAHIERS CANADIENS DE SOCIOLOGIE"] journal_keep = [x.lower() for x in journal_keep] def filter_rows(rows): for r in rows: if r['DT'] != "Article": continue refs = r["CR"].strip().split(";") if not len(refs): continue authors = r['AU'].split(";") authors = [x.strip() for x in authors] if False: for i in range(10): print("-"*20) uid = r['UT'] try: int(r['PY']) except ValueError: continue r['SO'] = r['SO'].lower() # REMEMBER THIS! lol everything is in lowercase... not case sensitive if r['SO'].lower() not in journal_keep: continue yield r # processes WoS txt output files one by one, counting relevant cooccurrences as it goes debug=False dcount=0 files = list(basedir.glob("**/*.txt")) rows = [] for i in range(100): f = sample(files,1)[0] with f.open(encoding='utf8') as pfile: r = DictReader(pfile, delimiter="\t") my_f_rows = list(r) if i % 50 == 0: print("File %s/100" % (i,)) results = list(filter_rows(my_f_rows)) if not len(results): print("zero matches, skipping...") continue r = sample(results,1)[0] rows.append({ "pub": r['PY'], "title": r['TI'].title(), "journal": r['SO'].title() }) rows = sorted(rows, key=lambda x: -int(x['pub'])) pd.set_option('display.max_rows', 100) pd.DataFrame.from_records(rows) ```
github_jupyter
``` def mySpindleStats(edf_path,stages_path): # Programmed by Mohsen Naji, Aug 2018 # Email me if you need to know the detection method # output is spindle-related stats such as numbers and densities # This function detects the sleep spindles in the re-referenced high density EEG # After calling this function, you will also get power spectrum densities as a byproduct. # It calculates the EEG power spectrum (variable P; you may need the "squeeze" command to access powers) for every 30-sec epoch (variable mrk), # and five separate average power spectra for each stage # The outputs are in Matlab format in different folders: PowerSpectra and spindle_stats # It may fail saving the output on Windows OS due to the / \ issue # input example: edf_path='/Volumes/Mohsen/PSTIM/allscalp/PSTIM_729_V1.edf' # input example: stages_path='/Volumes/Mohsen/PSTIM/allscalp/PSTIM_729_V1.mat' import numpy as np import scipy.io as sio from scipy import signal import os Q=4 # number of quantiles (4 to have quartiles!) # required functions #################### def myEDFread(path): fid=open(path,'rb') a=fid.read(236) ndr=int(fid.read(8)) #number of data records in sec drdur=float(fid.read(8)) #duration of each data record in sec ns=int(fid.read(4)) #number of signal channels Channels=[] for i in range(0,int(ns)): Channels.append(fid.read(16).decode('UTF-8')) # changing bytes to str tdu=fid.read(ns*80) #transducer type units=fid.read(ns*8) #physical dimensions phmn=[] phmx=[] dmn=[] dmx=[] for i in range(0,int(ns)): phmn.append(float(fid.read(8))) # physical min for i in range(0,int(ns)): phmx.append(float(fid.read(8))) # physical max for i in range(0,int(ns)): dmn.append(float(fid.read(8))) # digital min for i in range(0,int(ns)): dmx.append(float(fid.read(8))) # digital max scalefac=[] for i in range(0,len(phmn)): scalefac.append((phmx[i]-phmn[i])/(dmx[i]-dmn[i])) dc=[] for i in range(0,len(phmn)): dc.append(phmx[i]-scalefac[i]*dmx[i]) prefilters=fid.read(ns*80) #prefilters nr=[] for i in range(0,ns): nr.append(int(fid.read(8))) #samples per data record if sum(nr)/len(nr)==nr[0]: fs=nr[0]/int(drdur) else: disp('cannot proceed. one of the channels has a different sampling rate') othr=fid.read(ns*32) X=np.zeros((ns,int(nr[0]*ndr))) for i in range(0,ndr): for j in range(0,ns): X[j][i*nr[j]:(i+1)*nr[j]]=np.fromstring(fid.read(nr[j]*2), 'int16')*scalefac[j]+dc[j] fid.close() return X, fs, Channels def myEPOCHpower(X, fs, ar, epl=30, rjth=300): # X: Data matrix with channels in row # fs: sampling rate (Hz), use int(fs) # ar: artifact rejection switch. set 1 if you want better estimation, but 0 if you want something fast # epl: sleep scoring epoch length (e.g. 30 sec) # returns power spectrum P for every channel and epoch in every frequencies in f b2, a2 = signal.butter(4, 0.5/(fs/2), 'high') for i in range(1, 4*fs): if (2 ** i >= 4*fs): win=2 ** i break P=[] f=[] for i in range(0,X.shape[0]): P.append([]) f.append([]) for i in range(0,X.shape[0]): for j in range(0,int(X.shape[1]/(epl*fs))): x = X[i][j*epl*fs:(j+1)*epl*fs]; if ar==1: rj=abs(signal.filtfilt(b2, a2, x))>rjth for ii in range(0,len(rj)): if rj[ii]==True: rj[ii-2*fs:ii+2*fs]=True x=x[~rj] if len(x)>8*fs: fp, Pxx_den = signal.welch(x, fs=fs, window='hanning', nperseg=win, noverlap=win/2, nfft=win, detrend='constant', return_onesided=True, scaling='density', axis=-1) P[i].append(Pxx_den) f[i].append(fp) else: P[i].append(np.zeros((1,int(win/2)+1))[0]) f[i].append(np.zeros((1,int(win/2)+1))[0]) return P, f def myspecpeak(P,f,ind,f1=9,f2=20): fpk=np.zeros((1,np.shape(P)[0])) fpk=fpk[0] for j in range(0,np.shape(P)[0]): tmpp=P[j] PN=np.array(P[j]).take(ind2,axis=0) res=0 while res==0: fN=np.array(f[j]).take(ind2,axis=0)[0] res=fN[1]-fN[0] ind_f1=find_ind(fN,f1) ind_f2=find_ind(fN,f2) f_des=np.arange(f1, f2, res) m=PN[:,ind_f1:ind_f2].mean(axis=1) indf=[i for i, x in enumerate(m<(m.mean()+m.std())) if x] avP=PN[indf,ind_f1:ind_f2].mean(axis=0) pl=([np.logical_and((avP[1:-2]-avP[0:-3])>0,(avP[1:-2]-avP[2:-1])>0)])[0] ind_peaks=[i+1 for i, x in enumerate(pl) if x] p=avP[np.ix_(ind_peaks)] f_peaks=f_des[np.ix_(ind_peaks)] if len(ind_peaks)>1: p=p[(f_peaks>=11) & (f_peaks<=13.5)] f_peaks=f_peaks[(f_peaks>=11) & (f_peaks<=13.5)] if len(p)>1: f_peaks=f_peaks[np.argmax(p)] p=[p[np.argmax(p)]] if len(p)==0: f_peaks=f_des[np.argmax(avP)] p=avP[np.argmax(avP)] fpk[j]=f_peaks tmpf=fpk for j in range(0,len(fpk)): if fpk[j]==f1 or fpk[j]==f2: fpk[j]=tmpf[(fpk!=f1) & (fpk!=f2)].mean() return fpk def find_ind(x, a): return np.argmin(abs(x-a)) def myEEGbursts(X,fs,ind_epoch,fc,bw,thrfactor=4,epl=30,rjth=200,intrvmin=0.25): # X: EEG Data (re-referenced) with channels in rows (at least 2 channels are required) # fs: sampling rate in Hz (e.g., 256) # epl: scoring epoch length (e.g., 30) # ind_epoch: list of epoch indexes for the stage of interest (e.g., indices for stage 2) # fc: list(or array) of peak frequency of the burst activity (e.g. 12 Hz for spindle) for each channel # bw: bandwidth around fc for detecting bursts. for example for fs=12 Hz and bw=3 Hz, 10.5-13.5 Hz range is considered # rjth: epochs with maximum absolute value greater than rjth (e.g. 200 uV) will be discarded for baseline activity calculation # intrvmin: minimum duration for detected bursts (e.g. 0.25 sec) fc=np.array(fc) b2, a2 = signal.butter(4, 0.5/(fs/2), 'high') spindle_intrv=[] spindle_pks=[] for i in range(0,X.shape[0]): spindle_intrv.append([]) spindle_pks.append([]) for j in range(0,X.shape[0]): # finding clean epochs for baseline activity calculation # print(j) ind_cln=[] for e in range(0,len(ind_epoch)): if max(abs(signal.filtfilt(b2,a2,X[j][int(ind_epoch[e]*epl*fs):int((ind_epoch[e]+1)*epl*fs)])))<rjth: ind_cln.append(ind_epoch[e]) # wavelet spectrogram and baseline activity calculation for each channel tmpth=[] spec=[] for e in range(0,len(ind_epoch)): EP_energy = morlet_spectrogram(X[j][int(ind_epoch[e]*epl*fs):int((ind_epoch[e]+1)*epl*fs)],fs,[fc[j]-bw/2,fc[j]+bw/2], 0.1, 10, 5) av=np.mean(EP_energy,axis=0)**2 spec.append(av) if sum([ np.sum(a == ind_epoch[e]) for a in ind_cln]): tmpth.append(np.mean(av)) th=np.mean(tmpth) # finding EEG bursts by applying the criteria to the average spectrogram for e in range(0,len(ind_epoch)): intrv, pks = bnds_over_th(spec[e],thrfactor*th,ind_epoch[e]*epl*fs) for i in range(0,len(pks)): if (intrv[i][1]-intrv[i][0])/fs>intrvmin and max(abs(signal.filtfilt(b2,a2,X[j][int(intrv[i][0]):int(intrv[i][1])])))<(0.4*rjth): spindle_intrv[j].append(intrv[i]) spindle_pks[j].append(pks[i]) return spindle_intrv def bnds_over_th(a,th,ep_beg): # a is an array # threshold # ep_beg: epoch first point index in the sleep record (put 0 if not applicable) intrv=[] pks=[] overt=[i for i, x in enumerate(a>th) if x] pos=[] if len(overt)>1: pos.append(overt[0]) df=[overt[i+1]-overt[i] for i in range(0,len(overt)-1)] for i in range(0,len(df)): if df[i]!=1: pos.append(overt[i]) pos.append(overt[i+1]) pos.append(overt[-1]) if a[pos[0]-1]>a[pos[0]+1]: del pos[0] if len(pos)%2==1: del pos[-1] for i in range(0,int(len(pos)/2)): intrv.append(pos[i*2:(i+1)*2]) pks=[] for i in range(0,len(intrv)): pks.append(max(a[intrv[i][0]:intrv[i][1]+1])) if ep_beg>0: if len(intrv)>0: for i in range(0,len(intrv)): intrv[i][0]= intrv[i][0]+ep_beg intrv[i][1]= intrv[i][1]+ep_beg return intrv, pks def morlet_spectrogram(sig, samp_rate, freq_range, f_step, wave_num, timescale): # example freq_range: [2, 18] # f_step: freq resoulution in Hz (e.g., 0.1 Hz) # wave_num: parameter for number of sinusoidal cycles in a morlet, 10 worked well for eeg # timescale: 5 worked well for eeg frecs=np.arange(freq_range[0], freq_range[1]+f_step, f_step) len_sig = len(sig) samp_period = 1/float(samp_rate) row_coef = len(frecs) col_coef = len_sig EP_energy= np.zeros((row_coef,col_coef)) for k in range(0,row_coef): SD_f = frecs[k]/wave_num SD_t = 1/(2*np.pi*SD_f) x=np.arange(-timescale*SD_t, timescale*SD_t+samp_period, samp_period) Morlets = (1/np.sqrt(SD_t*np.sqrt(np.pi))) * (np.exp( -(x**2)/(2*SD_t**2) ) * np.exp(1j*2*np.pi*frecs[k]*x )) Morlets=Morlets[[i for i, x in enumerate(abs(Morlets)>=max(abs(Morlets))/100) if x]] coef_freq = np.convolve(sig,Morlets) EP_energy[k] = (abs(coef_freq)**2)[round(len(Morlets)/2):col_coef+round(len(Morlets)/2)] return EP_energy def myspindle_refine(X,spindle_intrv): for j in range(0,X.shape[0]): issp=[] #print(len(spindle_intrv[j])) for i in range(0,len(spindle_intrv[j])): if not mytest_spindle(X[j][int(spindle_intrv[j][i][0]):int(spindle_intrv[j][i][1])],fs): issp.append(i) spindle_intrv[j]=np.delete(spindle_intrv[j],issp,0) return spindle_intrv def mytest_spindle(x,fs): b2, a2 = signal.butter(4, 2/(fs/2), 'high') b1, a1 = signal.butter(4, 30/(fs/2), 'low') y = signal.filtfilt(b2, a2, x) y = signal.filtfilt(b1, a1, y) out= 0 pl=(y[0:-2]*y[1:-1])<0 zci=[i+1 for i, x in enumerate(pl) if x] if len(zci)>2: if len(zci)%2==0: del zci[-1] ncyc= (len(zci)-1)/2 fest=fs/((zci[-1]-zci[0]+1)/ncyc) if fest>=9 and fest<=16: out=1 else: out=0 return out def myPowerUNZIP(P,f,fs,StgInds): res=0 Nstd=1 #rejection threshold = mean+Nstd*standard_dev P_stg=[]; for j in range(0,len(P)): while res==0: fN=np.array(f[j]).take(StgInds,axis=0)[0] if sum(fN) == 0: break else: res=fN[1]-fN[0] frqs=np.arange(0, fs/2+res, res) if len(StgInds)!=0: for j in range(0,len(P)): tmpp=P[j] PN=np.array(P[j]).take(StgInds,axis=0) m=PN.mean(axis=0) ind_f1=find_ind(fN,6) ind_f2=find_ind(fN,20) f_des=np.arange(6, 20, res) m=PN[:,ind_f1:ind_f2].mean(axis=1) indf=[np.logical_and(m<=(m.mean()+Nstd*m.std()),m>0)][0] avP=PN[indf,:].mean(axis=0) P_stg.append(avP) else: for j in range(0,len(P)): P_stg.append(len(frqs)*[0]) return P_stg, frqs ###### main print('reading EDF...') X, fs, Channels= myEDFread(edf_path) print('reading sleep stages...') mat_contents = sio.loadmat(stages_path) stageData= mat_contents['stageData'] val=stageData[0,0] mrk=val['stages'] print('calculating power spectra...') P, f= myEPOCHpower(X, int(fs), 1) ind2=[i for i, x in enumerate(mrk==2) if x] # indices for stage 2 epochs # ind2 = [i for i in ind2 if i <= min(np.shape(P)[1],ind2[-1])] print('estimating spindle peak frequency (Stage 2)...') fpk_stg2= myspecpeak(P,f,ind2) print('spindle detection (Stage 2)...') spindle_intrv_stg2= myEEGbursts(X,fs,ind2,fpk_stg2,3) print('spindle refinement (Stage 2)...') spindle_intrv_stg2= myspindle_refine(X,spindle_intrv_stg2) ind3=[i for i, x in enumerate(mrk==3) if x] # indices for stage 3 epochs # ind3 = [i for i in ind3 if i <= min(np.shape(P)[1],ind3[-1])] print('estimating spindle peak frequency (SWS)...') fpk_stg3= myspecpeak(P,f,ind3) print('spindle detection (SWS)...') spindle_intrv_stg3= myEEGbursts(X,fs,ind2,fpk_stg3,3) print('spindle refinement (SWS)...') spindle_intrv_stg3= myspindle_refine(X,spindle_intrv_stg3) ind5=[i for i, x in enumerate(mrk==5) if x] # indices for REM epochs ind1=[i for i, x in enumerate(mrk==1) if x] # indices for Stage1 epochs ind0=[i for i, x in enumerate(mrk==0) if x] # indices for Wake epochs ##### output exports spN_stg2=[] spN_stg3=[] spDns_stg2=[] spDns_stg3=[] for j in range(0,len(spindle_intrv_stg2)): spN_stg2.append(len(spindle_intrv_stg2[j])) spN_stg3.append(len(spindle_intrv_stg3[j])) spDns_stg2.append(len(spindle_intrv_stg2[j])/(len(ind2)*0.5)) spDns_stg3.append(len(spindle_intrv_stg3[j])/(len(ind3)*0.5)) o=[i for i in range(0,len(mrk)) if mrk[i]>0 and mrk[i]!=7][0] e=[i for i in range(0,len(mrk)) if mrk[i]>0 and mrk[i]!=7][-1] qs=int((int((e)*30*fs)-int((o-1)*30*fs))/4) Q_spN_stg2=[] Q_spN_stg3=[] Q_spDns_stg2=[] Q_spDns_stg3=[] for ii in range(0,Q): Q_spN_stg2.append([]) Q_spN_stg3.append([]) Q_spDns_stg2.append([]) Q_spDns_stg3.append([]) for ii in range(0,4): beg = int((o-1)*30*fs) + ii*qs en = int((o-1)*30*fs) + (ii+1)*qs for j in range(0,len(spindle_intrv_stg2)): cnt=0 for i in range(0,len(spindle_intrv_stg2[j])): if spindle_intrv_stg2[j][i][0]>=beg and spindle_intrv_stg2[j][i][0]<en: cnt+=1 Q_spN_stg2[ii].append(cnt) Q_spDns_stg2[ii].append(cnt/(len(ind2)*0.5)) cnt=0 for i in range(0,len(spindle_intrv_stg3[j])): if spindle_intrv_stg3[j][i][0]>=beg and spindle_intrv_stg3[j][i][0]<en: cnt+=1 Q_spN_stg3[ii].append(cnt) Q_spDns_stg3[ii].append(cnt/(len(ind3)*0.5)) print('saving spindle outputs to mat...') #sio.savemat(edf_path[1:-4]+'_spindles',{"Channels":Channels,"fs":fs,"spindle_intrv_stg2":spindle_intrv_stg2,"spindle_intrv_stg3":spindle_intrv_stg3}) slsh=[i for i in range(0,len(edf_path)) if edf_path[i]=='/'] if not os.path.exists(edf_path[0:slsh[-1]+1]+'spindle_stats'): os.makedirs(edf_path[0:slsh[-1]+1]+'spindle_stats') struct = {"Channels":Channels,"fs":fs,"spindle_intrv_stg2":spindle_intrv_stg2,"spindle_intrv_stg3":spindle_intrv_stg3,"spN_stg2":spN_stg2,"spN_stg3":spN_stg3,"Q_spN_stg2":Q_spN_stg2,"Q_spN_stg3":Q_spN_stg3,"spDns_stg2":spDns_stg2,"spDns_stg3":spDns_stg3,"Q_spDns_stg2":Q_spDns_stg2,"Q_spDns_stg3":Q_spDns_stg3} sio.savemat(edf_path[0:slsh[-1]+1]+'spindle_stats'+edf_path[slsh[-1]:-4]+'_spindles',struct) print('saving power outputs to mat...') Pav_wake, frqs = myPowerUNZIP(P,f,fs,ind0) Pav_stg1, frqs = myPowerUNZIP(P,f,fs,ind1) Pav_REM, frqs = myPowerUNZIP(P,f,fs,ind5) Pav_stg3, frqs = myPowerUNZIP(P,f,fs,ind3) Pav_stg2, frqs = myPowerUNZIP(P,f,fs,ind2) if not os.path.exists(edf_path[0:slsh[-1]+1]+'PowerSpectra'): os.makedirs(edf_path[0:slsh[-1]+1]+'PowerSpectra') structPzip = {"Channels":Channels,"P":P,"frqs":frqs,"fs":fs,"mrk":mrk,"Pav_wake":Pav_wake,"Pav_stg1":Pav_stg1,"Pav_stg2":Pav_stg2,"Pav_stg3":Pav_stg3,"Pav_REM":Pav_REM} sio.savemat(edf_path[0:slsh[-1]+1]+'PowerSpectra'+edf_path[slsh[-1]:-4]+'_PwrSpctr',structPzip) ################ edf_path='/Volumes/Mohsen/PSTIM/allscalp/PSTIM_733_V4.edf' stages_path='/Volumes/Mohsen/PSTIM/allscalp/PSTIM_733_V4.mat' mySpindleStats(edf_path,stages_path) ```
github_jupyter
##### Copyright 2021 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. ``` # Displaying text data in TensorBoard <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tensorboard/text_summaries"><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/tensorboard/blob/master/docs/text_summaries.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/tensorboard/blob/master/docs/text_summaries.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/tensorboard/docs/text_summaries.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> ## Overview Using the **TensorFlow Text Summary API,** you can easily log arbitrary text and view it in TensorBoard. This can be extremely helpful to sample and examine your input data, or to record execution metadata or generated text. You can also log diagnostic data as text that can be helpful in the course of your model development. In this tutorial, you will try out some basic use cases of the Text Summary API. ## Setup ``` try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass # Load the TensorBoard notebook extension. %load_ext tensorboard import tensorflow as tf from datetime import datetime import json from packaging import version import tempfile print("TensorFlow version: ", tf.__version__) assert version.parse(tf.__version__).release[0] >= 2, \ "This notebook requires TensorFlow 2.0 or above." ``` ## Logging a single piece of text To understand how the Text Summary API works, you're going to simply log a bit of text and see how it is presented in TensorBoard. ``` my_text = "Hello world! 😃" # Clear out any prior log data. !rm -rf logs # Sets up a timestamped log directory. logdir = "logs/text_basics/" + datetime.now().strftime("%Y%m%d-%H%M%S") # Creates a file writer for the log directory. file_writer = tf.summary.create_file_writer(logdir) # Using the file writer, log the text. with file_writer.as_default(): tf.summary.text("first_text", my_text, step=0) ``` Now, use TensorBoard to examine the text. Wait a few seconds for the UI to spin up. ``` %tensorboard --logdir logs ``` <!-- <img class="tfo-display-only-on-site" src="https://github.com/tensorflow/tensorboard/blob/master/docs/images/images_single.png?raw=1"/> --> ## Organizing multiple text streams If you have multiple streams of text, you can keep them in separate namespaces to help organize them, just like scalars or other data. Note that if you log text at many steps, TensorBoard will subsample the steps to display so as to make the presentation manageable. You can control the sampling rate using the `--samples_per_plugin` flag. ``` # Sets up a second directory to not overwrite the first one. logdir = "logs/multiple_texts/" + datetime.now().strftime("%Y%m%d-%H%M%S") # Creates a file writer for the log directory. file_writer = tf.summary.create_file_writer(logdir) # Using the file writer, log the text. with file_writer.as_default(): with tf.name_scope("name_scope_1"): for step in range(20): tf.summary.text("a_stream_of_text", f"Hello from step {step}", step=step) tf.summary.text("another_stream_of_text", f"This can be kept separate {step}", step=step) with tf.name_scope("name_scope_2"): tf.summary.text("just_from_step_0", "This is an important announcement from step 0", step=0) %tensorboard --logdir logs/multiple_texts --samples_per_plugin 'text=5' ``` ## Markdown interpretation TensorBoard interprets text summaries as Markdown, since rich formatting can make the data you log easier to read and understand, as shown below. (If you don't want Markdown interpretation, see [this issue](https://github.com/tensorflow/tensorboard/issues/830) for workarounds to suppress interpretation.) ``` # Sets up a third timestamped log directory under "logs" logdir = "logs/markdown/" + datetime.now().strftime("%Y%m%d-%H%M%S") # Creates a file writer for the log directory. file_writer = tf.summary.create_file_writer(logdir) some_obj_worth_noting = { "tfds_training_data": { "name": "mnist", "split": "train", "shuffle_files": "True", }, "keras_optimizer": { "name": "Adagrad", "learning_rate": "0.001", "epsilon": 1e-07, }, "hardware": "Cloud TPU", } # TODO: Update this example when TensorBoard is released with # https://github.com/tensorflow/tensorboard/pull/4585 # which supports fenced codeblocks in Markdown. def pretty_json(hp): json_hp = json.dumps(hp, indent=2) return "".join("\t" + line for line in json_hp.splitlines(True)) markdown_text = """ ### Markdown Text TensorBoard supports basic markdown syntax, including: preformatted code **bold text** | and | tables | | ---- | ---------- | | among | others | """ with file_writer.as_default(): tf.summary.text("run_params", pretty_json(some_obj_worth_noting), step=0) tf.summary.text("markdown_jubiliee", markdown_text, step=0) %tensorboard --logdir logs/markdown ```
github_jupyter
# NumPy http://www.numpy.org/ * Vamos começar convertendo uma lista de Python em um Numpy Array. ``` lista = [1,2,3,4,5] lista import numpy as np #Por convenção, importamos numpy como np. np.array(lista) arr = np.array(lista) ``` Agora possuímos um NumPy Array, que é mais sofisticado que uma lista comum. ``` arr ``` Vamos criar um NumPy Array que contém os valores de 0 a 49. ``` np.arange(0,50) #np.arange(50) #Podemos fazer simplesmente np.arange(50), o valor default de começo é 0. arr = np.arange(50) arr.shape #Verificar o modelo do nosso NumPy Array ``` Possuímos um vetor com 50 valores, 0 a 49. Podemos utilizar o método "reshape" para remodelar o nosso array em uma matriz de _**n**_ dimensões ``` arr.reshape(5,10) #Podemos fazer isso pois 5*10 = 50, que é o número de valores que possuímos. ``` Com isso geramos uma matriz bidimensional (note a quantidade de colchetes no início) Vamos gerar agora uma tridimensional: ``` arr.reshape(5,2,5) ``` # **Vale a pena pesquisar também sobre Broadcast, slicing, indexing e selection em NumPy Arrays e como difere da lista comum.** ## Mais alguns métodos e atributos interessantes ``` #Fazer um vetor de zeros np.zeros(3) #Uma matriz de zeros np.zeros( (3,3) ) #Vetor de uns np.ones(7) #Matriz de uns np.ones( (8,6) ) ``` O método **linspace** retorna números igualmente espaçados em um intervalo especificado, cuidado para não confundir com **arange**. ``` np.linspace(0,5,100) #100 números igualmente espaçados de 0 a 5. ``` **Criando uma matriz identidade** Matriz muito útil para lidar com problemas de Álgebra Linear. Por ser uma matriz quadrada, apenas temos que passar um valor como argumento. ``` np.eye(5) ``` ### Criando valores aleatórios * **np.random.rand()** cria um array da "shape" que você passar e o preenche com amostras aleatórias retiradas de uma **distribuição uniforme** de 0 a 1. * **np.random.randn()** é similar ao rand(), mas retorna amostras de uma **distribuição normal** centrada em torno de 0. * **np.random.randint()** retorna inteiros aleatórios de um "low" (valor mais baixo) até um "high" (valor mais alto) ``` #Um vetor de valores aleatórios retirados de uma distribuição uniforme de 0 a 1 np.random.rand(5) #Matriz de valores aleatórios np.random.rand(5,10) #2d #Um vetor de valores aleatórios retirados de uma distribuição normal ou Gaussiana centrada em 0. np.random.randn(5) #Matriz np.random.randn(5,5) np.random.randint(low=2, high=50) #não precisa explicitar "low" e "high", foi apenas para demonstrar. np.random.randint(2,50) #Note que o retorno é um número e não um NumPy Array! #Também podemos escolher a quantidade de valores aleatórios que queremos no caso do randint() np.random.randint(2,50,3) ``` ## Combinando os conceitos ``` np.random.rand(20,10) np.random.rand(20,10).reshape(10,5,4) #Numa só linha fazendo reshape np.arange(70).reshape(35,2) ```
github_jupyter
# Fluxing with PYPIT [v2] ``` %matplotlib inline # import from importlib import reload import os from matplotlib import pyplot as plt import glob import numpy as np from astropy.table import Table from pypeit import fluxspec from pypeit.spectrographs.util import load_spectrograph ``` # For the standard User (Running the script) ### Generate the sensitivity function from an extracted standard star #### Here is an example fluxing file (see the fluxing docs for details): # User-defined fluxing parameters [rdx] spectrograph = vlt_fors2 [fluxcalib] balm_mask_wid = 12. std_file = spec1d_STD_vlt_fors2_2018Dec04T004939.578.fits sensfunc = bpm16274_fors2.fits #### Here is the call, and the sensitivity function is written to bpm16274_fors2.fits pypit_flux_spec fluxing_filename --plot ### Apply it to all spectra a spec1d science file #### Add a flux block and you can comment out the std_file parameter to avoid remaking the sensitivity function # User-defined fluxing parameters [rdx] spectrograph = vlt_fors2 [fluxcalib] balm_mask_wid = 12. #std_file = spec1d_STD_vlt_fors2_2018Dec04T004939.578.fits sensfunc = bpm16274_fors2.fits flux read spec1d_UnknownFRBHostY_vlt_fors2_2018Dec05T020241.687.fits FRB181112_fors2_1.fits spec1d_UnknownFRBHostY_vlt_fors2_2018Dec05T021815.356.fits FRB181112_fors2_2.fits spec1d_UnknownFRBHostY_vlt_fors2_2018Dec05T023349.816.fits FRB181112_fors2_3.fits flux end #### The new files contain fluxed spectra (and the original, unfluxed data too) pypit_flux_spec fluxing_filename ### Multi-detector (DEIMOS) pypit_flux_spec sensfunc --std_file=spec1d_G191B2B_DEIMOS_2017Sep14T152432.fits --instr=keck_deimos --sensfunc_file=sens.yaml --multi_det=3,7 ---- # For Developers (primarily) ## To play along from here, you need the Development suite *reduced* ### And the $PYPIT_DEV environmental variable pointed at it ``` os.getenv('PYPEIT_DEV') ``` ## Instrument and parameters ``` spectrograph = load_spectrograph('shane_kast_blue') par = spectrograph.default_pypeit_par() ``` ## Instantiate ``` FxSpec = fluxspec.FluxSpec(spectrograph, par['fluxcalib']) ``` ## Sensitivity function ``` std_file = os.getenv('PYPEIT_DEV')+'Cooked/Science/spec1d_Feige66_KASTb_2015May20T041246.960.fits' sci_file = os.getenv('PYPEIT_DEV')+'Cooked/Science/spec1d_J1217p3905_KASTb_2015May20T045733.560.fits' ``` ### Load ``` FxSpec.load_objs(std_file, std=True) ``` ## Find the standard (from the brightest spectrum) ``` _ = FxSpec.find_standard() ``` ## Sensitivity Function ``` sensfunc = FxSpec.generate_sensfunc() sensfunc ``` ### Plot ``` FxSpec.show_sensfunc() FxSpec.steps ``` ### Write ``` _ = FxSpec.save_sens_dict(FxSpec.sens_dict, outfile='sensfunc.fits') ``` ## Flux science ``` FxSpec.flux_science(sci_file) FxSpec.sci_specobjs FxSpec.sci_specobjs[0].optimal ``` ### Plot ``` plt.clf() ax = plt.gca() ax.plot(FxSpec.sci_specobjs[0].optimal['WAVE'], FxSpec.sci_specobjs[0].optimal['FLAM']) ax.plot(FxSpec.sci_specobjs[0].optimal['WAVE'], FxSpec.sci_specobjs[0].optimal['FLAM_SIG']) ax.set_ylim(-2, 30.) # ax.set_xlabel('Wavelength') ax.set_ylabel('Flux (cgs 1e-17)') plt.show() ``` ### Write science frames ``` FxSpec.write_science('tmp.fits') FxSpec.steps ``` ## Instantiate and Load a sensitivity function ``` par['fluxcalib']['sensfunc'] = 'sensfunc.fits' FxSpec2 = fluxspec.FluxSpec(spectrograph, par['fluxcalib']) FxSpec2.show_sensfunc() ``` ## Clean up ``` os.remove('sensfunc.fits') os.remove('tmp.fits') ``` ---- ## Additional Development
github_jupyter
## Simple neural network in plain Python This notebook implements a simple neural network architecture that can map $2$ dimensional input vectors onto binary output values. Our network will have $2$ input neurons, one hidden layer with $6$ hidden neurons and an output layer with $1$ output neuron. We will represent the architecture by means of the weight matrices between the layers. In our example, the weight matrix between the input and hidden layer will be denoted as $W_h$, the weight matrix between the hidden and output layer as $W_o$. In addition to the weights connecting the neurons, each hidden and output neuron will have a bias weight with a constant input of $+1$. Our training set consists of $m = 750$ examples. Therefore, we will have the following matrix shapes: - Training set shape: $X = (750, 2)$ - Targets shape: $Y = (750, 1)$ - $W_h$ shape: $(n_{features}, n_{hidden}) = (2, 6)$ - $b_h$ shape (bias vector): $(1, n_{hidden}) = (1, 6)$ - $W_o$ shape: $(n_{hidden}, n_{outputs}) = (6, 1)$ - $b_o$ shape (bias vector): $(1, n_{outputs}) = (1, 1)$ ![caption](figures/neural_net.png) ### Loss Function We will use the same loss function as in logistic regression: \begin{equation} J(\boldsymbol{w},b) = - \frac{1}{m} \sum_{i=1}^m \Big[ y^{(i)} \log(\hat{y}^{(i)}) + (1 - y^{(i)}) \big(1 - \log(\hat{y}^{(i)})\big) \Big] \end{equation} For a classification task with more than two classes, we would use a generalization of this function, namely the categorical cross-entropy. ### Training We will train our network with gradient descent and we will use backpropagation to compute the required partial derivatives. The training procedure has the following steps: 1. Initialize the parameters (i.e. the weights and biases) 2. Repeat until convergence: 2.1. Propagate the current input batch forward through the network. To do so, compute the activations and outputs of all hidden and output units. 2.2 Compute the partial derivatives of the loss function with respect to each parameter 2.3 Update the parameters ### Forward Pass We start by computing the activation and output of each unit in our network. To speed up the implementation, we won't do this for each input example individually but for all examples at once, using vectorization. We will use the following notation: - $\boldsymbol{A}_h$: matrix with activations of all hidden units for all training examples - $\boldsymbol{O}_h$: matrix with outputs of all hidden units for all training examples The hidden neurons will have $\tanh$ as their activation function: \begin{equation} \tanh(x) = \frac{sinh(x)}{cosh(x)} = \frac{\exp(x) - exp(-x)}{\exp(x) + exp(-x)} \end{equation} \begin{equation} \tanh'(x) = 1 - tanh^2(x) \end{equation} The output neurons will have the $\textit{sigmoid}$ activation function: \begin{equation} \sigma(x) = \frac{1}{1 + \exp(-x)} \end{equation} \begin{equation} \sigma'(x) = 1 - (1 + \sigma(x)) \end{equation} The activations and outputs can then be computed as follows ($\cdot$ denotes the dot product): \begin{equation} \boldsymbol{A}_h = \boldsymbol{X} \cdot \boldsymbol{W}_h + \boldsymbol{b}_h, \text{shape: } (750, 6) \end{equation} \begin{equation} \boldsymbol{O}_h = \sigma(\boldsymbol{A}_h), \text{shape: } (750, 6) \end{equation} \begin{equation} \boldsymbol{A}_o = \boldsymbol{O}_h \cdot \boldsymbol{W}_o + b_o, \text{shape: } (750, 1) \end{equation} \begin{equation} \boldsymbol{O}_o = \sigma(\boldsymbol{A}_o), \text{shape: } (750, 1) \end{equation} ### Backward pass To compute the weight updates we need the partial derivatives of the loss function with respect to each unit. I won't give the derivation of these equations here, you will find plenty of good explanations on other websites (for example [here](https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/)). For the output neurons, the gradients are given by (matrix notation): $\frac{\partial L}{\partial \boldsymbol{A}_o} = d\boldsymbol{A}_o = (\boldsymbol{O}_o - \boldsymbol{Y})$ $\frac{\partial L}{\partial \boldsymbol{W}_o} = \frac{1}{m} (\boldsymbol{O}_h^T \cdot d\boldsymbol{A}_o)$ $\frac{\partial L}{\partial \boldsymbol{b}_o} = \frac{1}{m} \sum d\boldsymbol{A}_o$ For the weight matrix between input and hidden layer we have: $\frac{\partial L}{\partial \boldsymbol{A}_h} = d\boldsymbol{A}_h = (\boldsymbol{W}_o^T \cdot d\boldsymbol{A}_o) * (1 - \tanh^2 (\boldsymbol{A}_h))$ $\frac{\partial L}{\partial \boldsymbol{W}_h} = \frac{1}{m} (\boldsymbol{X}^T \cdot d\boldsymbol{A}_h)$ $\frac{\partial L}{\partial \boldsymbol{b}_h} = \frac{1}{m} \sum d\boldsymbol{A}_h$ ### Weight Update $\boldsymbol{W}_h = \boldsymbol{W}_h - \eta * \frac{\partial L}{\partial \boldsymbol{W}_h}$ $\boldsymbol{b}_h = \boldsymbol{b}_h - \eta * \frac{\partial L}{\partial \boldsymbol{b}_h} $ $\boldsymbol{W}_o = \boldsymbol{W}_o - \eta * \frac{\partial L}{\partial \boldsymbol{W}_o} $ $\boldsymbol{b}_o = \boldsymbol{b}_o - \eta * \frac{\partial L}{\partial \boldsymbol{b}_o} $ ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import make_circles from sklearn.model_selection import train_test_split np.random.seed(123) % matplotlib inline ``` ## Dataset ``` X, y = make_circles(n_samples=1000, factor=0.5, noise=.1) fig = plt.figure(figsize=(8,6)) plt.scatter(X[:,0], X[:,1], c=y) plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) plt.title("Dataset") plt.xlabel("First feature") plt.ylabel("Second feature") plt.show() # reshape targets to get column vector with shape (n_samples, 1) y_true = y[:, np.newaxis] # Split the data into a training and test set X_train, X_test, y_train, y_test = train_test_split(X, y_true) print(f'Shape X_train: {X_train.shape}') print(f'Shape y_train: {y_train.shape}') print(f'Shape X_test: {X_test.shape}') print(f'Shape y_test: {y_test.shape}') ``` ## Neural Network Class Some parts of this implementation are inspired by the exercises of Andrew Ng's [coursera course](https://www.coursera.org/learn/neural-networks-deep-learning) ``` class NeuralNet(): def __init__(self, n_inputs, n_outputs, n_hidden): self.n_inputs = n_inputs self.n_outputs = n_outputs self.hidden = n_hidden # Initialize weight matrices and bias vectors self.W_h = np.random.randn(self.n_inputs, self.hidden) self.b_h = np.zeros((1, self.hidden)) self.W_o = np.random.randn(self.hidden, self.n_outputs) self.b_o = np.zeros((1, self.n_outputs)) def sigmoid(self, a): return 1 / (1 + np.exp(-a)) def forward_pass(self, X): """ Propagates the given input X forward through the net. Returns: A_h: matrix with activations of all hidden neurons for all input examples O_h: matrix with outputs of all hidden neurons for all input examples A_o: matrix with activations of all output neurons for all input examples O_o: matrix with outputs of all output neurons for all input examples """ # Compute activations and outputs of hidden units A_h = np.dot(X, self.W_h) + self.b_h O_h = np.tanh(A_h) # Compute activations and outputs of output units A_o = np.dot(O_h, self.W_o) + self.b_o O_o = self.sigmoid(A_o) outputs = { "A_h": A_h, "A_o": A_o, "O_h": O_h, "O_o": O_o, } return outputs def cost(self, y_true, y_predict, n_samples): """ Computes and returns the cost over all examples """ # same cost function as in logistic regression cost = (- 1 / n_samples) * np.sum(y_true * np.log(y_predict) + (1 - y_true) * (np.log(1 - y_predict))) cost = np.squeeze(cost) assert isinstance(cost, float) return cost def backward_pass(self, X, Y, n_samples, outputs): """ Propagates the errors backward through the net. Returns: dW_h: partial derivatives of loss function w.r.t hidden weights db_h: partial derivatives of loss function w.r.t hidden bias dW_o: partial derivatives of loss function w.r.t output weights db_o: partial derivatives of loss function w.r.t output bias """ dA_o = (outputs["O_o"] - Y) dW_o = (1 / n_samples) * np.dot(outputs["O_h"].T, dA_o) db_o = (1 / n_samples) * np.sum(dA_o) dA_h = (np.dot(dA_o, self.W_o.T)) * (1 - np.power(outputs["O_h"], 2)) dW_h = (1 / n_samples) * np.dot(X.T, dA_h) db_h = (1 / n_samples) * np.sum(dA_h) gradients = { "dW_o": dW_o, "db_o": db_o, "dW_h": dW_h, "db_h": db_h, } return gradients def update_weights(self, gradients, eta): """ Updates the model parameters using a fixed learning rate """ self.W_o = self.W_o - eta * gradients["dW_o"] self.W_h = self.W_h - eta * gradients["dW_h"] self.b_o = self.b_o - eta * gradients["db_o"] self.b_h = self.b_h - eta * gradients["db_h"] def train(self, X, y, n_iters=500, eta=0.3): """ Trains the neural net on the given input data """ n_samples, _ = X.shape for i in range(n_iters): outputs = self.forward_pass(X) cost = self.cost(y, outputs["O_o"], n_samples=n_samples) gradients = self.backward_pass(X, y, n_samples, outputs) if i % 100 == 0: print(f'Cost at iteration {i}: {np.round(cost, 4)}') self.update_weights(gradients, eta) def predict(self, X): """ Computes and returns network predictions for given dataset """ outputs = self.forward_pass(X) y_pred = [1 if elem >= 0.5 else 0 for elem in outputs["O_o"]] return np.array(y_pred)[:, np.newaxis] ``` ## Initializing and training the neural network ``` nn = NeuralNet(n_inputs=2, n_hidden=6, n_outputs=1) print("Shape of weight matrices and bias vectors:") print(f'W_h shape: {nn.W_h.shape}') print(f'b_h shape: {nn.b_h.shape}') print(f'W_o shape: {nn.W_o.shape}') print(f'b_o shape: {nn.b_o.shape}') print() print("Training:") nn.train(X_train, y_train, n_iters=2000, eta=0.7) ``` ## Testing the neural network ``` n_test_samples, _ = X_test.shape y_predict = nn.predict(X_test) print(f"Classification accuracy on test set: {(np.sum(y_predict == y_test)/n_test_samples)*100} %") ``` ## Visualizing the decision boundary In the lowermost plot we can see which parts of the input space are classified as positive and which are classified as negative by the trained network. ``` X_temp, y_temp = make_circles(n_samples=60000, noise=.5) y_predict_temp = nn.predict(X_temp) y_predict_temp = np.ravel(y_predict_temp) fig = plt.figure(figsize=(8,12)) ax = fig.add_subplot(2,1,1) plt.scatter(X[:,0], X[:,1], c=y) plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) plt.xlabel("First feature") plt.ylabel("Second feature") plt.title("Training and test set") ax = fig.add_subplot(2,1,2) plt.scatter(X_temp[:,0], X_temp[:,1], c=y_predict_temp) plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) plt.xlabel("First feature") plt.ylabel("Second feature") plt.title("Decision boundary") ```
github_jupyter
# Writing Functions **Teaching**: 15min<br> **Exercises**: 5min ## Break down programs into functions * Readability: human beings can only keep a few items in working memory at a time. Encapsulate complexity so that we can treat it as a single “thing”. * Reuse: write one time, use many times. * Testing: components with well-defined boundaries are easier to test. ## Define a function using `def` with a name, parameters, and a block of code * Function name must obey the same rules as variable names * Put *parameters* in parentheses * Then a colon, then an indented code block ``` # Empty parentheses if the function doesn't take any inputs: def print_greeting(): print('Hello!') ``` ## Arguments in call are matched to parameters in definition ``` def print_date(year, month, day): joined = str(year) + '/' + str(month) + '/' + str(day) print(joined) print_date(1871, 3, 19) ``` ## Functions may return a result to their caller using `return` * May occur anywhere in the function * But functions are easier to understand if `return` occurs * At the start, to handle special cases * At the very end, with a final result * Functions without explicit `return` produce `None` ``` def average(values): if len(values) == 0: return None return sum(values) / len(values) a = average([1, 3, 4]) print('average of actual values:', a) print('average of empty list:', average([])) result = print_date(1871, 3, 19) print('result of call is:', result) ``` ## Can specify default values for parameters * All paramters with defaults must come *after* all parameters without. * Otherwise, argument-to-parameter matching would be ambigious. * Makes common cases simpler, and signals intent ``` def my_sum(values, scale=1.0): result = 0.0 for v in values: result += v * scale return result print('my_sum with default:', my_sum([1, 2, 3])) print('sum with factor:', my_sum([1, 2, 3], 0.5)) # Succinctly... def my_sum(values, scale=1.0): return sum(v * scale for v in values) ``` ## Can pass parameters by name * Helpful when functions have lots of options > If you have a procedure with ten parameters, you probably missed some. <br>-- from "Epigrams in Programming", by Alan J. Perlis ``` print('out of order:', my_sum(scale=0.25, values=[1, 2, 3])) ``` ## Functions can take a variable number of arguments * Prefix at most one parameter's name with `*`. * By convention, everyone calls the parameters `*args`. * All "extra" paramters are put in a list-like structure assigned to that parameter ``` def total(scale, *args): return sum(a * scale for a in args) print('with one value:', total(0.5, 1)) print('with two values:', total(0.5, 1, 3)) ``` ## Functions can return multiple values * This is just a special case of many-to-many assignment ``` red, green, blue = 10, 50, 180 def order(a, b): if a < b: return a, b else: return b, a low, high = order(10, 5) print('order(10, 5):', low, high) ``` ## Exercise: Find the first Fill in the blanks to create a function that takes a list of numbers as an argument and returns the first negative value in the list. What does your function do if the list is empty? ``` def first_negative(values): for v in ____: if ____: return ____ ``` ## Exercise : Running sum Write a function that calculates the running sum of any number of input arguments, returning the result as a list. For example: * running(1, 2) => [1, 3] * running(-5, 2, 7) => [-5, -3, 4] What should running() return, and why? ## Exercise: How's your phase-change memory? A chalcogenide is a chemical compound consisting of at least one chalcogen anion (commonly restricted to ‘S’, ‘Se’, or ‘Te’) and at least one more electropositive element. Generalize the `halide` function below as `compound_class`, a function that takes a crystal and function as parameters and returns whether or not the compound is of that class. ``` import json from operator import attrgetter import random from pymatgen import Element with open('../data/crystals.json') as f: crystals = json.load(f) def halogen(element): return element.is_halogen def halide(crystal): elts = [Element(s) for s in crystal['elements']] anion = sorted(elts)[-1] # sorts by electronegativity return halogen(anion) def chalcogen(crystal): return element.is_chalogen def compound_class(crystal, predicate): # Fill this in. pass my_crystal = random.sample( [c for c in crystals if halide(c)], 1)[0] assert (compound_class(my_crystal, halogen) == halide(my_crystal)), "`compound_class` fails" ```
github_jupyter
# Homework pandas <table align="left"> <tr> <td><a href="https://colab.research.google.com/github/airnandez/numpandas/blob/master/exam/2020-exam.ipynb"> <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/> </a></td> <td><a href="https://mybinder.org/v2/gh/airnandez/numpandas/master?filepath=exam%2F2020-exam.ipynb"> <img src="https://mybinder.org/badge_logo.svg" alt="Launch Binder"/> </a></td> </tr> </table> *Author: Fabio Hernandez* *Last updated: 2021-04-02* *Location:* https://github.com/airnandez/numpandas/exam -------------------- ## Instructions For this excercise we will use a public dataset curated and made available by [Our World in Data](https://ourworldindata.org) located in [this repository](https://github.com/owid/covid-19-data/tree/master/public/data). We will use a snapshot of the dataset as of 2021-04-02. For your convenience, this notebook is prepared with code for downloading the snapshot dataset from its source, loading it into memory as a **pandas** dataframe and with some cleaning and helper functions. Your mission is execute the provided cells and to write the code to answer the questions below. You must not modify the code provided. You must provide code for answering the questions, following the instructions for each one of them. When you have finished, please save your notebook in the form of a `.ipynb` file and send it to your instructor according to the instructions you received by e-mail. --------------------- ## Dependencies ``` import datetime import os import glob import pandas as pd pd.set_option('display.max_columns', None) pd.__version__ import numpy as np np.__version__ ``` ------ ## Download the dataset Define a helper function for downloading data to a local file: ``` import requests def download(url, path): """Download file at url and save it locally at path""" with requests.get(url, stream=True) as resp: mode, data = 'wb', resp.content if 'text/plain' in resp.headers['Content-Type']: mode, data = 'wt', resp.text with open(path, mode) as f: f.write(data) ``` Download the data files. We store the downloaded data in the directory `../data` relative to the location of this notebook. If a file has been already been downloaded, don't download it again. ``` # Download files data_sources = ( "https://raw.githubusercontent.com/airnandez/numpandas/master/data/2021-04-02-owid-covid-data.csv", ) # Create destination directory os.makedirs(os.path.join('..', 'data'), exist_ok=True) for url in data_sources: # Build the URL and the destination file path path = os.path.join('..', 'data', os.path.basename(url)) # If file already exists don't download it again if not os.path.isfile(path) : print(f'downloading {url} to {path}') download(url, path) ``` Check what files we have for our analysis: ``` file_paths = glob.glob(os.path.join('..', 'data', '2021-*-owid-*')) print('\n'.join(f for f in file_paths)) ``` --------------------- ## Load the data Load the file `2021-04-02-owid-covid-data.csv` to a **pandas** dataframe. ⚠️ **Make sure you get familiar with the contents of that file, by reading the [codebook](https://github.com/owid/covid-19-data/blob/master/public/data/owid-covid-codebook.csv), which describes the meaning of each column.** ``` path = os.path.join('..', 'data', '2021-04-02-owid-covid-data.csv') df = pd.read_csv(path, parse_dates=['date']) df.sample(5) ``` ------------------------ ## Question 1: number of cases, incidence and fatality ratio We want to compute the total number of cases, deaths and fatality ratio in France and in the world as of 2021-04-01. The fatality ratio is the fraction of deaths over the total number of confirmed COVID-19 cases. The incidence is the ratio of the total number of confirmed cases over the population. ### Question 1a (3 points) Compute the total number of cases, deaths, incidence and fatality ratio for France. You must write code to extract the relevant information from the dataframe and assign the appropriate values to the variables defined in the cell below. ``` # Total confirmed cases of COVID-19 in France ... total_cases_fr = ... # Population in France population_fr = ... # Total number of deaths attributed to COVID-19 in France total_deaths_fr = ... # Incidence in France incidence_fr = (total_cases_fr / population_fr) * 100 # Fatality ratio: deaths vs confirmed cases fatality_fr = (total_deaths_fr / total_cases_fr) * 100 print(f'Population in France: {population_fr:>12,.0f}') print(f'Total number of cases in France: {total_cases_fr:>12,.0f}') print(f'Total number of deaths in France: {total_deaths_fr:>12,.0f}') print(f'Incidence in France: {incidence_fr:>12,.2f}%') print(f'Fatality ratio in France: {fatality_fr:>12.2f}%') ``` ### Question 1b (3 points) As done for France in the previous question, here you need to compute the total number of cases, deaths, incidence and fatality ratio for the entire world: ``` # Select data for the whole world ... population_world = ... total_cases_world = ... total_deaths_world = ... incidence_world = (total_cases_world / population_world) * 100 fatality_world = (total_deaths_world / total_cases_world) * 100 print(f'World population {population_world:>14,.0f}') print(f'Total number of cases in the world: {total_cases_world:>14,.0f}') print(f'Total number of deaths in the world: {total_deaths_world:>14,.0f}') print(f'Incidence in the world: {incidence_world:>14,.2f}%') print(f'Fatality ratio in the world: {fatality_world:>14.2f}%') ``` ------------------ ## Question 2 (7 points) Compute and print a list with the name of the **countries** that have administered 80% of the global number of vaccination doses. ⚠️ Please note that in this dataframe there are rows that contain information about a region (e.g. Europe, Asia, World), in addition to information about individual countries. ``` # Select only the rows which contain information about a country (as opposed to a region) # Regions are encoded with a 'iso_code' of the form 'OWID_XXXXX' ... # Compute the vaccination doses administered by all countries ... # Sort the countries by their value of vaccination doses administered ... # Build the list of countries which have administered 80% of the # doses administered around the world .... ``` _____ ## Question 3 (7 points) Compute an ordered list of the top 10 countries with population more than 1 million, ranked by the fraction of their population which have already taken **all the doses** prescribed by the vaccination protocol. ``` # Build a dataframe with one row per country and two columns: 'people_fully_vaccinated' and 'population' .... # Extract the number of people fully vaccinated and the population for each country ... # Among the countries with more than 1M people, select the top 10 # ranked by percentage of fully vaccinated population .... ``` ---------------- ## Bonus question (3 points) The function `plot` below generates an displays a figure for visualizing a set of countries and the percentage of their population which is fully vaccinated. You need to provide the information to visualize the top 10 countries with populations at least 1 million people which have the largest fraction of their population fully vaccinated (see Question 3). To use this function, you must compute two Python lists: * the list `countries` which contains the name of the top 10 countries with population of at least 1 million people, which have the largest fraction of their population fully vaccinated, * the list `percents` which contains the percentage of the fully vaccinated population of those 10 countries After computing those two lists call the function `plot` to visualize the figure, as shown below: ```python countries = [ 'France', 'Germany', 'Italy', ... ] percents = [ 0.3, 0.2, 0.1, ... ] plot(countries, percent) ``` ``` import bokeh import bokeh.plotting bokeh.plotting.output_notebook() def plot(countries, percents): """Generates and displays a Bokeh plot with horizontal bars, one bar per country""" figure = bokeh.plotting.figure( title = 'Percentage of population fully vaccinated (countries with population ≥ 1M)', x_axis_label = 'percentage', x_range = (0, 1), y_range = countries, plot_width = 800, plot_height = 400, background_fill_color = 'whitesmoke', background_fill_alpha = 0.8 ) figure.xaxis.formatter = bokeh.models.formatters.NumeralTickFormatter(format='0%') figure.ygrid.grid_line_color = None figure.hbar(right=percents, y=countries, height=0.5, color='coral') bokeh.plotting.show(figure) countries = ... percents = ... plot(countries, percents) ```
github_jupyter
## First, let's install and import all required libraries ``` #!pip install -r requirements.txt import collections #This library adds some extras to the standard python data structures import folium #Great library for plotting data on maps import json #This library allows us to load and handle json files with python import os #This module is usefull for handling paths and directories import webbrowser #This library allows to handle the webbrowser from python import time import datetime import pandas as pd from folium.plugins import HeatMap ``` ## Now, let's load and analyze our location history json file ``` data = json.load(open('Location_History.json', encoding="utf8")) data type(data) data["locations"] df = pd.DataFrame(data["locations"]) df = df.drop(columns=['activity']) df ``` ## Now we can extract and tranform the data we need to make our map ``` coordinates = collections.defaultdict(int) coordinates unique_coordinates = (0, 0) max_magnitude = 0 """Here you transfor the coordinates given by google in actual longitude and latitude coordinates""" for i, loc in enumerate(data["locations"]): # print(i) # print(loc) if "latitudeE7" not in loc or "longitudeE7" not in loc: continue coords = (round(loc["latitudeE7"] / 1e7, 6), round(loc["longitudeE7"] / 1e7, 6)) # print(coords) """Here you calculate the magnitude for all coordinates""" #print(loc["timestampMs"]) coordinates[coords] += 1 #these are the magnitude values we will need for the coordinates dictionary #print(coordinates[coords]) if coordinates[coords] > max_magnitude: unique_coordinates = coords max_magnitude = coordinates[coords] #print(unique_coordinates) #print(max_magnitude) coordinates tilesoptions = ["openstreetmap", "StamenTerrain", "stamentoner", "stamenwatercolor", "cartodbpositron", "cartodbdark_matter"] tiles = tilesoptions[0] zoom_start = 10 radius = 7 blur = 4 min_opacity = 0.2 max_zoom = 10 map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in coordinates.items()] map_data # Generate background map m = folium.Map(location=unique_coordinates, zoom_start=zoom_start, tiles=tiles) # Generate heat map heatmap = HeatMap(map_data, max_val=max_magnitude, min_opacity=min_opacity, radius=radius, blur=blur, max_zoom=max_zoom) # Combine both maps m.add_child(heatmap) ``` ## We can now save our map as an html file and launch it in the browser ``` output_file = tiles + 'heatmapSpicedStudent.html' m.save(output_file) webbrowser.open("file://" + os.path.realpath(output_file)) ``` ## Now let's wrap everything into functions and play with it ``` def transformcoordinates(inputdata): coordinates = collections.defaultdict(int) unique_coordinates = (0, 0) max_magnitude = 0 for i, loc in enumerate(inputdata): # print(i) # print(loc) if "latitudeE7" not in loc or "longitudeE7" not in loc: continue coords = (round(loc["latitudeE7"] / 1e7, 6), round(loc["longitudeE7"] / 1e7, 6)) # print(coords) """Here you calculate the magnitude for all coordinates""" #print(loc["timestampMs"]) coordinates[coords] += 1 #these are the magnitude values we will need for the coordinates dictionary #print(coordinates[coords]) if coordinates[coords] > max_magnitude: unique_coordinates = coords max_magnitude = coordinates[coords] #print(unique_coordinates) #print(max_magnitude) return coordinates coordinates = transformcoordinates(data["locations"]) coordinates def plotmymaps(Tiles, Zoom_start=10, Radius=7, Blur=4, Min_opacity=0.2, Max_zoom=10): tilesoptions = ["openstreetmap", "StamenTerrain", "stamentoner", "stamenwatercolor", "cartodbpositron", "cartodbdark_matter"] tiles = tilesoptions[Tiles] zoom_start = Zoom_start radius = Radius blur = Blur min_opacity = Min_opacity max_zoom = Max_zoom map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in coordinates.items()] # Generate background map m = folium.Map(location=unique_coordinates, zoom_start=zoom_start, tiles=tiles) # Generate heat map heatmap = HeatMap(map_data, max_val=max_magnitude, min_opacity=min_opacity, radius=radius, blur=blur, max_zoom=max_zoom) m.add_child(heatmap) output_file = tiles + 'heatmapSpicedStudent.html' m.save(output_file) webbrowser.open("file://" + os.path.realpath(output_file)) plotmymaps(5,3,3,3,3,3) ``` ## What if we only want to plot data for a specific time range? ``` df min_date='2020-1-1' max_date='2020-1-31' def transformdate(date): element = datetime.datetime.strptime(date,"%Y-%m-%d") elementtuple = element.timetuple() timestamp = time.mktime(elementtuple) return timestamp min_timestamp=(transformdate(min_date))*1000 min_timestamp max_timestamp=(transformdate(max_date))*1000 max_timestamp df["timestampMs"] = pd.to_numeric(df["timestampMs"]) df2 = df[df.timestampMs > min_timestamp] df2 = df2[df.timestampMs < max_timestamp] df2 df2.to_json('tempStudents.json', orient='records', lines=True) data2 = [json.loads(line) for line in open('tempStudents.json', 'r')] data2 coordinates = transformcoordinates(data2) coordinates plotmymaps(1) ```
github_jupyter
### Web scrapping. Load table from website. NOTE: Clean data is loaded later in case website is no longer available. ### Team Name ``` team_name = 'Rams' #https://www.coursera.org/learn/python-plotting/discussions/weeks/4/threads/yMT7zw2KEeeqzRJFs29uDA import pandas as pd from IPython.display import display, HTML def install_module(module): ! conda install "$module" -y js_cmd = ['IPython.notebook.kernel.restart();', 'IPython.notebook.select(1);', 'IPython.notebook.execute_cell();' ] js = "<script>{0}</script>".format(' '.join(js_cmd)) display(HTML(js)) #url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states' url = 'https://en.wikipedia.org/wiki/List_of_Los_Angeles_Rams_seasons' try: df_list = pd.read_html(url) except Exception as e: print(e) # #install necessary modules for read_html module = str(e).split()[0] install_module(module) print('Number of Data Frames {}'.format(len(df_list))) df_list[0].columns = df_list[0].iloc[0] df = df_list[0].iloc[1:] df.head() ``` ### Multiple tables found. Capture them all in a list of dataframes. ``` # https://stackoverflow.com/questions/42225204/use-pandas-to-get-multiple-tables-from-webpage import urllib from bs4 import BeautifulSoup url = 'https://en.wikipedia.org/wiki/List_of_Los_Angeles_Rams_seasons' html_table = urllib.request.urlopen(url).read() # fix HTML soup = BeautifulSoup(html_table, "html.parser") # warn! id ratings-table is your page specific for table in soup.findChildren(attrs={'id': 'ratings-table'}): for c in table.children: if c.name in ['tbody', 'thead']: c.unwrap() list_df = pd.read_html(str(soup), flavor="bs4") len(list_df[0]) ``` ### This is the table we are interested it. ``` #list_df[2][15:].head() #list_df[0].head() #list_df[0].tail(10) df_rams = list_df[2] df_rams.head() ``` ### Save raw data .csv ``` file_name = team_name +'_data_raw' #csv df_rams.to_csv( file_name +'.csv') ``` ### Clean the data. Make the first row the header for the columns. ``` # Make the first row the header column # NOTE: This does not get rid of the row. df_rams.columns = df_rams.iloc[0] # Re-index and drop the first row. df_rams_cleaned = df_rams.reindex(df_rams.index.drop(0)) # Keep the rows we want (i.e. the years they became the team for the city.) df_rams_cleaned = df_rams_cleaned[37:87] # Drop the rows we do not need. df_rams_cleaned.reset_index(drop = True, inplace = True) df_rams_cleaned = df_rams_cleaned.drop(df_rams_cleaned.index[[25,47,49]]) # Keep columns of interest. # https://stackoverflow.com/questions/14940743/selecting-excluding-sets-of-columns-in-pandas columns_to_keep = ['Season', 'Postseason results', 'Awards'] df_rams_cleaned = df_rams_cleaned[columns_to_keep] # Rename the columns df_rams_cleaned.columns = ['Season', 'Wins', 'Losses'] # Change the year to have only the first year and not a range. # i.e. 1960 and not 1961-62 df_rams_cleaned['Season'] = df_rams_cleaned['Season'].apply(lambda x: x[:4]) # # # Check type # # #df_rams_cleaned.dtypes # # # NOTE: # # # Year 2004-05, Season cancelled due to 2004–05 NHL lockout # # # # # # https://stackoverflow.com/questions/18434208/pandas-converting-to-numeric-creating-nans-when-necessary df_rams_cleaned = df_rams_cleaned.apply(pd.to_numeric, errors='coerce') #df_rams_cleaned['Wins'] = df_rams_cleaned['Wins'].apply(pd.to_numeric, errors='coerce') # # df_rams_cleaned['Losses'] = df_rams_cleaned['Losses'].apply(pd.to_numeric, errors='coerce') # # # Convert to date float because int64 can't use NaN (not a number) # # # https://stackoverflow.com/questions/41550746/error-using-astype-when-nan-exists-in-a-dataframe # # # # # #df_rams_cleaned['Season'] = df_rams_cleaned['Season'].astype('int64') df_rams_cleaned = df_rams_cleaned.astype('float') # # #df_rams_cleaned = df_rams_cleaned.astype('int64') # # # Front fill and NaN value. # # # Front fill means use the last known value # # # Back fill means use the next known value df_rams_cleaned = df_rams_cleaned.ffill() # # # Check type # # # df_rams_cleaned.dtypes # # # Make column of win percent df_rams_cleaned['Win_Percent'] = df_rams_cleaned['Wins'] / (df_rams_cleaned['Wins'] + df_rams_cleaned['Losses']) # Make column for moving average (rolling mean) # # NOTE: You will not see the rolling mean for the first few rows because you need # the minimum window size before it calculates. # This will be deprecated in the future # df_rams_cleaned['Rolling Mean'] = pd.rolling_mean( df_rams_cleaned['Wins'], # # # window to calculate # 10) df_rams_cleaned['Rolling_Mean'] = df_rams_cleaned['Win_Percent'].rolling( window = 10, center = False).mean() # Only save from 1980 because that is the only # overlap from all the data. # # NOTE: Not including 2017 to line up with the other data. df_rams_cleaned = df_rams_cleaned[10:] # Reset index. # NOTE: drop = True means do not make a new index and keep old. # inplace = True means update this variable and not return a copy # leaving original intact. df_rams_cleaned.reset_index(drop = True, inplace = True) # # #df_rams_cleaned.head(20) df_rams_cleaned ``` ### Save clean data to .csv ``` file_name = team_name +'_data_cleaned' #csv df_rams_cleaned.to_csv( file_name +'.csv') ``` ### Load clean data from file instead of web scrapping. ``` file_name = team_name +'_data_cleaned' df_rams_cleaned = pd.read_csv( file_name +'.csv', # Use the first column as the index index_col = 0) df_rams_cleaned.tail() ``` ### Plot moving average ``` import matplotlib.pyplot as plt import numpy as np #---------------- # Variables # (Start) #---------------- graph_color = 'orange' #---------------- # Variables # (End) #---------------- # Create new figure fig_lakers = plt.figure(figsize = (16,8)) ax = fig_lakers.add_subplot(111) # TODO # # -Set title # -Set x label # -Set y lable # -Set x-axis to be the whole data but only show 10 year intervals # -Set y-axis for 0.0 to 1.0 but have dotted lines from 0.0, 0.25, 0.75, 1.0 BUT only use the highest that contain data. # -Set thick lines. # -Set dotted lines at y-axis intervals # -Set annotations for names of team next to plot lines # -Set annotations for win% # Remove plot box # Change the name of the figure to be generic for all teams and the save image. # Title plt.title('Los Angeles Sports Teams Win %' '\n(10 Year Moving Average)', fontsize=20 ) # Labels for x and y axes plt.xlabel( 'Season', fontsize=15 ) plt.ylabel( '10 Year Moving Average Win %', fontsize=15 ) # Create graph plot_lakers = plt.plot( df_rams_cleaned['Season'], df_rams_cleaned['Rolling_Mean'], c=graph_color, label='Lakers') # Set limit on x-axis #ax.set_xlim([datetime.date(2016, 1, 1), datetime.date(2016, 12, 31)]) ax.set_ylim(0.0, 0.85) # Set line thickness and style (like dotted) # https://matplotlib.org/examples/pylab_examples/set_and_get.html # plt.setp(plot_lakers, # linestyle='--') plt.setp(plot_lakers, linewidth=4) # https://stackoverflow.com/questions/24943991/matplotlib-change-grid-interval-and-specify-tick-labels # # Set x-axis to be the whole data but only show 10 year intervals x_major_ticks = np.arange(1980, 2020, 10) #x_minor_ticks = np.arange(1980, 2020, 1) # ax.set_xticks(x_major_ticks) # ax.set_xticks(x_minor_ticks, minor=True) # # Set y-axis for 0.0 to 1.0 but have dotted lines from 0.0, 0.25, 0.75, 1.0 BUT only use the highest that contain data. y_major_ticks = np.arange(0.0, 1.1, 0.25) # # Slice to exclude the first and last entry. #y_major_ticks = y_major_ticks[:-1] ax.set_yticks(y_major_ticks) # Draw horizontal lines for num in y_major_ticks: plt.axhline(y = num, linestyle = '--', color = 'grey', alpha = 0.2 ) # Text for team names. # Setting up equations in matplotlib text. # https://matplotlib.org/users/mathtext.html #team_name = 'Lakers' x_pos = 2017 y_pos = df_rams_cleaned['Rolling_Mean'].iloc[-1] team_color = graph_color font_size = 10 # # Drop Shadow # plt.text(x_pos + 0.0005, # y_pos - 0.0005, # team_name, # color = 'black', # fontsize = font_size) plt.text(x_pos, y_pos, team_name, color = team_color, fontsize = font_size) # Legend plt.text(1980, 0.1, #'Win % = Games Won\(Games Won + Games Lost)', #r'$\frac{5 - \frac{1}{x}}{4}$', r'Win % = $\frac{Games Won}{Games Won + Games Lost}$', fontsize = 15, bbox={'facecolor':'lightgrey', 'alpha':0.5, 'pad':5}) # Remove axis #plt.axis('off') ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Show the graph. plt.show() ``` ### Save graph to .png ``` # https://stackoverflow.com/questions/9012487/matplotlib-pyplot-savefig-outputs-blank-image # plt.show() creates a new figure. # Use the figure captured when created. #plt.savefig('Los_Angeles_Sports_Teams_Win_Percentage.png') file_name = team_name +'_win_percentage' # For some reason, matplotlib saves the image name with upper case as the first letter # even if it is lowercase. fig_lakers.savefig( file_name +'.png' ) ```
github_jupyter
# multi-band constraints for HEB scenarios in TOI-837 ``` import chronos as cr import numpy as np TEFF = 6047 #± 406 FEH = -0.065 #± 0.035 LOGG = 4.467 #± 0.01 RSTAR = 1.022 #±0.015 MSTAR = 1.118 #±0.011 LOG10AGE = np.log10(40e6) DELTA_OBS_TESS = 0.004 import astropy.units as u t.toi_params['Planet Radius (R_Earth) err']*u.Rearth.to(u.Rsun)/t.toi_params['Stellar Radius (R_Sun) err'] import matplotlib.pyplot as pl from scipy.interpolate import interp1d #timmy/drivers/contrast_to_masslimit.py import numpy as np from astropy.modeling.models import BlackBody from astropy import units as u from astropy import constants as const M_bol_sun = 4.83 # from isochrones.mist import MISTIsochroneGrid # mist_iso_grid = MISTIsochroneGrid() # def get_isochrones(age, feh, cols='Teff mass logL'.split(), # age_tol=0.1, feh_tol=0.1 # ): # """ # get Lstar, Teff, Mstar from isochrones given system age and metallicity # """ # df = mist_iso_grid.df # #age # age_indices = df.index.get_level_values(0).unique() # nearest_age_index = np.argmin(np.abs(age_indices - age)) # nearest_age = age_indices[nearest_age_index] # errmsg=f"{age:.2f}-{nearest_age:.2f}={age-nearest_age:.2f}<{age_tol}" # assert np.allclose(age, nearest_age, atol=age_tol), errmsg # #feh # feh_indices = df.index.get_level_values(1).unique() # nearest_feh_index = np.argmin(np.abs(feh_indices - feh)) # nearest_feh = feh_indices[nearest_feh_index] # errmsg=f"{feh:.2f}-{nearest_feh:.2f}={feh-nearest_feh:.2f}<{feh_tol}" # assert np.allclose(feh, nearest_feh, atol=feh_tol), errmsg # df = df.loc[nearest_age, nearest_feh][cols].reset_index(drop=True) # return df # def _find_nearest_index(df, param, value): # return np.argmin(np.abs(np.array(df[param]) - value)) from isochrones.mist import MIST_EvolutionTrack mist_track = MIST_EvolutionTrack() def get_isochrones(mass, log10age, feh, cols='Teff mass radius logL'.split()): """interpolate params""" eep = mist_track.get_eep(mass, log10age, feh) return mist_track.interp_value([mass, eep, feh], cols) def get_blackbody_functions(teffs, lums, wvlen): """ returns dict for each component teff and lum """ B_lambda_dict = {} for ix, (temperature, luminosity) in enumerate(zip(teffs*u.K, lums*u.Lsun)): bb = BlackBody(temperature=temperature) B_nu_vals = bb(wvlen) B_lambda_vals = ( B_nu_vals * (const.c / wvlen**2) ).to(u.erg/u.nm/u.s/u.sr/u.cm**2) B_lambda_dict[ix] = B_lambda_vals return B_lambda_dict def get_luminosity(teff, rstar): return (4*np.pi*(rstar*u.Rsun)**2 * const.sigma_sb*(teff*u.K)**4).to(u.Lsun).value def get_rstar(teff, luminosity): return np.sqrt( luminosity / (4*np.pi * const.sigma_sb * teff**4) ).to(u.Rsun).value def get_filter_transmissions(bandpasses): """ bandpasses: list telescope/filter format """ filter_transmissions = {} for bp in bandpasses: telescope, filter = bp.split('/') bpdf = cr.get_filter_transmission_from_SVO(filter, telescope) filter_transmissions[bp] = bpdf return filter_transmissions def get_bolometric_magnitude_from_SED(teffs, lums, wav_nm, transmission): """ """ M_Xs = [] for temperature, luminosity in zip(teffs*u.K, lums*u.Lsun): bb = BlackBody(temperature=temperature) wvlen = np.array(wav_nm)*u.nm B_nu_vals = bb(wvlen) B_lambda_vals = B_nu_vals * (const.c / wvlen**2) T_lambda = np.array(transmission) F_X = 4*np.pi*u.sr * np.trapz(B_lambda_vals * T_lambda, wvlen) F = const.sigma_sb * temperature**4 # https://nssdc.gsfc.nasa.gov/planetary/factsheet/sunfact.html M_bol_star = ( -5/2 * np.log10(luminosity/(1*u.Lsun)) + M_bol_sun ) # bolometric magnitude of the star, in the bandpass! M_X = M_bol_star - 5/2*np.log10( F_X/F ) M_Xs.append(M_X.value) return M_Xs def get_delta_obs_given_mstars(m2, m3, m1=MSTAR, filter_transmissions, make_plot=0, verbose=1): """ Given a hierarchical eclipsing binary system (HEB), where Star 1 is the main source of light, and Stars 2 and 3 are eclipsing, compute the observed eclipse depth of Star 3 in front of Star 2 in each of a number of bandpasses, assuming maximum large eclipses, and blackbodies. This also assumes MIST isochrones. Steps: * get Lstar, Teff, Mstar from isochrones given system age and metallicity * interpolate Lstar & Teff given component masses * compute blackbody functions given Teffs * get instrument filter transmission response function from SVO * integrate blackbody and transmission function using np.trapz * compute Fbol using integrated functions above * compute Rstar using stefan-boltzman law given isochronal Teff/Lstar * compute Lstar given Rstar and Fbol * compute depth from Lstar assuming tertiary eclipsing the secondary """ assert isinstance(filter_transmissions, dict) mstars = np.array([m1, m2, m3]) # #get Lstar, Teff, Mstar from isochrones given system age and metallicity # df_ic = get_isochrones(LOG10AGE, FEH) # df_ic['lum'] = 10**(df_ic.logL) # #interpolate Lstar & Teff given component masses # m1_idx = _find_nearest_index(df_ic, 'mass', m1) # m2_idx = _find_nearest_index(df_ic, 'mass', m2) # m3_idx = _find_nearest_index(df_ic, 'mass', m3) # teff1 = TEFF #teff1 = df_ic.loc[m1_idx, 'Teff'] # teff2 = df_ic.loc[m2_idx, 'Teff'] # teff3 = df_ic.loc[m3_idx, 'Teff'] # lum1 = get_luminosity(teff1, RSTAR) #lum1 = df_ic.loc[m1_idx, 'lum'] # lum2 = df_ic.loc[m2_idx, 'lum'] # lum3 = df_ic.loc[m3_idx, 'lum'] teff1, mass, radius, logL1 = get_isochrones(m1, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum1 = 10**(logL) teff2, mass, radius, logL2 = get_isochrones(m2, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum2 = 10**(logL2) teff3, mass, radius, logL3 = get_isochrones(m3, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum3 = 10**(logL3) teffs = np.array([teff1, teff2, teff3]) lums = np.array([lum1, lum2, lum3]) #compute blackbody functions given Teffs wvlen = np.logspace(1, 5, 2000)*u.nm B_lambda_dict = get_blackbody_functions(teffs, lums, wvlen) # get the flux in each bandpass F_X_dict = {} F_dict = {} M_X_dict = {} M_dict = {} T_dict = {} L_X_dict = {} bandpasses = list(filter_transmissions.keys()) for bp in bandpasses: # get filter transmission from SVO bpdf = filter_transmissions[bp] bp_wvlen = np.array(bpdf['wav_nm']) T_lambda = np.array(bpdf.transmission) if np.nanmax(T_lambda) > 1.1: if np.nanmax(T_lambda) < 100: T_lambda /= 100 # unit convert else: raise NotImplementedError eps = 1e-6 if not np.all(np.diff(bp_wvlen) > eps): raise NotImplementedError interp_fn = interp1d(bp_wvlen, T_lambda, bounds_error=False, fill_value=0, kind='quadratic') T_lambda_interp = interp_fn(wvlen) T_dict[bp] = T_lambda_interp F_X_dict[bp] = {} M_X_dict[bp] = {} L_X_dict[bp] = {} # # for each star, calculate erg/s in bandpass # NOTE: the quantity of interest is in fact counts/sec. # (this is probably a small consideration, but could still be worth # checking) # rstars = [] for ix, (temperature, luminosity) in enumerate(zip(teffs*u.K, lums*u.Lsun)): # flux (erg/s/cm^2) in bandpass _F_X = ( 4*np.pi*u.sr * np.trapz(B_lambda_dict[ix] * T_lambda_interp, wvlen) ) F_X_dict[bp][ix] = _F_X # bolometric flux, according to the blackbody function _F_bol = ( 4*np.pi*u.sr * np.trapz(B_lambda_dict[ix] * np.ones_like(T_lambda_interp), wvlen) ) # stefan-boltzman law to get rstar from the isochronal temp/lum. rstar = get_rstar(temperature, luminosity) rstars.append(rstar) # erg/s in bandpass _L_X = _F_X * 4*np.pi * rstar**2 L_X_dict[bp][ix] = _L_X.cgs if DEBUG: print(42*'-') print(f'{_F_X:.2e}, {_F_bol:.2e}, {L_X_dict[bp][ix]:.2e}') if ix not in F_dict.keys(): F_dict[ix] = _F_bol # get bolometric magnitude of the star, in the bandpass, as a # sanity check M_bol_star = ( -5/2 * np.log10(luminosity/(1*u.Lsun)) + M_bol_sun ) M_X = M_bol_star - 5/2*np.log10( F_X_dict[bp][ix]/F_dict[ix] ) if ix not in M_dict.keys(): M_dict[ix] = M_bol_star.value M_X_dict[bp][ix] = M_X.value delta_obs_dict = {} for k in L_X_dict.keys(): # out of eclipse L_ooe = L_X_dict[k][0] + L_X_dict[k][1] + L_X_dict[k][2] # in eclipse. assume maximum depth f = (rstars[2]/rstars[1])**2 L_ie = L_X_dict[k][0] + L_X_dict[k][2] + (1-f)*L_X_dict[k][1] # assume the tertiary is eclipsing the secondary. delta_obs_dict[k] = ( (L_ooe - L_ie)/L_ooe ).value if verbose: for k in delta_obs_dict.keys(): print(f'{k}: {delta_obs_dict[k]:.2e}') if make_plot: from astropy.visualization import quantity_support pl.close('all') linestyles = ['-','-','--'] f, ax = pl.subplots(figsize=(8,6)) with quantity_support(): for ix in range(3): l = f'{teffs[ix]:.0f} K, {mstars[ix]:.3f} M$_\odot$' ax.plot(wvlen, B_lambda_dict[ix], ls=linestyles[ix], label=l) ax.set_yscale('log') ax.set_ylim([1e-3,10*np.nanmax(np.array(list(B_lambda_dict.values())))]) ax.set_xlabel('Wavelength [nm]') ax.legend(loc='best')#, fontsize='xx-small') ax.set_ylabel('$B_\lambda$ [erg nm$^{-1}$ s$^{-1}$ sr$^{-1}$ cm$^{-2}$ ]') tax = ax.twinx() tax.set_ylabel('Transmission [%]') for k in T_dict.keys(): sel = T_dict[k] > 0 tax.plot(wvlen[sel], 100*T_dict[k][sel], c='k', lw=0.5) tax.set_xscale('log') tax.set_ylim([0,105]) ax.set_xlim([5e1, 1.1e4]) f.tight_layout() return delta_obs_dict ``` ## isochrones ``` # df_ic = get_isochrones(LOG10AGE, FEH) # df_ic['lum'] = 10**(df_ic.logL) # df_ic teff, mass, radius, logL = get_isochrones(MSTAR, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) teff, mass, radius, logL ``` ## filter transmissions ``` filter_transmissions = {} t = cr.get_filter_transmission_from_SVO('Red', 'TESS') b = cr.get_filter_transmission_from_SVO('R', 'Generic', 'Cousins') #proxy to ASTEP400 r = cr.get_filter_transmission_from_SVO('B', 'Generic', 'Johnson') #proxy to El Sauce filter_transmissions['TESS/Red'] = t filter_transmissions['Cousins-R'] = r filter_transmissions['Johnson-B'] = b ax = t.plot(x='wav_nm', y='transmission', label='TESS/Red') _ = b.plot(ax=ax, x='wav_nm', y='transmission', label='Cousins-R') _ = r.plot(ax=ax, x='wav_nm', y='transmission', label='Johnson-B') ax.set_xlabel('wavelength [nm]') ax.set_ylabel('Transmission') filter_transmissions ``` ## blackbodies ``` #interpolate Lstar & Teff given component masses m1, m2, m3 = MSTAR, 0.4, 0.6 mstars = np.array([m1, m2, m3]) # #get Lstar, Teff, Mstar from isochrones given system age and metallicity # df_ic = get_isochrones(LOG10AGE, FEH) # df_ic['lum'] = 10**(df_ic.logL) # #interpolate Lstar & Teff given component masses # m1_idx = _find_nearest_index(df_ic, 'mass', m1) # m2_idx = _find_nearest_index(df_ic, 'mass', m2) # m3_idx = _find_nearest_index(df_ic, 'mass', m3) # teff1 = df_ic.loc[m1_idx, 'Teff'] #TEFF # teff2 = df_ic.loc[m2_idx, 'Teff'] # teff3 = df_ic.loc[m3_idx, 'Teff'] # lum1 = df_ic.loc[m1_idx, 'lum']#get_luminosity(teff1, RSTAR) # lum2 = df_ic.loc[m2_idx, 'lum'] # lum3 = df_ic.loc[m3_idx, 'lum'] teff1, mass, radius, logL1 = get_isochrones(m1, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum1 = 10**(logL) teff2, mass, radius, logL2 = get_isochrones(m2, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum2 = 10**(logL2) teff3, mass, radius, logL3 = get_isochrones(m3, LOG10AGE, FEH, cols='Teff mass radius logL'.split() ) lum3 = 10**(logL3) teffs = np.array([teff1, teff2, teff3]) lums = np.array([lum1, lum2, lum3]) #compute blackbody functions given Teffs wvlen = np.logspace(1, 5, 2000)*u.nm B_lambda_dict = get_blackbody_functions(teffs, lums, wvlen) pl.plot(wvlen, B_lambda_dict[0], label=f'm1={m1:.2f}') pl.plot(wvlen, B_lambda_dict[1], label=f'm2={m2:.2f}') pl.plot(wvlen, B_lambda_dict[2], ls='--', label=f'm3={m3:.2f}') pl.xscale('log') pl.legend(title='mass [Msun]') pl.xlabel('Wavelength [nm]') pl.ylabel('$B_\lambda$ [erg nm$^{-1}$ s$^{-1}$ sr$^{-1}$ cm$^{-2}$ ]') pl.xlim(1e2,2e3) ``` ## bolometric flux ``` for ix,bp in enumerate(filter_transmissions): bpdf = filter_transmissions[bp] bp_wvlen = np.array(bpdf['wav_nm']) T_lambda = np.array(bpdf.transmission) #interpolate interp_fn = interp1d(bp_wvlen, T_lambda, bounds_error=False, fill_value=0, kind='quadratic') T_lambda_interp = interp_fn(wvlen) #flux _F_X = 4*np.pi*u.sr * np.trapz(B_lambda_dict[ix] * T_lambda_interp, wvlen) # bolometric flux, according to the blackbody function _F_bol = 4*np.pi*u.sr * np.trapz(B_lambda_dict[ix] * np.ones_like(T_lambda_interp), wvlen) pl.plot(B_lambda_dict[ix] * T_lambda_interp, label=f'{_F_bol.value:.2e}') pl.xlim(7e2,1.2e3) pl.legend(title=f'Fbol ({_F_bol.unit})') ``` ## maximum eclipse depths ``` colors = { 'TESS/Red': 'r', 'Johnson-B': 'g', 'Cousins-R': 'b' } def plot_depth_per_passband(depths, filter_transmissions, masses): m1,m2,m3 = masses bp = 'TESS/Red' df = filter_transmissions[bp] ax = df.plot(x='wav_nm', y='transmission', ls='--', c=colors[bp], label=bp) bandpasses = list(filter_transmissions.keys()) for bp in bandpasses[1:]: df = filter_transmissions[bp] df.plot(ax=ax, x='wav_nm', y='transmission', ls='--', c=colors[bp], label=bp) ax.set_xlabel('wavelength [nm]') ax.set_ylabel('Transmission') ax.set_title(f'm1={m1}, m2={m2}, m3={m3} [Msun]') ax.set_ylim(0,1) tax = ax.twinx() tax.set_ylabel('Eclipse Depth') for bp in bandpasses: x1 = filter_transmissions[bp].wav_nm.min() x2 = filter_transmissions[bp].wav_nm.max() tax.hlines(depths[bp], x1, x2, color=colors[bp]) tax.set_xscale('log') tax.set_ylim(0,1) return ax ``` ### equal mass triple star system ``` DEBUG = False m2, m3 = 0.8, 0.8 depths = get_delta_obs_given_mstars(m2, m3, MSTAR, filter_transmissions, make_plot=True, verbose=True ) ax = plot_depth_per_passband(depths, filter_transmissions, [MSTAR,m2,m3]) ``` ### low-mass companions ``` m2, m3 = 0.4, 0.6 depths = get_delta_obs_given_mstars(m2, m3, MSTAR, filter_transmissions, make_plot=True, verbose=True ) ax = plot_depth_per_passband(depths, filter_transmissions, [MSTAR,m2,m3]) ``` For a typical HEB system with low-mass companion, the g-band produces an eclipse roughly 2 times shallower than in z-band, because the M-dwarf blackbody function emits more energy (roughly factor of 10) at longer wavelengths than the G-dwarf blackbody. ### higher-mass companions ``` m2, m3 = 0.9, 1.1 depths = get_delta_obs_given_mstars(m2, m3, MSTAR, filter_transmissions, make_plot=True, verbose=True ) ax = plot_depth_per_passband(depths, filter_transmissions, [MSTAR,m2,m3]) ``` ## mass grid ``` from tqdm import tqdm N_samples = 20 m2s = np.linspace(0.1, 1.0, N_samples) m3s = np.linspace(0.1, 1.0, N_samples) mass_grid_tess = np.zeros((N_samples,N_samples)) mass_grid_b = np.zeros((N_samples,N_samples)) mass_grid_r = np.zeros((N_samples,N_samples)) for i,m2 in tqdm(enumerate(m2s)): for j,m3 in enumerate(m3s): depths = get_delta_obs_given_mstars(m2, m3, MSTAR, filter_transmissions, make_plot=False, verbose=False ) mass_grid_tess[i,j] = depths['TESS/Red'] mass_grid_r[i,j] = depths['Cousins-R'] mass_grid_b[i,j] = depths['Johnson-B'] import matplotlib.colors as mcolors import matplotlib.pyplot as pl pl.style.use("default") class MidPointLogNorm(mcolors.LogNorm): """ Log normalization with midpoint offset from https://stackoverflow.com/questions/48625475/python-shifted-logarithmic-colorbar-white-color-offset-to-center """ def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): mcolors.LogNorm.__init__(self,vmin=vmin, vmax=vmax, clip=clip) self.midpoint=midpoint def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [np.log(self.vmin), np.log(self.midpoint), np.log(self.vmax)], [0, 0.5, 1] return np.ma.masked_array(np.interp(np.log(value), x, y)) def plot_eclipse_depth_grid(mass_grid, depth, bandpass): """ """ fig, ax = pl.subplots(1,1, figsize=(8,4)) xmin, xmax = m2s[0], m2s[-1] ymin, ymax = m3s[0], m3s[-1] #make a diverging color map such that profit<0 is red and blue otherwise cmap = pl.get_cmap('RdBu_r') norm = MidPointLogNorm(vmin=mass_grid.min(), vmax = 1, #mass_grid.max(), midpoint=depth ) #plot matrix cbar = ax.imshow(mass_grid, origin='lower', interpolation='none', extent=[xmin, xmax, ymin, ymax], cmap=cmap, norm=norm ) pl.colorbar(cbar, ax=ax, shrink=0.9, label='eclipse depth', orientation="vertical") # add labels # ax.set_aspect(5) pl.setp(ax, xlim=(xmin,xmax), ylim=(ymin,ymax), xlabel='secondary star mass (Msun)', ylabel='tertiary star mass (Msun)', title=f'HEB eclipse depths in {bandpass}' ); return fig DELTA_OBS_TESS fig = plot_eclipse_depth_grid(mass_grid_tess, DELTA_OBS_TESS, 'TESS/Red') depth_r = 0.00282 fig = plot_eclipse_depth_grid(mass_grid_r, depth_r, 'Cousins-R') depth_b = 0.00177 fig = plot_eclipse_depth_grid(mass_grid_b, depth_b, 'Johnson-B') ```
github_jupyter
# Week 4: Multi-class Classification Welcome to this assignment! In this exercise, you will get a chance to work on a multi-class classification problem. You will be using the [Sign Language MNIST](https://www.kaggle.com/datamunge/sign-language-mnist) dataset, which contains 28x28 images of hands depicting the 26 letters of the english alphabet. You will need to pre-process the data so that it can be fed into your convolutional neural network to correctly classify each image as the letter it represents. Let's get started! ``` import csv import string import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img %%capture !pip install --upgrade --no-cache-dir gdown ``` Download the training and test sets (the test set will actually be used as a validation set): ``` # sign_mnist_train.csv !gdown --id 1z0DkA9BytlLxO1C0BAWzknLyQmZAp0HR # sign_mnist_test.csv !gdown --id 1z1BIj4qmri59GWBG4ivMNFtpZ4AXIbzg ``` Define some globals with the path to both files you just downloaded: ``` TRAINING_FILE = './sign_mnist_train.csv' VALIDATION_FILE = './sign_mnist_test.csv' ``` Unlike previous assignments, you will not have the actual images provided, instead you will have the data serialized as `csv` files. Take a look at how the data looks like within the `csv` file: ``` with open(TRAINING_FILE) as training_file: line = training_file.readline() print(f"First line (header) looks like this:\n{line}") line = training_file.readline() print(f"Each subsequent line (data points) look like this:\n{line}") ``` As you can see, each file includes a header (the first line) and each subsequent data point is represented as a line that contains 785 values. The first value is the label (the numeric representation of each letter) and the other 784 values are the value of each pixel of the image. Remember that the original images have a resolution of 28x28, which sums up to 784 pixels. ## Parsing the dataset Now complete the `parse_data_from_input` below. This function should be able to read a file passed as input and return 2 numpy arrays, one containing the labels and one containing the 28x28 representation of each image within the file. These numpy arrays should have type `float64`. A couple of things to keep in mind: - The first line contains the column headers, so you should ignore it. - Each successive line contains 785 comma-separated values between 0 and 255 - The first value is the label - The rest are the pixel values for that picture Tips: - `csv.reader` returns an iterable that returns a row of the csv file in each iteration. Following this convention, row[0] has the label and row[1:] has the 784 pixel values. - To reshape the arrays (going from 784 to 28x28), you can use functions such as [`np.array_split`](https://numpy.org/doc/stable/reference/generated/numpy.array_split.html) or [`np.reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html). - For type conversion of the numpy arrays, use the method [`np.ndarray.astype`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html). ``` # GRADED FUNCTION: parse_data_from_input def parse_data_from_input(filename): with open(filename) as file: ### START CODE HERE # Use csv.reader, passing in the appropriate delimiter # Remember that csv.reader can be iterated and returns one line in each iteration csv_reader = csv.reader(file, delimiter=',') next(csv_reader, None) labels, images = zip(*[(row[0],row[1:]) for row in csv_reader]) images = np.array(images).astype(float).reshape(np.array(images).shape[0],28,28) labels = np.array(labels).astype(float) ### END CODE HERE return images, labels # Test your function training_images, training_labels = parse_data_from_input(TRAINING_FILE) validation_images, validation_labels = parse_data_from_input(VALIDATION_FILE) print(f"Training images has shape: {training_images.shape}") print(f"Training labels has shape: {training_labels.shape}") print(f"Validation images has shape: {validation_images.shape}") print(f"Validation labels has shape: {validation_labels.shape}") ``` **Expected Output:** ``` Training images has shape: (27455, 28, 28) Training labels has shape: (27455,) Testing images has shape: (7172, 28, 28) Testing labels has shape: (7172,) ``` ## Visualizing the numpy arrays Now that you have converted the initial csv data into a format that is compatible with computer vision tasks, take a moment to actually see how the images of the dataset look like: ``` # Plot a sample of 10 images from the training set def plot_categories(training_images, training_labels): fig, axes = plt.subplots(1, 10, figsize=(16, 15)) axes = axes.flatten() letters = list(string.ascii_lowercase) for k in range(10): img = training_images[k] img = np.expand_dims(img, axis=-1) img = array_to_img(img) ax = axes[k] ax.imshow(img, cmap="Greys_r") ax.set_title(f"{letters[int(training_labels[k])]}") ax.set_axis_off() plt.tight_layout() plt.show() plot_categories(training_images, training_labels) ``` ## Creating the generators for the CNN Now that you have successfully organized the data in a way that can be easily fed to Keras' `ImageDataGenerator`, it is time for you to code the generators that will yield batches of images, both for training and validation. For this complete the `train_val_generators` function below. Some important notes: - The images in this dataset come in the same resolution so you don't need to set a custom `target_size` in this case. In fact, you can't even do so because this time you will not be using the `flow_from_directory` method (as in previous assignments). Instead you will use the [`flow`](https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator#flow) method. - You need to add the "color" dimension to the numpy arrays that encode the images. These are black and white images, so this new dimension should have a size of 1 (instead of 3, which is used when dealing with colored images). Take a look at the function [`np.expand_dims`](https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html) for this. ``` # GRADED FUNCTION: train_val_generators def train_val_generators(training_images, training_labels, validation_images, validation_labels): ### START CODE HERE # In this section you will have to add another dimension to the data # So, for example, if your array is (10000, 28, 28) # You will need to make it (10000, 28, 28, 1) # Hint: np.expand_dims training_images = training_images[:, :, :, np.newaxis] validation_images = validation_images[:, :, :, np.newaxis] # Instantiate the ImageDataGenerator class # Don't forget to normalize pixel values # and set arguments to augment the images (if desired) train_datagen = ImageDataGenerator( rescale=1./255., rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest' ) # Pass in the appropriate arguments to the flow method train_generator = train_datagen.flow(x=training_images, y=training_labels, batch_size=32) # Instantiate the ImageDataGenerator class (don't forget to set the rescale argument) # Remember that validation data should not be augmented validation_datagen = ImageDataGenerator(rescale=1./255., ) # Pass in the appropriate arguments to the flow method validation_generator = validation_datagen.flow(x=validation_images, y=validation_labels, batch_size=32) ### END CODE HERE return train_generator, validation_generator # Test your generators train_generator, validation_generator = train_val_generators(training_images, training_labels, validation_images, validation_labels) print(f"Images of training generator have shape: {train_generator.x.shape}") print(f"Labels of training generator have shape: {train_generator.y.shape}") print(f"Images of validation generator have shape: {validation_generator.x.shape}") print(f"Labels of validation generator have shape: {validation_generator.y.shape}") ``` **Expected Output:** ``` Images of training generator have shape: (27455, 28, 28, 1) Labels of training generator have shape: (27455,) Images of validation generator have shape: (7172, 28, 28, 1) Labels of validation generator have shape: (7172,) ``` ## Coding the CNN One last step before training is to define the architecture of the model that will be trained. Complete the `create_model` function below. This function should return a Keras' model that uses the `Sequential` or the `Functional` API. The last layer of your model should have a number of units that corresponds to the number of possible categories, as well as the correct activation function. Aside from defining the architecture of the model, you should also compile it so make sure to use a `loss` function that is suitable for multi-class classification. **Note that you should use no more than 2 Conv2D and 2 MaxPooling2D layers to achieve the desired performance.** ``` def create_model(): ### START CODE HERE # Define the model # Use no more than 2 Conv2D and 2 MaxPooling2D model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(64, (3,3), input_shape=(28,28,1), activation='relu'), tf.keras.layers.MaxPool2D(2,2), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPool2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(26, activation='softmax') ]) model.compile(optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001), loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) ### END CODE HERE return model # Save your model model = create_model() # Train your model history = model.fit(train_generator, epochs=15, validation_data=validation_generator) ``` Now take a look at your training history: ``` # Plot the chart for accuracy and loss on both training and validation acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'r', label='Training Loss') plt.plot(epochs, val_loss, 'b', label='Validation Loss') plt.title('Training and validation loss') plt.legend() plt.show() ``` You will not be graded based on the accuracy of your model but try making it as high as possible for both training and validation, as an optional exercise, **after submitting your notebook for grading**. A reasonable benchmark is to achieve over 99% accuracy for training and over 95% accuracy for validation within 15 epochs. Try tweaking your model's architecture or the augmentation techniques to see if you can achieve these levels of accuracy. You need to submit this notebook for grading. To download it, click on the `File` tab in the upper left corner of the screen then click on `Download` -> `Download .ipynb`. You can name it anything you want as long as it is a valid `.ipynb` (jupyter notebook) file. **Congratulations on finishing this week's assignment!** You have successfully implemented a convolutional neural network that is able to perform multi-class classification tasks! Nice job! **Keep it up!**
github_jupyter
``` import numpy as np import tensorflow as tf import tensorflow.keras import tensorflow.keras.backend as K # import os from tensorflow.keras.datasets import imdb # import keras.backend as K from tensorflow.keras.layers import Conv2D,Activation,BatchNormalization,UpSampling2D,Conv2DTranspose,MaxPooling1D, Embedding,Input, Conv1D, Flatten, Dense, Reshape, LeakyReLU, Dropout,MaxPooling2D from tensorflow.keras.models import Sequential, Model from tensorflow.keras.optimizers import Adam, SGD, RMSprop from tensorflow.keras import regularizers from tensorflow.keras.utils import Progbar from tensorflow.keras.initializers import RandomNormal import random from sklearn.model_selection import train_test_split # from keras.utils import np_utils from tensorflow.keras import utils as np_utils from keras.preprocessing import sequence top_words = 1000 # Now we split our data-set into training and test data (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words) max_words = 500 X_train = sequence.pad_sequences(X_train, maxlen=max_words) X_test = sequence.pad_sequences(X_test, maxlen=max_words) model = Sequential() model.add(Embedding(1000, 32, input_length=max_words)) model.add(Conv1D(64, 3, padding='same', activation='relu')) model.add(Conv1D(64, 3, padding='same', activation='relu')) model.add(MaxPooling1D()) model.add(Flatten()) # model.add(Dense(256, activation='relu')) model.add(Dense(256, activation='relu',name="d1")) model.add(Dense(1, activation='sigmoid', name="d2")) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() # Fitting the data onto model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128, verbose=1) scores = model.evaluate(X_test, y_test, verbose=1) print("Accuracy: %.2f%%" % (scores[1]*100)) scores = model.evaluate(X_test, y_test, verbose=1) # Displays the accuracy of correct sentiment prediction over test data print("Accuracy: %.2f%%" % (scores[1]*100)) teacher_WO_Softmax = Model(model.input, model.get_layer('d1').output) train_dense = teacher_WO_Softmax.predict(X_train) # val_dense = teacher_WO_Softmax.predict(X_val) s1Train=train_dense[:,:128] s2Train=train_dense[:,128:] def build_gan(gen,disc): disc.trainable = False input= Input(shape=(500,)) output = gen(input) output2= disc(output) gan=Model(input,output2) gan.compile('adam',loss=['binary_crossentropy','mse'],loss_weights=[0.5,0.5],metrics=['accuracy']) return gan def build_sdiscriminator(): input2 = Input(shape=(128,),name='input') inp=Dense(64)(input2) leaky_relu = LeakyReLU(alpha=0.2)(inp) conv3 = Dense(128,activation='relu')(leaky_relu) b_n = BatchNormalization()(conv3) conv3 = Dense(128,activation='relu')(leaky_relu) b_n = BatchNormalization()(conv3) b_n=Dropout(0.25)(b_n) conv3 = Dense(256,activation='relu')(b_n) b_n = BatchNormalization()(conv3) conv4 = Dense(512,activation='relu')(b_n) b_n = BatchNormalization()(conv4) dense = Dense(1,activation='sigmoid')(b_n) output2=Dense(128)(b_n) disc = Model(input2,[dense,output2]) disc.compile(Adam(lr=0.0002,beta_1=0.5),loss=['binary_crossentropy','mse',],metrics=['accuracy']) return disc def define_model(name): model = Sequential() model.add(tf.keras.layers.Embedding(1000, 10, input_length=500,name=name)) model.add(Dropout(0.2)) model.add(Conv1D(128, 3,strides=3, activation='relu')) model.add(MaxPooling1D()) model.add(Conv1D(64, 3,strides=3, activation='relu')) model.add(MaxPooling1D()) model.add(Flatten()) model.add(Dropout(0.4)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(128, activation='relu',name=name+"req")) # compile model model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) return model define_model("s1").summary() def training(generator,discriminator,gan,features,epo=20): # Setup Models here BATCH_SIZE = 128 # discriminator.trainable = True total_size = X_train.shape[0] indices = np.arange(0,total_size ,BATCH_SIZE) all_disc_loss = [] all_gen_loss = [] all_class_loss=[] if total_size % BATCH_SIZE: indices = indices[:-1] for e in range(epo): progress_bar = Progbar(target=len(indices)) np.random.shuffle(indices) epoch_gen_loss = [] epoch_disc_loss = [] epoch_class_loss= [] for i,index in enumerate(indices): # Write your code here inputs=X_train[index:index+BATCH_SIZE] sXtrain = features[index:index+BATCH_SIZE] y_real = np.ones((BATCH_SIZE,1)) y_fake = np.zeros((BATCH_SIZE,1)) #Generator Training fake_images = generator.predict_on_batch(inputs) #Disrciminator Training disc_real_loss1,_,disc_real_loss2,_,_= discriminator.train_on_batch(sXtrain,[y_real,sXtrain]) disc_fake_loss1,_,disc_fake_loss2,_,_= discriminator.train_on_batch(fake_images,[y_fake,sXtrain]) #Gans Training discriminator.trainable = False gan_loss,_,gan_loss2,_,_ = gan.train_on_batch(inputs, [y_real,sXtrain]) discriminator.trainable = True disc_loss = (disc_fake_loss1 + disc_real_loss1)/2 epoch_disc_loss.append(disc_loss) progress_bar.update(i+1) epoch_gen_loss.append((gan_loss)) avg_epoch_disc_loss = np.array(epoch_disc_loss).mean() avg_epoch_gen_loss = np.array(epoch_gen_loss).mean() all_disc_loss.append(avg_epoch_disc_loss) all_gen_loss.append(avg_epoch_gen_loss) print("Epoch: %d | Discriminator Loss: %f | Generator Loss: %f | " % (e+1,avg_epoch_disc_loss,avg_epoch_gen_loss)) return generator s1=define_model("s1") d1 = build_sdiscriminator() gan1 = build_gan(s1,d1) s2=define_model("s2") d2 = build_sdiscriminator() gan2 = build_gan(s2,d2) s1=training(s1,d1,gan1,s1Train,20) s2=training(s2,d2,gan2,s2Train,20) o1=s1.get_layer("s1req").output o2=s2.get_layer("s2req").output out = tensorflow.keras.layers.concatenate([o1,o2]) output=Activation('relu')(out) output2=Dropout(0.5)(output) output3=Dense(1,activation="sigmoid", name="d11")(output2) mm2=Model([s1.get_layer("s1").input, s2.get_layer("s2").input], output3) my_weights=model.get_layer('d2').get_weights() mm2.get_layer('d11').set_weights(my_weights) i=0 for l in mm2.layers[:len(mm2.layers)-1]: l.trainable=False adam = Adam(0.0002,0.5,0.999) mm2.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) batch_size = 128 mm2_history=mm2.fit([X_train,X_train], y_train, batch_size=batch_size, epochs=10, verbose=1, validation_data=([X_test,X_test], y_test)) # 1 student evaluate model _, acc = mm2.evaluate([X_test,X_test], y_test, verbose=1) print('> %.2f' % (acc * 100.0)) mm2.summary() ``` ## FF ``` s1= define_model("s1") s2= define_model("s2") batch_size = 128 mm_history=s1.fit(X_train, s1Train, batch_size=batch_size, epochs=10,verbose=1) mm2_history=s2.fit(X_train, s2Train, batch_size=batch_size, epochs=10,verbose=1) o1=s1.get_layer("s1req").output o2=s2.get_layer("s2req").output out = tensorflow.keras.layers.concatenate([o1,o2]) output=Activation('relu')(out) output2=Dropout(0.5)(output) output3=Dense(1,activation="sigmoid", name="d11")(output2) # output4=Activation('softmax')(output3) mm=Model([s1.get_layer("s1").input,s2.get_layer("s2").input], output3) my_weights=model.get_layer('d2').get_weights() mm.get_layer('d11').set_weights(my_weights) i=0 for l in mm.layers[:len(mm.layers)-1]: l.trainable=False adam = Adam(0.0002,0.5,0.999) mm.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) batch_size = 128 mm_history=mm.fit([X_train,X_train], y_train, batch_size=batch_size, epochs=10, verbose=1, validation_data=([X_test,X_test], y_test)) _, acc = mm.evaluate([X_test,X_test], y_test, verbose=1) ```
github_jupyter
# Exp 110 analysis See `./informercial/Makefile` for experimental details. ``` import os import numpy as np from IPython.display import Image import matplotlib import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' import seaborn as sns sns.set_style('ticks') matplotlib.rcParams.update({'font.size': 16}) matplotlib.rc('axes', titlesize=16) from infomercial.exp import meta_bandit from infomercial.exp import epsilon_bandit from infomercial.exp import beta_bandit from infomercial.exp import softbeta_bandit from infomercial.local_gym import bandit from infomercial.exp.meta_bandit import load_checkpoint import gym def plot_meta(env_name, result): """Plots!""" # episodes, actions, scores_E, scores_R, values_E, values_R, ties, policies episodes = result["episodes"] actions =result["actions"] bests =result["p_bests"] scores_E = result["scores_E"] scores_R = result["scores_R"] values_R = result["values_R"] values_E = result["values_E"] ties = result["ties"] policies = result["policies"] # - env = gym.make(env_name) best = env.best print(f"Best arm: {best}, last arm: {actions[-1]}") # Plotz fig = plt.figure(figsize=(6, 14)) grid = plt.GridSpec(6, 1, wspace=0.3, hspace=0.8) # Arm plt.subplot(grid[0, 0]) plt.scatter(episodes, actions, color="black", alpha=.5, s=2, label="Bandit") plt.plot(episodes, np.repeat(best, np.max(episodes)+1), color="red", alpha=0.8, ls='--', linewidth=2) plt.ylim(-.1, np.max(actions)+1.1) plt.ylabel("Arm choice") plt.xlabel("Episode") # Policy policies = np.asarray(policies) episodes = np.asarray(episodes) plt.subplot(grid[1, 0]) m = policies == 0 plt.scatter(episodes[m], policies[m], alpha=.4, s=2, label="$\pi_E$", color="purple") m = policies == 1 plt.scatter(episodes[m], policies[m], alpha=.4, s=2, label="$\pi_R$", color="grey") plt.ylim(-.1, 1+.1) plt.ylabel("Controlling\npolicy") plt.xlabel("Episode") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # score plt.subplot(grid[2, 0]) plt.scatter(episodes, scores_E, color="purple", alpha=0.4, s=2, label="E") plt.plot(episodes, scores_E, color="purple", alpha=0.4) plt.scatter(episodes, scores_R, color="grey", alpha=0.4, s=2, label="R") plt.plot(episodes, scores_R, color="grey", alpha=0.4) plt.plot(episodes, np.repeat(tie_threshold, np.max(episodes)+1), color="violet", alpha=0.8, ls='--', linewidth=2) plt.ylabel("Score") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # Q plt.subplot(grid[3, 0]) plt.scatter(episodes, values_E, color="purple", alpha=0.4, s=2, label="$Q_E$") plt.scatter(episodes, values_R, color="grey", alpha=0.4, s=2, label="$Q_R$") plt.plot(episodes, np.repeat(tie_threshold, np.max(episodes)+1), color="violet", alpha=0.8, ls='--', linewidth=2) plt.ylabel("Value") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # Ties plt.subplot(grid[4, 0]) plt.scatter(episodes, bests, color="red", alpha=.5, s=2) plt.ylabel("p(best)") plt.xlabel("Episode") plt.ylim(0, 1) # Ties plt.subplot(grid[5, 0]) plt.scatter(episodes, ties, color="black", alpha=.5, s=2, label="$\pi_{tie}$ : 1\n $\pi_\pi$ : 0") plt.ylim(-.1, 1+.1) plt.ylabel("Ties index") plt.xlabel("Episode") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) def plot_epsilon(env_name, result): """Plots!""" # episodes, actions, scores_E, scores_R, values_E, values_R, ties, policies episodes = result["episodes"] actions =result["actions"] bests =result["p_bests"] scores_R = result["scores_R"] values_R = result["values_R"] epsilons = result["epsilons"] # - env = gym.make(env_name) best = env.best print(f"Best arm: {best}, last arm: {actions[-1]}") # Plotz fig = plt.figure(figsize=(6, 14)) grid = plt.GridSpec(6, 1, wspace=0.3, hspace=0.8) # Arm plt.subplot(grid[0, 0]) plt.scatter(episodes, actions, color="black", alpha=.5, s=2, label="Bandit") plt.plot(episodes, np.repeat(best, np.max(episodes)+1), color="red", alpha=0.8, ls='--', linewidth=2) plt.ylim(-.1, np.max(actions)+1.1) plt.ylabel("Arm choice") plt.xlabel("Episode") # score plt.subplot(grid[1, 0]) plt.scatter(episodes, scores_R, color="grey", alpha=0.4, s=2, label="R") plt.ylabel("Score") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # Q plt.subplot(grid[2, 0]) plt.scatter(episodes, values_R, color="grey", alpha=0.4, s=2, label="$Q_R$") plt.ylabel("Value") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # best plt.subplot(grid[3, 0]) plt.scatter(episodes, bests, color="red", alpha=.5, s=2) plt.ylabel("p(best)") plt.xlabel("Episode") plt.ylim(0, 1) # Decay plt.subplot(grid[4, 0]) plt.scatter(episodes, epsilons, color="black", alpha=.5, s=2) plt.ylabel("$\epsilon_R$") plt.xlabel("Episode") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) def plot_beta(env_name, result): """Plots!""" # episodes, actions, scores_E, scores_R, values_E, values_R, ties, policies episodes = result["episodes"] actions =result["actions"] bests =result["p_bests"] scores_R = result["scores_R"] values_R = result["values_R"] beta = result["beta"] # - env = gym.make(env_name) best = env.best print(f"Best arm: {best}, last arm: {actions[-1]}") # Plotz fig = plt.figure(figsize=(6, 14)) grid = plt.GridSpec(6, 1, wspace=0.3, hspace=0.8) # Arm plt.subplot(grid[0, 0]) plt.scatter(episodes, actions, color="black", alpha=.5, s=2, label="Bandit") plt.plot(episodes, np.repeat(best, np.max(episodes)+1), color="red", alpha=0.8, ls='--', linewidth=2) plt.ylim(-.1, np.max(actions)+1.1) plt.ylabel("Arm choice") plt.xlabel("Episode") # score plt.subplot(grid[1, 0]) plt.scatter(episodes, scores_R, color="grey", alpha=0.4, s=2, label="R") plt.ylabel("Score") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # Q plt.subplot(grid[2, 0]) plt.scatter(episodes, values_R, color="grey", alpha=0.4, s=2, label="$Q_R$") plt.ylabel("Value") plt.xlabel("Episode") # plt.semilogy() plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) _ = sns.despine() # best plt.subplot(grid[3, 0]) plt.scatter(episodes, bests, color="red", alpha=.5, s=2) plt.ylabel("p(best)") plt.xlabel("Episode") plt.ylim(0, 1) def plot_critic(critic_name, env_name, result): # - env = gym.make(env_name) best = env.best # Data critic = result[critic_name] arms = list(critic.keys()) values = list(critic.values()) # Plotz fig = plt.figure(figsize=(8, 3)) grid = plt.GridSpec(1, 1, wspace=0.3, hspace=0.8) # Arm plt.subplot(grid[0]) plt.scatter(arms, values, color="black", alpha=.5, s=30) plt.plot([best]*10, np.linspace(min(values), max(values), 10), color="red", alpha=0.8, ls='--', linewidth=2) plt.ylabel("Value") plt.xlabel("Arm") ``` # Load and process data ``` data_path ="/Users/qualia/Code/infomercial/data/" exp_name = "exp110" sorted_params = load_checkpoint(os.path.join(data_path, f"{exp_name}_sorted.pkl")) # print(sorted_params.keys()) best_params = sorted_params[0] beta = best_params['beta'] sorted_params ``` # Performance of best parameters ``` env_name = 'BanditHardAndSparse10-v0' num_episodes = 50000 # Run w/ best params result = beta_bandit( env_name=env_name, num_episodes=num_episodes, lr_R=best_params["lr_R"], beta=best_params["beta"], seed_value=2, ) print(best_params) plot_beta(env_name, result=result) plot_critic('critic', env_name, result) ``` # Sensitivity to parameter choices ``` total_Rs = [] betas = [] lrs_R = [] lrs_E = [] trials = list(sorted_params.keys()) for t in trials: total_Rs.append(sorted_params[t]['total_R']) lrs_R.append(sorted_params[t]['lr_R']) betas.append(sorted_params[t]['beta']) # Init plot fig = plt.figure(figsize=(5, 18)) grid = plt.GridSpec(6, 1, wspace=0.3, hspace=0.8) # Do plots: # Arm plt.subplot(grid[0, 0]) plt.scatter(trials, total_Rs, color="black", alpha=.5, s=6, label="total R") plt.xlabel("Sorted params") plt.ylabel("total R") _ = sns.despine() plt.subplot(grid[1, 0]) plt.scatter(trials, lrs_R, color="black", alpha=.5, s=6, label="total R") plt.xlabel("Sorted params") plt.ylabel("lr_R") _ = sns.despine() plt.subplot(grid[2, 0]) plt.scatter(lrs_R, total_Rs, color="black", alpha=.5, s=6, label="total R") plt.xlabel("lrs_R") plt.ylabel("total_Rs") _ = sns.despine() plt.subplot(grid[3, 0]) plt.scatter(betas, total_Rs, color="black", alpha=.5, s=6, label="total R") plt.xlabel("beta") plt.ylabel("total_Rs") _ = sns.despine() ``` # Parameter correlations ``` from scipy.stats import spearmanr spearmanr(total_Rs, lrs_R) spearmanr(betas, total_Rs) spearmanr(betas, lrs_R) ``` # Distributions of parameters ``` # Init plot fig = plt.figure(figsize=(5, 6)) grid = plt.GridSpec(3, 1, wspace=0.3, hspace=0.8) plt.subplot(grid[0, 0]) plt.hist(betas, color="black") plt.xlabel("beta") plt.ylabel("Count") _ = sns.despine() plt.subplot(grid[1, 0]) plt.hist(lrs_R, color="black") plt.xlabel("lr_R") plt.ylabel("Count") _ = sns.despine() ``` of total reward ``` # Init plot fig = plt.figure(figsize=(5, 2)) grid = plt.GridSpec(1, 1, wspace=0.3, hspace=0.8) plt.subplot(grid[0, 0]) plt.hist(total_Rs, color="black", bins=50) plt.xlabel("Total reward") plt.ylabel("Count") # plt.xlim(0, 10) _ = sns.despine() ```
github_jupyter
# Regression with Amazon SageMaker XGBoost algorithm _**Single machine training for regression with Amazon SageMaker XGBoost algorithm**_ --- --- ## Contents 1. [Introduction](#Introduction) 2. [Setup](#Setup) 1. [Fetching the dataset](#Fetching-the-dataset) 2. [Data Ingestion](#Data-ingestion) 3. [Training the XGBoost model](#Training-the-XGBoost-model) 1. [Plotting evaluation metrics](#Plotting-evaluation-metrics) 4. [Set up hosting for the model](#Set-up-hosting-for-the-model) 1. [Import model into hosting](#Import-model-into-hosting) 2. [Create endpoint configuration](#Create-endpoint-configuration) 3. [Create endpoint](#Create-endpoint) 5. [Validate the model for use](#Validate-the-model-for-use) --- ## Introduction This notebook demonstrates the use of Amazon SageMaker’s implementation of the XGBoost algorithm to train and host a regression model. We use the [Abalone data](https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression.html) originally from the UCI data repository [1]. More details about the original dataset can be found [here](https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.names). In the libsvm converted [version](https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression.html), the nominal feature (Male/Female/Infant) has been converted into a real valued feature. Age of abalone is to be predicted from eight physical measurements. Dataset is already processed and stored on S3. Scripts used for processing the data can be found in the [Appendix](#Appendix). These include downloading the data, splitting into train, validation and test, and uploading to S3 bucket. >[1] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science. ## Setup This notebook was tested in Amazon SageMaker Studio on a ml.t3.medium instance with Python 3 (Data Science) kernel. Let's start by specifying: 1. The S3 buckets and prefixes that you want to use for saving the model and where training data is located. This should be within the same region as the Notebook Instance, training, and hosting. 1. The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with a the appropriate full IAM role arn string(s). ``` %%time import os import boto3 import re import sagemaker role = sagemaker.get_execution_role() region = boto3.Session().region_name # S3 bucket where the training data is located. # Feel free to specify a different bucket and prefix data_bucket = f"jumpstart-cache-prod-{region}" data_prefix = "1p-notebooks-datasets/abalone/libsvm" data_bucket_path = f"s3://{data_bucket}" # S3 bucket for saving code and model artifacts. # Feel free to specify a different bucket and prefix output_bucket = sagemaker.Session().default_bucket() output_prefix = "sagemaker/DEMO-xgboost-abalone-default" output_bucket_path = f"s3://{output_bucket}" ``` ## Training the XGBoost model After setting training parameters, we kick off training, and poll for status until training is completed, which in this example, takes between 5 and 6 minutes. ``` from sagemaker.amazon.amazon_estimator import get_image_uri container = get_image_uri(region, "xgboost", "1.0-1") %%time import boto3 from time import gmtime, strftime job_name = f"DEMO-xgboost-regression-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" print("Training job", job_name) # Ensure that the training and validation data folders generated above are reflected in the "InputDataConfig" parameter below. create_training_params = { "AlgorithmSpecification": {"TrainingImage": container, "TrainingInputMode": "File"}, "RoleArn": role, "OutputDataConfig": {"S3OutputPath": f"{output_bucket_path}/{output_prefix}/single-xgboost"}, "ResourceConfig": {"InstanceCount": 1, "InstanceType": "ml.m5.2xlarge", "VolumeSizeInGB": 5}, "TrainingJobName": job_name, "HyperParameters": { "max_depth": "5", "eta": "0.2", "gamma": "4", "min_child_weight": "6", "subsample": "0.7", "silent": "0", "objective": "reg:linear", "num_round": "50", }, "StoppingCondition": {"MaxRuntimeInSeconds": 3600}, "InputDataConfig": [ { "ChannelName": "train", "DataSource": { "S3DataSource": { "S3DataType": "S3Prefix", "S3Uri": f"{data_bucket_path}/{data_prefix}/train", "S3DataDistributionType": "FullyReplicated", } }, "ContentType": "libsvm", "CompressionType": "None", }, { "ChannelName": "validation", "DataSource": { "S3DataSource": { "S3DataType": "S3Prefix", "S3Uri": f"{data_bucket_path}/{data_prefix}/validation", "S3DataDistributionType": "FullyReplicated", } }, "ContentType": "libsvm", "CompressionType": "None", }, ], } client = boto3.client("sagemaker", region_name=region) client.create_training_job(**create_training_params) import time status = client.describe_training_job(TrainingJobName=job_name)["TrainingJobStatus"] print(status) while status != "Completed" and status != "Failed": time.sleep(60) status = client.describe_training_job(TrainingJobName=job_name)["TrainingJobStatus"] print(status) ``` Note that the "validation" channel has been initialized too. The SageMaker XGBoost algorithm actually calculates RMSE and writes it to the CloudWatch logs on the data passed to the "validation" channel. ## Set up hosting for the model In order to set up hosting, we have to import the model from training to hosting. ### Import model into hosting Register the model with hosting. This allows the flexibility of importing models trained elsewhere. ``` %%time import boto3 from time import gmtime, strftime model_name = f"{job_name}-model" print(model_name) info = client.describe_training_job(TrainingJobName=job_name) model_data = info["ModelArtifacts"]["S3ModelArtifacts"] print(model_data) primary_container = {"Image": container, "ModelDataUrl": model_data} create_model_response = client.create_model( ModelName=model_name, ExecutionRoleArn=role, PrimaryContainer=primary_container ) print(create_model_response["ModelArn"]) ``` ### Create endpoint configuration SageMaker supports configuring REST endpoints in hosting with multiple models, e.g. for A/B testing purposes. In order to support this, customers create an endpoint configuration, that describes the distribution of traffic across the models, whether split, shadowed, or sampled in some way. In addition, the endpoint configuration describes the instance type required for model deployment. ``` from time import gmtime, strftime endpoint_config_name = f"DEMO-XGBoostEndpointConfig-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" print(endpoint_config_name) create_endpoint_config_response = client.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=[ { "InstanceType": "ml.m5.xlarge", "InitialVariantWeight": 1, "InitialInstanceCount": 1, "ModelName": model_name, "VariantName": "AllTraffic", } ], ) print(f"Endpoint Config Arn: {create_endpoint_config_response['EndpointConfigArn']}") ``` ### Create endpoint Lastly, the customer creates the endpoint that serves up the model, through specifying the name and configuration defined above. The end result is an endpoint that can be validated and incorporated into production applications. This takes 9-11 minutes to complete. ``` %%time import time endpoint_name = f'DEMO-XGBoostEndpoint-{strftime("%Y-%m-%d-%H-%M-%S", gmtime())}' print(endpoint_name) create_endpoint_response = client.create_endpoint( EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name ) print(create_endpoint_response["EndpointArn"]) resp = client.describe_endpoint(EndpointName=endpoint_name) status = resp["EndpointStatus"] while status == "Creating": print(f"Status: {status}") time.sleep(60) resp = client.describe_endpoint(EndpointName=endpoint_name) status = resp["EndpointStatus"] print(f"Arn: {resp['EndpointArn']}") print(f"Status: {status}") ``` ## Validate the model for use Finally, the customer can now validate the model for use. They can obtain the endpoint from the client library using the result from previous operations, and generate classifications from the trained model using that endpoint. ``` runtime_client = boto3.client("runtime.sagemaker", region_name=region) ``` Download test data ``` FILE_TEST = "abalone.test" s3 = boto3.client("s3") s3.download_file(data_bucket, f"{data_prefix}/test/{FILE_TEST}", FILE_TEST) ``` Start with a single prediction. ``` !head -1 abalone.test > abalone.single.test %%time import json from itertools import islice import math import struct file_name = "abalone.single.test" # customize to your test file with open(file_name, "r") as f: payload = f.read().strip() response = runtime_client.invoke_endpoint( EndpointName=endpoint_name, ContentType="text/x-libsvm", Body=payload ) result = response["Body"].read() result = result.decode("utf-8") result = result.split(",") result = [math.ceil(float(i)) for i in result] label = payload.strip(" ").split()[0] print(f"Label: {label}\nPrediction: {result[0]}") ``` OK, a single prediction works. Let's do a whole batch to see how good is the predictions accuracy. ``` import sys import math def do_predict(data, endpoint_name, content_type): payload = "\n".join(data) response = runtime_client.invoke_endpoint( EndpointName=endpoint_name, ContentType=content_type, Body=payload ) result = response["Body"].read() result = result.decode("utf-8") result = result.split(",") preds = [float((num)) for num in result] preds = [math.ceil(num) for num in preds] return preds def batch_predict(data, batch_size, endpoint_name, content_type): items = len(data) arrs = [] for offset in range(0, items, batch_size): if offset + batch_size < items: results = do_predict(data[offset : (offset + batch_size)], endpoint_name, content_type) arrs.extend(results) else: arrs.extend(do_predict(data[offset:items], endpoint_name, content_type)) sys.stdout.write(".") return arrs ``` The following helps us calculate the Median Absolute Percent Error (MdAPE) on the batch dataset. ``` %%time import json import numpy as np with open(FILE_TEST, "r") as f: payload = f.read().strip() labels = [int(line.split(" ")[0]) for line in payload.split("\n")] test_data = [line for line in payload.split("\n")] preds = batch_predict(test_data, 100, endpoint_name, "text/x-libsvm") print( "\n Median Absolute Percent Error (MdAPE) = ", np.median(np.abs(np.array(labels) - np.array(preds)) / np.array(labels)), ) ``` ### Delete Endpoint Once you are done using the endpoint, you can use the following to delete it. ``` client.delete_endpoint(EndpointName=endpoint_name) ``` # Appendix ### Data split and upload Following methods split the data into train/test/validation datasets and upload files to S3. ``` import io import boto3 import random def data_split( FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST ): data = [l for l in open(FILE_DATA, "r")] train_file = open(FILE_TRAIN, "w") valid_file = open(FILE_VALIDATION, "w") tests_file = open(FILE_TEST, "w") num_of_data = len(data) num_train = int((PERCENT_TRAIN / 100.0) * num_of_data) num_valid = int((PERCENT_VALIDATION / 100.0) * num_of_data) num_tests = int((PERCENT_TEST / 100.0) * num_of_data) data_fractions = [num_train, num_valid, num_tests] split_data = [[], [], []] rand_data_ind = 0 for split_ind, fraction in enumerate(data_fractions): for i in range(fraction): rand_data_ind = random.randint(0, len(data) - 1) split_data[split_ind].append(data[rand_data_ind]) data.pop(rand_data_ind) for l in split_data[0]: train_file.write(l) for l in split_data[1]: valid_file.write(l) for l in split_data[2]: tests_file.write(l) train_file.close() valid_file.close() tests_file.close() def write_to_s3(fobj, bucket, key): return ( boto3.Session(region_name=region).resource("s3").Bucket(bucket).Object(key).upload_fileobj(fobj) ) def upload_to_s3(bucket, channel, filename): fobj = open(filename, "rb") key = f"{prefix}/{channel}" url = f"s3://{bucket}/{key}/{filename}" print(f"Writing to {url}") write_to_s3(fobj, bucket, key) ``` ### Data ingestion Next, we read the dataset from the existing repository into memory, for preprocessing prior to training. This processing could be done *in situ* by Amazon Athena, Apache Spark in Amazon EMR, Amazon Redshift, etc., assuming the dataset is present in the appropriate location. Then, the next step would be to transfer the data to S3 for use in training. For small datasets, such as this one, reading into memory isn't onerous, though it would be for larger datasets. ``` %%time import urllib.request bucket = sagemaker.Session().default_bucket() prefix = "sagemaker/DEMO-xgboost-abalone-default" # Load the dataset FILE_DATA = "abalone" urllib.request.urlretrieve( "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone", FILE_DATA ) # split the downloaded data into train/test/validation files FILE_TRAIN = "abalone.train" FILE_VALIDATION = "abalone.validation" FILE_TEST = "abalone.test" PERCENT_TRAIN = 70 PERCENT_VALIDATION = 15 PERCENT_TEST = 15 data_split( FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST ) # upload the files to the S3 bucket upload_to_s3(bucket, "train", FILE_TRAIN) upload_to_s3(bucket, "validation", FILE_VALIDATION) upload_to_s3(bucket, "test", FILE_TEST) ```
github_jupyter
# Preprocessing and Feature Creation In this notebook we import the data, preprocess the data and create features for supervised and unsupervised cross-lingual-information retrieval models. ## I. Import Data In this section we import the English and German europarl datasets and combine them into a parallel sentence translation dataframe. ``` %load_ext autoreload %autoreload 2 import os import sys sys.path.append(os.path.dirname((os.path.abspath('')))) from src.data import create_data_subset create_data_subset(sentence_data_source_path='../data/external/europarl-v7.pl-en.en', sentence_data_target_path='../data/external/europarl-v7.pl-en.pl', sample_size=25000, sentence_data_sampled_path="../data/interim/europarl_en_pl.pkl",) !python -m spacy download pl_core_news_sm ``` ## II. Preprocess data In this section we preprocess the parallel sentence data for the feature generation ``` import spacy from nltk.corpus import stopwords from textblob import TextBlob as textblob_source from textblob_de import TextBlobDE as textblob_target import en_core_web_sm # import de_core_news_sm # import it_core_news_sm import pl_core_news_sm import time from src.data import PreprocessingEuroParl from stop_words import get_stop_words stopwords_source = stopwords.words('english') # stopwords_target = stopwords.words('german') # German stopwords # stopwords_target = stopwords.words('italian') # Italian stopwords stopwords_target = get_stop_words('polish') # Polish stopwords nlp_source = en_core_web_sm.load() # nlp_target = de_core_news_sm.load() # German pipeline # nlp_target = it_core_news_sm.load() # Italian pipeline nlp_target = pl_core_news_sm.load() # Polish pipeline # parallel_sentences = PreprocessingEuroParl(df_sampled_path="../data/interim/europarl_en_de.pkl") # German # parallel_sentences = PreprocessingEuroParl(df_sampled_path="../data/interim/europarl_en_it.pkl") # Italien parallel_sentences = PreprocessingEuroParl(df_sampled_path="../data/interim/europarl_en_pl.pkl") # Polnisch parallel_sentences.preprocess_sentences(nlp_source, nlp_target, stopwords_source, stopwords_target) parallel_sentences.extract_sentence_information(nlp_source, nlp_target) parallel_sentences.create_embedding_information("proc_5k", language_pair="en_pl") parallel_sentences.create_embedding_information("proc_b_1k", language_pair="en_pl") parallel_sentences.create_embedding_information("vecmap", language_pair="en_pl") parallel_sentences.preprocessed.to_json("../data/interim/preprocessed_data_en_pl.json") parallel_sentences.preprocessed parallel_sentences.dataframe import pandas as pd preprocessed_data = pd.read_json("../data/interim/preprocessed_data_en_pl.json") parallel_sentences = PreprocessingEuroParl(df_sampled_path="../data/interim/europarl_en_pl.pkl") parallel_sentences.preprocessed = preprocessed_data ``` ## III. Create data set In this section we create the datasets for the training of the supervised model and the data for the supervised and unsupervised retrieval. ``` from src.data import DataSet n_model = 20000 n_queries = 100 n_retrieval = 5000 k = 10 sample_size_k = 100 dataset = DataSet(parallel_sentences.preprocessed) #dataset = DataSet(preprocessed_data) dataset.split_model_retrieval(n_model, n_retrieval) dataset.create_model_index(n_model, k, sample_size_k, "sentence_embedding_tf_idf_proc_5k_source", "sentence_embedding_tf_idf_proc_5k_target") dataset.model_dataset_index.reset_index(drop=True).to_feather("../data/processed/dataset_model_index_en_pl.feather") # import pandas as pd # pd.read_feather("../data/processed/dataset_model_index.feather") #dataset.create_retrieval_index(n_queries) import pandas as pd # If your pandas version is old, use this instead query = pd.DataFrame({"id_source": dataset.retrieval_subset.iloc[:n_queries]["id_source"]}) documents = pd.DataFrame({"id_target": dataset.retrieval_subset["id_target"]}) index = pd.MultiIndex.from_product([dataset.retrieval_subset.iloc[:n_queries]["id_source"], dataset.retrieval_subset["id_target"]], names = ["id_source", "id_target"]) dataset.retrieval_dataset_index = pd.DataFrame(index = index).reset_index() dataset.retrieval_dataset_index.reset_index(drop=True).to_feather("../data/processed/dataset_retrieval_index_en_pl.feather") # import pandas as pd # pd.read_feather("../data/processed/dataset_retrieval_index.feather") ``` ## IV. Create features In this section we create features for our model, that are sentence based and should be created before the text is preprocessed. ``` #%autoreload 2 from src.features import feature_generation_class # import pickle # with open(r"../data/processed/correlated_features.pkl", "rb") as file: # chosen_features = pickle.load(file) ``` Generation of the training data for the supervised classifciation model. ``` features_model = feature_generation_class.FeatureGeneration(dataset.model_dataset_index, parallel_sentences.preprocessed) features_model.create_feature_dataframe() features_model.create_sentence_features() features_model.create_embedding_features("proc_5k") features_model.create_embedding_features("proc_b_1k") features_model.create_embedding_features("vecmap") features_model.feature_dataframe.reset_index(drop=True).to_feather("../data/processed/feature_model_en_pl.feather") # import pandas as pd # pd.read_feather("../data/processed/feature_model.feather") ``` Generation of the data for the crosslingual information retrieval task. ``` features_retrieval = feature_generation_class.FeatureGeneration(dataset.retrieval_dataset_index, parallel_sentences.preprocessed) features_retrieval.create_feature_dataframe() features_retrieval.create_sentence_features() features_retrieval.create_embedding_features("proc_5k") features_retrieval.create_embedding_features("proc_b_1k") features_retrieval.create_embedding_features("vecmap") features_retrieval.feature_dataframe.reset_index(drop=True).to_feather("../data/processed/feature_retrieval_en_pl.feather") # import pandas as pd # pd.read_feather("../data/processed/feature_retrieval.feather") ```
github_jupyter
``` %%configure -f { "executorMemory": "4g", "driverMemory": "4g", "executorCores": 4, "driverCores": 2, "numExecutors": 1 } # For informational purposes, # print the hostname of the container # where the Spark driver is running import subprocess stdout = subprocess.check_output( "hostname", stderr=subprocess.STDOUT, shell=True).decode("utf-8") print(stdout) # Install NVIDIA GPU libraries and TensorFlow for GPU # in the container where the Spark driver is running import subprocess stdout = subprocess.check_output( ''' echo $CUDA_VERSION export CUDA_PKG_VERSION="8-0=$CUDA_VERSION-1" echo $CUDA_PKG_VERSION export PATH=/usr/local/nvidia/bin:/usr/local/cuda/bin:${PATH} export LD_LIBRARY_PATH=/usr/local/nvidia/lib:/usr/local/nvidia/lib64 # nvidia-container-runtime export NVIDIA_VISIBLE_DEVICES=all export NVIDIA_DRIVER_CAPABILITIES="compute,utility" export NVIDIA_REQUIRE_CUDA="cuda>=8.0" apt-get update && apt-get install -y --no-install-recommends ca-certificates apt-transport-https gnupg-curl && \\ rm -rf /var/lib/apt/lists/* && \\ NVIDIA_GPGKEY_SUM=d1be581509378368edeec8c1eb2958702feedf3bc3d17011adbf24efacce4ab5 && \\ NVIDIA_GPGKEY_FPR=ae09fe4bbd223a84b2ccfce3f60f4b3d7fa2af80 && \\ apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub && \\ apt-key adv --export --no-emit-version -a $NVIDIA_GPGKEY_FPR | tail -n +5 > cudasign.pub && \\ echo "$NVIDIA_GPGKEY_SUM cudasign.pub" | sha256sum -c --strict - && rm cudasign.pub && \\ echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64 /" > /etc/apt/sources.list.d/cuda.list apt-get update && apt-get install -y --no-install-recommends \\ cuda-nvrtc-$CUDA_PKG_VERSION \\ cuda-nvgraph-$CUDA_PKG_VERSION \\ cuda-cusolver-$CUDA_PKG_VERSION \\ cuda-cublas-8-0=8.0.61.2-1 \\ cuda-cufft-$CUDA_PKG_VERSION \\ cuda-curand-$CUDA_PKG_VERSION \\ cuda-cusparse-$CUDA_PKG_VERSION \\ cuda-npp-$CUDA_PKG_VERSION \\ cuda-cudart-$CUDA_PKG_VERSION && \\ ln -s cuda-8.0 /usr/local/cuda && \\ rm -rf /var/lib/apt/lists/* # Install tensorflow pip3 install tensorflow-gpu==1.4.0 # add cudnn 6 echo "deb https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list export CUDNN_VERSION=6.0.21 #LABEL com.nvidia.cudnn.version="${CUDNN_VERSION}" apt-get update && apt-get install -y --no-install-recommends \\ libcudnn6=$CUDNN_VERSION-1+cuda8.0 && \\ rm -rf /var/lib/apt/lists/* ''', stderr=subprocess.STDOUT, shell=True).decode("utf-8") print(stdout) # List CPU and GPU devices from tensorflow.python.client import device_lib device_lib.list_local_devices() # Fit and evaluate TensorFlow model on MNIST data import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), # input_shape needed for older tensorflow tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5) print("\n") metrics = model.evaluate(x_test, y_test) print("\n") print(metrics) # Check available disk space import subprocess stdout = subprocess.check_output( ''' df -h ''', stderr=subprocess.STDOUT, shell=True).decode("utf-8") print(stdout) # Download code for the CIFAR 10 benchmark import subprocess import os if os.path.isdir("/tmp/models"): print("CIFAR 10 repo already cloned") else: stdout = subprocess.check_output( ''' apt-get update && apt-get install -y git cd /tmp git clone https://github.com/tensorflow/models.git ''', stderr=subprocess.STDOUT, shell=True).decode("utf-8") print(stdout) # Run the CIFAR 10 benchmark import subprocess stdout = subprocess.check_output( ''' python3 /tmp/models/tutorials/image/cifar10/cifar10_train.py --max_steps 100 ''', stderr=subprocess.STDOUT, shell=True).decode("utf-8") print(stdout) ```
github_jupyter
``` %matplotlib inline ``` # Quantization Quickstart Here is a four-minute video to get you started with model quantization. .. youtube:: MSfV7AyfiA4 :align: center Quantization reduces model size and speeds up inference time by reducing the number of bits required to represent weights or activations. In NNI, both post-training quantization algorithms and quantization-aware training algorithms are supported. Here we use `QAT_Quantizer` as an example to show the usage of quantization in NNI. ## Preparation In this tutorial, we use a simple model and pre-train on MNIST dataset. If you are familiar with defining a model and training in pytorch, you can skip directly to `Quantizing Model`_. ``` import torch import torch.nn.functional as F from torch.optim import SGD from scripts.compression_mnist_model import TorchModel, trainer, evaluator, device, test_trt # define the model model = TorchModel().to(device) # define the optimizer and criterion for pre-training optimizer = SGD(model.parameters(), 1e-2) criterion = F.nll_loss # pre-train and evaluate the model on MNIST dataset for epoch in range(3): trainer(model, optimizer, criterion) evaluator(model) ``` ## Quantizing Model Initialize a `config_list`. Detailed about how to write ``config_list`` please refer :doc:`compression config specification <../compression/compression_config_list>`. ``` config_list = [{ 'quant_types': ['input', 'weight'], 'quant_bits': {'input': 8, 'weight': 8}, 'op_types': ['Conv2d'] }, { 'quant_types': ['output'], 'quant_bits': {'output': 8}, 'op_types': ['ReLU'] }, { 'quant_types': ['input', 'weight'], 'quant_bits': {'input': 8, 'weight': 8}, 'op_names': ['fc1', 'fc2'] }] ``` finetuning the model by using QAT ``` from nni.algorithms.compression.pytorch.quantization import QAT_Quantizer dummy_input = torch.rand(32, 1, 28, 28).to(device) quantizer = QAT_Quantizer(model, config_list, optimizer, dummy_input) quantizer.compress() ``` The model has now been wrapped, and quantization targets ('quant_types' setting in `config_list`) will be quantized & dequantized for simulated quantization in the wrapped layers. QAT is a training-aware quantizer, it will update scale and zero point during training. ``` for epoch in range(3): trainer(model, optimizer, criterion) evaluator(model) ``` export model and get calibration_config ``` model_path = "./log/mnist_model.pth" calibration_path = "./log/mnist_calibration.pth" calibration_config = quantizer.export_model(model_path, calibration_path) print("calibration_config: ", calibration_config) ``` build tensorRT engine to make a real speedup, for more information about speedup, please refer :doc:`quantization_speedup`. ``` from nni.compression.pytorch.quantization_speedup import ModelSpeedupTensorRT input_shape = (32, 1, 28, 28) engine = ModelSpeedupTensorRT(model, input_shape, config=calibration_config, batchsize=32) engine.compress() test_trt(engine) ```
github_jupyter
``` import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt !pip install plotly import plotly.express as px r09 = pd.read_csv('https://raw.githubusercontent.com/PacktWorkshops/The-Data-Analysis-Workshop/master/Chapter08/Datasets/online_retail_II.csv') r09.head() r10 = pd.read_csv('https://raw.githubusercontent.com/PacktWorkshops/The-Data-Analysis-Workshop/master/Chapter08/Datasets/online_retail_II2.csv') r10.head() dfs = [r09, r10] retail = pd.concat(dfs, keys = ['09-10', '10-11']) retail retail.rename(index = str, columns = { 'Invoice' : 'invoice', 'StockCode' : 'stock_code', 'Quantity' : 'quantity', 'InvoiceDate' : 'date', 'Price' : 'unit_price', 'Country' : 'country', 'Description' : 'desc', 'Customer ID' : 'cust_id' }, inplace = True) retail.head() retail.isnull().sum().sort_values(ascending = False) retail.describe() retail.loc[retail['unit_price'] == 38970.0] retail.loc[retail['unit_price'] == -53594.360000] (retail['unit_price'] <= 0).sum() (retail['quantity'] <= 0).sum() retail[(retail['unit_price'] <= 0) & (retail['quantity'] <= 0) & (retail['cust_id'].isnull())] null_retail = retail[retail.isnull().any(axis=1)] null_retail new_retail = retail[(retail['unit_price'] > 0) & (retail['quantity'] > 0)] new_retail.describe() plt.subplots(figsize = (12, 6)) up = sns.boxplot(new_retail.unit_price) new_retail = new_retail[new_retail.unit_price < 15000] new_retail.describe() up_new = sns.boxplot(new_retail.unit_price) plt.subplots(figsize = (12, 6)) q = sns.boxplot(new_retail.quantity) new_retail = new_retail[new_retail.quantity < 25000] new_retail.describe() q_new = sns.boxplot(new_retail.quantity) new_retail[(new_retail.desc.isnull()) & (new_retail.cust_id.isnull())] new_retail.info() new_retail = new_retail.dropna() new_retail.info() retail = new_retail retail.head() retail.desc = retail.desc.str.lower() retail.head() retail['date'] = pd.to_datetime(retail.date, format = '%d/%m/%Y %H:%M') retail.head() retail.insert(loc = 4, column = 'year_month', value = retail.date.map(lambda x: 100 * x.year + x.month)) retail.insert(loc = 5, column = 'year', value = retail.date.dt.year) retail.insert(loc = 6, column = 'month', value = retail.date.dt.month) retail.insert(loc = 7, column = 'day', value = retail.date.dt.day) retail.insert(loc = 8, column ='hour', value = retail.date.dt.hour) retail.insert(loc = 9, column='day_of_week', value=(retail.date.dt.dayofweek)+1) retail.head() retail.insert(loc = 11, column = 'spent', value = (retail['quantity'] * retail['unit_price'])) retail.head() retail = retail[['invoice', 'country', 'cust_id', 'stock_code', 'desc','quantity', 'unit_price', 'date', 'spent', 'year_month', 'year', 'month', 'day', 'day_of_week', 'hour']] retail.head() #orders made by each customer ord_cust = retail.groupby(by = ['cust_id', 'country'], as_index = False)['invoice'].count() ord_cust.head(10) plt.subplots(figsize = (15, 6)) oc = plt.plot(ord_cust.cust_id, ord_cust.invoice) plt.xlabel('Customer ID') plt.ylabel('Number of Orders') plt.title('Number of Orders made by Customers') plt.show() ord_cust.describe() # 5 customers who ordered the most number of times ord_cust.sort_values(by = 'invoice', ascending = False).head() # money spent spent_cust = retail.groupby(by = ['cust_id', 'country'], as_index = False)['spent'].sum() spent_cust.head() plt.subplots(figsize = (15, 6)) sc = plt.plot(spent_cust.cust_id, spent_cust.spent) plt.xlabel('Customer ID') plt.ylabel('Total Amount Spent') plt.title('Amount Spent by Customers') plt.show() spent_cust.sort_values(by = 'spent', ascending = False).head() retail.tail() retail.head() #orders per month ord_month = retail.groupby(['invoice'])['year_month'].unique().value_counts().sort_index() ord_month om = ord_month.plot(kind='bar', figsize = (15, 6)) om.set_xlabel('Month') om.set_ylabel('Number of Orders') om.set_title('Orders per Month') om.set_xticklabels(('Dec 09', 'Jan 10', 'Feb 10', 'Mar 10', 'Apr 10', 'May 10', 'Jun 10', 'Jul 10', 'Aug 10', 'Sep 10', 'Oct 10', 'Nov 10', 'Dec 10', 'Jan 11', 'Feb 11', 'Mar 11', 'Apr 11', 'May 11', 'Jun 11', 'Jul 11', 'Aug 11', 'Sep 11', 'Oct 11', 'Nov 11', 'Dec 11'), rotation = 'horizontal') plt.show() # most popular time of the month to order ord_day = retail.groupby('invoice')['day'].unique().value_counts().sort_index() ord_day od = ord_day.plot(kind='bar', figsize = (15, 6)) od.set_xlabel('Day of the Month') od.set_ylabel('Number of Orders') od.set_title('Orders per Day of the Month') od.set_xticklabels(labels = [i for i in range (1, 32)], rotation = 'horizontal') plt.show() # orders per day of the week ord_dayofweek = retail.groupby('invoice')['day_of_week'].unique().value_counts().sort_index() ord_dayofweek odw = ord_dayofweek.plot(kind='bar', figsize = (15, 6)) odw.set_xlabel('Day of the Week') odw.set_ylabel('Number of Orders') odw.set_title('Orders per Day of the Week') odw.set_xticklabels(labels = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'], rotation = 'horizontal') plt.show() q_item = retail.groupby(by = ['desc'], as_index = False)['quantity'].sum() q_item.head() q_item.sort_values(by = 'quantity', ascending = False).head() item_month = retail.groupby(by = ['desc', 'year_month'], as_index = False)['quantity'].sum() item_month.sort_values(by = 'quantity', ascending = False).head() item_dayofweek = retail.groupby(by = ['desc', 'day_of_week'], as_index = False)['quantity'].sum() item_dayofweek.sort_values(by = 'quantity', ascending = False).head() item_coun = retail.groupby(by = ['desc', 'country'], as_index = False)['quantity'].sum() item_coun.sort_values(by = 'quantity', ascending = False).head() retail_sort = retail.sort_values(['cust_id', 'stock_code', 'date']) retail_sort_shift1 = retail_sort.shift(1) retail_sort_reorder = retail_sort.copy() retail_sort_reorder['reorder'] = np.where(retail_sort['stock_code'] == retail_sort_shift1['stock_code'], 1, 0) retail_sort_reorder.head() rsr = pd.DataFrame((retail_sort_reorder.groupby('desc')['reorder'].sum())).sort_values('reorder', ascending = False) rsr.head() q_up = retail.groupby(by = ['unit_price'], as_index = False)['quantity'].sum() q_up.sort_values('quantity', ascending = False).head(10) up_arr = np.array(retail.unit_price) q_arr = np.array(retail.quantity) np.corrcoef(up_arr, q_arr) ord_coun = retail.groupby(['country'])['invoice'].count().sort_values() ord_coun.head() ocoun = ord_coun.plot(kind='barh', figsize = (15, 6)) ocoun.set_xlabel('Number of Orders') ocoun.set_ylabel('Country') ocoun.set_title('Orders per Country') plt.show() del ord_coun['United Kingdom'] ocoun2 = ord_coun.plot(kind='barh', figsize = (15, 6)) ocoun2.set_xlabel('Number of Orders') ocoun2.set_ylabel('Country') ocoun2.set_title('Orders per Country') plt.show() coun_spent = retail.groupby('country')['spent'].sum().sort_values() cs = coun_spent.plot(kind='barh', figsize = (15, 6)) cs.set_xlabel('Amount Spent') cs.set_ylabel('Country') cs.set_title('Amount Spent per Country') plt.show() del coun_spent['United Kingdom'] cs2 = coun_spent.plot(kind='barh', figsize = (15, 6)) cs2.set_xlabel('Amount Spent') cs2.set_ylabel('Country') cs2.set_title('Amount Spent per Country') plt.show() ```
github_jupyter
# Dano's CORVO & TPOT notebook In this notebook, I will try and use TPOT to asses what traditional ML algorithms would be useful to predict cognitive performance from EEG data in Neurodoro ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import sklearn as sk from os import walk from os import listdir from os.path import isfile, join from sklearn.model_selection import train_test_split from tpot import TPOTRegressor EPOCH_LENGTH = 440 # 2 seconds # Data has been collected, let's import it data = pd.read_csv("../muse-data/PSD_dataset_may_17.csv", header=0, index_col=False) data = data.iloc[:500,:] data.describe # Let's get our labels data set first because it's easier. We'll grab every 4th row from the Performance column labels = data['Difficulty'].iloc[::4] # Then we'll reindex the dataframe labels = labels.reset_index().drop('index', axis=1) # Convert to 1D array for TPOT labels = np.array(labels).ravel() # Seperate data into 4 dataframes, 1 for each electrode chan1 = data.loc[:,'Channel':'60 hz'].loc[data['Channel'] == 1,].reset_index(drop=True) chan1.columns = np.arange(1000,1061) chan2 = data.loc[:,'Channel':'60 hz'].loc[data['Channel'] == 2,].reset_index(drop=True) chan2.columns = np.arange(2000,2061) chan3 = data.loc[:,'Channel':'60 hz'].loc[data['Channel'] == 3,].reset_index(drop=True) chan3.columns = np.arange(3000,3061) chan4 = data.loc[:,'Channel':'60 hz'].loc[data['Channel'] == 4,].reset_index(drop=True) chan4.columns = np.arange(4000,4061) # Concat all channel-specific dataframes together so that row = 2s epoch # columns = [electrode 1 FFT bins] + [electrode 2 FFT bins] + ... training_data = pd.concat([chan1.iloc[:,1:], chan2.iloc[:,1:], chan3.iloc[:,1:], chan4.iloc[:,1:]], axis=1, join_axes=[chan1.index]) print(training_data.shape) labels.shape ``` # Nice! ``` # Create a TPOTClassifier that will run for 10 generations pipeline_optimizer = TPOTRegressor(generations=10, population_size=30, cv=5, random_state=42, verbosity=3) # Fit this baby! Takes a long time to run pipeline_optimizer.fit(training_data, labels) # See what kind of score we get print(pipeline_optimizer.score(training_data, labels)) pipeline_optimizer.export('tpot_exported_pipeline3.py') print(pipeline_optimizer.score(training_data, labels)) # Split values and labels arrays into random train and test subsets (20% set aside for testing) X_train, X_test, y_train, y_test = train_test_split(training_data,labels,test_size=0.2) print(pipeline_optimizer.score(X_test, y_test)) ```
github_jupyter
``` !git clone https://github.com/JoyPang123/RL-Explore-with-Own-made-Env.git !mv RL-Explore-with-Own-made-Env/snake ./snake !pip install -e snake from collections import Counter import torch import torch.nn as nn import torch.nn.functional as F import torch.multiprocessing as mp from torch.distributions import Categorical import torchvision.transforms as transforms from torchvision.transforms import InterpolationMode import numpy as np import matplotlib.pyplot as plt import cv2 import gym class ActorCritic(nn.Module): """Adapted from https://github.com/raillab/a2c/blob/master/a2c/model.py """ def __init__(self, num_actions): super().__init__() # Create the layers for the model self.actor = nn.Sequential( nn.Conv2d( in_channels=3, out_channels=32, kernel_size=5, padding=2, stride=2 ), # (32, 32, 32) nn.ReLU(), nn.Conv2d( in_channels=32, out_channels=64, kernel_size=3, padding=1, stride=2 ), # (64, 16, 16) nn.ReLU(), nn.Conv2d( in_channels=64, out_channels=64, kernel_size=3, padding=1, stride=2 ), # (64, 8, 8) nn.ReLU(), nn.Conv2d( in_channels=64, out_channels=128, kernel_size=3, padding=1, stride=2 ), # (128, 4, 4) nn.ReLU(), nn.Flatten(start_dim=1), # (2048) nn.Linear(128 * 4 * 4, 512), nn.ReLU(), nn.Linear(512, num_actions) ) # Create the layers for the model self.critic = nn.Sequential( nn.Conv2d( in_channels=3, out_channels=32, kernel_size=5, padding=2, stride=2 ), # (32, 32, 32) nn.ReLU(), nn.Conv2d( in_channels=32, out_channels=64, kernel_size=3, padding=1, stride=2 ), # (64, 16, 16) nn.ReLU(), nn.Conv2d( in_channels=64, out_channels=64, kernel_size=3, padding=1, stride=2 ), # (64, 8, 8) nn.ReLU(), nn.Conv2d( in_channels=64, out_channels=128, kernel_size=3, padding=1, stride=2 ), # (128, 4, 4) nn.ReLU(), nn.Flatten(start_dim=1), # (2048) nn.Linear(128 * 4 * 4, 512), nn.ReLU(), nn.Linear(512, 1) ) def forward(self, x): actor = F.log_softmax(self.actor(x), dim=1) critic = self.critic(x) return actor, critic def run_episode(worker_env, worker_model, N_steps=1000): # Transform the image img_transforms = transforms.Compose([ transforms.ToTensor(), transforms.Resize((64, 64)) ]) state = worker_env.reset() state = img_transforms(state["frame"]) values, logprobs, rewards, actions = [], [], [], [] count_length = 0 while True: count_length += 1 policy, value = worker_model(state.unsqueeze(0).float()) values.append(value.view(-1)) logits = policy.view(-1) action_dist = Categorical(logits=logits) action = action_dist.sample() actions.append(action.item()) logprob_ = policy.view(-1)[action] logprobs.append(logprob_.view(-1)) state_, reward, done, info = worker_env.step(action.item()) state = img_transforms(state_["frame"]) rewards.append(torch.tensor([reward])) if done: break return values, logprobs, rewards, actions def update_params(worker_optim, values, log_probs, rewards, critic_coeff=1.0, gamma=0.9): logprobs = torch.cat(log_probs).float().flip(dims=(0,)) values = torch.cat(values).float().flip(dims=(0,)) rewards = torch.cat(rewards).float().flip(dims=(0,)) # eps = np.finfo(np.float32).eps.item() returns = [] ret_ = torch.tensor([0.]) for reward in rewards: ret_ = reward + gamma * ret_ returns.append(ret_) returns = torch.FloatTensor(returns) actor_loss = -1 * logprobs * (returns - values).detach() critic_loss = F.smooth_l1_loss(values, returns) loss = actor_loss.sum() + critic_loss.sum() worker_optim.zero_grad() loss.backward() worker_optim.step() return actor_loss, critic_loss, rewards.sum().item() def worker(model, episodes): worker_env = gym.make("snake:snake-v0") worker_optim = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.5) for episode in range(episodes): total_reward = 0 values, logprobs, rewards, actions = run_episode(worker_env, model) actor_loss, critic_loss, get_reward = update_params( worker_optim, values, logprobs, rewards ) total_reward += get_reward if (episode % 100) == 0: print(f"==========Episode: {episode}============") print(f"snake's length: {worker_env.snake.length}, reward: {total_reward}") action_counter = dict(Counter(actions)) for key, value in action_counter.items(): print(f"{key}:{value}", end=" ") print() def train(args, num_actions=4): actor_critic = ActorCritic(num_actions) worker(actor_critic, args["episodes"]) args = { "episodes": 4000, "num_workers": 1 } train(args) ```
github_jupyter
# ENV/ATM 415: Climate Laboratory [Brian E. J. Rose](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany # Lecture 3: The Climate System and Climate Models ___________ ## Contents 1. [The climate system and its interactions](#section1) 2. [Simulation versus Parameterization](#section2) 3. [A taxonomy of climate models](#section3) 4. [Introducing the GCM](#section4) 5. [What can we resolve with a 2º atmosphere?](#section5) ____________ <a id='section1'></a> ## 1. The climate system and its interactions ____________ ### Definition of the “climate system”: From the IPCC AR5 report: > **Climate System:** “The climate system is the highly complex system consisting of five major components: the atmosphere, the hydrosphere, the cryosphere, the lithosphere and the biosphere, and the interactions between them. The climate system evolves in time under the influence of its own internal dynamics and because of external forcings such as volcanic eruptions, solar variations and anthropogenic forcings such as the changing composition of the atmosphere and land use change.” Which begs some further definitions: #### Atmosphere >The gaseous envelope surrounding the Earth. #### Hydrosphere >The component of the climate system comprising liquid surface and subterranean water, such as oceans, seas, rivers, lakes, underground water, etc. #### **Biosphere** (terrestrial and marine): > The part of the Earth system comprising all ecosystems and living organisms… including derived dead organic matter, such as litter, soil organic matter and oceanic detritus. #### **Cryosphere**: > All regions on and beneath the surface of the Earth and ocean where water is in solid form, including sea ice, lake ice, river ice, snow cover, glaciers and ice sheets, and frozen ground (which includes permafrost). #### **Lithosphere**: > The upper layer of the solid Earth, both continental and oceanic, which comprises all crustal rocks and the cold, mainly elastic part of the uppermost mantle. ### Let’s think about WHY we should want to include all these “spheres” into our models. Here are two nice figures from the IPCC AR5 WG1 report: ![Main drivers of climate change](http://www.climatechange2013.org/images/figures/WGI_AR5_Fig1-1.jpg) >Figure 1.1 | Main drivers of climate change. The radiative balance between incoming solar shortwave radiation (SWR) and outgoing longwave radiation (OLR) is influenced by global climate ‘drivers’. Natural fluctuations in solar output (solar cycles) can cause changes in the energy balance (through fluctuations in the amount of incoming SWR) (Section 2.3). Human activity changes the emissions of gases and aerosols, which are involved in atmospheric chemical reactions, resulting in modified O3 and aerosol amounts (Section 2.2). O3 and aerosol particles absorb, scatter and reflect SWR, changing the energy balance. Some aerosols act as cloud condensation nuclei modifying the properties of cloud droplets and possibly affecting precipitation (Section 7.4). Because cloud interactions with SWR and LWR are large, small changes in the properties of clouds have important implications for the radiative budget (Section 7.4). Anthropogenic changes in GHGs (e.g., CO2, CH4, N2O, O3, CFCs) and large aerosols (>2.5 μm in size) modify the amount of outgoing LWR by absorbing outgoing LWR and re-emitting less energy at a lower temperature (Section 2.2). Surface albedo is changed by changes in vegetation or land surface properties, snow or ice cover and ocean colour (Section 2.3). These changes are driven by natural seasonal and diurnal changes (e.g., snow cover), as well as human influence (e.g., changes in vegetation types) (Forster et al., 2007). ![Climate feedbacks and timescales](http://www.climatechange2013.org/images/figures/WGI_AR5_Fig1-2.jpg) > Figure 1.2 | Climate feedbacks and timescales. The climate feedbacks related to increasing CO2 and rising temperature include negative feedbacks (–) such as LWR, lapse rate (see Glossary in Annex III), and air–sea carbon exchange and positive feedbacks (+) such as water vapour and snow/ice albedo feedbacks. Some feedbacks may be positive or negative (±): clouds, ocean circulation changes, air–land CO2 exchange, and emissions of non-GHGs and aerosols from natural systems. In the smaller box, the large difference in timescales for the various feedbacks is highlighted. ### The key is that all these processes ultimately affect the planetary energy budget. Let’s talk about **timescales**. Note that the IPCC figure only goes out to centuries – deep ocean circulation – but there are many even longer timescales in the climate system. e.g. growth and decay of ice sheets, geological processes like chemical weathering, continental drift The choice of which processes to include in a model should therefore be **guided by the timescales of interest**. For example, the IPCC process is primarily concerned with the century timescale – because it is of special concern to human affairs. So we don’t tend to include ice sheet and geological feedbacks – though coupled ice sheet modeling is becoming more important. ![Primer Table 1.8](http://www.atmos.albany.edu/facstaff/brose/classes/ENV415_Spring2018/images/Primer_Table1.8.png) ____________ <a id='section2'></a> ## 2. Simulation versus Parameterization ____________ The *Climate Modelling Primer* (4th ed., page 124) defines **parameterization** as > The process of capturing a physical process through some mathematical relationship between important parameters in the process, but without explicitly modeling all the actual processes. For example, the albedo of leaves might be related to the soil moisture (via some specification of wilting point) but the physical and biological mechanisms in the plant that happen when the leaf wilts are not modelled. An example from our own work so far: the **greenhouse effect**, which causes the OLR to be much lower than the surface emission, and the equilibrium temperature of the surface to be much warmer than it would otherwise be. In reality the greenhouse effect arises from the contributions of several different gases, at various levels, to the absorption and emission of longwave radiation. Key greenhouse species include water vapor and cloud droplets, which both strongly tied to the day-to-day variations in weather. How can we represent this in a climate model? ### Parameterization Represent the time-averaged, net effect of the complex radiative transfer process, and its coupling to day-to-day water and cloud variations, with an **empirical relationship**, e.g. $$ OLR = \tau \sigma T_s^4 $$ Use observed temperature and OLR to choose an appropriate value for $\tau$ (this is what we have done so far) #### Pro Simple to implement, easy to understand the result #### Con How might the value of $\tau$ change with climate change? We have no way of knowing, and have to make assumptions. ### Simulation: Solve a large set of coupled equations for the time-dependent behavior of the atmosphere: - Equations of radiative transfer, with detailed information about the various greenhouse gases - Equations of fluid motion to predict growth and decay of weather system and movement of water vapor - Cloud microphysics to predict the formation of cloud droplets and their optical properties This is essentially what goes on in a so-called GCM (General Circulation Model or Global Climate Model). #### Pro Model is based on real physical principles (e.g. Newton’s laws of motion, conservation of mass and energy). It is therefore more likely to remain valid under changing climate conditions. #### Con Requires lots of computer resources. Must simulate the weather even though we really just want the climate (statistics of weather!) Essentially a **simulation** involves representing (at least some aspects of) the underlying rules that govern the process. *There is a chain of causality linking input to output*. **Parameterization** involves making assumptions about the **statistical properties** of the process – so we can calculate some relevant statistical properties of the output given the input, without needing to explicitly model the actual events. ____________ <a id='section3'></a> ## 3. A taxonomy of climate models ____________ ### Key components of a climate model #### Radiation The way in which the input and absorption of solar radiation and the emission of infrared radiation are handled #### Dynamics The movement of energy around the globe by winds and ocean currents (specifically from low to high latitudes) and vertical movements (e.g. small-scale turbulence, convection and deep-water formation) #### Surface processes Inclusion of the effects of sea and land ice, snow, vegetation and the resultant change in albedo, emissivity and surface-atmosphere energy and moisture interchanges. #### Chemistry The chemical composition of the atmosphere and interactions, including biological, with other components (e.g. carbon exchanges between ocean, land and atmosphere) #### Resolution (in both time and space) The timestep of the model and the horizontal and vertical scales resolved. ### The climate modeling pyramid The edges represent the basic elements of the models, with **complexity increasing upwards**. Around the base of the pyramid are the simpler climate models, which incorporate only one primary process. ![Figure 2.2: The Climate Modelling Pyramid](http://www.atmos.albany.edu/facstaff/brose/classes/ENV415_Spring2018/images/Primer_Figure2.2.png) ### Five basic types of climate model 1. Energy Balance Models (EBMs) 2. Radiative-Convective (RC) or Single-Column models (SCMs) 3. "Dimensionally Constrained" models 4. Global Circulation Models (GCMs) 5. Earth System Models (ESMs) The vertical axis in the pyramid figures shows increasing complexity BOTH in terms of number of processes included and linked together, AND increasing resolution in space and time. ### 1. Energy Balance Models (EBMs) Zero- or one-dimensional models predicting the surface (strictly the sea-level) temperature as a function of the energy balance of the Earth. Simplified relationships are used to calculate the terms contributing to the energy balance in each latitude zone in the one-dimensional case. *How might we extend our zero-dimensional model to include a latitude dimension? What new kinds of processes might we have to include?* ### 2. Radiative-Convective (RC) or Single-Column models (SCMs) Focus on processes in the vertical column. RC models compute the (usually global average) temperature profile by explicit modelling of radiative processes and a ‘convective adjustment’, which re-establishes a predetermined lapse rate. SCMs are single columns 'extracted' from a three-dimensional model and include all the processes that would be modelled in the three-dimensional version but without any of the horizontal energy transfers. ### 3. Dimensionally constrained models Include the following: - Statistical-Dynamical (SD) models, deal explicitly with surface processes and dynamics in a zonal average (average around latitude circles) framework and have a vertically resolved atmosphere. - Earth-System Models of Intermediate Complexity (EMICs) extend SD models to include interactive chemistry, especially the cycling of carbon between ocean, atmosphere and land. - Integrated Assessment Models (IAMs) couple the climate system to models of economic activity to more fully assess the impact of particular policy choices affective emissions. ### 4. Global Circulation Models (GCMs) The **three-dimensional nature** of the atmosphere and ocean is incorporated. These models can exists as *fully coupled ocean-atmosphere models* or, for testing and evaluation, as independent ocean or atmospheric circulation models. These models attempt to simulate as many processes as possible and produce a three-dimensional picture of the time evolution of the state of the whole climate system. Vertical resolution is much finer than horizontal resolution but, even so, the number of layers is usually much less than the number of columns. ### Fun fact Depending on who you ask, **GCM** stands for any of the following: - **General Circulation Model** (the original) - **Global Climate Model** (more common these days) - **Global Circulation Model** (possibly the most accurate name) A GCM was originally a representation of the processes that shape and maintain the **time-average circulation** of the atmosphere, e.g. why are the surface winds, on average, westerly in mid-latitudes and easterly in the tropics? Distinctions have historically been drawn between **oceanic** and **atmospheric** general circulation models, which are often denoted **OGCM** and **AGCM** respectively. As the pyramid is ascended, more processes are integrated to develop a coupled ocean-atmosphere global model, which might be denoted **AOGCM** or **CGCM**. ### 5. Earth System Models Ascending the pyramid even more and moving forward in climate modeling history, more processes that used to be fixed come to be incorporated into GCMs and the coupling becomes more complete: e.g. changes in biomes and vegetation, chemical changes in atmosphere, ocean and soil. Such models are now generally known as **Earth System Models**. For brevity we use the generic term GCM to mean any complex three-dimensional model of the atmosphere and ocean and possibly other components, used for climate simulation. We will be more precise where necessary. ### Simple vs. Complex models: their different roles in the science ![Table 2.1: Simple and Complex Models](http://www.atmos.albany.edu/facstaff/brose/classes/ENV415_Spring2018/images/Primer_Table2.1.png) In this course we are going to work extensively with two kinds of simple one-dimensional model: **EBM**s and **RCM**s. Section 2.2.1 and 2.2.2 of the text give a sneak peak on the ingredients and uses for these models. ____________ <a id='section4'></a> ## 4. Introducing the GCM ____________ The aim of the GCM is the calculation of the **full three-dimensional character** of the atmosphere and ocean. To **simulate** the fluid flow and its effects on other components of the climate system, instead of **parameterizing** the flow. This requires the solution of a series of equations governing the motion of fluids - Conservation of energy - Conservation of momentum, Newton's 2nd law of motion (F=ma) for a moving fluid - Conservation of mass, for the fluid itself (air or water) as well as any quantities carried by the fluid (e.g. water vapor in the atmosphere, salt in the ocean) - Equation of state, linking thermodynamic properties of the fluid (e.g. ideal gas law for atmosphere) - Also, equations for the formation of clouds, sea ice, etc. Atmospheric Science students will recognize this list - the so-called "governing equations" for the atmosphere. These equations are the basis of *numerical weather prediction* as well as climate modeling. The physical laws are expressed in terms of **differential equations**. Just as we saw with the zero-dimensional EBM, we need to approximate the derivatives in order to represent them on a computer. One way to do this is to divide the Earth into a **series of boxes on a regular grid**. The model then represents all the **state variables**, e.g. for the atmosphere - Temperature - Wind speed and direction - Humidity - Pressure for each box - essentially a spatial average of these quantities over the box. The discretized equations are then solved numerically by **timestepping**, (conceptually at least) just like we have already done with the EBM. ![Table 2.1: Simple and Complex Models](http://www.atmos.albany.edu/facstaff/brose/classes/ENV415_Spring2018/images/Primer_Figure2.5.png) ### Evolving complexity of GCMs ![WGI_AR5_Fig1-13](http://www.climatechange2013.org/images/figures/WGI_AR5_Fig1-13.jpg) > Figure 1.13 | The development of climate models over the last 35 years showing how the different components were coupled into comprehensive climate models over time. In each aspect (e.g., the atmosphere, which comprises a wide range of atmospheric processes) the complexity and range of processes has increased over time (illustrated by growing cylinders). Note that during the same time the horizontal and vertical resolution has increased considerably e.g., for spectral models from T21L9 (roughly 500 km horizontal resolu- tion and 9 vertical levels) in the 1970s to T95L95 (roughly 100 km horizontal resolution and 95 vertical levels) at present, and that now ensembles with at least three independent experiments can be considered as standard. ![WGI_AR5_Fig1-14](http://www.climatechange2013.org/images/figures/WGI_AR5_Fig1-14.jpg) > Figure 1.14 | Horizontal resolutions considered in today’s higher resolution models and in the very high resolution models now being tested: (a) Illustration of the European topography at a resolution of 87.5 × 87.5 km; (b) same as (a) but for a resolution of 30.0 × 30.0 km. One goal of all this complexity is to do **more simulation** and **less parameterization** in order to get a more accurate prediction of climate change. Ideally this means basing the model on **laws of physics and chemistry**. ### A hierarchy of complexity for ocean models ![Figure 2.9: ocean model hierarchy](http://www.atmos.albany.edu/facstaff/brose/classes/ENV415_Spring2018/images/Primer_Figure2.9.png) ____________ <a id='section5'></a> ## 5. What can we resolve with a 2º atmosphere? ____________ The following animation shows contours of sea level pressure in the control simulation. It is based on 6-hourly output from the numerical model. The atmosphere is simulated with a 2º finite volume dynamical core. ``` from IPython.display import YouTubeVideo YouTubeVideo('As85L34fKYQ') ``` ### Discussion point: How well does this represent the true general circulation of the atmosphere? ____________ ## Citation information The figures above are reproduced from Chapter 1 of the IPCC AR5 Working Group 1 report. The report and images can be found online at http://www.climatechange2013.org/report/full-report/ The full citation is: > Cubasch, U., D. Wuebbles, D. Chen, M.C. Facchini, D. Frame, N. Mahowald and J.-G. Winther, 2013: Introduction. In: Climate Change 2013: The Physical Science Basis. Contribution of Working Group I to the Fifth Assessment Report of the Intergovernmental Panel on Climate Change [Stocker, T.F., D. Qin, G.-K. Plattner, M. Tignor, S.K. Allen, J. Boschung, A. Nauels, Y. Xia, V. Bex and P.M. Midgley (eds.)]. Cambridge University Press, Cambridge, United Kingdom and New York, NY, USA, pp. 119–158, doi:10.1017/CBO9781107415324.007. ____________
github_jupyter
``` # Some basic imports and setup import numpy as np, numpy.random as nr, gym import matplotlib.pyplot as plt import time np.set_printoptions(precision=3) from robolearn.envs.frozen_lake import FrozenLakeEnv class MDP(object): """ mdp.P is a two-level dict where the first key is the state and the second key is the action. The 2D grid cells are associated with indices [0, 1, 2, ..., 15] from left to right and top to down, as in [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Action indices [0, 1, 2, 3] correspond to West, South, East and North. mdp.P[state][action] is a list of tuples (probability, nextstate, reward). For example, state 0 is the initial state, and the transition information for s=0, a=0 is P[0][0] = [(1.0, 0, 0.0)]", As another example, state 5 corresponds to a hole in the ice, in which all actions lead to the same state with probability 1 and reward 0: P[5][0] = [(1.0, 5, 0.0)] P[5][1] = [(1.0, 5, 0.0)] P[5][2] = [(1.0, 5, 0.0)] P[5][3] = [(1.0, 5, 0.0)] """ def __init__(self, P, nS, nA, desc=None): self.P = P # state transition and reward probabilities, explained below self.nS = nS # number of states self.nA = nA # number of actions self.desc = desc # 2D array specifying what each grid cell means (used for plotting) def value_iteration(mdp, gamma, nIt, show_log=False): """ Inputs: mdp: MDP gamma: discount factor nIt: number of iterations, corresponding to n above Outputs: (value_functions, policies) len(value_functions) == nIt+1 and len(policies) == nIt """ if show_log: print("Iteration | max|V-Vprev| | # chg actions | V[0]") print("----------+--------------+---------------+---------") Vs = [np.zeros(mdp.nS)] # list of value functions contains the initial value function V^{(0)}, which is zero pis = [] for it in range(nIt): oldpi = pis[-1] if len(pis) > 0 else None # \pi^{(it)} = Greedy[V^{(it-1)}]. Just used for printout Vprev = Vs[-1] # V^{(it)} # Your code should fill in meaningful values for the following two variables # pi: greedy policy for Vprev (not V), # corresponding to the math above: \pi^{(it)} = Greedy[V^{(it)}] # ** it needs to be numpy array of ints ** # V: bellman backup on Vprev # corresponding to the math above: V^{(it+1)} = T[V^{(it)}] # ** numpy array of floats ** # V = Vprev # REPLACE THIS LINE WITH YOUR CODE # pi = oldpi # REPLACE THIS LINE WITH YOUR CODE V = np.zeros_like(Vprev) pi = np.zeros_like(V) for s in range(mdp.nS): q = np.zeros(mdp.nA) for a in range(mdp.nA): for s_prime_prob, s_prime, reward in mdp.P[s][a]: q[a] += s_prime_prob*(reward + gamma * Vprev[s_prime]) V[s] = np.max(q) pi[s] = np.argmax(q) if show_log: max_diff = np.abs(V - Vprev).max() nChgActions="N/A" if oldpi is None else (pi != oldpi).sum() print("%4i | %6.5f | %4s | %5.3f"%(it, max_diff, nChgActions, V[0])) Vs.append(V) pis.append(pi) return Vs, pis def plot_value_iteration(Vs, pis, iters_to_plot=None, ncol=4, nrow=4): square_size = .5 if iters_to_plot is None: iters_to_plot = [-1] Vs_to_plot = [Vs[iteration] for iteration in iters_to_plot] pis_to_plot = [pis[iteration] for iteration in iters_to_plot] for pp, (_V, _pi) in enumerate(zip(Vs_to_plot, pis_to_plot)): plt.figure()#figsize=(3,3)) plt.imshow(_V.reshape(ncol,nrow), cmap='gray', interpolation='none', clim=(0,1)) ax = plt.gca() ax.set_xticks(np.arange(ncol)-square_size) ax.set_yticks(np.arange(nrow)-square_size) ax.set_xticklabels([]) ax.set_yticklabels([]) Y, X = np.mgrid[0:4, 0:4] a2uv = {0: (-1, 0), 1:(0, -1), 2:(1,0), 3:(0, 1)} Pi = _pi.reshape(ncol,nrow) for y in range(ncol): for x in range(nrow): a = Pi[y, x] # Arrow u, v = a2uv[a] plt.arrow(x, y,u*.3, -v*.3, color='m', head_width=0.1, head_length=0.1) # Text plt.text(x, y, str(env.desc[y,x].item().decode()), color='g', size=12, verticalalignment='center', horizontalalignment='center', fontweight='bold') plt.text(x-square_size/3, y-square_size/2, str(np.around(_V[4*y+x], decimals=2)), color='r', size=8, verticalalignment='center', horizontalalignment='center') plt.grid(color='b', lw=2, ls='-') print('Iter %d' % pp) plt.show() print('-'*20) class Agent(object): def __init__(self, policy): self.policy = policy def act(self, state): return self.policy[state] GAMMA = 0.95 # we'll be using this same value in subsequent problems nIt = 300 env = FrozenLakeEnv(map_name='4x4', is_slippery=False, reward_dict={'G':1, 'S':0, 'H':-1, 'F':-0.00}) # Create a MDP from the environment mdp = MDP( {s : {a : [tup[:3] for tup in tups] for (a, tups) in a2d.items()} for (s, a2d) in env.P.items()}, env.nS, env.nA, env.desc) # Learn with Value Iteration a policy Vs_VI, pis_VI = value_iteration(mdp, gamma=GAMMA, nIt=nIt, show_log=False) # Visualize Policy %matplotlib inline iters_to_plot = [-1] # Plot only last VI values plot_value_iteration(Vs_VI, pis_VI, iters_to_plot, env.ncol, env.nrow) %matplotlib notebook # Seed RNGs env.seed(0); from gym.spaces import prng; prng.seed(10) # Notebook figure fig = plt.figure() ax = fig.add_subplot(1,1,1) # Agent from previous VI agent = Agent(pis_VI[-1]) # Generate the episode ob = env.reset() render = ax.imshow(env.render(mode='rgb_array')) ret = 0 for t in range(50): fig.canvas.set_window_title('Frozen Lake -- Iteration: %02d' % t) time.sleep(0.5) render.set_data(env.render(mode='rgb_array')) fig.canvas.draw() # a = env.action_space.sample() a = agent.act(ob) ob, rew, done, _ = env.step(a) ret += rew print('iter', t, '| ob',ob,'| action',a,'| reward',rew) if done: break assert done fig.canvas.set_window_title('Frozen Lake -- Iteration: %02d' % t) time.sleep(0.5) render.set_data(env.render(mode='rgb_array')) fig.canvas.draw() # env.render(close=True) print('Finished at t=%d'%(t+1),'| Acum reward:', ret) ```
github_jupyter