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
Run function to create masks
labels = "/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-images/vgg/labeled/label_china/20180410_020421_0f31_labels.json" prepped_dir = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquacult...
/Users/Tyler-SFG/anaconda/envs/planet/lib/python3.6/site-packages/ipykernel/__main__.py:1: FutureWarning: The value of this property will change in version 1.0. Please see https://github.com/mapbox/rasterio/issues/86 for details. if __name__ == '__main__': /Users/Tyler-SFG/anaconda/envs/planet/lib/python3.6/site-pack...
MIT
notebooks/process_planet_scenes.ipynb
tclavelle/aqua_python
4.2 Positional Arguments
def add(operand_1, operand_2): print(f"The sum of {operand_1} and {operand_2} is {operand_1 + operand_2}")
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
Yipeee! we have created a new function called add which is expected to add two integers values, Just kidding 😜, thanks to the dynamic typing of the Python, we can even add float values, concat strings and many more using our `add` function, but for now, let's stick with the addition of integers 😎
add(1, 3)
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
Yup, we did got our result ⭐️. what if I forget passing a value? we would see a `TypeError` exception raised 👻
add(1)
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
The name **Positional arguments** itself says the arguments should be according to the function signature. But here's a deal, we can change the order of arguments being passed, just that we should pass them with the respective keyword 🙂 `Example`
def difference(a, b): print(f"The difference of {b} from {a} is {a - b}") difference(5, 8) difference(b=8, a=5) # Positions are swapped, but passing the objects as keywords.
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
We can see in the above example that even if the positions are changed, but as we have are passing them through keywords, the result remains the same. ⭐️ Position only arguments We do have the power ✊ to make the user call the function's position only arguments the way we want, Thanks to [PEP-570](https://www.python.o...
def greet(greet_word, /, name_of_the_user): print(f"{greet_word} {name_of_the_user}!")
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
In the above example, we do have two arguments `greet_word` and `name_of_the_user` we used **`/`** to say that **Hey Python! Consider `greet_word` as Positional only Argument** When we try to call our function `greet` with greet_word as keyword name, Boom 💣, we get a `TypeError` exception.
greet(greet_word="Hello", name_of_the_user="Pythonist")
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
Try to call our `greet` with `greet_word` as positional only argument, meaning not passing it by keyword name. We can hope that there won't be any exception raised. 😁
# Calling greet function with name_of_the_user as Positional keyword. greet("Hello", "Pythonist") # Calling greet function with name_of_the_user with keyword name. greet("Hello", name_of_the_user="Pythoneer😍")
_____no_output_____
MIT
Chapters_1-5/Chapter_4/2_Positional_Arguments.ipynb
NaveenKumarReddy8/MyPython
Read data function examples for basic DEA models在此示範如何使用csv2dict()、csv2dict_sep()來讀取要被衡量的資料,以利後續放入DEA主程式時使用,並顯示它們最終形成的資料形式。※示範程式碼及csv資料存放於[這裡](https://github.com/wurmen/DEA/tree/master/Functions/basic_DEA_data%26code),可自行下載測試。
#導入存放csv2dict()、csv2dict_sep()的py檔(在此名為DEA) import DEA
_____no_output_____
MIT
Functions/basic_DEA_data&code/read_data_example.ipynb
PO-LAB/DEA
csv2dict()------- Exampl1當產出與投入資料放置同一csv檔時,並且**不指定**以2~4行當成投入資料,5~8行當成產出資料。
DMU,X,Y=DEA.csv2dict("data.csv",in_range=[2,4],out_range=[5,8],assign=False) # return DMU、X、Y print(DMU) # DMU list print(X) # input data dict print(Y) # output data dict
{'A': [23756.0, 4.0, 2.0, 870.0], 'B': [24183.0, 5.0, 3.0, 1359.0], 'C': [163483.0, 6.0, 4.0, 12449.0], 'D': [10370.0, 7.0, 5.0, 509.0], 'E': [99047.0, 8.0, 6.0, 3726.0], 'F': [128635.0, 9.0, 7.0, 9214.0], 'G': [11962.0, 10.0, 8.0, 536.0], 'I': [32436.0, 11.0, 9.0, 1462.0], 'J': [83862.0, 12.0, 10.0, 6337.0], 'K': [146...
MIT
Functions/basic_DEA_data&code/read_data_example.ipynb
PO-LAB/DEA
Example2當產出與投入資料放置同一csv檔時,並且**指定**以2、4行當成投入資料,5、8行當成產出資料。
DMU,X,Y=DEA.csv2dict("data.csv",in_range=[2,4],out_range=[5,8],assign=True) print(DMU) print(X) print(Y)
{'A': [23756.0, 870.0], 'B': [24183.0, 1359.0], 'C': [163483.0, 12449.0], 'D': [10370.0, 509.0], 'E': [99047.0, 3726.0], 'F': [128635.0, 9214.0], 'G': [11962.0, 536.0], 'I': [32436.0, 1462.0], 'J': [83862.0, 6337.0], 'K': [14618.0, 785.0], 'L': [99636.0, 6597.0], 'M': [135480.0, 10928.0], 'O': [74106.0, 4258.0]}
MIT
Functions/basic_DEA_data&code/read_data_example.ipynb
PO-LAB/DEA
csv2dict_sep()--------------------- Example1當產出與投入分別放在不同檔案時,且**不指定**投入或產出資料。
DMU, X = DEA.csv2dict_sep("data_input.csv") print(DMU) print(X)
{'A': [392.0, 8259.0], 'B': [381.0, 9628.0], 'C': [2673.0, 70923.0], 'D': [282.0, 9683.0], 'E': [1608.0, 40630.0], 'F': [2074.0, 47420.0], 'G': [75.0, 7115.0], 'I': [458.0, 10177.0], 'J': [1722.0, 29124.0], 'K': [400.0, 8987.0], 'L': [1217.0, 34680.0], 'M': [2532.0, 51536.0], 'O': [1303.0, 32683.0]}
MIT
Functions/basic_DEA_data&code/read_data_example.ipynb
PO-LAB/DEA
Example2當產出與投入分別放在不同檔案時,且**指定**投入或產出資料。
DMU, Y = DEA.csv2dict_sep("data_output.csv", vrange =[2,4], assign=True) print(X)
{'A': [392.0, 8259.0], 'B': [381.0, 9628.0], 'C': [2673.0, 70923.0], 'D': [282.0, 9683.0], 'E': [1608.0, 40630.0], 'F': [2074.0, 47420.0], 'G': [75.0, 7115.0], 'I': [458.0, 10177.0], 'J': [1722.0, 29124.0], 'K': [400.0, 8987.0], 'L': [1217.0, 34680.0], 'M': [2532.0, 51536.0], 'O': [1303.0, 32683.0]}
MIT
Functions/basic_DEA_data&code/read_data_example.ipynb
PO-LAB/DEA
Import packages & Connect the database
# Install MYSQL client pip install PyMySQL import sklearn print('The scikit-learn version is {}.'.format(sklearn.__version__)) %load_ext autoreload %autoreload 2 %matplotlib inline import numpy as np import pandas as pd import datetime as dt # Connect to database import pymysql conn = pymysql.connect( host='34.6...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Prepare data
# Get Stations df_station_snapshot = pd.read_sql_query("SELECT station_number, station_service_available, creation_date FROM station_snapshot WHERE station_number=31", conn) def substractTime(x): date = dt.datetime(x.year, x.month, x.day, x.hour) return (date - dt.timedelta(hours=1)) def addTime(x): date = d...
DATA AGGREGATED FOR STATION: 31
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Visualize the data
# Load libraries import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerLine2D import seaborn as sns; # HEATMAP CHART PER MIN (10) heatmap_data = pd.pivot_table(df[df['id']==31], values='available', index='hour', columns='date') fig, ax = plt.subplots(figsize=(20,5)) sns...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Start prediction
# Load libraries import math from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor, GradientBoostingRegressor from sklearn.linear_model import LinearRegression, Lasso, LassoLars, Ridge from sklearn.tree import DecisionTreeRegressor from scipy.stats import randint as sp_randint from sklearn.model_selecti...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Find best algoritm for our data
def quick_eval(pipeline, X_train, y_train, X_test, y_test, verbose=True): """ Quickly trains modeling pipeline and evaluates on test data. Returns original model, training RMSE, and testing RMSE as a tuple. """ pipeline.fit(X_train, y_train) y_train_pred = pipeline.predict(X_train) ...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
After review the result we see that **RandomForestRegressor** is the best option to predict our data Random Forest
# Create a new dataframe for random forest df_rf = df[['id', 'year', 'month', 'dayofweek', 'hour', 'holiday', 'football', 'basketball', 'temperature', 'humidity', 'wind', 'cloud', 'available_prev', 'available', 'available_next']] # Prepare data for train and test # We want to predict ("available_next") X = df_rf.drop(...
Regression algorithm: LinearRegression Train RMSE: 2.121484327745336 Test RMSE: 2.065697137562799 ---------------------------- Regression algorithm: Lasso Train RMSE: 2.179074981399763 Test RMSE: 2.106610689982148 ---------------------------- Regression algorithm: Ridge Train RMSE: 2.1215248913825184 Test RMSE: 2.06633...
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Find best params for Random Forest Check each property
# Find N_ESTIMATORS n_estimators = [int(x) for x in np.linspace(start = 1, stop = 200, num=50)] train_results = [] test_results = [] for estimator in n_estimators: rf = RandomForestRegressor(n_estimators=estimator, n_jobs=-1) rf.fit(X_train, y_train) train_pred = rf.predict(X_train) train_results.append(np.sqrt...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Find the best combination of params**TRY ALL PARAMS TO FIND THE BEST PARAMS FOR OUR DATA**Now that we know where to concentrate our search, we can explicitly specify every combination of settings to try.
#@title Default title text def searchBestParamsForRF(params, train_features, train_labels): # First create the base model to tune rf = RandomForestRegressor() # Instantiate the grid search model grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, scoring = 'neg_mean_squared_error', cv = 5, n_job...
Fitting 5 folds for each of 128 candidates, totalling 640 fits
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Train and evaluate model
m = RandomForestRegressor(n_estimators=60, max_features=X.shape[1]) m.fit(X_train, y_train) evaluate(m, X_train, y_train, X_test, y_test) # MODEL PERFORMANCE # Train set # | Mean Absolute Error: 0.5758625862586259 # | Mean Square Error: 0.6365449044904491 # | Root Mean Square Error: 0.7978376429389936 # | Train Sco...
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
Download model
# Import package import pickle # Generate file with open('model.pkl', 'wb') as model_file: pickle.dump(m, model_file)
_____no_output_____
MIT
Valencia/Equipo3-IAmobilitat/Grupo3SaturdaysAI_IAmobilitat.ipynb
tozanni/Projects
In Depth: Principal Component Analysis In this section, we explore what is perhaps one of the most broadly used of unsupervised algorithms, principal component analysis (PCA).PCA is fundamentally a dimensionality reduction algorithm, but it can also be useful as a tool for visualization, for noise filtering, for fea...
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set()
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Introducing Principal Component AnalysisPrincipal component analysis is a fast and flexible unsupervised method for dimensionality reduction in data.Its behavior is easiest to visualize by looking at a two-dimensional dataset.Consider the following 200 points:
rng = np.random.RandomState(1) X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T plt.scatter(X[:, 0], X[:, 1]) plt.axis('equal');
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
By eye, it is clear that there is a nearly linear relationship between the x and y variables.This is reminiscent of the linear regression data, but the problem setting here is slightly different: rather than attempting to *predict* the y values from the x values, the unsupervised learning problem attempts to learn abou...
from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(X)
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
The fit learns some quantities from the data, most importantly the "components" and "explained variance":
print(pca.components_) print(pca.explained_variance_)
[0.7625315 0.0184779]
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
To see what these numbers mean, let's visualize them as vectors over the input data, using the "components" to define the direction of the vector, and the "explained variance" to define the squared-length of the vector:
def draw_vector(v0, v1, ax=None): ax = ax or plt.gca() arrowprops=dict(arrowstyle='->', linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1, v0, arrowprops=arrowprops) # plot data plt.scatter(X[:, 0], X[:, 1], alpha=0.2) for length, vector in zip(pca.explained_vari...
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
These vectors represent the *principal axes* of the data, and the length of the vector is an indication of how "important" that axis is in describing the distribution of the data—more precisely, it is a measure of the variance of the data when projected onto that axis.The projection of each data point onto the principa...
pca = PCA(n_components=1) pca.fit(X) X_pca = pca.transform(X) print("original shape: ", X.shape) print("transformed shape:", X_pca.shape)
original shape: (200, 2) transformed shape: (200, 1)
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
The transformed data has been reduced to a single dimension.To understand the effect of this dimensionality reduction, we can perform the inverse transform of this reduced data and plot it along with the original data:
X_new = pca.inverse_transform(X_pca) plt.scatter(X[:, 0], X[:, 1], alpha=0.2) plt.scatter(X_new[:, 0], X_new[:, 1], alpha=0.8) plt.axis('equal');
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
The light points are the original data, while the dark points are the projected version.This makes clear what a PCA dimensionality reduction means: the information along the least important principal axis or axes is removed, leaving only the component(s) of the data with the highest variance.The fraction of variance th...
from sklearn.datasets import load_digits digits = load_digits() digits.data.shape
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Recall that the data consists of 8×8 pixel images, meaning that they are 64-dimensional.To gain some intuition into the relationships between these points, we can use PCA to project them to a more manageable number of dimensions, say two:
pca = PCA(2) # project from 64 to 2 dimensions projected = pca.fit_transform(digits.data) print(digits.data.shape) print(projected.shape)
(1797, 64) (1797, 2)
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
We can now plot the first two principal components of each point to learn about the data:
plt.scatter(projected[:, 0], projected[:, 1], c=digits.target, edgecolor='none', alpha=0.5, cmap=plt.cm.get_cmap('Accent', 10) ) plt.xlabel('component 1') plt.ylabel('component 2') plt.colorbar();
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Recall what these components mean: the full data is a 64-dimensional point cloud, and these points are the projection of each data point along the directions with the largest variance.Essentially, we have found the optimal stretch and rotation in 64-dimensional space that allows us to see the layout of the digits in tw...
pca = PCA().fit(digits.data) plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance');
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
This curve quantifies how much of the total, 64-dimensional variance is contained within the first $N$ components.For example, we see that with the digits the first 10 components contain approximately 75% of the variance, while you need around 50 components to describe close to 100% of the variance.Here we see that our...
def plot_digits(data): fig, axes = plt.subplots(4, 10, figsize=(10, 4), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(data[i].reshape(8, 8), cmap='b...
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Now lets add some random noise to create a noisy dataset, and re-plot it:
np.random.seed(42) noisy = np.random.normal(digits.data, 4) plot_digits(noisy)
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
It's clear by eye that the images are noisy, and contain spurious pixels.Let's train a PCA on the noisy data, requesting that the projection preserve 50% of the variance:
pca = PCA(0.50).fit(noisy) pca.n_components_
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Here 50% of the variance amounts to 12 principal components.Now we compute these components, and then use the inverse of the transform to reconstruct the filtered digits:
components = pca.transform(noisy) filtered = pca.inverse_transform(components) plot_digits(filtered)
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
This signal preserving/noise filtering property makes PCA a very useful feature selection routine—for example, rather than training a classifier on very high-dimensional data, you might instead train the classifier on the lower-dimensional representation, which will automatically serve to filter out random noise in the...
from sklearn.datasets import fetch_lfw_people faces = fetch_lfw_people(min_faces_per_person=60) print(faces.target_names) print(faces.images.shape)
Downloading LFW metadata: https://ndownloader.figshare.com/files/5976012 Downloading LFW metadata: https://ndownloader.figshare.com/files/5976009 Downloading LFW metadata: https://ndownloader.figshare.com/files/5976006 Downloading LFW data (~200MB): https://ndownloader.figshare.com/files/5976015
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
Let's take a look at the principal axes that span this dataset.Because this is a large dataset, we will use ``RandomizedPCA``—it contains a randomized method to approximate the first $N$ principal components much more quickly than the standard ``PCA`` estimator, and thus is very useful for high-dimensional data (here, ...
from sklearn.decomposition import PCA as RandomizedPCA pca = RandomizedPCA(150) pca.fit(faces.data)
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
In this case, it can be interesting to visualize the images associated with the first several principal components (these components are technically known as "eigenvectors,"so these types of images are often called "eigenfaces").As you can see in this figure, they are as creepy as they sound:
fig, axes = plt.subplots(3, 8, figsize=(9, 4), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(pca.components_[i].reshape(62, 47), cmap='bone')
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
The results are very interesting, and give us insight into how the images vary: for example, the first few eigenfaces (from the top left) seem to be associated with the angle of lighting on the face, and later principal vectors seem to be picking out certain features, such as eyes, noses, and lips.Let's take a look at ...
plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance');
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
We see that these 150 components account for just over 90% of the variance.That would lead us to believe that using these 150 components, we would recover most of the essential characteristics of the data.To make this more concrete, we can compare the input images with the images reconstructed from these 150 components...
# Compute the components and projected faces pca = RandomizedPCA(150).fit(faces.data) components = pca.transform(faces.data) projected = pca.inverse_transform(components) # Plot the results fig, ax = plt.subplots(2, 10, figsize=(10, 2.5), subplot_kw={'xticks':[], 'yticks':[]}, ...
_____no_output_____
Apache-2.0
notebooks/machine-learning/RECOMMENDED_Principal_Component_Analysis.ipynb
dlmacedo/machine-learning-class
**Experiment for obtaining 24 Hr prediction from Dense Model in rainymotion library**Author: Divya S. VidyadharanFile use: For predicting 24 Hr precipitation images with **3 hr lead time.** Date Created: 19-03-21Last Updated: 20-03-21Python version: 3.8.2
import h5py import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.misc import sys import os module_path = os.path.abspath(os.path.join('/home/divya/divya/OtherNowcastings/rainymotion-master')) if module_path not in sys.path: sys.path.append(module_path) from rainymotion.models import Den...
_____no_output_____
MIT
examples/Dense24HrPredictionNew-3Hr.ipynb
DivyaSDV/pySINDy
**1.2 Dense**
def doDenseNowcasting(startpredtime, saveimages): model = Dense() model.input_data = readRadarImages(startpredtime,inputFolder,height,width, noOfImages,fileType) start = timeit.timeit() nowcastDense = model.run() end = timeit.timeit() sparseTime = end - start print("Dense took ",end - start...
_____no_output_____
MIT
examples/Dense24HrPredictionNew-3Hr.ipynb
DivyaSDV/pySINDy
**2. Performance Evaluation**
def getGroundTruthImages(pred_times,leadsteps,recentFramePath,height,width,fileType): files = (os.listdir(recentFramePath)) files.sort() groundTruthImages = [] i = 0 while (i<leadsteps): groundtruthtime = "_"+pred_times[i] i = i +1 for fileName in files: ...
_____no_output_____
MIT
examples/Dense24HrPredictionNew-3Hr.ipynb
DivyaSDV/pySINDy
**2. 24 Hr Prediction**
startpredtime = '0110' #'1100' index = times.index(startpredtime) indexlimit = times.index('2250') # Since we have only 6 more ground truths available from this time print(index) print("Last prediction is at index ", indexlimit) csilist = [] maelist = [] podlist = [] farlist = [] pred_time = startpredtime while index<...
78 78 78 78
MIT
examples/Dense24HrPredictionNew-3Hr.ipynb
DivyaSDV/pySINDy
**To save results in excel workbook**
import xlwt from xlwt import Workbook # Workbook is created wb = Workbook() def writeinexcelsheet(sheetname, wb, results): sheet1 = wb.add_sheet(sheetname) sheet1.write(0, 0, 'Pred.no.') sheet1.write(0, 1, 't (pred start time)') sheet1.write(0, 2, 't + 10') sheet1.write(0, 3, 't + ...
6 6 6 6
MIT
examples/Dense24HrPredictionNew-3Hr.ipynb
DivyaSDV/pySINDy
%load_ext rpy2.ipython %%writefile binom.stan data{ int X; int N; } parameters{ real<lower=0,upper=1> p; real q; } model{ X ~ binomial(N,p); p ~ beta(10,1); } %%R d <- list(X=28, N=50) %%R d %%R system("apt-get install -y libv8-dev") install.packages("V8") %%R install.packages("rstan") %%R library(rstan)...
_____no_output_____
MIT
MOOCs/MathCalture/binom.ipynb
KeisukeShimokawa/CarND-Advanced-Lane-Lines
Dynamic Typing Python is dunamically typed.This means that the type of a variable is simply the type of the object the variable name points to (references). The variable itself has no associated type.
a = "hello" type(a) a = 10 type(a) a = lambda x: x**2 a(2) type(a)
_____no_output_____
Apache-2.0
python-tuts/0-beginner/2-Variables-Memory/04 - Dynamic vs Static Typing.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
**M**odel **U**ncertainty-based Data **Augment**ation (muAugment)&nbsp;| Mariana Alves | https://supaerodatascience.github.io/deep-learning/ Preliminary work for colab **This notebook was written in google colab, so it is recommended that you run it in colab as well.** Before starting to work on the notebook, make...
!git clone https://github.com/Mariana-Andrade-Alves/muAugment/
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Preliminary Imports
# !pip install matplotlib # !pip install torch torchvision import torch import torchvision import numpy as np %matplotlib inline import matplotlib.pyplot as plt from torch import nn, optim import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from ...
cpu
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Overview of Data Augmentation Modern machine learning models, such as deep neural networks, may have billions of parameters and, consequently, require massive labeled training datasets, which are often not available. In order to avoid the **problem of data scarcity** in such models, data augmentation has become the st...
batch_size = 4 n_images = 10 if (batch_size>10) else batch_size # data must be normalized between -1 and 1 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) full_trainset = FashionMNIST(root='../data', train=True, download=True, transform=tra...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
We can verify the normalization of our data.
images,labels = next(iter(trainloader)) images.min(),images.max()
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Let's look at some example images from the FashionMNIST set.
# get the first batch of images and labels labels_text = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] plt.figure(figsize=(n_images,4)) for i in range(n_images): l = labels[i].numpy() plt.subplot(2, n_images/2, i+1) plt.title('%d: %s' % (l, label...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
The Model As mentioned above, the advantage of the **muAugment** algorithm is that it uses the learning model to automate data augmentation. The goal is to generate data which will improve our training model.In today's example, we wish to learn to classify images into 10 possible labels:
labels_text
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
In order to do this, the training model we will use is a convolutional neural network, presented during a [previous class](https://github.com/SupaeroDataScience/deep-learning/blob/main/deep/PyTorch%20Ignite.ipynb).
class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.convlayer1 = nn.Sequential( nn.Conv2d(1, 32, 3,padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) ) self.con...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Training In order to train the model, we must first create it and define the loss function and optimizer.
#creating model for original data model_original = CNN() # creating model for augmented data model = CNN() # moving models to gpu if available device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) model_original.to(device)
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
By using the parameter `weight_decay` in our optimizer we are applying a similar penalty parameter to the one in ridge regression.
lr = 0.001 # learning rate # defining optimizer and loss for original model optimizer_original = torch.optim.SGD(model_original.parameters(), lr=lr, weight_decay=0.0001, momentum=0.9) criterion_original = nn.CrossEntropyLoss() # defining optimizer and loss for augmented model optimizer = torch.optim.SGD(model.parameter...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
In a typical training phase, each batch of images would be treated in the following loop:```pythonfor epoch in range(max_epochs): for batch in trainloader: zero the parameter gradients optimizer.zero_grad() get inputs and labels from batch inputs, labels = batch forward + backward + optimize outpu...
# the load command only works on jupyter notebook # %load solutions/compute_composed_data.py def compute_composed_data(transform_list,L, C, xb,yb): BS,N_CHANNELS,HEIGHT,WIDTH = xb.shape C_images = torch.zeros(C, BS, N_CHANNELS, HEIGHT, WIDTH, device=device) C_targets = torch.zeros(C, BS, device=device, dty...
cat: muAugment/solutions/compute_composed_data.py: No such file or directory
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Now that we have implemented the data augmentation part, we can attempt to code the content of the main loop of the algorithm. **Remember**: the idea is to feed the transformed batches to the model without updating it and compare the losses obtained for each batch. Since you do not want to call `python loss.backward()`...
# the load command only works on jupyter notebook # %load solutions/compute_selected_data.py #disable gradient calculation def compute_selected_data(model, loss, C_images, C_targets, S): C, BS, N_CHANNELS, HEIGHT, WIDTH = C_images.shape # create a list of predictions 'pred' by applying the model to the augme...
cat: muAugment/solutions/compute_selected_data.py: No such file or directory
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
We have created two functions which give us the augmented data we wish to use in the training phase of our model. Back to Training (hands-on exercise) Let's consider the following arguments for the algorithm:
# algorithm arguments L = 3 # number of linear transformations sampled for each composition C = 4 # number of compositions placed on each image. S = 1 # number of selected compositions for each image
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Let's consider the following list of linear transformations, similar to the ones used in the original paper:
MAGN = 4 # (int) Magnitude of augmentation applied. Ranges from [0, 10] with 10 being the max magnitude. # function of list of linear transformations def transform_list(MAGN,p): return [transforms.RandomAutocontrast(p=p), transforms.ColorJitter(brightness=MAGN/30), transforms.ColorJitter(co...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
The following three code boxes were adapted from the tutorial on pytorch done in [class](https://github.com/SupaeroDataScience/deep-learning/blob/main/deep/Deep%20Learning.ipynb). In order to compare validation and training losses, we will calculate the validation losses and accuracy at each epoch.
def validation(model,criterion): correct_pred = 0 total_pred = 0 valid_loss = 0 with torch.no_grad(): for data in validloader: images, labels = data images = images.to(device) labels = labels.to(device) outputs = model(images) loss = cr...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
In order to avoid overfitting, we will implement early stopping.
class EarlyStopping: def __init__(self, patience=5, delta=0): self.patience = patience self.counter = 0 self.best_score = None self.delta = delta self.early_stop = False def step(self, val_loss): score = -val_loss if self.best_score is None: ...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
It is time to implement the algorithm in the training loop! > **In the final exercise, take the almost complete code of the training loop presented bellow (adapted from the [pytorch class](https://github.com/SupaeroDataScience/deep-learning/blob/main/deep/Deep%20Learning.ipynb)) and change it, so that the algorithm is ...
# the load command only works on jupyter notebook # %load solutions/train.py def train(model,criterion,optimizer, earlystopping=True,max_epochs=30,patience=2, augment=False): train_history = [] valid_history = [] accuracy_history = [] estop = EarlyStopping(patience=patience) for epoch in range(max_e...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
We did it! Let's train our models: one without and one with augmented data.
max_epochs = 30 patience = 5 #early stopping parameter print("\n Training for the original dataset...\n") train_history_original, valid_history_original, accuracy_history_original = train(model_original,criterion_original,optimizer_original,max_epochs=max_epochs,patience=patience) print("\n Training for the augmented ...
Training for the original dataset... Epoch 00: train loss 53.41990, validation loss 5.85852, validation loss 86.0 Epoch 01: train loss 49.32130, validation loss 5.79052, validation loss 86.7 Epoch 02: train loss 47.43125, validation loss 5.62790, validation loss 87.0 Epoch 03: train loss 44.78354, validation loss...
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Plotting the Training and Validation Loss Now that we trained both models, we can compare how the loss of training and validation evolves in both cases.
plot_train_val(train_history_original, valid_history_original,"Original Data") plot_train_val(train_history, valid_history,"Augmented Data")
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Although it is not always verified, most times you can see that the training loss tends to decrease less while using the augmented data and, even, sometimes augment. This is consistent with the fact that the augmented data is more difficult to predict. However, because the model with augmented data does not excessively...
plot_train_val(accuracy_history, accuracy_history_original,"Accuracy",label1='Augmented',label2='Original')
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Verifying models with Testing Dataset Finally, let's check the results by applying our model to the test dataset.
# put model in evaluation mode model.eval() # moving model to cpu for inference model.to('cpu') # creating arrays to save predictions y_true = [] y_pred = [] images_ = [] # disable all gradients things with torch.no_grad(): for data in iter(testloader): images, labels = data outputs = ...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Firstly, let's examine the confusion matrix.
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix print("Confusion matrix") cm = confusion_matrix(y_true, y_pred) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=labels_text) fig, ax = plt.subplots(figsize=(10,10)) disp.plot(ax=ax) plt.show()
Confusion matrix
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
We can also plot some of the results of the test dataset.
# plotting the results fig = plt.figure(figsize=(n_images+5,4)) for i in range(n_images): ax = fig.add_subplot(2, n_images/2, i+1, xticks=[], yticks=[]) ax.imshow(images_[i].resize_(1, 28, 28).numpy().squeeze()) ax.set_title("{} ({})".format(labels_text[y_pred[i]], labels_text[y_true[i]]), ...
_____no_output_____
CC0-1.0
muAugment.ipynb
Mariana-Andrade-Alves/muAugment
Adversarial Variational Optimization: PYTHIA TuningIn this notebook Adversarial Variational Optimization (https://arxiv.org/abs/1707.07113) is applied to tuning parameters of a simplistic detector.**Note: this notebook takes quite a long time to execute. It is recommended to run all cells at the beginning.** **Please,...
%env CUDA_DEVICE_ORDER=PCI_BUS_ID %matplotlib inline import matplotlib.pyplot as plt from tqdm import tqdm_notebook as tqdm_notebook import numpy as np ### don't forget about others! import keras import tensorflow as tf gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.2) tf_session =...
Using TensorFlow backend.
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
GeneratorsPythia-mill is a python binding to Pythia generator that can run in multiple threads (processes).For more details, please, visit https://github.com/maxim-borisyak/pythia-mill
import pythiamill as pm SEED=123
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Note about the change of problemThe reason the detector parameters (instead of Pythia parameters) are the target for the tune is a purely technical one: on each step AVO requires samples from multiples configurations of generator + detector. However, Pythia requires about half of a second to be reconfigured, which ind...
### ground truth offset, unknown in the real world problems. TRUE_OFFSET=1 options = [ ### telling pythia to be quiet. 'Print:quiet = on', 'Init:showProcesses = off', 'Init:showMultipartonInteractions = off', 'Init:showChangedSettings = off', 'Init:showChangedParticleData = off', 'Next:numbe...
(32768, 32, 32, 1) (32768, 32, 32, 1)
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Taking a look at events
n = 5 plt.subplots(nrows=n, ncols=n, figsize=(3 * n, 3 * n)) max_energy = np.max(X_true_train[:n * n]) for i in range(n): for j in range(n): k = i * n + j plt.subplot(n, n, k + 1) plt.imshow(X_true_train[k, :, :, 0], vmin=0, vmax=max_energy) plt.show()
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Aggregated events
plt.figure(figsize=(6, 6)) plt.imshow(np.sum(X_true_train, axis=(0, 3)), vmin=0) plt.show()
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Discriminator
from keras.models import Model from keras.layers import Input, Conv2D, MaxPool2D, Dense, Flatten, GlobalMaxPool2D from keras.activations import softplus, sigmoid, relu from keras.utils.vis_utils import model_to_dot
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Building conv net
inputs = Input(shape=(32, 32, 1)) activation = lambda x: relu(x, 0.05) net = Conv2D(8, kernel_size=(3, 3), padding='same', activation=activation)(inputs) net = MaxPool2D(pool_size=(2, 2))(net) net = Conv2D(12, kernel_size=(3, 3), padding='same', activation=activation)(net) net = MaxPool2D(pool_size=(2, 2))(net) # ne...
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
In Adversarial Variational Optimization, instead of searching for a single value of detector parameters, a parametrized distribution is introduced (with parameters $\psi$):$$\mathcal{L}(\psi) = \mathrm{JS}(X_\psi, X_\mathrm{data})$$where:- $X_\psi \sim \mathrm{detector}(\theta), \theta \sim P_\psi$;- $X_\mathrm{data} \...
X = tf.placeholder(dtype='float32', shape=(None, 32, 32, 1)) proba = discriminator(X)[:, 0] detector_params = tf.placeholder(dtype='float32', shape=(None, 1)) detector_params_mean = tf.Variable( initial_value=np.array([0.0], dtype='float32'), dtype='float32' ) detector_params_sigma_raw = tf.Variable( in...
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Pretraining AVO makes small changes in parameter distribution. When starting with the optimal discriminator from the previous iterations, adjusting discriminator to these changes should require relatively few optimization steps.However, the initial discriminator state (which is just random weights), most probably, doe...
%%time train_discriminator(n_samples=2**16, n_epoches=4, plot=True)
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
Variational optimization
from IPython import display n_iterations = 256 generator_mean_history = np.ndarray(shape=(n_iterations, )) generator_sigma_history = np.ndarray(shape=(n_iterations, )) for i in range(n_iterations): train_discriminator(n_samples=2**12, n_epoches=1) train_generator() m, s = get_distribution_params() ...
_____no_output_____
Apache-2.0
day4-Fri/Pythia-Tune-AVO.ipynb
mi-stankai/mlhep2018
1) Matplotlib Part 1 1) Functional method
import numpy as np import matplotlib.pyplot as plt from numpy.random import randint x = np.linspace(0,10,20) x y = randint(0,50,20) y y = np.sort(y) y plt.plot(x,y, color='m', linestyle='--', marker='*', markersize=10, lw=1.5) plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('X vs Y axis') plt.show() # multiple plot...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
2) Object Oriented Method
import numpy as np import matplotlib.pyplot as plt from numpy.random import randint x = np.linspace(0,10,20) y = randint(1, 50, 20) y = np.sort(y) x y fig = plt.figure() axes = fig.add_axes([0.1,0.1,1,1]) axes.plot(x,y) axes.set_xlabel('X axis') axes.set_ylabel('Y axis') axes.set_title('X vs Y axis') # 2 sets of figure...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
2) Matplotlib Part 2 1) Subplots method
import numpy as np import matplotlib.pyplot as plt from numpy.random import randint x = np.linspace(0,10,20) y = randint(1, 50, 20) y = np.sort(y) x y fig,axes = plt.subplots() axes.plot(x,y) fig,axes = plt.subplots(nrows=2,ncols=3) plt.tight_layout() axes fig,axes = plt.subplots(nrows=1,ncols=2) for current_ax in axes...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
2) Figure size, Aspect ratio and DPI
import numpy as np import matplotlib.pyplot as plt from numpy.random import randint x = np.linspace(0,10,20) y = randint(1, 50, 20) y = np.sort(y) fig = plt.figure(figsize=(3,2),dpi=100) ax = fig.add_axes([0,0,1,1]) ax.plot(x,y) fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(7,2)) axes[0].plot(x,y) axes[1].plot(x,y) ...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
3) Matplotlib Part 3
import numpy as np import matplotlib.pyplot as plt from numpy.random import randint x = np.linspace(0,10,20) y = randint(1, 50, 20) y = np.sort(y) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='g',linewidth=3,ls='--',alpha=0.8,marker='o',markersize=10,markerfacecolor='yellow') fig = plt.figure() ax ...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
4) Different Plots 1) Scatter Plots
import matplotlib.pyplot as plt y_views=[534,690,258,402,724,689,352] f_views=[123,342,700,305,406,648,325] t_views=[202,209,176,415,824,389,550] days=[1,2,3,4,5,6,7] plt.scatter(days,y_views,label='Youtube Views',marker='o') plt.scatter(days,f_views,label='Facebook Views',marker='o') plt.scatter(days,t_views,label='Tw...
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
2) Bar plot
plt.bar(days,y_views,label='Youtube views') plt.bar(days,f_views,label='Facebook views') plt.xlabel('Days') plt.ylabel('Views') plt.title('Social Media Views') plt.legend()
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
3) Histogram
points=[22,55,62,45,21,22,99,34,42,4,102,110,27,48,99,84] bins=[0,20,40,60,80,100,120] plt.hist(points,bins) plt.xlabel('Bins') plt.ylabel('Frequency') plt.title('Bins vs Frequency') plt.show()
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
4) Pie chart
labels_1=['Facebook','Instagram','Youtube','linkedin'] views=[300,350,400,450] explode_1=[0,0,0,0.2] plt.pie(views,labels=labels_1,autopct='%1.1f%%',explode=explode_1,shadow=True) plt.show()
_____no_output_____
MIT
16DataVisualizationWithMatplotlib.ipynb
MBadriNarayanan/NaturalLanguageProcessing
!git clone https://github.com/MadhabBarman/Epidemic-Control-Model.git cd Epidemic-Control-Model/ %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.integrate import odeint from scipy.io import savemat, loadmat import numpy.linalg as la from matplotlib.lines import Lin...
_____no_output_____
MIT
SEIRD_ControlModel.ipynb
MadhabBarman/Epidemic-Control-Model
**Simulated individuals figure**
fig = plt.figure(num=None, figsize=(28, 12), dpi=80, facecolor='w', edgecolor='k') plt.rcParams.update({'font.size': 26}) plt.plot(t, (tempA + tempI + tempH)/N, '--', lw=6, color='g', label='Active Case', alpha=0.8) plt.plot(t, (tempA + tempI)/N , '-', lw=7, color='k', label='$A + I$', alpha=0.8) plt.plot(t, IC_death/N...
_____no_output_____
MIT
SEIRD_ControlModel.ipynb
MadhabBarman/Epidemic-Control-Model
**Analysis between real case data vs numerical**
fig = plt.figure(num=None, figsize=(28, 12), dpi=80, facecolor='w', edgecolor='k') plt.rcParams.update({'font.size': 26, 'text.color':'black'}) plt.plot(t, tempA + tempI + tempH, '--', lw=4, color='g', label='Active case numerical', alpha=0.8) plt.plot(active_new, 'o-', lw=4, color='#348ABD', ms=16, label='Active case ...
_____no_output_____
MIT
SEIRD_ControlModel.ipynb
MadhabBarman/Epidemic-Control-Model
**Sensitivity of hospitalization parameter $\rho$**
q = 1.0 rhos = [0.0, 0.25, 0.5, 0.75, 1.0] fig = plt.figure(num=None, figsize=(20, 8), dpi=80, facecolor='w', edgecolor='k') plt.rcParams.update({'font.size': 20}) for rho in rhos: data = odeint(rhs, np.concatenate((S_0, E_0, Q_0, A_0, I_0, H_0, R_0)), t, args=(cont,beta_f)) tempS, tempE, tempQ, tempA, tempI, ...
_____no_output_____
MIT
SEIRD_ControlModel.ipynb
MadhabBarman/Epidemic-Control-Model
**Sensitivity of quarantine parameter $q$**
rho = 1.0 qs = [0.0, 0.25, 0.5, 0.75, 1.0] fig = plt.figure(num=None, figsize=(20, 8), dpi=80, facecolor='w', edgecolor='k') plt.rcParams.update({'font.size': 20}) for q in qs: data = odeint(rhs, np.concatenate((S_0, E_0, Q_0, A_0, I_0, H_0, R_0)), t, args=(cont,beta_f)) tempS, tempE, tempQ, tempA, tempI, temp...
_____no_output_____
MIT
SEIRD_ControlModel.ipynb
MadhabBarman/Epidemic-Control-Model
Select no SQLite
import sqlite3 import random import time import datetime # criando conexão conn = sqlite3.connect('dsa.db') # cursor c = conn.cursor() # criar tabela def create_table(): comando_create = 'CREATE TABLE IF NOT EXISTS produtos(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date TEXT, prod_name TEXT,valor REAL)' ...
_____no_output_____
MIT
06-Manipulando_Banco_Dados_Python/04-SQLite - Select no SQLite.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Archive dataThe Wellcome archive sits in a collections management system called CALM, which follows a rough set of standards and guidelines for storing archival records called [ISAD(G)](https://en.wikipedia.org/wiki/ISAD(G). The archive is comprised of _collections_, each of which has a hierarchical set of series, sec...
%matplotlib inline import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") plt.rcParams["figure.figsize"] = (20, 20) import pandas as pd import numpy as np import networkx as nx from sklearn.cluster import AgglomerativeClustering from umap import UMAP from tqdm import tqdm_notebook as tqdm def ...
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
let's load up our CALM data. The data has been exported in its entirety as a single `.json` where each line is a record. You can download the data yourself using [this script](https://github.com/wellcometrust/platform/blob/master/misc/download_oai_harvest.py). Stick the `.json` in the neighbouring `/data` directory t...
df = pd.read_json("data/calm_records.json") len(df) df.astype(str).describe()
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science
Exploring individual columnsAt the moment I have no idea what kind of information CALM contains - lets look at the list of column names
list(df)
_____no_output_____
MIT
notebooks/archive_exploration/notebooks/01 - subject coocurrence.ipynb
wellcomecollection/data-science