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 |
|---|---|---|---|---|---|
SageMakerClarifyProcessor | from sagemaker import clarify
clarify_processor = clarify.SageMakerClarifyProcessor(
role=role,
instance_count=1,
instance_type="ml.c5.2xlarge",
sagemaker_session=sess
) | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
Writing DataConfig and ModelConfigA `DataConfig` object communicates some basic information about data I/O to Clarify. We specify where to find the input dataset, where to store the output, the target column (`label`), the header names, and the dataset type.Similarly, the `ModelConfig` object communicates information ... | bias_report_prefix = "bias/report-{}".format(pipeline_model_name)
bias_report_output_path = "s3://{}/{}".format(bucket, bias_report_prefix)
data_config = clarify.DataConfig(
s3_data_input_path=test_data_bias_s3_uri,
s3_output_path=bias_report_output_path,
label="star_rating",
features="features",
... | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
ModelConfig | model_config = clarify.ModelConfig(
model_name=pipeline_model_name,
instance_type="ml.m5.4xlarge",
instance_count=1,
content_type="application/jsonlines",
accept_type="application/jsonlines",
# {"features": ["the worst", "Digital_Software"]}
content_template='{"features":$features}',
) | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
_Note: `label` is set to the JSON key for the model prediction results_ | predictions_config = clarify.ModelPredictedLabelConfig(label="predicted_label") | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
BiasConfig | bias_config = clarify.BiasConfig(
label_values_or_threshold=[
5,
4,
], # needs to be int or str for continuous dtype, needs to be >1 for categorical dtype
facet_name="product_category",
) | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
Run Clarify Job | clarify_processor.run_post_training_bias(
data_config=data_config,
data_bias_config=bias_config,
model_config=model_config,
model_predicted_label_config=predictions_config,
# methods='all', # FlipTest requires all columns to be numeric
methods=["DPPL", "DI", "DCA", "DCR", "RD", "DAR", "DRR", ... | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
Download Report From S3 | !aws s3 ls $bias_report_output_path/
!aws s3 cp --recursive $bias_report_output_path ./generated_bias_report/
from IPython.core.display import display, HTML
display(HTML('<b>Review <a target="blank" href="./generated_bias_report/report.html">Bias Report</a></b>')) | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
View Bias Report in StudioIn Studio, you can view the results under the experiments tab.Each bias metric has detailed explanations with examples that you can explore.You could also summarize the results in a handy table! Release Resources | %%html
<p><b>Shutting down your kernel for this notebook to release resources.</b></p>
<button class="sm-command-button" data-commandlinker-command="kernelmenu:shutdown" style="display:none;">Shutdown Kernel</button>
<script>
try {
els = document.getElementsByClassName("sm-command-button");
els[0].cli... | _____no_output_____ | Apache-2.0 | 00_quickstart/09_Detect_Model_Bias_Clarify.ipynb | MarcusFra/workshop |
Covid 19 Prediction Study - CBC Importing libraries | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
| _____no_output_____ | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Baskent Data | # başkent university data
veriler = pd.read_excel(r'covid data 05.xlsx')
# başkent uni data
print('total number of pcr results: ',len(veriler['pcr']))
print('number of positive pcr results: ',len(veriler[veriler['pcr']=='positive']))
print('number of negative pcr results: ',len(veriler[veriler['pcr']=='negative'])) | total number of pcr results: 1391
number of positive pcr results: 707
number of negative pcr results: 684
| MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Sao Paulo dataset | veri_saopaulo = pd.read_excel(r'sao_dataset.xlsx' )
print('total number of pcr results: ',len(veri_saopaulo['SARS-Cov-2 exam result']))
print('number of positive pcr results: ',len(veri_saopaulo[veri_saopaulo['SARS-Cov-2 exam result']=='positive']))
print('number of negative pcr results: ',len(veri_saopaulo[veri_saopa... | _____no_output_____ | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Baskent Data features (demographic data) | # Exporting demographical data to excel
veriler.describe().to_excel(r'/Users/hikmetcancubukcu/Desktop/covidai/veriler başkent covid/covid cbc demographic2.xlsx')
veriler.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 1391 entries, 0 to 1390
Data columns (total 24 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 hastano 1391 non-null int64
1 yasiondalik 1391 non-null f... | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Baskent Data preprocessing | # Gender to integer (0 : E, 1 : K)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
veriler["gender"] = le.fit_transform(veriler["cinsiyet"])
# Pcr to numeric values (negative : 0 , positive : 1)
veriler["pcr_result"] = le.fit_transform(veriler["pcr"])
veriler.info() # başkent uni data
# Depend... | _____no_output_____ | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Logistic Regression | # importing library
from sklearn.linear_model import LogisticRegression
logr= LogisticRegression(random_state=0)
logr.fit(X_train,y_train)
y_hat= logr.predict(X_test)
yhat_logr = logr.predict_proba(X_test)
y_hat22 = y_hat
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, y_hat, labels=[1,0])
np.set_prin... | precision recall f1-score support
0 0.85 0.59 0.69 75
1 0.68 0.89 0.77 75
accuracy 0.74 150
macro avg 0.76 0.74 0.73 150
weighted avg 0.76 0.74 0.73 ... | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Support Vector Machines | from sklearn.svm import SVC
svc= SVC(kernel="rbf",probability=True)
svc.fit(X_train, y_train)
yhat= svc.predict(X_test)
yhat_svm = svc.predict_proba(X_test)
yhat4 = yhat # svm prediction => yhat4
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat4, labels=[1,0])
np.set_printoptions(precision=2)
# P... | precision recall f1-score support
0 0.91 0.67 0.77 75
1 0.74 0.93 0.82 75
accuracy 0.80 150
macro avg 0.82 0.80 0.80 150
weighted avg 0.82 0.80 0.80 ... | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
RANDOM FOREST CLASSIFIER | from sklearn.ensemble import RandomForestClassifier
rfc= RandomForestClassifier(n_estimators=200,criterion="entropy")
rfc.fit(X_train,y_train)
yhat7= rfc.predict(X_test)
yhat_rf = rfc.predict_proba(X_test)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat7, labels=[1,0])
np.set_printoptions(precisi... | precision recall f1-score support
0 0.88 0.68 0.77 75
1 0.74 0.91 0.81 75
accuracy 0.79 150
macro avg 0.81 0.79 0.79 150
weighted avg 0.81 0.79 0.79 ... | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
XGBOOST | from sklearn.ensemble import GradientBoostingClassifier
classifier = GradientBoostingClassifier()
classifier.fit(X_train, y_train)
yhat8 = classifier.predict(X_test)
yhat_xgboost = classifier.predict_proba(X_test)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat8, labels=[1,0])
np.set_printoptions... | precision recall f1-score support
0 0.81 0.63 0.71 75
1 0.70 0.85 0.77 75
accuracy 0.74 150
macro avg 0.75 0.74 0.74 150
weighted avg 0.75 0.74 0.74 ... | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
ROC & AUC | #baskent dataset
from sklearn.metrics import roc_curve, auc
logr_fpr, logr_tpr, threshold = roc_curve(y_test, yhat_logr[:,1]) # logr roc data
auc_logr = auc(logr_fpr, logr_tpr)
svm_fpr, svm_tpr, threshold = roc_curve(y_test, yhat_svm[:,1]) # svm roc data
auc_svm = auc(svm_fpr, svm_tpr)
rf_fpr, rf_tpr, thresho... | _____no_output_____ | MIT | covid_study_ver_cbc_4_sao.ipynb | hikmetc/COVID-19-AI |
Uncomment the following line to install [geemap](https://geemap.org) and [cartopy](https://scitools.org.uk/cartopy/docs/latest/installing.htmlinstalling) if needed. Keep in mind that cartopy can be challenging to install. If you are unable to install cartopy on your computer, you can try Google Colab with this the [not... | # !pip install cartopy scipy
# !pip install geemap | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
How to create publication quality maps using `cartoee``cartoee` is a lightweight module to aid in creatig publication quality maps from Earth Engine processing results without having to download data. The `cartoee` package does this by requesting png images from EE results (which are usually good enough for visualizat... | %pylab inline
import ee
import geemap
# import the cartoee functionality from geemap
from geemap import cartoee
geemap.ee_initialize() | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
Plotting an imageIn this first example we will explore the most basic functionality including plotting and image, adding a colorbar, and adding visual aethetic features. Here we will use SRTM data to plot global elevation. | # get an image
srtm = ee.Image("CGIAR/SRTM90_V4")
# geospatial region in format [E,S,W,N]
region = [180, -60, -180, 85] # define bounding box to request data
vis = {'min':0, 'max':3000} # define visualization parameters for image
fig = plt.figure(figsize=(15, 10))
# use cartoee to get a map
ax = cartoee.get_map(srtm, ... | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
This is a decent map for minimal amount of code. But we can also easily use matplotlib colormaps to visualize our EE results to add more color. Here we add a `cmap` keyword to the `.get_map()` and `.add_colorbar()` functions. | fig = plt.figure(figsize=(15, 10))
cmap = "gist_earth" # colormap we want to use
# cmap = "terrain"
# use cartoee to get a map
ax = cartoee.get_map(srtm, region=region, vis_params=vis, cmap=cmap)
# add a colorbar to the map using the visualization params we passed to the map
cartoee.add_colorbar(ax, vis, cmap=cmap, ... | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
Plotting an RGB image`cartoee` also allows for plotting of RGB image results directly. Here is an example of plotting a Landsat false-color scene. | # get a landsat image to visualize
image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318')
# define the visualization parameters to view
vis ={"bands": ['B5', 'B4', 'B3'], "min": 0, "max":5000, "gamma":1.3}
fig = plt.figure(figsize=(15, 10))
# use cartoee to get a map
ax = cartoee.get_map(image, vis_params=vi... | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
By default, if a region is not provided via the `region` keyword the whole extent of the image will be plotted as seen in the previous Landsat example. We can also zoom to a specific region of an image by defining the region to plot. | fig = plt.figure(figsize=(15, 10))
# here is the bounding box of the map extent we want to use
# formatted a [E,S,W,N]
zoom_region = [-121.8025, 37.3458, -122.6265, 37.9178]
# plot the map over the region of interest
ax = cartoee.get_map(image, vis_params=vis, region=zoom_region)
# add the gridlines and specify that... | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
Adding north arrow and scale bar | fig = plt.figure(figsize=(15, 10))
# here is the bounding box of the map extent we want to use
# formatted a [E,S,W,N]
zoom_region = [-121.8025, 37.3458, -122.6265, 37.9178]
# plot the map over the region of interest
ax = cartoee.get_map(image, vis_params=vis, region=zoom_region)
# add the gridlines and specify that... | _____no_output_____ | MIT | examples/notebooks/50_cartoee_quickstart.ipynb | Yisheng-Li/geemap |
EJERCICIO 8El trigo es uno de los tres granos más ampliamente producidos globalmente, junto al maíz y el arroz, y el más ampliamente consumido por el hombre en la civilización occidental desde la antigüedad. El grano de trigo es utilizado para hacer harina, harina integral, sémola, cerveza y una gran variedad de produ... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import mpld3
%matplotlib inline
mpld3.enable_notebook()
from cperceptron import Perceptron
from cbackpropagation import ANN #, Identidad, Sigmoide
import patrones as magia
def progreso(ann, X, T, y=None, n=-1, E=None):
if n % 20 == 0:
... | _____no_output_____ | MIT | Argentina - Mondiola Rock - 90 pts/Practica/TP1/ejercicio 8/.ipynb_checkpoints/Ejercicio 8-checkpoint.ipynb | parolaraul/itChallengeML2017 |
Model Description- Apply a transformer based model to pfam/unirep_50 data and extract the embedding features> In this tutorial, we train nn.TransformerEncoder model on a language modeling task. The language modeling task is to assign a probability for the likelihood of a given word (or a sequence of words) to follow a... | import math
import torch.nn as nn
import argparse
import random
import warnings
import numpy as np
import torch
import torch.nn.functional as F
from torch import optim
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from torch.autograd import Variable
im... | _____no_output_____ | MIT | code/first_try/.ipynb_checkpoints/transformer_encoder-checkpoint.ipynb | steveyu323/motor_embedding |
Meridional Overturning`mom6_tools.moc` functions for computing and plotting meridional overturning. The goal of this notebook is the following:1) server as an example on to compute a meridional overturning streamfunction (global and Atalntic) from CESM/MOM output; 2) evaluate model experiments by comparing transports ... | %matplotlib inline
import matplotlib
import numpy as np
import xarray as xr
# mom6_tools
from mom6_tools.moc import *
from mom6_tools.m6toolbox import check_time_interval, genBasinMasks
import matplotlib.pyplot as plt
# The following parameters must be set accordingly
################################################... | _____no_output_____ | Apache-2.0 | docs/source/examples/meridional_overturning.ipynb | gustavo-marques/mom6-tools |
Mean = $\frac{1}{n} \sum_{i=1}^n a_i$ | # create a rdd from 0 to 99
rdd = sc.parallelize(range(100))
sum_ = rdd.sum()
n = rdd.count()
mean = sum_/n
print(mean) | 49.5
| Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Median (1) sort the list (2) pick the middle element | rdd.collect()
rdd.sortBy(lambda x:x).collect() | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
To access the middle element, we need to access the index. | rdd.sortBy(lambda x:x).zipWithIndex().collect()
sortedandindexed = rdd.sortBy(lambda x:x).zipWithIndex().map(lambda x:x)
n = sortedandindexed.count()
if (n%2 == 1):
index = (n-1)/2;
print(sortedandindexed.lookup(index))
else:
index1 = (n/2)-1
index2 = n/2
value1 = sortedandindexed.lookup(index1)[0]
... | 49.5
| Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Standard Deviation: - tells you how wide the is spread around the mean so if SD is low, all the values should be close to the mean - to calculate it first calculate the mean $\bar{x}$ - SD = $\sqrt{\frac{1}{N}\sum_{i=1}^N(x_i - \bar{x})^2}$ | from math import sqrt
sum_ = rdd.sum()
n = rdd.count()
mean = sum_/n
sqrt(rdd.map(lambda x: pow(x-mean,2)).sum()/n) | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Skewness- tells us how asymmetric data is spread around the mean - check positive skew, negative skew - Skew = $\frac{1}{n}\frac{\sum_{j=1}^n (x_j- \bar{x})^3}{\text{SD}^3}$, x_j= individual value | sd= sqrt(rdd.map(lambda x: pow(x-mean,2)).sum()/n)
n = float(n) # to round off
skw = (1/n)*rdd.map(lambda x : pow(x- mean,3)/pow(sd,3)).sum()
skw | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Kurtosis- tells us the shape of the data- indicates outlier content within the data- kurt = $\frac{1}{n}\frac{\sum_{j=1}^n (x_j- \bar{x})^4}{\text{SD}^4}$, x_j= individual value | (1/n)*rdd.map(lambda x : pow(x- mean,4)/pow(sd,4)).sum()
| _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Covariance \& Correlation- how two columns interact with each other- how all columns interact with each other- cov(X,Y) = $\frac{1}{n} \sum_{i=1}^n (x_i-\bar{x})(y_i -\bar{y})$ | rddX = sc.parallelize(range(100))
rddY = sc.parallelize(range(100))
# to avoid loss of precision use float
meanX = rddX.sum()/float(rddX.count())
meanY = rddY.sum()/float(rddY.count())
# since we need to use rddx, rddy same time we need to zip them together
rddXY = rddX.zip(rddY)
covXY = rddXY.map(lambda x:(x[0]-meanX)... | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Correlation- corr(X,Y) =$ \frac{\text{cov(X,Y)}}{SD_X SD_Y}$Measure of dependency - Correlation +1 Columns totally correlate 0 columns show no interaction -1 inverse dependency | from math import sqrt
n = rddXY.count()
mean = sum_/n
SDX = sqrt(rdd.map(lambda x: pow(x-meanX,2)).sum()/n)
SDY = sqrt(rdd.map(lambda y: pow(y-meanY,2)).sum()/n)
corrXY = covXY/(SDX *SDY)
corrXY
# corellation matrix in practice
import random
from pyspark.mllib.stat import Statistics
col1 = sc.parallelize(range(100))
co... | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Welcome to exercise one of week two of “Apache Spark for Scalable Machine Learning on BigData”. In this exercise you’ll read a DataFrame in order to perform a simple statistical analysis. Then you’ll rebalance the dataset. No worries, we’ll explain everything to you, let’s get started.Let’s create a data frame from a r... | # delete files from previous runs
!rm -f hmp.parquet*
# download the file containing the data in PARQUET format
!wget https://github.com/IBM/coursera/raw/master/hmp.parquet
# create a dataframe out of it
df = spark.read.parquet('hmp.parquet')
# register a corresponding query table
df.createOrReplaceTempView('df'... | --2020-11-06 02:38:52-- https://github.com/IBM/coursera/raw/master/hmp.parquet
Resolving github.com (github.com)... 140.82.114.3
Connecting to github.com (github.com)|140.82.114.3|:443... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://github.com/IBM/skillsnetwork/raw/master/... | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
This is a classical classification data set. One thing we always do during data analysis is checking if the classes are balanced. In other words, if there are more or less the same number of example in each class. Let’s find out by a simple aggregation using SQL. | from pyspark.sql.functions import col
counts = df.groupBy('class').count().orderBy('count')
display(counts)
df.groupBy('class').count().show()
spark.sql('select class,count(*) from df group by class').show() | +--------------+--------+
| class|count(1)|
+--------------+--------+
| Use_telephone| 15225|
| Standup_chair| 25417|
| Eat_meat| 31236|
| Getup_bed| 45801|
| Drink_glass| 42792|
| Pour_water| 41673|
| Comb_hair| 23504|
| Walk| 92254|
| Climb_stairs| 40258|
| Sitdow... | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
This looks nice, but it would be nice if we can aggregate further to obtain some quantitative metrics on the imbalance like, min, max, mean and standard deviation. If we divide max by min we get a measure called minmax ration which tells us something about the relationship between the smallest and largest class. Again,... | spark.sql('''
select
*,
max/min as minmaxratio -- compute minmaxratio based on previously computed values
from (
select
min(ct) as min, -- compute minimum value of all classes
max(ct) as max, -- compute maximum value of all classes
... | +----+-----+------------------+------------------+-----------------+
| min| max| mean| stddev| minmaxratio|
+----+-----+------------------+------------------+-----------------+
|6683|92254|31894.928571428572|21284.893716741157|13.80427951518779|
+----+-----+------------------+-------------... | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
The same query can be expressed using the DataFrame API. Again, don’t be scared. It’s just a sequential expression of transformation steps. You now an choose which syntax you like better. | df.show()
df.printSchema()
from pyspark.sql.functions import col, min, max, mean, stddev
df \
.groupBy('class') \
.count() \
.select([
min(col("count")).alias('min'),
max(col("count")).alias('max'),
mean(col("count")).alias('mean'),
stddev(col("count")).alias('stddev')
... | +----+-----+------------------+------------------+-----------------+
| min| max| mean| stddev| minmaxratio|
+----+-----+------------------+------------------+-----------------+
|6683|92254|31894.928571428572|21284.893716741157|13.80427951518779|
+----+-----+------------------+-------------... | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Now it’s time for you to work on the data set. First, please create a table of all classes with the respective counts, but this time, please order the table by the count number, ascending. | df1 = df.groupBy('class').count()
df1.sort('count',ascending=True).show() | +--------------+-----+
| class|count|
+--------------+-----+
| Eat_soup| 6683|
| Liedown_bed|11446|
| Use_telephone|15225|
|Descend_stairs|15375|
| Comb_hair|23504|
| Sitdown_chair|25036|
| Standup_chair|25417|
| Brush_teeth|29829|
| Eat_meat|31236|
| Climb_stairs|40258|
| Pour_water|41673... | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Pixiedust is a very sophisticated library. It takes care of sorting as well. Please modify the bar chart so that it gets sorted by the number of elements per class, ascending. Hint: It’s an option available in the UI once rendered using the display() function. | import pixiedust
from pyspark.sql.functions import col
counts = df.groupBy('class').count().orderBy('count')
display(counts) | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Imbalanced classes can cause pain in machine learning. Therefore let’s rebalance. In the flowing we limit the number of elements per class to the amount of the least represented class. This is called undersampling. Other ways of rebalancing can be found here:[https://machinelearningmastery.com/tactics-to-combat-imbalan... | from pyspark.sql.functions import min
# create a lot of distinct classes from the dataset
classes = [row[0] for row in df.select('class').distinct().collect()]
# compute the number of elements of the smallest class in order to limit the number of samples per calss
min = df.groupBy('class').count().select(min('count')... | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Please verify, by using the code cell below, if df_balanced has the same number of elements per class. You should get 6683 elements per class. | $$$ | _____no_output_____ | Apache-2.0 | (b)intro 2.ipynb | fahimalamabir/scalable_machine_learning_Apache_Spark |
Importing NLTK packages | import nltk
import pandas as pd
restuarant = pd.read_csv("User_restaurants_reviews.csv")
restuarant.head()
from nltk.tokenize import sent_tokenize, word_tokenize
example_text = restuarant["Review"][1]
print(example_text)
nltk.download('stopwords') | [nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\Aditya\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!
| MIT | NLP Basics.ipynb | SaiAdityaGarlapati/nlp-peronsal-archive |
Importing stopwords and filtering data using list comprehension | from nltk.corpus import stopwords
stop_words = set(stopwords.words('english')) ##Selecting the stop words we want
print(len(stop_words))
print(stop_words)
nltk.download('punkt')
word_tokens = word_tokenize(example_text)
print(word_tokens)
filtered_sentence = [word for word in word_tokens if not word in stop_words]
pr... | ['I', 'learned', 'electric', 'slicer', 'used', 'blade', 'becomes', 'hot', 'enough', 'start', 'cook', 'prosciutto', '.']
| MIT | NLP Basics.ipynb | SaiAdityaGarlapati/nlp-peronsal-archive |
Stemming the sentence | from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
stem_tokens=[stemmer.stem(word) for word in word_tokens]
print(stem_tokens) | ['I', 'learn', 'that', 'if', 'an', 'electr', 'slicer', 'is', 'use', 'the', 'blade', 'becom', 'hot', 'enough', 'to', 'start', 'to', 'cook', 'the', 'prosciutto', '.']
| MIT | NLP Basics.ipynb | SaiAdityaGarlapati/nlp-peronsal-archive |
Comparing the stemmed sentence using jaccard similarity | from sklearn.metrics import jaccard_similarity_score
score = jaccard_similarity_score(word_tokens,stem_tokens)
print(score)
nltk.download('averaged_perceptron_tagger')
#Write a function to get all the possible POS tags of NLTK?
text = word_tokenize("And then therefore it was something completely different")
nltk.pos_t... | _____no_output_____ | MIT | NLP Basics.ipynb | SaiAdityaGarlapati/nlp-peronsal-archive |
0. Setup Paths | import os
CUSTOM_MODEL_NAME = 'my_ssd_mobnet'
PRETRAINED_MODEL_NAME = 'ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8'
PRETRAINED_MODEL_URL = 'http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz'
TF_RECORD_SCRIPT_NAME = 'generate_tfrecord.py'
LABEL_MA... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
1. Download TF Models Pretrained Models from Tensorflow Model Zoo and Install TFOD | # https://www.tensorflow.org/install/source_windows
if os.name=='nt':
!pip install wget
import wget
if not os.path.exists(os.path.join(paths['APIMODEL_PATH'], 'research', 'object_detection')):
!git clone https://github.com/tensorflow/models {paths['APIMODEL_PATH']}
# Install Tensorflow Object Detection
if ... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
2. Create Label Map | labels = [{'name':'stone', 'id':1}, {'name':'cloth', 'id':2}, {'name':'scissors', 'id':3}]
with open(files['LABELMAP'], 'w') as f:
for label in labels:
f.write('item { \n')
f.write('\tname:\'{}\'\n'.format(label['name']))
f.write('\tid:{}\n'.format(label['id']))
f.write('}\n') | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
3. Create TF records | # OPTIONAL IF RUNNING ON COLAB
ARCHIVE_FILES = os.path.join(paths['IMAGE_PATH'], 'archive.tar.gz')
if os.path.exists(ARCHIVE_FILES):
!tar -zxvf {ARCHIVE_FILES}
if not os.path.exists(files['TF_RECORD_SCRIPT']):
!git clone https://github.com/nicknochnack/GenerateTFRecord {paths['SCRIPTS_PATH']}
!python {files['TF_R... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
4. Copy Model Config to Training Folder | if os.name =='posix':
!cp {os.path.join(paths['PRETRAINED_MODEL_PATH'], PRETRAINED_MODEL_NAME, 'pipeline.config')} {os.path.join(paths['CHECKPOINT_PATH'])}
if os.name == 'nt':
!copy {os.path.join(paths['PRETRAINED_MODEL_PATH'], PRETRAINED_MODEL_NAME, 'pipeline.config')} {os.path.join(paths['CHECKPOINT_PATH'])} | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
5. Update Config For Transfer Learning | import tensorflow as tf
from object_detection.utils import config_util
from object_detection.protos import pipeline_pb2
from google.protobuf import text_format
config = config_util.get_configs_from_pipeline_file(files['PIPELINE_CONFIG'])
config
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.io.gfile.G... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
6. Train the model | !pip install lvis
!pip install gin
!pip install gin-config
!pip install tensorflow_addons
TRAINING_SCRIPT = os.path.join(paths['APIMODEL_PATH'], 'research', 'object_detection', 'model_main_tf2.py')
command = "python {} --model_dir={} --pipeline_config_path={} --num_train_steps=2000".format(TRAINING_SCRIPT, paths['CHECK... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
7. Evaluate the Model | command = "python {} --model_dir={} --pipeline_config_path={} --checkpoint_dir={}".format(TRAINING_SCRIPT, paths['CHECKPOINT_PATH'],files['PIPELINE_CONFIG'], paths['CHECKPOINT_PATH'])
print(command)
#!{command} | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
8. Load Train Model From Checkpoint | import os
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from object_detection.builders import model_builder
from object_detection.utils import config_util
# Load pipeline config and build a detection model
configs = config_u... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
9. Detect from an Image | import cv2
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
category_index = label_map_util.create_category_index_from_labelmap(files['LABELMAP'])
IMAGE_PATH = os.path.join(paths['IMAGE_PATH'], 'test', 'scissors.ce01a4a7-a850-11ec-85bd-005056c00008.jpg')
img = cv2.imread(IMAGE_PATH)
image_np ... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
10. Real Time Detections from your Webcam | !pip uninstall opencv-python-headless -y
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
while cap.isOpened():
ret, frame = cap.read()
frame = cv2.flip(frame,1,dst=None) #水平镜像
image_np = np.array(frame)
input_tensor = tf.co... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
10. Freezing the Graph | FREEZE_SCRIPT = os.path.join(paths['APIMODEL_PATH'], 'research', 'object_detection', 'exporter_main_v2.py ')
FREEZE_SCRIPT
command = "python {} --input_type=image_tensor --pipeline_config_path={} --trained_checkpoint_dir={} --output_directory={}".format(FREEZE_SCRIPT ,files['PIPELINE_CONFIG'], paths['CHECKPOINT_PATH'],... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
11. Conversion to TFJS | !pip install tensorflowjs
command = "tensorflowjs_converter --input_format=tf_saved_model --output_node_names='detection_boxes,detection_classes,detection_features,detection_multiclass_scores,detection_scores,num_detections,raw_detection_boxes,raw_detection_scores' --output_format=tfjs_graph_model --signature_name=serv... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
12. Conversion to TFLite | TFLITE_SCRIPT = os.path.join(paths['APIMODEL_PATH'], 'research', 'object_detection', 'export_tflite_graph_tf2.py ')
command = "python {} --pipeline_config_path={} --trained_checkpoint_dir={} --output_directory={}".format(TFLITE_SCRIPT ,files['PIPELINE_CONFIG'], paths['CHECKPOINT_PATH'], paths['TFLITE_PATH'])
print(comm... | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
13. Zip and Export Models | !tar -czf models.tar.gz {paths['CHECKPOINT_PATH']}
from google.colab import drive
drive.mount('/content/drive') | _____no_output_____ | MIT | 2. Training and Detection.ipynb | luchaoshi45/tensorflow_jupyter_cnn |
15天入门Python3CopyRight by 黑板客 转载请联系heibanke_at_aliyun.com **上节作业**汉诺塔如何存储和操作数据? | %load day07/hnt.py
| _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
day08:生成器—临阵磨枪1. 生成器2. itertools4. 作业——八皇后 生成器生成器函数 1) return关键词被yield取代 2) 当调用这个“函数”的时候,它会立即返回一个迭代器,而不立即执行函数内容,直到调用其返回迭代器的next方法是才开始执行,直到遇到yield语句暂停。 3) 继续调用生成器返回的迭代器的next方法,恢复函数执行,直到再次遇到yield语句 4) 如此反复,一直到遇到StopIteration | # 最简单的例子,产生0~N个整数
def irange(N):
a = 0
while a<N:
yield a
a = a+1
b = irange(10)
print(b)
next(b) | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
当你要产生的数据只用来遍历。那么这个数据就适合用生成器来实现。不过要注意,生成器只能遍历一次。 | # fabonacci序列
from __future__ import print_function
def fib():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
for i in fib():
if i > 1000:
break
else:
print(i) | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
生成器表达式 | a = (x**2 for x in range(10))
next(a)
%%timeit -n 1 -r 1
sum([x**2 for x in range(10000000)])
%%timeit -n 1 -r 1
sum(x**2 for x in range(10000000)) | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
send生成器可以修改遍历过程,插入指定的数据 | def counter(maximum):
i = 0
while i < maximum:
val = (yield i)
print("i=%s, val=%s"%(i, val))
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
it = counter(10)
print("yield value: %s"%(next(it)))
print("yield value: %s"... | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
itertools1. chain 将多个生成器串起来2. repeat 重复元素3. permutations 排列,从N个数里取m个,考虑顺序。4. combinations 组合,从N个数里取m个,不考虑顺序。5. product 依次从不同集合里任选一个数。笛卡尔乘积 | import itertools
horses=[1,2,3,4]
races = itertools.permutations(horses,3)
a=itertools.product([1,2],[3,4],[5,6])
b=itertools.repeat([1,2,3],4)
c=itertools.combinations([1,2,3,4],3)
d=itertools.chain(races, a, b, c)
print([i for i in races])
print("====================")
print([i for i in a])
print("===============... | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
**作业:八皇后问题**8*8的棋盘上放下8个皇后,彼此吃不到对方。找出所有的位置组合。1. 棋盘的每一行,每一列,每一个条正斜线,每一条反斜线,都只能有1个皇后2. 使用生成器3. 支持N皇后 | from day08.eight_queen import gen_n_queen, printsolution
solves = gen_n_queen(5)
s = next(solves)
print(s)
printsolution(s)
def printsolution(solve):
n = len(solve)
sep = "+" + "-+" * n
print(sep)
for i in range(n):
squares = [" " for j in range(n)]
squares[solve[i]] = "Q"
print... | _____no_output_____ | MIT | Code/day08.ipynb | heibanke/learn_python_in_15days |
Вычислить $ \sqrt[k]{a} $ | import numpy as np
def printable_test(a, k, f, prc=1e-4):
ans = f(a, k)
print(f'Our result: {a}^(1/{k}) ~ {ans:.10f}')
print(f'True result: {a**(1/k):.10f}\n')
print(f'Approx a ~ {ans**k:.10f}')
print(f'True a = {a}')
assert abs(a - ans**k) < prc, f'the answer differs by {abs(a - ans**k):.10f} ... | Our result: 1350^(1/12) ~ 1.8233126596
True result: 1.8233126596
Approx a ~ 1350.0000000000
True a = 1350
Our result: -1^(1/1) ~ -1.0000000000
True result: -1.0000000000
Approx a ~ -1.0000000000
True a = -1
| MIT | savinov-vlad/hw1.ipynb | dingearteom/co-mkn-hw-2021 |
Дан многочлен P степени не больше 5 и отрезок [L, R] Локализовать корни: $ P(L_i) \cdot P(R_i) <0 $ И найти на каждом таком отрезке корни | from typing import List
import numpy as np
class Polynom:
def __init__(self, coefs: List[float]):
# self.coefs = [a0, a1, a2, ...., an]
self.coefs = coefs
def __str__(self):
if not self.coefs:
return ''
descr = str(self.coefs[0])
for i, coef in enumerate(sel... | _____no_output_____ | MIT | savinov-vlad/hw1.ipynb | dingearteom/co-mkn-hw-2021 |
Найти минимум функции $ e^{ax} + e^{-bx} + c(x - d)^2$ | from numpy import exp
from typing import Tuple
class ExpMinFinder:
def __init__(self, a: float, b: float, c: float, d: float):
if a <= 0 or b <= 0 or c <= 0:
raise ValueError("Parameters must be non-negative")
self.a = a
self.b = b
self.c = c
self.d = d
... | _____no_output_____ | MIT | savinov-vlad/hw1.ipynb | dingearteom/co-mkn-hw-2021 |
En este Nootebock se realiza la limpieza del conjunto train, de tal manera, que al terminar la pipeline ya se puede emplear dicho conjunto para el entrenamiento de modelos.Se expondrá en un pequeño comentario en la parte superior por la razon que se realiza el cambioPara una mejor descripción se puede consultar *Prepro... | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.decomposition import PCA
df = pd.read_table('Modelar_UH2019.txt', sep = '|', dtype={'HY_cod_postal':str})
df = pd.read_table('Modelar_UH2019.txt', sep = '|', dtype={'HY_cod_postal':str})
# Tenemos varios Nans en HY_provincias, po... | _____no_output_____ | MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Entrenamiento de modelosHemos entrenado una gran cantidad de modelos, incluso podríamos llegar a decir que más de 1000 (a base de bucles y funciones) para ver cual es el que más se ajusta a nuestro dataset. Y para no tenerlos nadando entre los cientos de pruebas que hemos reaalizado en los notebooks *Modelos2\_Testing... | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from sklearn import neighbors
from sklearn import tree
from sklearn.ensemble imp... | DecisionTreeRegressor10: 21.55431393653663
RandomForestRegressor20: 18.580995303598044
RandomForestRegressor50: 19.072373408609195
RandomForestRegressor100: 18.861664050362826
ExtraTreesRegressor10: 19.80307387148771
ExtraTreesRegressor100: 18.588761921652768
ExtraTreesRegressor150: 18.57115721270116
GradientBoostingRe... | MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Para la optimización de los parámetros implementamos un grid search manual con el que vamos variando los parámetros mediante bucles for. Nosotros encontramos el óptimo en *n_estimators= 30, reg_lambda* = 0.9, *subsample = 0.6*, *colsample_bytree = 0.7* | models = {'BestXGBoost' : XGBRegressor(max_depth = 10,
n_estimators= 30,
reg_lambda = 0.9,
subsample = 0.6,
colsample_bytree = 0.7,
... | BestXGBoost: 17.369460296630855
| MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Una vez definido el mejor modelo vamos a realizar una búsqueda de las mejores variables. Y para ello definimos una función forward que nos vaya añadiendo variables según su error. | def Entrenar(X,y,model):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)
model = model.fit(X_train, y_train)
y_pred = model.predict(X_test)
error = median_absolute_error(np.exp(y_test)-1, np.exp(y_pred)-1)
return error
def EntrenarForward(X, y... | Best var: GA_page_views --> 18.8182
Best var: PV_pca2 --> 18.6006
Best var: IDEA_pc_1960_69 --> 18.4076
Best var: GA_mean_bounce --> 18.2948
Best var: GA_exit_rate --> 18.1165
Best var: PV_longitud_descripcion --> 18.1131
Best var: IDEA_pc_2000_10 --> 18.0981
Best var: IDEA_pc_1990_99 --> 17.9477
Best var: PV_pca3 --> ... | MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Observemos las feature importances de nuestro mejor árbol ya que no mejoramos con el forward. | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)
xgb_model = XGBRegressor(max_depth = 10,
n_estimators= 30,
reg_lambda = 0.9,
subsample = 0.6,
colsample_bytree = 0.7,
o... | BestXGBoost: 20.791393280029297
| MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Por lo que el mejor modelo es el primer XGBoost entrenado Conjunto de TestRealizamos las mismas transforaciones para test | df = pd.read_table('Estimar_UH2019.txt', sep = '|', dtype={'HY_cod_postal':str})
# Tenemos varios Nans en HY_provincias, por lo que creamos la siguiente función que nos ayudará a imputarlos con
# ayuda del código postal
def ArreglarProvincias(df):
# Diccionario de los códigos postales. 'xxddd' --> xx es el códi... | _____no_output_____ | MIT | NotebookFinalTrainTest.ipynb | Riferji/Cajamar-2019 |
Black Scholes Exercise 1: Naive implementation- Use cProfile and Line Profiler to look for bottlenecks and hotspots in the code | # Boilerplate for the example
import cProfile
import pstats
try:
import numpy.random_intel as rnd
except:
import numpy.random as rnd
# make xrange available in python 3
try:
xrange
except NameError:
xrange = range
SEED = 7777777
S0L = 10.0
S0H = 50.0
XL = 10.0
XH = 50.0
TL = 1.0
TH = 2.0
RISK_FREE =... | _____no_output_____ | MIT | 1_BlackScholes_naive.ipynb | IntelPython/workshop |
The Naive Black Scholes algorithm (looped) | from math import log, sqrt, exp, erf
invsqrt = lambda x: 1.0/sqrt(x)
def black_scholes(nopt, price, strike, t, rate, vol, call, put):
mr = -rate
sig_sig_two = vol * vol * 2
for i in range(nopt):
P = float( price [i] )
S = strike [i]
T = t [i]
a = log(P / S)
... | _____no_output_____ | MIT | 1_BlackScholes_naive.ipynb | IntelPython/workshop |
Timeit and CProfile TestsWhat do you notice about the times?%timeit function(args)%prun function(args) Line_Profiler testsHow many times does the function items get called (hits)? | %load_ext line_profiler | _____no_output_____ | MIT | 1_BlackScholes_naive.ipynb | IntelPython/workshop |
Return Forecasting: Read Historical Daily Yen Futures DataIn this notebook, you will load historical Dollar-Yen exchange rate futures data and apply time series analysis and modeling to determine whether there is any predictable behavior. | # Futures contract on the Yen-dollar exchange rate:
# This is the continuous chain of the futures contracts that are 1 month to expiration
yen_futures = pd.read_csv(
Path("yen.csv"), index_col="Date", infer_datetime_format=True, parse_dates=True
)
yen_futures.head()
# Trim the dataset to begin on January 1st, 1990
... | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
Return Forecasting: Initial Time-Series Plotting Start by plotting the "Settle" price. Do you see any patterns, long-term and/or short? | # Plot just the "Settle" column from the dataframe:
yen_futures.Settle.plot(figsize=[15,10],title='Yen Future Settle Prices',legend=True) | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
--- Decomposition Using a Hodrick-Prescott Filter Using a Hodrick-Prescott Filter, decompose the Settle price into a trend and noise. | import statsmodels.api as sm
# Apply the Hodrick-Prescott Filter by decomposing the "Settle" price into two separate series:
noise, trend = sm.tsa.filters.hpfilter(yen_futures['Settle'])
# Create a dataframe of just the settle price, and add columns for "noise" and "trend" series from above:
df = yen_futures['Settle']... | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
--- Forecasting Returns using an ARMA Model Using futures Settle *Returns*, estimate an ARMA model1. ARMA: Create an ARMA model and fit it to the returns data. Note: Set the AR and MA ("p" and "q") parameters to p=2 and q=1: order=(2, 1).2. Output the ARMA summary table and take note of the p-values of the lags. Based... | # Create a series using "Settle" price percentage returns, drop any nan"s, and check the results:
# (Make sure to multiply the pct_change() results by 100)
# In this case, you may have to replace inf, -inf values with np.nan"s
returns = (yen_futures[["Settle"]].pct_change() * 100)
returns = returns.replace(-np.inf, np.... | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
--- Forecasting the Settle Price using an ARIMA Model 1. Using the *raw* Yen **Settle Price**, estimate an ARIMA model. 1. Set P=5, D=1, and Q=1 in the model (e.g., ARIMA(df, order=(5,1,1)) 2. P= of Auto-Regressive Lags, D= of Differences (this is usually =1), Q= of Moving Average Lags 2. Output the ARIMA ... | from statsmodels.tsa.arima_model import ARIMA
# Estimate and ARIMA Model:
# Hint: ARIMA(df, order=(p, d, q))
arima_model = ARIMA(yen_futures['Settle'], order=(5,1,1))
# Fit the model
arima_results = arima_model.fit()
# Output model summary results:
arima_results.summary()
# Plot the 5 Day Price Forecast
pd.DataFrame(... | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
--- Volatility Forecasting with GARCHRather than predicting returns, let's forecast near-term **volatility** of Japanese Yen futures returns. Being able to accurately predict volatility will be extremely useful if we want to trade in derivatives or quantify our maximum loss. Using futures Settle *Returns*, estimate an... | from arch import arch_model
# Estimate a GARCH model:
garch_model = arch_model(returns, mean="Zero", vol="GARCH", p=2, q=1)
# Fit the model
garch_results = garch_model.fit(disp="off")
# Summarize the model results
garch_results.summary()
# Find the last day of the dataset
last_day = returns.index.max().strftime('%Y-%m... | _____no_output_____ | ADSL | time_series_analysis.ipynb | EAC49/timeseries_homework |
Visit MIT Deep Learning Run in Google Colab View Source on GitHub Copyright Information | # Copyright 2021 MIT 6.S191 Introduction to Deep Learning. All Rights Reserved.
#
# Licensed under the MIT License. You may not use this file except in compliance
# with the License. Use and/or modification of this code outside of 6.S191 must
# reference:
#
# © MIT 6.S191: Introduction to Deep Learning
# http://introt... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Lab 1: Intro to TensorFlow and Music Generation with RNNs Part 2: Music Generation with RNNsIn this portion of the lab, we will explore building a Recurrent Neural Network (RNN) for music generation. We will train a model to learn the patterns in raw sheet music in [ABC notation](https://en.wikipedia.org/wiki/ABC_nota... | # Import Tensorflow 2.0
#%tensorflow_version 2.x
import tensorflow as tf
# Download and import the MIT 6.S191 package
#!pip install mitdeeplearning
import mitdeeplearning as mdl
# Import all remaining packages
import numpy as np
import os
import time
import functools
from IPython import display as ipythondisplay
fro... | Num GPUs Available: 0
| MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
2.2 DatasetWe've gathered a dataset of thousands of Irish folk songs, represented in the ABC notation. Let's download the dataset and inspect it: | mdl.__file__
# Download the dataset
songs = mdl.lab1.load_training_data()
# Print one of the songs to inspect it in greater detail!
example_song = songs[0]
print("\nExample song: ")
print(example_song)
songs[0]
len(songs) | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
We can easily convert a song in ABC notation to an audio waveform and play it back. Be patient for this conversion to run, it can take some time. | # Convert the ABC notation to audio file and listen to it
mdl.lab1.play_song(example_song) | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
One important thing to think about is that this notation of music does not simply contain information on the notes being played, but additionally there is meta information such as the song title, key, and tempo. How does the number of different characters that are present in the text file impact the complexity of the l... | # Join our list of song strings into a single string containing all songs
songs_joined = "\n\n".join(songs)
# Find all unique characters in the joined string
vocab = sorted(set(songs_joined))
print("There are", len(vocab), "unique characters in the dataset")
songs_joined
print(vocab) | ['\n', ' ', '!', '"', '#', "'", '(', ')', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', '<', '=', '>', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', ']', '^', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'... | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
2.3 Process the dataset for the learning taskLet's take a step back and consider our prediction task. We're trying to train a RNN model to learn patterns in ABC music, and then use this model to generate (i.e., predict) a new piece of music based on this learned information. Breaking this down, what we're really askin... | ### Define numerical representation of text ###
# Create a mapping from character to unique index.
# For example, to get the index of the character "d",
# we can evaluate `char2idx["d"]`.
char2idx = {u:i for i, u in enumerate(vocab)}
# Create a mapping from indices to characters. This is
# the inverse of char2... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
This gives us an integer representation for each character. Observe that the unique characters (i.e., our vocabulary) in the text are mapped as indices from 0 to `len(unique)`. Let's take a peek at this numerical representation of our dataset: | print('{')
for char,_ in zip(char2idx, range(5)):
print(' {:4s}: {:3d},'.format(repr(char), char2idx[char]))
print(' ...\n}')
char2idx['A']
### Vectorize the songs string ###
'''TODO: Write a function to convert the all songs string to a vectorized
(i.e., numeric) representation. Use the appropriate mapping
... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
We can also look at how the first part of the text is mapped to an integer representation: | print ('{} ---- characters mapped to int ----> {}'.format(repr(songs_joined[:10]), vectorized_songs[:10]))
# check that vectorized_songs is a numpy array
assert isinstance(vectorized_songs, np.ndarray), "returned result should be a numpy array" | 'X:1\nT:Alex' ---- characters mapped to int ----> [49 22 13 0 45 22 26 67 60 79]
| MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Create training examples and targetsOur next step is to actually divide the text into example sequences that we'll use during training. Each input sequence that we feed into our RNN will contain `seq_length` characters from the text. We'll also need to define a target sequence for each input sequence, which will be us... | ### Batch definition to create training examples ###
def get_batch(vectorized_songs, seq_length, batch_size):
# the length of the vectorized songs string
n = vectorized_songs.shape[0] - 1
# randomly choose the starting indices for the examples in the training batch
idx = np.random.choice(n-seq_length, batch_si... | [PASS] test_batch_func_types
[PASS] test_batch_func_shapes
[PASS] test_batch_func_next_step
======
[PASS] passed all tests!
| MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
For each of these vectors, each index is processed at a single time step. So, for the input at time step 0, the model receives the index for the first character in the sequence, and tries to predict the index of the next character. At the next timestep, it does the same thing, but the RNN considers the information from... | x_batch, y_batch = get_batch(vectorized_songs, seq_length=5, batch_size=1)
for i, (input_idx, target_idx) in enumerate(zip(np.squeeze(x_batch), np.squeeze(y_batch))):
print("Step {:3d}".format(i))
print(" input: {} ({:s})".format(input_idx, repr(idx2char[input_idx])))
print(" expected output: {} ({:s})".... | Step 0
input: 10 ('.')
expected output: 1 (' ')
Step 1
input: 1 (' ')
expected output: 13 ('1')
Step 2
input: 13 ('1')
expected output: 0 ('\n')
Step 3
input: 0 ('\n')
expected output: 51 ('Z')
Step 4
input: 51 ('Z')
expected output: 22 (':')
| MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
2.4 The Recurrent Neural Network (RNN) model Now we're ready to define and train a RNN model on our ABC music dataset, and then use that trained model to generate a new song. We'll train our RNN using batches of song snippets from our dataset, which we generated in the previous section.The model is based off the LSTM ... | def LSTM(rnn_units):
return tf.keras.layers.LSTM(
rnn_units,
return_sequences=True,
recurrent_initializer='glorot_uniform',
recurrent_activation='sigmoid',
stateful=True,
) | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
The time has come! Fill in the `TODOs` to define the RNN model within the `build_model` function, and then call the function you just defined to instantiate the model! | len(vocab)
### Defining the RNN Model ###
'''TODO: Add LSTM and Dense layers to define the RNN model using the Sequential API.'''
def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
model = tf.keras.Sequential([
# Layer 1: Embedding layer to transform indices into dense vectors of a fixed embeddin... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.