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 |
|---|---|---|---|---|---|
**LSTM for Regression Using the Window Method** | # load the dataset
dataframe = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python')
dataset = dataframe.values
dataset = dataset.astype('float32')
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = ... | _____no_output_____ | MIT | time-series-prediction.ipynb | srivarshan-s/LSTM-Trials |
**LSTM for Regression with Time Steps** | # load the dataset
dataframe = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python')
dataset = dataframe.values
dataset = dataset.astype('float32')
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = ... | _____no_output_____ | MIT | time-series-prediction.ipynb | srivarshan-s/LSTM-Trials |
**LSTM with Memory Between Batches** | # load the dataset
dataframe = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python')
dataset = dataframe.values
dataset = dataset.astype('float32')
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = ... | _____no_output_____ | MIT | time-series-prediction.ipynb | srivarshan-s/LSTM-Trials |
**Stacked LSTMs with Memory Between Batches** | # load the dataset
dataframe = pandas.read_csv('airline-passengers.csv', usecols=[1], engine='python')
dataset = dataframe.values
dataset = dataset.astype('float32')
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = ... | _____no_output_____ | MIT | time-series-prediction.ipynb | srivarshan-s/LSTM-Trials |
**Time series prediction of TESLA closing stock price** | # Importing libraries
import numpy
import matplotlib.pyplot as plt
from pandas import read_csv
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
! pip install nsepy
fr... | _____no_output_____ | MIT | time-series-prediction.ipynb | srivarshan-s/LSTM-Trials |
The YUSAG Football Model by Matt Robinson, matthew.robinson@yale.edu, Yale Undergraduate Sports Analytics Group This notebook introduces the model we at the Yale Undergraduate Sports Analytics Group (YUSAG) use for our college football rankings. This specific notebook details our FBS rankings at the beginning of... | import numpy as np
import pandas as pd
import math | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Let's start by reading in the NCAA FBS football data from 2013-2016: | df_1 = pd.read_csv('NCAA_FBS_Results_2013_.csv')
df_2 = pd.read_csv('NCAA_FBS_Results_2014_.csv')
df_3 = pd.read_csv('NCAA_FBS_Results_2015_.csv')
df_4 = pd.read_csv('NCAA_FBS_Results_2016_.csv')
df = pd.concat([df_1,df_2,df_3,df_4],ignore_index=True)
df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
As you can see, the `OT` column has some `NaN` values that we will replace with 0. | # fill missing data with 0
df = df.fillna(0)
df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
I'm also going to make some weights for when we run our linear regression. I have found that using the factorial of the difference between the year and 2012 seems to work decently well. Clearly, the most recent seasons are weighted quite heavily in this scheme. | # update the weights based on a factorial scheme
df['weights'] = (df['year']-2012)
df['weights'] = df['weights'].apply(lambda x: math.factorial(x)) | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
And now, we also are going to make a `scorediff` column that we can use in our linear regression. | df['scorediff'] = (df['teamscore']-df['oppscore'])
df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Since we need numerical values for the linear regression algorithm, I am going to replace the locations with what seem like reasonable numbers:* Visiting = -1* Neutral = 0* Home = 1The reason we picked these exact numbers will become clearer in a little bit. | df['location'] = df['location'].replace('V',-1)
df['location'] = df['location'].replace('N',0)
df['location'] = df['location'].replace('H',1)
df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
The way our linear regression model works is a little tricky to code up in scikit-learn. It's much easier to do in R, but then you don't have a full understanding of what's happening when we make the model.In simplest terms, our model predicts the score differential (`scorediff`) of each game based on three things: the... | # create dummy variables, need to do this in python b/c does not handle automatically like R
team_dummies = pd.get_dummies(df.team, prefix='team')
opponent_dummies = pd.get_dummies(df.opponent, prefix='opponent')
df = pd.concat([df, team_dummies, opponent_dummies], axis=1)
df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Now let's make our training data, so that we can construct the model. At this point, I am going to use all the avaiable data to train the model, using our predetermined hyperparameters. This way, the model is ready to make predictions for the 2017 season. | # make the training data
X = df.drop(['year','month','day','team','opponent','teamscore','oppscore','D1','OT','weights','scorediff'], axis=1)
y = df['scorediff']
weights = df['weights']
X.head()
y.head()
weights.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Now let's train the linear regression model. You'll notice that I'm actually using ridge regression (adds an l2 penalty with alpha = 1.0) because that prevents the model from overfitting and also limits the values of the coefficients to be more interpretable. If I did not add this penalty, the coefficients would be hug... | from sklearn.linear_model import Ridge
ridge_reg = Ridge()
ridge_reg.fit(X, y, sample_weight=weights)
# get the R^2 value
r_squared = ridge_reg.score(X, y, sample_weight=weights)
print('R^2 on the training data:')
print(r_squared) | R^2 on the training data:
0.495412735743
| MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Now that the model is trained, we can use it to provide our rankings. Note that in this model, a team's ranking is simply defined as its linear regression coefficient, which we call the YUSAG coefficient. When predicting a game's score differential on a neutral field, the predicted score differential (`scorediff`) is j... | # get the coefficients for each feature
coef_data = list(zip(X.columns,ridge_reg.coef_))
coef_df = pd.DataFrame(coef_data,columns=['feature','feature_coef'])
coef_df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Let's get only the team variables, so that it is a proper ranking | # first get rid of opponent_ variables
team_df = coef_df[~coef_df['feature'].str.contains("opponent")]
# get rid of the location variable
team_df = team_df.iloc[1:]
team_df.head()
# rank them by coef, not alphabetical order
ranked_team_df = team_df.sort_values(['feature_coef'],ascending=False)
# reset the indices at 0... | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
I'm goint to change the name of the columns and remove the 'team_' part of every string: | ranked_team_df.rename(columns={'feature':'team', 'feature_coef':'YUSAG_coef'}, inplace=True)
ranked_team_df['team'] = ranked_team_df['team'].str.replace('team_', '')
ranked_team_df.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Lastly, I'm just going to shift the index to start at 1, so that it corresponds to the ranking. | ranked_team_df.index = ranked_team_df.index + 1
ranked_team_df.to_csv("FBS_power_rankings.csv") | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Additional stuff: Testing the modelThis section is mostly about how own could test the performance of the model or how one could choose appropriate hyperparamters. Creating a new dataframeFirst let's take the original dataframe and sort it by date, so that the order of games in the dataframe matches the order the game... | # sort by date and reset the indices to 0
df_dated = df.sort_values(['year', 'month','day'], ascending=[True, True, True])
df_dated = df_dated.reset_index(drop=True)
df_dated.head() | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Let's first make a dataframe with training data (the first three years of results) | thirteen_df = df_dated.loc[df_dated['year']==2013]
fourteen_df = df_dated.loc[df_dated['year']==2014]
fifteen_df = df_dated.loc[df_dated['year']==2015]
train_df = pd.concat([thirteen_df,fourteen_df,fifteen_df], ignore_index=True) | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Now let's make an initial testing dataframe with the data from this past year. | sixteen_df = df_dated.loc[df_dated['year']==2016]
seventeen_df = df_dated.loc[df_dated['year']==2017]
test_df = pd.concat([sixteen_df,seventeen_df], ignore_index=True) | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
I am now going to set up a testing/validation scheme for the model. It works like this:First I start off where my training data is all games from 2012-2015. Using the model trained on this data, I then predict games from the first week of the 2016 season and look at the results.Next, I add that first week's worth of ga... | def train_test_model(train_df, test_df):
# make the training data
X_train = train_df.drop(['year','month','day','team','opponent','teamscore','oppscore','D1','OT','weights','scorediff'], axis=1)
y_train = train_df['scorediff']
weights_train = train_df['weights']
# train the model
ridge_reg... | _____no_output_____ | MIT | YUSAG_FBS_football_linear_model.ipynb | mc-robinson/YUSAG_football_model |
Using fmriprep [fmriprep](https://fmriprep.readthedocs.io/en/stable/) is a package developed by the Poldrack lab to do the minimal preprocessing of fMRI data required. It covers brain extraction, motion correction, field unwarping, and registration. It uses a combination of well-known software packages (e.g., FSL, SPM... | #!fmriprep \
# --ignore slicetiming \
# --ignore fieldmaps \
# --output-space template \
# --template MNI152NLin2009cAsym \
# --template-resampling-grid 2mm \
# --fs-no-reconall \
# --fs-license-file \
# ../license.txt \
# ../data/ds000030 ../data/ds000030/derivatives/fmriprep participant | _____no_output_____ | CC-BY-4.0 | code/01_preprocessing.ipynb | maxim-belkin/SDC-BIDS-fMRI |
Скачайте данные в формате csv, выберите из таблицы данные по России, начиная с 3 марта 2020 г. (в этот момент впервые стало больше 2 заболевших). В качестве целевой переменной возьмём число случаев заболевания (столбцы total_cases и new_cases); для упрощения обработки можно заменить в столбце new_cases все нули на един... | from datetime import datetime
import pandas as pd
import numpy as np
import scipy
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = 16, 6 | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
Загрузка и предобработка данных | # загрузим данные
df = pd.read_csv('full_data.csv')
df = df[(df['location'] == 'Russia') & (df['date'] >= '2020-03-03')].reset_index(drop=True)
df.loc[df['new_cases'] == 0, 'new_cases'] = 1
df['day'] = df.index
start_day = datetime.strptime('2020-03-03', '%Y-%m-%d')
may_first = datetime.strptime('2020-05-01', '%Y-%m-%d... | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
Разделим на трейн и тест | # разделим на трейн и тест. Возьмем 60! дней, т.к. результаты получаются более адекватные
TRAIN_DAYS = 60
train = df[:TRAIN_DAYS]
test = df[TRAIN_DAYS:] | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
Код для байесовской регрессии | class BayesLR(BaseEstimator, TransformerMixin):
def __init__(self, mu, sigma, noise=None):
self.mu = mu
self.sigma = sigma
self.noise = None
def _estimate_noise(self, X, y):
return np.std(y - X.dot(np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y))) # linear regression
... | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
Часть 1: моделирование экспонентной 1.1 Графики | plt.plot(train['total_cases'], label='общее число зараженных')
plt.plot(train['new_cases'], label='количество новых случаев за день')
plt.title('Графики целевых переменных')
plt.legend(); | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
1.2 Линейная регрессия y ~ exp(wX) Чтобы построить линейную регрессию для такого случая, прологарифмируем целевую переменную (общее количество зараженных). | X_tr = train[['day']].values
y_tr = np.log(train['total_cases'].values)
X_te = test[['day']].values
y_te = np.log(test['total_cases'].values)
X_full = np.arange(till_year_end + 1).reshape(-1, 1) # до конца года
# Выберем uninformative prior
mu_prior = np.array([0, 0])
sigma_prior = 100 * np.array([[1, 0],
... | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
1.3 Предсказания | # Семплируем экспоненты для трейна
sampled_train = np.exp(bayes_lr.sample(X_tr))
plot_sampled(sampled_train)
plt.plot(np.exp(y_tr), color='red', label='Реальное число зараженных')
plt.legend()
plt.title('Предсказания для трейна');
# Посемплируем экспоненты для теста
sampled_test = np.exp(bayes_lr.sample(X_te, n_samples... | 1 мая: 0.3274 млн зараженных
1 июня: 99.7141 млн зараженных
1 сентября: 2342098539.3834 млн зараженных
| MIT | homework2.ipynb | x-sile/made_ml |
Получается, что к 1 июня 2/3 России вымрет, не очень реалистично. | # Посемплируем экспоненты на будущее
sampled_full = np.exp(bayes_lr.sample(X_full, n_samples=10000))
fig, ax = plt.subplots(2, 2, figsize=(16, 10))
ax[0][0].hist(sampled_full[till_may], bins=50)
ax[0][0].set_title('Предсказательное распределение количества зараженных к маю')
ax[0][1].hist(sampled_full[till_june], bin... | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
Вывод: моделирование экспонентой - это шляпа =) Часть 2: моделирование сигмоидой 2.1 Как такое обучать Справа у нас интеграл - можем взять производную, а затем прологарифмировать, в итоге получим:$ln$($\Delta$y) = w_2 * x^2 + w_1 * x + w_0 Другими словами, мы можем замоделировать количество новых случаев заражения с ... | # Функция для приведения наших предсказаний приростов к общему числу зараженных
def to_total(preds):
return 2 + np.cumsum(np.exp(preds), axis=0)
X_tr = np.hstack([X_tr, X_tr ** 2])
y_tr = np.log(train['new_cases'].values)
X_te = np.hstack([X_te, X_te ** 2])
y_te = np.log(test['new_cases'].values)
X_full = np.hsta... | _____no_output_____ | MIT | homework2.ipynb | x-sile/made_ml |
2.3 Предсказываем | # Семплируем сигмоиды для трейна
sampled_train = to_total(bayes_lr.sample(X_tr))
plot_sampled(sampled_train)
plt.plot(to_total(y_tr), color='red', label='Реальное число зараженных')
plt.legend()
plt.title('Предсказания для трейна');
# Посемплируем сигмоиды для теста
sampled_test = to_total(bayes_lr.sample(X_te))
# Дел... | Оптимистичный прогноз к концу года: 0.2409 млн человек
Пессимистичный прогноз к концу года: 1.3295 млн человек
| MIT | homework2.ipynb | x-sile/made_ml |
SVM | import pandas as pd
from sklearn import svm, metrics
from sklearn.model_selection import train_test_split
wesad_eda = pd.read_csv('D:\data\wesad-chest-combined-classification-eda.csv') # need to adjust a path of dataset
wesad_eda.columns
original_column_list = ['MEAN', 'MAX', 'MIN', 'RANGE', 'KURT', 'SKEW', 'MEAN_1ST_G... | 0.9998672250025533
| MIT | SVM/SVM_wesad_eda.ipynb | aiLocsRnD/classification |
Time series analysis on AWS*Chapter 1 - Time series analysis overview* Initializations--- | !pip install --quiet tqdm kaggle tsia ruptures | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Imports | import matplotlib.colors as mpl_colors
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import ruptures as rpt
import sys
import tsia
import warnings
import zipfile
from matplotlib import gridspec
from sklearn.preproce... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Parameters | RAW_DATA = os.path.join('..', 'Data', 'raw')
DATA = os.path.join('..', 'Data')
warnings.filterwarnings("ignore")
os.makedirs(RAW_DATA, exist_ok=True)
%matplotlib inline
# plt.style.use('Solarize_Light2')
plt.style.use('fivethirtyeight')
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Helper functions | def progress_report_hook(count, block_size, total_size):
mb = int(count * block_size // 1048576)
if count % 500 == 0:
sys.stdout.write("\r{} MB downloaded".format(mb))
sys.stdout.flush() | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Downloading datasets **Dataset 1:** Household energy consumption | ORIGINAL_DATA = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00321/LD2011_2014.txt.zip'
ARCHIVE_PATH = os.path.join(RAW_DATA, 'energy-consumption.zip')
FILE_NAME = 'energy-consumption.csv'
FILE_PATH = os.path.join(DATA, 'energy', FILE_NAME)
FILE_DIR = os.path.dirname(FILE_PATH)
if not os.pa... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**Dataset 2:** Nasa Turbofan remaining useful lifetime | ok = True
ok = ok and os.path.exists(os.path.join(DATA, 'turbofan', 'train_FD001.txt'))
ok = ok and os.path.exists(os.path.join(DATA, 'turbofan', 'test_FD001.txt'))
ok = ok and os.path.exists(os.path.join(DATA, 'turbofan', 'RUL_FD001.txt'))
if (ok):
print("File found, skipping download")
else:
print('Some dat... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**Dataset 3:** Human heartbeat | ECG_DATA_SOURCE = 'http://www.timeseriesclassification.com/Downloads/ECG200.zip'
ARCHIVE_PATH = os.path.join(RAW_DATA, 'ECG200.zip')
FILE_NAME = 'ecg.csv'
FILE_PATH = os.path.join(DATA, 'ecg', FILE_NAME)
FILE_DIR = os.path.dirname(FILE_PATH)
if not os.path.isfile(FILE_PATH):
urlretrieve(ECG_DATA_SOUR... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**Dataset 4:** Industrial pump dataTo download this dataset from Kaggle, you will need to have an account and create a token that you install on your machine. You can follow [**this link**](https://www.kaggle.com/docs/api) to get started with the Kaggle API. Once generated, make sure your Kaggle token is stored in the... | FILE_NAME = 'pump-sensor-data.zip'
ARCHIVE_PATH = os.path.join(RAW_DATA, FILE_NAME)
FILE_PATH = os.path.join(DATA, 'pump', 'sensor.csv')
FILE_DIR = os.path.dirname(FILE_PATH)
if not os.path.isfile(FILE_PATH):
if not os.path.exists('/home/ec2-user/.kaggle/kaggle.json'):
os.makedirs('/home/ec2-user... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**Dataset 5:** London household energy consumption with weather data | FILE_NAME = 'smart-meters-in-london.zip'
ARCHIVE_PATH = os.path.join(RAW_DATA, FILE_NAME)
FILE_PATH = os.path.join(DATA, 'energy-london', 'smart-meters-in-london.zip')
FILE_DIR = os.path.dirname(FILE_PATH)
# Checks if the data were already downloaded:
if os.path.exists(os.path.join(DATA, 'energy-london', 'ac... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Dataset visualization--- **1.** Household energy consumption | %%time
FILE_PATH = os.path.join(DATA, 'energy', 'energy-consumption.csv')
energy_df = pd.read_csv(FILE_PATH, sep=';', decimal=',')
energy_df = energy_df.rename(columns={'Unnamed: 0': 'Timestamp'})
energy_df['Timestamp'] = pd.to_datetime(energy_df['Timestamp'])
energy_df = energy_df.set_index('Timestamp')
energy_df.ilo... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**2.** NASA Turbofan data | FILE_PATH = os.path.join(DATA, 'turbofan', 'train_FD001.txt')
turbofan_df = pd.read_csv(FILE_PATH, header=None, sep=' ')
turbofan_df.dropna(axis='columns', how='all', inplace=True)
print('Shape:', turbofan_df.shape)
turbofan_df.head(5)
columns = [
'unit_number',
'cycle',
'setting_1',
'setting_2',
's... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**3.** ECG Data | FILE_PATH = os.path.join(DATA, 'ecg', 'ecg.csv')
ecg_df = pd.read_csv(FILE_PATH, header=None, sep=' ')
print('Shape:', ecg_df.shape)
ecg_df.head()
plt.rcParams['lines.linewidth'] = 0.7
fig = plt.figure(figsize=(5,2))
label_normal = False
label_ischemia = False
for i in range(0,100):
label = ecg_df.iloc[i, 0]
i... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**4.** Industrial pump data | FILE_PATH = os.path.join(DATA, 'pump', 'sensor.csv')
pump_df = pd.read_csv(FILE_PATH, sep=',')
pump_df.drop(columns={'Unnamed: 0'}, inplace=True)
pump_df['timestamp'] = pd.to_datetime(pump_df['timestamp'], format='%Y-%m-%d %H:%M:%S')
pump_df = pump_df.set_index('timestamp')
pump_df['machine_status'].replace(to_replace... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
**5.** London household energy consumption with weather data We want to filter out households that are are subject to the dToU tariff and keep only the ones with a known ACORN (i.e. not in the ACORN-U group): this will allow us to better model future analysis by adding the Acorn detail informations (which by definitio... | household_filename = os.path.join(DATA, 'energy-london', 'informations_households.csv')
household_df = pd.read_csv(household_filename)
household_df = household_df[(household_df['stdorToU'] == 'Std') & (household_df['Acorn'] == 'ACORN-E')]
print(household_df.shape)
household_df.head() | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Associating households with they energy consumption dataEach household (with an ID starting by `MACxxxxx` in the table above) has its consumption data stored in a block file name `block_xx`. This file is also available from the `informations_household.csv` file extracted above. We have the association between `househo... | %%time
household_ids = household_df['LCLid'].tolist()
consumption_file = os.path.join(DATA, 'energy-london', 'hourly_consumption.csv')
min_data_points = ((pd.to_datetime('2020-12-31') - pd.to_datetime('2020-01-01')).days + 1)*24*2
if os.path.exists(consumption_file):
print('Half-hourly consumption file already ex... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
File structure exploration--- | from IPython.display import display_html
def display_multiple_dataframe(*args, max_rows=None, max_cols=None):
html_str = ''
for df in args:
html_str += df.to_html(max_cols=max_cols, max_rows=max_rows)
display_html(html_str.replace('table','table style="display:inline"'), raw=True)
display_... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Visualization--- | fig = plt.figure(figsize=(5,1))
ax1 = fig.add_subplot(1,1,1)
ax2 = ax1.twinx()
plot_sensor_0 = ax1.plot(pump_df['sensor_00'], label='Sensor 0', color=colors[0], linewidth=1, alpha=0.8)
plot_sensor_1 = ax2.plot(pump_df['sensor_01'], label='Sensor 1', color=colors[1], linewidth=1, alpha=0.8)
ax2.grid(False)
plt.title('P... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Recurrence plot | from pyts.image import RecurrencePlot
from pyts.image import GramianAngularField
from pyts.image import MarkovTransitionField
hhid = household_ids[2]
hh_energy = energy_df.loc[hhid, :]
pump_extract_df = pump_df.iloc[:800, 0].copy()
rp = RecurrencePlot(threshold='point', percentage=30)
weather_rp = rp.fit_transform(wea... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Symbolic representation--- | from pyts.bag_of_words import BagOfWords
window_size, word_size = 30, 5
bow = BagOfWords(window_size=window_size, word_size=word_size, window_step=window_size, numerosity_reduction=False)
X = weather_df.loc['2013-01-01':'2013-01-31']['temperature'].values.reshape(1, -1)
X_bow = bow.transform(X)
time_index = weather_df... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Statistics--- | plt.rcParams['xtick.labelsize'] = 3
import statsmodels.api as sm
fig = plt.figure(figsize=(5.5, 3))
gs = gridspec.GridSpec(nrows=3, ncols=2, width_ratios=[1,1], hspace=0.8)
# Pump
ax = fig.add_subplot(gs[0])
ax.plot(pump_extract_df, label='Pump sensor 0')
ax.set_title(f'Pump sensor 0')
ax.tick_params(axis='x', which... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
Binary segmentation--- | signal = weather_df.loc['2013-01-01':'2013-01-31']['temperature'].values.squeeze()
algo = rpt.Binseg(model='l2').fit(signal)
my_bkps = algo.predict(n_bkps=3)
my_bkps = [0] + my_bkps
my_bkps
fig = plt.figure(figsize=(5.5,1))
start = '2012-07-01'
end = '2012-07-15'
plt.plot(weather_df.loc['2013-01-01':'2013-01-31']['temp... | _____no_output_____ | MIT | Chapter01/chapter1-time-series-analysis-overview.ipynb | PacktPublishing/Time-Series-Analysis-on-AWS |
MOHID visualisation tools | from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
How to Parse time into datetime64 string format | from datetime import datetime, timedelta
from dateutil.parser import parse
def to_datetime64(time):
"""Convert string to string in datetime64[s] format
:arg time: string
:return datetime64: str in datetime64[s] format
"""
time = parse(time) # parse to datetime format
# now just take care of form... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Usage: | to_datetime64('1 Jan 2016') | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Generate heat maps of vertical velocities Getting depth slices | # load a profile
sog2015 = xr.open_dataset('Vertical_velocity_profiles/sog2015.nc')
sog2015
# slice by layer index
sog2015.vovecrtz.isel(depthw = slice(0,11))
# slice explicitly by layer depth
# print depth with corresponding index
for i in zip(range(40), sog2015.depthw.values):
print(i)
sog2015.vovecrtz.sel(depth... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Getting time slices using parsing | # this is where to_datetime64 comes in handy
# getting the first week in january
sog2015.sel(time_counter = slice(to_datetime64('1 jan 2015'), to_datetime64('7 jan 2015'))) | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Slicing by time and depth at the same time | slice_example = sog2015.vovecrtz.sel(time_counter = slice(to_datetime64('1 jan 2015'), to_datetime64('7 jan 2015'))).isel(depthw = slice(0,11))
slice_example | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Plotting the slice | slice_example.T.plot(cmap = 'RdBu') # transposed to have depth on y axis. cmap specified as RdBu.
plt.gca().invert_yaxis() | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Extracting the data you just visualised | a_slice.data() | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Plotting the trend of the depth of maximum vertical change | def find_bottom(array):
"""Find the bottom depth layer index
:arg array: one dimesional array (profile at giventime stamp)
:returns bottom: int, 1 + index of sea floor layer
"""
i=-1
for value in np.flip(array):
if value != 0:
bottom = 39-i
return bottom
e... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Salinity profiles with shaded range region | import seaborn as sns
palette = sns.color_palette("Reds", n_colors = 14)
sal_sog2015 = xr.open_dataset('salinity_profiles/salinity_sog2015.nc')
A = sal_sog2015.sel(time_counter = slice(to_datetime64('1 Jan 2015'),to_datetime64('8 Jan 2015')))
fig = plt.figure(figsize = (10,10))
ax = plt.subplot(111)
depths = A.deptht.v... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Heat maps of Salinity | salinity_slice = sal_sog2015.sel(time_counter=slice(to_datetime64('1 Jan 2015'), to_datetime64('7 jan 2015')))
salinity_slice.vosaline.T.plot(cmap = cmocean.cm.haline)
plt.gca().invert_yaxis() | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
Difference between surface and botttom salinity | salinity_slice = sal_sog2015.sel(time_counter=slice(to_datetime64('1 Jan 2015'), to_datetime64('7 jan 2015')))
bottom = find_bottom(sal_sog2015.vosaline.isel(time_counter=0).values)
# plot the difference between the surface and bottom salinity
diff = salinity_slice.isel(deptht = 0) - salinity_slice.isel(deptht = bottom... | _____no_output_____ | Apache-2.0 | climatology_analysis_notebooks/mohid_viz.ipynb | MIDOSS/analysis-ashutosh |
ML Lab 3 Neural NetworksIn the following exercise class we explore how to design and train neural networks in various ways. Prerequisites:In order to follow the exercises you need to:1. Activate your conda environment from last week via: `source activate ` 2. Install tensorflow (https://www.tensorflow.org) via: `pip i... | import numpy as np
def generate_xor_data():
X = [(i,j) for i in [0,1] for j in [0,1]]
y = [int(np.logical_xor(x[0], x[1])) for x in X]
return X, y
print(generate_xor_data()) | ([(0, 0), (0, 1), (1, 0), (1, 1)], [0, 1, 1, 0])
| Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
HintsA single layer in a multilayer perceptron can be described by the equation $y = f(\vec{b} + W\vec{x})$ with $f$ the logistic function, a smooth and differentiable version of the step function, and defined as $f(z) = \frac{1}{1+e^{-z}}$. $\vec{b}$ is the so called bias, a constant offset vector and $W$ is the weig... | """
Implement your solution here.
""" | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Solution | X | Y | AND(NOT X, Y) | AND(X,NOT Y) | OR[AND(NOT X, Y), AND(X, NOT Y)]| XOR(X,Y) ||---|---|---------------|--------------|---------------------------------|----------|| 0 | 0 | 0 | 0 | 0 | 0 || 0 | 1 | 1 | 0 | ... | """
Definitions:
Input = np.array([X,Y])
0 if value < 0.5
1 if value >= 0.5
"""
def threshold(vector):
return (vector>=0.5).astype(float)
def mlp(x, W0, W1, b0, b1, f):
x0 = f(np.dot(W0, x) + b0)
x1 = f(np.dot(W1, x0) + b1)
return x1
# AND(NOT X, Y)
w_andnotxy = np.array([-1.0, 1.0])
# AND(X, NOT Y... | Input Output XOR
(0, 0) 0 0
(0, 1) 1 1
(1, 0) 1 1
(1, 1) 0 0
| Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Exercise 2: Use Keras to design, train and evaluate a neural network that can classify points on a 2D plane. Data generator | import numpy as np
import matplotlib.pyplot as plt
def generate_spiral_data(n_points, noise=1.0):
n = np.sqrt(np.random.rand(n_points,1)) * 780 * (2*np.pi)/360
d1x = -np.cos(n)*n + np.random.rand(n_points,1) * noise
d1y = np.sin(n)*n + np.random.rand(n_points,1) * noise
return (np.vstack((np.hstack((d1... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Training data | X_train, y_train = generate_spiral_data(1000)
plt.title('Training set')
plt.plot(X_train[y_train==0,0], X_train[y_train==0,1], '.', label='Class 1')
plt.plot(X_train[y_train==1,0], X_train[y_train==1,1], '.', label='Class 2')
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Test data | X_test, y_test = generate_spiral_data(1000)
plt.title('Test set')
plt.plot(X_test[y_test==0,0], X_test[y_test==0,1], '.', label='Class 1')
plt.plot(X_test[y_test==1,0], X_test[y_test==1,1], '.', label='Class 2')
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
2.1. Design and train your modelThe current model performs badly, try to find a more advanced architecture that is able to solve the classification problem. Read the following code snippet and understand the involved functions. Vary width and depth of the network and play around with activation functions, loss functio... | from keras.models import Sequential
from keras.layers import Dense
"""
Replace the following model with yours and try to achieve better classification performance
"""
bad_model = Sequential()
bad_model.add(Dense(12, input_dim=2, activation='tanh'))
bad_model.add(Dense(1, activation='sigmoid'))
bad_model.compile(loss=... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Predict | bad_prediction = np.round(bad_model.predict(X_test).T[0]) | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Visualize | plt.subplot(1,2,1)
plt.title('Test set')
plt.plot(X_test[y_test==0,0], X_test[y_test==0,1], '.')
plt.plot(X_test[y_test==1,0], X_test[y_test==1,1], '.')
plt.subplot(1,2,2)
plt.title('Bad model classification')
plt.plot(X_test[bad_prediction==0,0], X_test[bad_prediction==0,1], '.')
plt.plot(X_test[bad_prediction==1,0]... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
2.2. Visualize the decision boundary of your model. | """
Implement your solution here.
""" | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Solution Model design and training | from keras.layers import Dense, Dropout
good_model = Sequential()
good_model.add(Dense(64, input_dim=2, activation='relu'))
good_model.add(Dense(64, activation='relu'))
good_model.add(Dense(64, activation='relu'))
good_model.add(Dense(1, activation='sigmoid'))
good_model.compile(loss='binary_crossentropy',
... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Prediction | good_prediction = np.round(good_model.predict(X_test).T[0]) | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Visualization Performance | plt.subplot(1,2,1)
plt.title('Test set')
plt.plot(X_test[y_test==0,0], X_test[y_test==0,1], '.')
plt.plot(X_test[y_test==1,0], X_test[y_test==1,1], '.')
plt.subplot(1,2,2)
plt.title('Good model classification')
plt.plot(X_test[good_prediction==0,0], X_test[good_prediction==0,1], '.')
plt.plot(X_test[good_prediction==1,... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Decision boundary | # Generate grid:
line = np.linspace(-15,15)
xx, yy = np.meshgrid(line,line)
grid = np.stack((xx,yy))
# Reshape to fit model input size:
grid = grid.T.reshape(-1,2)
# Predict:
good_prediction = good_model.predict(grid)
bad_prediction = bad_model.predict(grid)
# Reshape to grid for visualization:
plt.title("Good Decis... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Design, train and test a neural network that is able to classify MNIST digits using Keras. Data | from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
"""
Returns:
2 tuples:
x_train, x_test: uint8 array of grayscale image data with shape (num_samples, 28, 28).
y_train, y_test: uint8 array of digit labels (integers in range 0-9) with shape (num_samples,).
"""
# Show example d... | _____no_output_____ | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Solution | from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout, Conv2D, MaxPooling2D
"""
We need to add a channel dimension
to the image input.
"""
x_train = x_train.reshape(x_train.shape[0],
x_train.shape[1],
... | Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 38s 630us/step - loss: 0.1783 - acc: 0.9452 - val_loss: 0.0650 - val_acc: 0.9800
Epoch 2/10
60000/60000 [==============================] - 38s 636us/step - loss: 0.0683 - acc: 0.9798 - val_loss: 0.0501 - val_acc:... | Apache-2.0 | lecture_3/lab_3_solutions.ipynb | jakirkham/JaneliaMLCourse |
Linearly Weighted Moving Average https://www.investopedia.com/terms/l/linearlyweightedmovingaverage.asp | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
# fix_yahoo_finance is used to fetch data
import fix_yahoo_finance as yf
yf.pdr_override()
# input
symbol = 'AAPL'
start = '2018-08-01'
end = '2019-01-01'
# Read data
df = yf.download(symbol,sta... | _____no_output_____ | BSD-3-Clause | src/reference/Python_Stock/Technical_Indicators/Linear_Weighted_Moving_Average.ipynb | sumukshashidhar/toreda |
Candlestick with Linearly Weighted Moving Average | from matplotlib import dates as mdates
import datetime as dt
dfc = df.copy()
dfc['VolumePositive'] = dfc['Open'] < dfc['Adj Close']
#dfc = dfc.dropna()
dfc = dfc.reset_index()
dfc['Date'] = pd.to_datetime(dfc['Date'])
dfc['Date'] = dfc['Date'].apply(mdates.date2num)
dfc.head()
from mpl_finance import candlestick_ohlc
... | _____no_output_____ | BSD-3-Clause | src/reference/Python_Stock/Technical_Indicators/Linear_Weighted_Moving_Average.ipynb | sumukshashidhar/toreda |
data acquisition / processing homework 2> I pledge my Honor that I have abided by the Stevens Honor System. - Joshua Schmidt 2/27/21 Problem 1a. For a stationary AR(1) time series x(t), x(t) is uncorrelated to x(t-l) for l>=2.This is false. For AR(1), $x(t) = a_0 + a_1 \cdot x(t - 1) + \epsilon_t$. In this expression... | # imports
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima.model import ARIMA
q2_data = pd.read_csv('./q2.csv', header=None)
print('question 2 samples:')
q2_data.head()
q2_plot = sns.line... | _____no_output_____ | MIT | assignments/hw2/hw2.ipynb | jschmidtnj/ee627 |
Looking at these plots, the acf quickly converges towards 0 (like a cliff), but the pacf takes a lag of 9 before finally converging towards 0 (it is gradual). Therefore, the best predictive model of this time series is most likely an MA model, maybe moving average of 2. | q2_model = ARIMA(q2_data, order=(0, 0, 4))
q2_model_fit = q2_model.fit()
q2_model_fit.summary()
q2_residuals = pd.DataFrame(q2_model_fit.resid)
plot_acf(q2_residuals, title='q2 residuals acf')
plt.show()
plot_pacf(q2_residuals, title='q2 residuals pacf', zero=False)
plt.show()
q3_data = pd.read_csv('./q3.csv', header=N... | _____no_output_____ | MIT | assignments/hw2/hw2.ipynb | jschmidtnj/ee627 |
Looking at these plots, the acf does not converge to 0, but instead slowly decreases in value while the pacf quickly converges towards 0 (like a cliff). This suggests that there are correlation values, and it is not a statistical fluke. | q3_model = ARIMA(q3_data, order=(3, 1, 2))
q3_model_fit = q3_model.fit()
q3_model_fit.summary()
q3_residuals = pd.DataFrame(q3_model_fit.resid)
plot_acf(q3_residuals, title='q3 residuals acf')
plt.show()
plot_pacf(q3_residuals, title='q3 residuals pacf', zero=False)
plt.show() | _____no_output_____ | MIT | assignments/hw2/hw2.ipynb | jschmidtnj/ee627 |
Initiate the vissim instance | # COM-Server
import win32com.client as com
import igraph
import qgrid
from VISSIM_helpers import VissimRoadNet
from os.path import abspath, join, exists
import os
from shutil import copyfile
import pandas as pd
import math
from pythoncom import com_error | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Add autocompletion for VISSIM COM Object | from IPython.utils.generics import complete_object
@complete_object.register(com.DispatchBaseClass)
def complete_dispatch_base_class(obj, prev_completions):
try:
ole_props = set(obj._prop_map_get_).union(set(obj._prop_map_put_))
return list(ole_props) + prev_completions
except AttributeError:
... | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Start Vissim and load constants | Vissim = com.gencache.EnsureDispatch("Vissim.Vissim")
from win32com.client import constants as c | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Setting the parameters used for simulation | DTA_Parameters = dict(
# DTA Parameters
EvalInt = 600, # seconds
ScaleTotVol = False,
ScaleTotVolPerc = 1,
CostFile = 'costs.bew',
ChkEdgOnReadingCostFile = True,
PathFile = 'paths.weg',
ChkEdgOnReadingPathFile = True,
CreateArchiveFiles = True,
VehClasses = '',
)
# Simulation p... | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Resetting edge and path cost files | default_cost_file = abspath('..\SO sim files\costs_020.bew')
defualt_path_file = abspath('..\SO sim files\paths_020.weg')
current_cost_file = abspath(join(WorkingFolder, DTA_Parameters['CostFile']))
if exists(current_cost_file):
os.remove(current_cost_file)
copyfile(default_cost_file, current_cost_file)
current_p... | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Load the test network | Vissim.LoadNet(FileName) | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Read dynamic assignment network | vis_net = Vissim.Net
vis_net.Paths.ReadDynAssignPathFile()
network_graph = VissimRoadNet(vis_net) | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Check if dynamic assignment graph has changed | ref_edge_list = pd.read_pickle("edges_attr.pkl.gz")
assert (network_graph.visedges['ToNode'] == ref_edge_list['ToNode']).all()
network_graph.save(join(WorkingFolder, "network_graph.pkl.gz"), format="picklez") | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
We start by opening the network to be tested and adjust its settings | DynamicAssignment = Vissim.Net.DynamicAssignment
for attname, attvalue in DTA_Parameters.items():
DynamicAssignment.SetAttValue(attname, attvalue)
Simulation = Vissim.Net.Simulation
for attname, attvalue in Sim_Parameters.items():
Simulation.SetAttValue(attname, attvalue) | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Run first DTA period as usual | Vissim.Graphics.CurrentNetworkWindow.SetAttValue("QuickMode", 1)
Simulation.RunSingleStep()
while current_period() < 2:
network_graph.update_volume(vis_net)
Simulation.RunSingleStep() | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Run simulation with custom route assignment | bad_paths = []
while True:
network_graph.update_weights(vis_net)
new_vehs = vis_net.Vehicles.GetDeparted()
for veh in new_vehs:
origin_lot = int(veh.AttValue('OrigParkLot'))
destination_lot = int(veh.AttValue('DestParkLot'))
node_paths, edge_paths = network_graph.parking_lot_routes(... | _____no_output_____ | Apache-2.0 | SO runner.ipynb | EngTurtle/VISSIM_Routing_Thesis |
Some more on ```spaCy``` and ```pandas``` First we want to import some of the packages we need. | import os
import spacy
# Remember we need to initialise spaCy
nlp = spacy.load("en_core_web_sm") | _____no_output_____ | MIT | notebooks/session4_inclass_rdkm.ipynb | agnesbn/cds-language |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.