markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
To get an overview of the data we'll quickly sort it and then view the data for one year. | %%opts Table [aspect=1.5 fig_size=300]
macro = macro.sort()
macro[1988] | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Most of the examples above focus on converting a Table to simple Element types, but HoloViews also provides powerful container objects to explore high-dimensional data, such as [HoloMap](Containers.ipynbHoloMap), [NdOverlay](Containers.ipynbNdOverlay), [NdLayout](Containers.ipynbNdLayout), and [GridSpace](Containers.ip... | %%opts Curve (color=Palette('Set3'))
gdp_curves = macro.to.curve('Year', 'GDP Growth')
gdp_curves.overlay('Country') | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Now that we've extracted the ``gdp_curves``, we can apply some operations to them. As in the simpler example above we will ``collapse`` the HoloMap of Curves using a number of functions to visualize the distribution of GDP Growth rates over time. First we find the mean curve with ``np.std`` as the ``spreadfn`` and cast... | %%opts Overlay [bgcolor='w' legend_position='top_right'] Curve (color='k' linewidth=1) Spread (facecolor='gray' alpha=0.2)
hv.Spread(gdp_curves.collapse('Country', np.mean, np.std), label='std') *\
hv.Overlay([gdp_curves.collapse('Country', fn).relabel(name).opts(style=dict(linestyle=ls))
for name, fn, ls i... | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Many HoloViews Element types support multiple ``kdims``, including ``HeatMap``, ``Points``, ``Scatter``, ``Scatter3D``, and ``Bars``. ``Bars`` in particular allows you to lay out your data in groups, categories and stacks. By supplying the index of that dimension as a plotting option you can choose to lay out your data... | %opts Bars [bgcolor='w' aspect=3 figure_size=450 show_frame=False]
%%opts Bars [category_index=2 stack_index=0 group_index=1 legend_position='top' legend_cols=7 color_by=['stack']] (color=Palette('Dark2'))
macro.to.bars(['Country', 'Year'], 'Trade', []) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
This plot contains a lot of data, and so it's probably a good idea to focus on specific aspects of it, telling a simpler story about them. For instance, using the .select method we can then customize the palettes (e.g. to use consistent colors per country across multiple analyses).Palettes can customized by selecting ... | %%opts Bars [padding=0.02 color_by=['group']] (alpha=0.6, color=Palette('Set1', reverse=True)[0.:.2])
countries = {'Belgium', 'Netherlands', 'Sweden', 'Norway'}
macro.to.bars(['Country', 'Year'], 'Unemployment').select(Year=(1978, 1985), Country=countries) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Many HoloViews Elements support multiple key and value dimensions. A HeatMap is indexed by two kdims, so we can visualize each of the economic indicators by year and country in a Layout. Layouts are useful for heterogeneous data you want to lay out next to each other.Before we display the Layout let's apply some stylin... | %opts HeatMap [show_values=False xticks=40 xrotation=90 aspect=1.2 invert_yaxis=True colorbar=True]
%%opts Layout [aspect_weight=1 fig_size=150 sublabel_position=(-0.2, 1.)]
hv.Layout([macro.to.heatmap(['Year', 'Country'], value)
for value in macro.data.columns[2:]]).cols(2) | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Another way of combining heterogeneous data dimensions is to map them to a multi-dimensional plot type. Scatter Elements, for example, support multiple ``vdims``, which may be mapped onto the color and size of the drawn points in addition to the y-axis position. As for the Curves above we supply 'Year' as the sole key ... | %%opts Scatter [scaling_method='width' scaling_factor=2 size_index=2] (color=Palette('Set3') edgecolors='k')
gdp_unem_scatter = macro.to.scatter('Year', ['GDP Growth', 'Unemployment'])
gdp_unem_scatter.overlay('Country') | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
In this way we can plot any dimension against any other dimension, very easily allowing us to iterate through different ways of revealing relationships in the dataset. | %%opts NdOverlay [legend_cols=2] Scatter [size_index=1] (color=Palette('Blues'))
macro.to.scatter('GDP Growth', 'Unemployment', ['Year']).overlay() | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
This view, for example, immediately highlights the high unemployment rates of the 1980s. Since all HoloViews Elements are composable, we can generate complex figures just by applying the * operator. We'll simply reuse the GDP curves we generated earlier, combine them with the scatter points (which indicate the unemploy... | %%opts Curve (color='k') Scatter [color_index=2 size_index=2 scaling_factor=1.4] (cmap='Blues' edgecolors='k')
macro_overlay = gdp_curves * gdp_unem_scatter
annotations = hv.Arrow(1973, 8, 'Oil Crisis', 'v') * hv.Arrow(1975, 6, 'Stagflation', 'v') *\
hv.Arrow(1979, 8, 'Energy Crisis', 'v') * hv.Arrow(1981.9, 5, 'Early... | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Since we didn't map the country to some other container type, we get a widget allowing us to view the plot separately for each country, reducing the forest of curves we encountered before to manageable chunks. While looking at the plots individually like this allows us to study trends for each country, we may want to l... | %%opts NdLayout [figure_size=100] Overlay [aspect=1] Scatter [color_index=2] (cmap='Reds')
countries = {'United States', 'Canada', 'United Kingdom'}
(gdp_curves * gdp_unem_scatter).select(Country=countries).layout('Country') | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Finally, let's combine some plots for each country into a Layout, giving us a quick overview of each economic indicator for each country: | %%opts Scatter [color_index=2] (cmap='Reds') Overlay [aspect=1]
(macro_overlay.relabel('GDP Growth', depth=1) +\
macro.to.curve('Year', 'Unemployment', ['Country'], group='Unemployment',) +\
macro.to.curve('Year', 'Trade', ['Country'], group='Trade') +\
macro.to.scatter('GDP Growth', 'Unemployment', ['Country'])).cols(... | _____no_output_____ | BSD-3-Clause | doc/Tutorials/Columnar_Data.ipynb | stuarteberg/holoviews |
Proving Universality What does it mean for a computer to do everything that it could possibly do? This was a question tackled by Alan Turing before we even had a good idea of what a computer was.To ask this question for our classical computers, and specifically for our standard digital computers, we need to strip away... | import qiskit
qiskit.__qiskit_version__ | _____no_output_____ | Apache-2.0 | qiskit-textbook/content/ch-gates/proving-universality.ipynb | RenatoFarruggio/Quantum-information-course-Basel |
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... | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Обучи свою первую нейросеть: простая классификация Смотрите на TensorFlow.org Запустите в Google Colab Изучайте код на GitHub Скачайте ноутбук Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не ... | # TensorFlow и tf.keras
import tensorflow as tf
from tensorflow import keras
# Вспомогательные библиотеки
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Загружаем датасет Fashion MNIST Это руководство использует датасет [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) который содержит 70,000 монохромных изображений в 10 категориях. На каждом изображении содержится по одному предмету одежды в низком разрешении (28 на 28 пикселей): <img src="https:... | fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Загрузка датасета возвращает четыре массива NumPy:* Массивы `train_images` и `train_labels` являются *тренировочным сетом* — данными, на которых модель будет обучаться.* Модель тестируется на *проверочном сете*, а именно массивах `test_images` и `test_labels`.Изображения являются 28х28 массивами NumPy, где значение пик... | class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Изучите данныеДавайте посмотрим на формат данных перед обучением модели. Воспользовавшись shape мы видим, что в тренировочном датасете 60,000 изображений, каждое размером 28 x 28 пикселей: | train_images.shape | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Соответственно, в тренировочном сете 60,000 меток: | len(train_labels) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Каждая метка это целое число от 0 до 9: | train_labels | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Проверочный сет содержит 10,000 изображений, каждое - также 28 на 28 пикселей: | test_images.shape | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
И в проверочном сете - ровно 10,000 меток: | len(test_labels) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Предобработайте данныеДанные должны быть предобработаны перед обучением нейросети. Если вы посмотрите на первое изображение в тренировочном сете вы увидите, что значения пикселей находятся в диапазоне от 0 до 255: | plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show() | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Мы масштабируем эти значения к диапазону от 0 до 1 перед тем как скормить их нейросети. Для этого мы поделим значения на 255. Важно, чтобы *тренировочный сет* и *проверочный сет* были предобработаны одинаково: | train_images = train_images / 255.0
test_images = test_images / 255.0 | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Чтобы убедиться, что данные в правильном формате и мы готовы построить и обучить нейросеть, выведем на экран первые 25 изображений из *тренировочного сета* и отобразим под ними наименования их классов. | plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show() | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Постройте модельПостроение модели нейронной сети требует правильной конфигурации каждого слоя, и последующей компиляции модели. Настройте слоиБазовым строительным блоком нейронной сети является *слой*. Слои извлекают образы из данных, которые в них подаются. Надеемся, что эти образы имеют смысл для решаемой задачи.Бо... | model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
]) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Первый слой этой сети - `tf.keras.layers.Flatten`, преобразует формат изображения из двумерного массива (28 на 28 пикселей) в одномерный (размерностью 28 * 28 = 784 пикселя). Слой извлекает строки пикселей из изображения и выстраивает их в один ряд. Этот слой не имеет параметров для обучения; он только переформатирует ... | model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Обучите модельОбучение модели нейронной сети требует выполнения следующих шагов::1. Подайте тренировочный данные в модель. В этом примере тренировочные данные это массивы `train_images` и `train_labels`.2. Модель учится ассоциировать изображения с правильными классами.3. Мы просим модель сделать прогнозы для проверочн... | model.fit(train_images, train_labels, epochs=10) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
В процессе обучения модели отображаются метрики потери (loss) и точности (accuracy). Эта модель достигает на тренировочных данных точности равной приблизительно 0.88 (88%). Оцените точностьДалее, сравните какую точность модель покажет на проверчном датасете: | test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nТочность на проверочных данных:', test_acc) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Полученная на проверочном сете точность оказалась немного ниже, чем на тренировочном. Этот разрыв между точностью на тренировке и тесте является примером *переобучения (overfitting)* . Переобучение возникает, когда модель машинного обучения показывает на новых данных худший результат, чем на тех, на которых она обучала... | predictions = model.predict(test_images) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Здесь полученная модель предсказала класс одежды для каждого изображения в проверочном датасете. Давайте посмотрим на первое предсказание: | predictions[0] | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Прогноз представляет из себя массив из 10 чисел. Они описывают "уверенность" (confidence) модели в том, насколько изображение соответствует каждому из 10 разных видов одежды. Мы можем посмотреть какой метке соответствует максимальное значение: | np.argmax(predictions[0]) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Модель полагает, что на первой картинке изображен ботинок (ankle boot), или class_names[9]. Проверка показывает, что классификация верна: | test_labels[0] | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Мы можем построить график, чтобы взглянуть на полный набор из 10 предсказаний классов. | def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
c... | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Давайте посмотрим на нулевое изображение, предсказание и массив предсказаний. | 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)
plt.show()
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_arra... | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Давайте посмотрим несколько изображений с их прогнозами. Цвет верных предсказаний синий, а неверных - красный. Число это процент уверенности (от 100) для предсказанной метки. Отметим, что модель может ошибаться даже если она очень уверена. | # Отображаем первые X тестовых изображений, их предсказанную и настоящую метки.
# Корректные предсказания окрашиваем в синий цвет, ошибочные в красный.
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, ... | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Наконец, используем обученную модель для предсказания класса на одном изображении. | # Берем одну картинку из проверочного сета.
img = test_images[0]
print(img.shape) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Модели tf.keras оптимизированы для предсказаний на *пакетах (batch)* данных, или на множестве примеров сразу. Таким образом, даже если мы используем всего 1 картинку, нам все равно необходимо добавить ее в список: | # Добавляем изображение в пакет данных, состоящий только из одного элемента.
img = (np.expand_dims(img,0))
print(img.shape) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Сейчас предскажем правильную метку для изображения: | predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
Метод `model.predict` возвращает нам список списков, по одному для каждой картинки в пакете данных. Получите прогнозы для нашего (единственного) изображения в пакете: | np.argmax(predictions_single[0]) | _____no_output_____ | Apache-2.0 | site/ru/tutorials/keras/classification.ipynb | ilyaspiridonov/docs-l10n |
San Francisco Rental Prices DashboardIn this notebook, you will compile the visualizations from the previous analysis into functions that can be used for a Panel dashboard. | # imports
import panel as pn
pn.extension('plotly')
import plotly.express as px
import pandas as pd
import hvplot.pandas
import matplotlib.pyplot as plt
import os
from pathlib import Path
from dotenv import load_dotenv
from panel.interact import interact
# Read the Mapbox API key
load_dotenv()
map_box_api = os.getenv("... | _____no_output_____ | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
Import Data | # Import the necessary CSVs to Pandas DataFrames
sfo_data = pd.read_csv(Path("Data/sfo_neighborhoods_census_data.csv"), index_col="year")
neighborhood_locations = pd.read_csv(Path("Data/neighborhoods_coordinates.csv"))
neighborhood_locations.columns = ["neighborhood", "Lat", "Lon"]
print(sfo_data.head())
print(neighbo... | neighborhood sale_price_sqr_foot housing_units gross_rent
year
2010 Alamo Square 291.182945 372560 1239
2010 Anza Vista 267.932583 372560 1239
2010 Bayview 170... | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
- - - Panel VisualizationsIn this section, you will copy the code for each plot type from your analysis notebook and place it into separate functions that Panel can use to create panes for the dashboard. These functions will convert the plot object to a Panel pane.Be sure to include any DataFrame transformation/manipu... | # caculations reused for different functions below
top_ten_expensive_neighborhood=sfo_data.groupby(['neighborhood']).mean().sort_values(by=['sale_price_sqr_foot'],ascending=False).reset_index().head(10)
neighborhood_mean=sfo_data.groupby(['neighborhood']).mean().sort_values(by=['sale_price_sqr_foot'],ascending=False).... | _____no_output_____ | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
Panel DashboardIn this section, you will combine all of the plots into a single dashboard view using Panel. Be creative with your dashboard design! |
title = '##Real Estate Analysis of San Francisco'
welcome_tab = pn.Column(pn.Column(title), neighborhood_map())
market_analysis_row = pn.Row(housing_units_per_year(), average_gross_rent(), average_sales_price())
neighborhood_analysis_tab = pn.Column(average_price_by_neighborhood(),
top_most_expensive_neighborh... | /Users/manishrajkarnikar/opt/anaconda3/envs/alpacaenv/lib/python3.7/site-packages/ipykernel_launcher.py:15: FutureWarning:
Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.
/Users/manishrajkarnikar/opt/anaconda3/envs/alpacaenv/lib/python3.7/site-packages/ipy... | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
Serve the Panel Dashboard | # Serve the# dashboard
SF_dashboard.servable() | _____no_output_____ | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
DebuggingNote: Some of the Plotly express plots may not render in the notebook through the panel functions.However, you can test each plot by uncommenting the following code | housing_units_per_year()
average_gross_rent()
average_sales_price()
average_price_by_neighborhood()
top_most_expensive_neighborhoods()
most_expensive_neighborhoods_rent_sales()
neighborhood_map()
parallel_categories()
parallel_coordinates()
sunburst() | _____no_output_____ | RSA-MD | dashboard.ipynb | mrajkarnikar/06-PyViz |
Softmax exercise*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*This exercise is analo... | %matplotlib inline
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-re... | _____no_output_____ | MIT | cs231n_assignment1/softmax.ipynb | gongjue/cs231n |
Softmax ClassifierYour code for this section will all be written inside **cs231n/classifiers/softmax.py**. | # First implement the naive softmax loss function with nested loops.
# Open the file cs231n/classifiers/softmax.py and implement the
# softmax_loss_naive function.
from cs231n.classifiers.softmax import softmax_loss_naive
import time
# Generate a random softmax weight matrix and use it to compute the loss.
W = np.ran... | _____no_output_____ | MIT | cs231n_assignment1/softmax.ipynb | gongjue/cs231n |
Inline Question 1:Why do we expect our loss to be close to -log(0.1)? Explain briefly.****Your answer:** *Fill this in* | # Complete the implementation of softmax_loss_naive and implement a (naive)
# version of the gradient that uses nested loops.
loss, grad = softmax_loss_naive(W, X_dev, y_dev, 0.0)
# As we did for the SVM, use numeric gradient checking as a debugging tool.
# The numeric gradient should be close to the analytic gradient... | _____no_output_____ | MIT | cs231n_assignment1/softmax.ipynb | gongjue/cs231n |
HMDP Topic Model IPython WrapperThis is a Python class which wraps the Java binaries from the HMDP topic model from the PROMOSS topic modelling toolbox. The *promoss.jar* is expected to be in *../promoss.jar*. HMDP classThe HMDP class contains all the methods required to run the HMDP topic model. Mandatory parameters... | # coding: utf-8
%matplotlib inline
import json
import io, os, shutil, time, datetime
import subprocess
import folium
from IPython.core.display import HTML
from IPython.display import IFrame, display
import matplotlib.pyplot as plt
import pandas as pd
class HMDP(object):
directory = "";
meta_params = "";
T... | _____no_output_____ | Apache-2.0 | ipynb/hmdp.ipynb | ckling/hmdp |
Tables to Networks, Networks to TablesNetworks can be represented in a tabular form in two ways: As an adjacency list with edge attributes stored as columnar values, and as a node list with node attributes stored as columnar values.Storing the network data as a single massive adjacency table, with node attributes repe... | # This block of code checks to make sure that a particular directory is present.
if "divvy_2013" not in os.listdir('datasets/'):
print('Unzip the divvy_2013.zip file in the datasets folder.')
stations = pd.read_csv('datasets/divvy_2013/Divvy_Stations_2013.csv', parse_dates=['online date'], index_col='id', encoding=... | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
At this point, we have our `stations` and `trips` data loaded into memory. How we construct the graph depends on the kind of questions we want to answer, which makes the definition of the "unit of consideration" (or the entities for which we are trying to model their relationships) is extremely important. Let's try to ... | G = nx.DiGraph() | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
Then, let's iterate over the `stations` DataFrame, and add in the node attributes. | for r, d in stations.iterrows(): # call the pandas DataFrame row-by-row iterator
G.add_node(r, attr_dict=d.to_dict()) | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
In order to answer the question of "which stations are important", we need to specify things a bit more. Perhaps a measure such as **betweenness centrality** or **degree centrality** may be appropriate here.The naive way would be to iterate over all the rows. Go ahead and try it at your own risk - it may take a long ti... | # # Run the following code at your own risk :)
# for r, d in trips.iterrows():
# start = d['from_station_id']
# end = d['to_station_id']
# if (start, end) not in G.edges():
# G.add_edge(start, end, count=1)
# else:
# G.edge[start][end]['count'] += 1
for (start, stop), d in trips.groupby(... | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
ExerciseFlex your memory muscles: can you make a scatter plot of the distribution of the number edges that have a certain number of trips? The key should be the number of trips between two nodes, and the value should be the number of edges that have that number of trips. | from collections import Counter
# Count the number of edges that have x trips recorded on them.
trip_count_distr = ______________________________
# Then plot the distribution of these
plt.scatter(_______________, _______________, alpha=0.1)
plt.yscale('log')
plt.xlabel('num. of trips')
plt.ylabel('num. of edges') | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
ExerciseCreate a new graph, and filter out the edges such that only those with more than 100 trips taken (i.e. `count >= 100`) are left. | # Filter the edges to just those with more than 100 trips.
G_filtered = G.copy()
for u, v, d in G.edges(data=True):
# Fill in your code here.
len(G_filtered.edges()) | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
Let's now try drawing the graph. ExerciseUse `nx.draw(my_graph)` to draw the filtered graph to screen. | # Fill in your code here.
| _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
ExerciseTry visualizing the graph using a CircosPlot. Order the nodes by their connectivity in the **original** graph, but plot only the **filtered** graph edges. | nodes = sorted(_________________, key=lambda x:_________________)
edges = ___________
edgeprops = dict(alpha=0.1)
nodecolor = plt.cm.viridis(np.arange(len(nodes)) / len(nodes))
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
c = CircosPlot(nodes, edges, radius=10, ax=ax, fig=fig, edgeprops=edgeprops, nodecol... | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
In this visual, nodes are sorted from highest connectivity to lowest connectivity in the **unfiltered** graph.Edges represent only trips that were taken >100 times between those two nodes.Some things should be quite evident here. There are lots of trips between the highly connected nodes and other nodes, but there are ... | nx.write_gpickle(G, 'datasets/divvy_2013/divvy_graph.pkl')
G = nx.read_gpickle('datasets/divvy_2013/divvy_graph.pkl') | _____no_output_____ | MIT | 5. Loading and Visualizing Network Data (Student).ipynb | sbrown97/network-analysis |
SIEM Data Exploration with Spark Data Formatting Data SourceData used in this example is from a market leading SIEM File NamesIndividual CSV files are converted from CSV to Parquet files (see `architecture.pdf` for more info) then saved by hour with the name format `YYYY-MM-DD-HH` Field NamesField names match from the... | # HDFS config parameters
hdfsNameNode = "10.0.0.1"
hdfsPort = "8020" | _____no_output_____ | BSD-3-Clause | examples.ipynb | accenturelabs/blackhat-arsenal-2016 |
Import Spark Libraries | # Import libraries for PySpark/SparkSQL
from pyspark import SQLContext
from pyspark.sql.functions import *
# Create a SQLContext to use for SQL queries
sq = SQLContext(sc)ß | _____no_output_____ | BSD-3-Clause | examples.ipynb | accenturelabs/blackhat-arsenal-2016 |
Example 1 Network communication lookup, from source subnet to multiple destinations SQL Example: ```WHERE sourceAddress CONTAINS "55.54.53." AND ( ( destinationAddress = "10.0.0.50" ) OR ( destinationAddress = "10.0.0.51" ) OR ( destinationAddress = "10.0.0.52" ) )``` | %%time
### One Day
data1 = sq.read.parquet("hdfs://"+hdfsNameNode+":"+hdfsPort+"/data/2016-06-01*")
pdf1 = data1.filter(data1.sourceAddress.startswith("55.54.53.")) \
.filter("destinationAddress = '10.0.0.50' OR destinationAddress = '10.0.0.51' OR destinationAddress = '10.0.0.52'") \
.toPandas()
### Number of r... | _____no_output_____ | BSD-3-Clause | examples.ipynb | accenturelabs/blackhat-arsenal-2016 |
Example 2 Account failed logon attempts lookup, using startswith keyword SQL Example:```WHERE destinationUserName startswith "ads." AND categoryOutcome = "/Failure"``` | %%time
### One Day
data5 = sq.read.parquet("hdfs://"+hdfsNameNode+":"+hdfsPort+"/data/2016-06-01*")
pdf5 = data5.filter(data5.destinationUserName.startswith("ads.")) \
.filter(data5.categoryOutcome == "/Failure") \
.toPandas()
### Number of results
len(pdf5)
### Display the first 10 results
pdf5.head(10)
%%time... | _____no_output_____ | BSD-3-Clause | examples.ipynb | accenturelabs/blackhat-arsenal-2016 |
Example 3 Malware infection lookup, particular keyword in message field SQL Example:```WHERE deviceVendor="Symantec" AND message contains "exe"``` | %%time
### One Day
data3 = sq.read.parquet("hdfs://"+hdfsNameNode+":"+hdfsPort+"/data/2016-06-01*")
pdf3 = data3.filter(data3.deviceVendor == "Symantec") \
.filter(data3.message.like("%exe%")) \
.toPandas()
### Number of results
len(pdf3)
### Display the first 10 results
pdf3.head(10)
%%time
### One Week
data4 ... | _____no_output_____ | BSD-3-Clause | examples.ipynb | accenturelabs/blackhat-arsenal-2016 |
TOC __Chapter 2 - Text wrangling and processing__1. [Import](Import)1. [Text wrangling](Text-wrangling)1. [Tokenization](Tokenization)1. [Stemming](Stemming)1. [Lemmatization](Lemmatization)1. [Stop word removal](Stop-word-removal)1. [Spelling correction](Spelling-correction) Import | # Standard libary and settings
import os
import sys
import importlib
import itertools
import warnings
warnings.simplefilter("ignore")
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
# Data extensions and settings
import numpy as np
np.set_printopti... | _____no_output_____ | MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
Text wrangling | nltk.download()
# split into sentences using sent_tokenize
from nltk.tokenize import sent_tokenize
inputstring = "this is an example sent. the sentence splitter will split on sent markers. Ohh really!!"
all_sent = sent_tokenize(inputstring)
print(all_sent)
# create a custom sentence splitter
import nltk.tokenize.punk... | _____no_output_____ | MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
TokenizationA token, aka a word, is the minimal unit that a machine can evaluate and process. Tokenization is the process of splitting text data down to the point of building a collection of individual words. | # simple split using basic Python
s = "Hi everyone! hola gr8"
print(s.split())
# simple split nltk
from nltk.tokenize import word_tokenize
word_tokenize(s)
# basic examples with various tokenizers
from nltk.tokenize import regexp_tokenize, wordpunct_tokenize, blankline_tokenize
print(regexp_tokenize(s, pattern="\w+")... | ['Hi', 'everyone', 'hola', 'gr8']
['8']
['Hi', 'everyone', '!', 'hola', 'gr8']
['Hi everyone! hola gr8']
| MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
StemmingStemming is the process of reducing a token down to its stem, i.e. reducing 'eating' down to 'eat' | # basic stemming examples
from nltk.stem import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
pst = PorterStemmer()
lst = LancasterStemmer()
print(lst.stem("eating"))
print(pst.stem("shopping")) | eat
shop
| MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
LemmatizationLemmatization is a more precide way of converting tokens to their roots. Lemmatization uses context and parts of speech to determine how to get to the root, aka lemma. | # lemmatization that uses wordnet, a semantic dictionary for performing lookups
from nltk.stem import WordNetLemmatizer
wlem = WordNetLemmatizer()
wlem.lemmatize("dogs") | _____no_output_____ | MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
Stop word removalStop word removal is the process is removing words that occur commonly across documents and generally have no significance. These stop words lists are typically hand-curated lists of words | # remove stop words from a sample sentence
from nltk.corpus import stopwords
stoplist = stopwords.words("english")
text = "this is just a test, only a test"
cleanwords = [word for word in text.split() if word not in stoplist]
print(cleanwords) | ['test,', 'test']
| MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
Spelling correctionNLTK includes an algorithm called edit-distance that can be used to perform fuzzy string matching. | # calculate Levenshtein distance between two words
from nltk.metrics import edit_distance
edit_distance("rain", "shine") | _____no_output_____ | MIT | textbooks/NaturalLanguageProcessingPythonAndNLTK/Ch02_Text_wrangling_and_processing.ipynb | sudhu26/data-science-portfolio |
List available deep learning NER models | malaya.entity.available_deep_model() | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Describe supported entities | malaya.describe_entities()
string = 'KUALA LUMPUR: Sempena sambutan Aidilfitri minggu depan, Perdana Menteri Tun Dr Mahathir Mohamad dan Menteri Pengangkutan Anthony Loke Siew Fook menitipkan pesanan khas kepada orang ramai yang mahu pulang ke kampung halaman masing-masing. Dalam video pendek terbitan Jabatan Keselamat... | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Load CRF model | crf = malaya.entity.crf()
crf.predict(string) | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Load Case-Sensitive CRF model | crf = malaya.entity.crf(sensitive = True)
crf.predict(string) | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Print important features from CRF model | crf.print_features(10) | Top-10 positive:
14.340635 person word:pengarah
11.162717 person prev_word:perbendaharaan
10.906426 location word:dibuat-buat
10.462828 person word:berkelulusan
9.680613 organization word:pas
9.152880 person word:Presidennya
8.668067 OTHER prev_word:bergabungnya
8.637761 location word:Iran
8.336057 person ... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Print important transitions from CRF Model | crf.print_transitions(10) | Top-10 likely transitions:
OTHER -> OTHER 4.720173
organization -> organization 4.512877
event -> event 4.286578
quantity -> quantity 4.244444
person -> person 4.099601
location -> location 4.051204
law -> law 3.888215
time -> time 2.618322
OTHER -> location 0.361435
OTHER -> person 0.255809
Top-... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Load deep learning models | for i in malaya.entity.available_deep_model():
print('Testing %s model'%(i))
model = malaya.entity.deep_model(i)
print(model.predict(string))
print() | Testing concat model
[('kuala', 'location'), ('lumpur', 'location'), ('sempena', 'OTHER'), ('sambutan', 'event'), ('aidilfitri', 'event'), ('minggu', 'time'), ('depan', 'time'), ('perdana', 'person'), ('menteri', 'person'), ('tun', 'person'), ('dr', 'person'), ('mahathir', 'person'), ('mohamad', 'person'), ('dan', 'OTH... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Load Case-Sensitive deep learning models | for i in malaya.entity.available_deep_model():
print('Testing %s model'%(i))
model = malaya.entity.deep_model(i, sensitive = True)
print(model.predict(string))
print() | Testing concat model
[('Kuala', 'location'), ('Lumpur', 'location'), ('Sempena', 'OTHER'), ('sambutan', 'time'), ('Aidilfitri', 'time'), ('minggu', 'OTHER'), ('depan', 'OTHER'), ('Perdana', 'person'), ('Menteri', 'person'), ('Tun', 'person'), ('Dr', 'person'), ('Mahathir', 'person'), ('Mohamad', 'person'), ('dan', 'OTH... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Print important features from deep learning model | bahdanau = malaya.entity.deep_model('bahdanau')
bahdanau.print_features(10) | Top-10 positive:
made: 4.456522
effendi: 3.826650
dipo: 3.723355
djamil: 3.653246
noorfadila: 3.638877
ahad: 3.611547
kinabalu: 3.601939
yorrys: 3.546461
2008: 3.510597
ustaz: 3.450228
Top-10 negative:
memilih: -3.813004
gentar: -3.738811
kenalan: -3.586572
melanjutkan: -3.510132
istilah: -3.410603
seusai: -3.405963
k... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Print important transitions from deep learning model | bahdanau.print_transitions(10) | Top-10 likely transitions:
quantity -> quantity: 0.768479
law -> law: 0.748858
event -> event: 0.671466
time -> time: 0.566861
quantity -> PAD: 0.515885
organization -> time: 0.430649
PAD -> law: 0.396928
time -> person: 0.387298
time -> organization: 0.380183
OTHER -> time: 0.346963
Top-10 unlikely transitions:
perso... | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Visualize output alignment from attentionThis visualization only can call from `bahdanau` or `luong` model. | d_object, predicted, state_fw, state_bw = bahdanau.get_alignment(string)
d_object.to_graphvis() | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Voting stack model | entity_network = malaya.entity.deep_model('entity-network')
bahdanau = malaya.entity.deep_model('bahdanau')
luong = malaya.entity.deep_model('luong')
malaya.stack.voting_stack([entity_network, bahdanau, luong], string) | _____no_output_____ | MIT | example/entities/load-entities.ipynb | Jeansding/Malaya |
Import Libraries | import os
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import MNIST
from torchvision.utils import save_image
if not os.path.exists('./mlp_img'):
os.mkdir('./mlp_img')
d... | _____no_output_____ | MIT | Main/Autoencoder/Simple Autoencoder 1/Simple Autoencoder.ipynb | MalcolmGomes/CPS040-Thesis |
Microstructure features Market microstructure features aim to tease out useful information from the trading behavior of market participants on exchanges. These features have become more popular with the increased amount and granularity of data provided by exchanges. As a result, multiple models of liquidity, uncertain... | # help(mlfinlab.features.microstructural)
from mlfinlab.features.microstructural import tick_rule
aggressor = tick_rule(data['Price'])
| _____no_output_____ | BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
The Roll Model | from mlfinlab.features.microstructural import roll_model
spread, noise = roll_model(data['Price'])
spread, noise
| _____no_output_____ | BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
High-Low Volatility Estimator | # first create some bars
from mlfinlab.data_structures import get_dollar_bars
from mlfinlab.features.microstructural import high_low_estimator
date_time = data['Date and Time']
new_data = pd.concat([date_time, data['Price'], data['Volume']], axis=1)
new_data.columns = ['date', 'price', 'volume']
print(new_data.head(... | date price volume
0 2017/01/02 17:00:00.077 2240.75 1360
1 2017/01/02 17:00:00.140 2241.00 1
2 2017/01/02 17:00:00.140 2241.00 5
3 2017/01/02 17:00:00.140 2241.00 1
4 2017/01/02 17:00:00.140 2240.75 15
5 2017/01/02 17:00:00.140 2240.75 2
6 2... | BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Corwin-Shultz Algorithm | from mlfinlab.features.microstructural import corwin_shultz_spread, becker_parkinson_volatility
spread, start_ind = corwin_shultz_spread(bars.high, bars.low, 100)
vol = becker_parkinson_volatility(bars.high, bars.low, 100)
plt.figure(figsize=(10, 5))
spread.plot()
plt.figure(figsize=(10, 5))
vol.plot() | _____no_output_____ | BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Second generation: strategic trade models Kyle's Lambda | from mlfinlab.data_structures import BarFeature
from mlfinlab.features.microstructural import kyles_lambda, dollar_volume
kyles_lambda_feature = BarFeature(name='kyles_lambda', function= lambda df: kyles_lambda(df['price'], df['volume']))
bars = get_dollar_bars('./maks_tick_data.csv', threshold=70000000, batch_size=10... | Reading data in batches:
Batch number: 0
Returning bars
| BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Amihud's Lambda | from mlfinlab.features.microstructural import dollar_volume, amihuds_lambda
dollar_volume_feature = BarFeature(name='dollar_volume', function= lambda df: dollar_volume(df['price'], df['volume']))
bars = get_dollar_bars('./maks_tick_data.csv', threshold=70000000, batch_size=1000000,
additional_fea... | Reading data in batches:
Batch number: 0
Returning bars
| BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Hasbrouck's Lambda | from mlfinlab.features.microstructural import dollar_volume, hasbroucks_lambda, hasbroucks_flow
def get_hasbroucks_flow(df):
tick_signs = tick_rule(df['price'])
return hasbroucks_flow(df['price'], df['volume'], tick_signs)
hasbroucks_flow_feature = BarFeature(name='hasbroucks_flow', function=get_hasbroucks_fl... | Reading data in batches:
Batch number: 0
Returning bars
| BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Third generation: sequential trade models Volume-Synchronized Probability of Informed Trading | from mlfinlab.features.microstructural import vpin
from mlfinlab.data_structures import get_volume_bars
def buy_volume(df):
tick_signs = tick_rule(df['price'])
return (df['volume'] * (tick_signs > 0)).sum()
def sell_volume(df):
tick_signs = tick_rule(df['price'])
return (df['volume'] * (tick_signs < 0... | Reading data in batches:
Batch number: 0
Returning bars
| BSD-3-Clause-Clear | jupyter-notebooks/src/microstructural/Microstructural-Features.ipynb | BlackSwine/compendium |
Given an dictionary find the max value in a dictionary. Return the key with the max value dic ={'a':1,'b':3,'c':2} op=b | def max_dic_key(dic):
return max(dic,key=dic.get)
dic ={'a':1,'b':3,'c':2}
print(max_dic(dic))
def max_dic_value(dic):
max_key=max(dic,key=dic.get)
for k,y in dic.items():
if k==max_key:
return y
dic ={'a':1,'b':3,'c':2}
print(max_dic_value(dic)) | 3
| MIT | array_strings/ipynb/max_dictionary.ipynb | PRkudupu/Algo-python |
Sum of two sines and moving averageHere I will study how the statistics and the signal between a sine and its moving average. | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
%matplotlib inline
w1 = 0.3
w2 = 1.0
dt = 0.1
T = 200
Nt = int(T / dt)
Tperiod1 = 20.0
w1 = (2 * np.pi) / Tperiod1
Tperiod2 = 2.0
A2 = 10.0
w2 = (2 * np.pi) / Tperiod2
A = 5.0
t = np.arange(start=0, stop=T, step=dt)
... | _____no_output_____ | BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Create the moving average | y1 = np.zeros(Nt)
y2 = np.zeros(Nt)
aux = np.convolve(original_signal, a / Nwindow_size, mode='valid')
y2[Nwindow_size:] = aux[:-1]
for index in range(Nwindow_size, Nt):
x_windowed = original_signal[index - Nwindow_size:index]
product = np.dot(x_windowed, a) / Nwindow_size
y1[index] = product
... | _____no_output_____ | BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Now print the correlations | print(np.corrcoef(original_signal, y1))
print(np.corrcoef(original_signal, y2)) | [[ 1. -0.04154273]
[-0.04154273 1. ]]
[[ 1. -0.04154273]
[-0.04154273 1. ]]
| BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Autocorrelations of the Signal | nlags = 200
t = np.arange(0, int((nlags) * dt) + dt, dt)
# t = np.linspace(0, int(nlags * dt), num=nlags)
acf_original = sm.tsa.stattools.acf(original_signal, nlags=nlags)
acf_y1 = sm.tsa.stattools.acf(y1, nlags=nlags)
acf_y2 = sm.tsa.stattools.acf(y2, nlags=nlags)
plt.plot(t, acf_original)
plt.plot(t, acf_y1)
plt.plot... | _____no_output_____ | BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Now we Process our data with Nexa | import sys
sys.path.append("../")
from inputs.sensors import Sensor, PerceptualSpace
from inputs.lag_structure import LagStructure
# Visualization libraries
from visualization.sensor_clustering import visualize_cluster_matrix
from visualization.sensors import visualize_SLM
from visualization.sensors import visualize_... | _____no_output_____ | BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Nexa Visualizations | %matplotlib inline
fig = visualize_SLM(nexa_object)
plt.show(fig)
# %matplotlib qt
# fig = visualize_STDM(nexa_object)
fig = visualize_STDM_seaborn(nexa_object)
plt.show(fig)
%matplotlib inline
fig = visualize_cluster_matrix(nexa_object)
%matplotlib inline
cluster = 0
time_center = 0
fig = visualize_time_cluster_matri... | _____no_output_____ | BSD-3-Clause | presentations/2015-09-17(Sum of Two Sines and Moving Average).ipynb | h-mayorquin/time_series_basic |
Stellar UCL Workshop26 November, 2021Goal: Issuing an asset on Stellar (called "XU") to tokenize your professor's office hours.Section 1: Configure the SDKSection 2: Assets & Payments- Set up a wallet, and receive funds from the faucet.- Issuing an asset on Stellar.- Receiving and paying XU asset with a memo, to book ... | import requests
import stellar_sdk
# Configure StellarSdk to talk to the horizon instance hosted by Stellar.org
# To use the live network, set the hostname to 'horizon.stellar.org'
horizon_url = "https://horizon-testnet.stellar.org"
horizon = stellar_sdk.Server(horizon_url=horizon_url) | _____no_output_____ | MIT | stellar/stellar_ucl.ipynb | xujiahuayz/stellar_workshop |
The Stellar network's native asset is the "lumen", or "XLM". It is used to pay network fees. When it is used, it is destroyed. | xlm = stellar_sdk.Asset.native() | _____no_output_____ | MIT | stellar/stellar_ucl.ipynb | xujiahuayz/stellar_workshop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.