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 |
|---|---|---|---|---|---|
You will be able to check the expected output of `one_step_attention()` after you've coded the `model()` function. **Exercise**: Implement `model()` as explained in figure 2 and the text above. Again, we have defined global layers that will share weights to be used in `model()`. | n_a = 32
n_s = 64
post_activation_LSTM_cell = LSTM(n_s, return_state = True)
output_layer = Dense(len(machine_vocab), activation=softmax) | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Now you can use these layers $T_y$ times in a `for` loop to generate the outputs, and their parameters will not be reinitialized. You will have to carry out the following steps: 1. Propagate the input into a [Bidirectional](https://keras.io/layers/wrappers/bidirectional) [LSTM](https://keras.io/layers/recurrent/lstm)2.... | # GRADED FUNCTION: model
def model(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):
"""
Arguments:
Tx -- length of the input sequence
Ty -- length of the output sequence
n_a -- hidden state size of the Bi-LSTM
n_s -- hidden state size of the post-attention LSTM
human_vocab_size -- s... | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Run the following cell to create your model. | model = model(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab)) | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Let's get a summary of the model to check if it matches the expected output. | model.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_1 (InputLay... | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
**Expected Output**:Here is the summary you should see **Total params:** 52,960 **Trainable params:** 52,960 **Non-trainable params:** 0 ... | ### START CODE HERE ### (≈2 lines)
opt = Adam(lr = 0.005, beta_1 = 0.9, beta_2 = 0.999, decay = 0.01)
model.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])
### END CODE HERE ### | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
The last step is to define all your inputs and outputs to fit the model:- You already have X of shape $(m = 10000, T_x = 30)$ containing the training examples.- You need to create `s0` and `c0` to initialize your `post_activation_LSTM_cell` with 0s.- Given the `model()` you coded, you need the "outputs" to be a list of... | s0 = np.zeros((m, n_s))
c0 = np.zeros((m, n_s))
outputs = list(Yoh.swapaxes(0,1)) | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Let's now fit the model and run it for one epoch. | model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100) | Epoch 1/1
10000/10000 [==============================] - 35s - loss: 16.1592 - dense_3_loss_1: 1.1816 - dense_3_loss_2: 0.9146 - dense_3_loss_3: 1.6444 - dense_3_loss_4: 2.6827 - dense_3_loss_5: 0.7530 - dense_3_loss_6: 1.2778 - dense_3_loss_7: 2.5924 - dense_3_loss_8: 0.8461 - dense_3_loss_9: 1.6718 - dense_3_loss_10:... | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
While training you can see the loss as well as the accuracy on each of the 10 positions of the output. The table below gives you an example of what the accuracies could be if the batch had 2 examples: Thus, `dense_2_acc_8: 0.89` means that you are predicting the 7th character of the output correctly 89% of the time in... | model.load_weights('models/model.h5') | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
You can now see the results on new examples. | EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']
for example in EXAMPLES:
source = string_to_int(example, Tx, human_vocab)
source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_v... | source: 3 May 1979
output: 1979-05-03
source: 5 April 09
output: 2009-05-05
source: 21th of August 2016
output: 2016-08-21
source: Tue 10 Jul 2007
output: 2007-07-10
source: Saturday May 9 2018
output: 2018-05-09
source: March 3 2001
output: 2001-03-03
source: March 3rd 2001
output: 2001-03-03
source: 1 March 2001
outp... | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
You can also change these examples to test with your own examples. The next part will give you a better sense on what the attention mechanism is doing--i.e., what part of the input the network is paying attention to when generating a particular output character. 3 - Visualizing Attention (Optional / Ungraded)Since th... | model.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_1 (InputLay... | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Navigate through the output of `model.summary()` above. You can see that the layer named `attention_weights` outputs the `alphas` of shape (m, 30, 1) before `dot_2` computes the context vector for every time step $t = 0, \ldots, T_y-1$. Lets get the activations from this layer.The function `attention_map()` pulls out t... | attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, "Tuesday 09 Oct 1993", num = 7, n_s = 64) | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
LassoLars Regression with PowerTransformer This Code template is for the regression analysis using a simple LassoLars Regression with Feature Transformation technique PowerTransformer in a pipeline. It is a lasso model implemented using the LARS algorithm. Required Packages | import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PowerTransformer
from sklearn.metrics import r2_score, mean_absolute_error, m... | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X=df[features]
Y=df[target] | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Feature TransformationPower transforms are a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to heteroscedasticity (non-constant variance), or other situations where normality is desired.[More on PowerTransformer module and pa... | model = make_pipeline(PowerTransformer(),LassoLars(random_state=123))
model.fit(x_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.score: The score function returns the coefficient of determination R2 of the prediction. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 72.55 %
| Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) b... | y_pred=model.predict(x_test)
print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100))
print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred)))
print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) | R2 Score: 72.55 %
Mean Absolute Error 303.15
Mean Squared Error 126073.78
| Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(14,10))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(x_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_PowerTransformer.ipynb | mohityogesh44/ds-seed |
Pymongo - mongo in pythonTo use python with mongo we need to use the pymongo package - install using `pip install pymongo`, or via the anaconda application ConnectingTo connect to our Database we need to instantiate a client connection. To do this wee need: - hostname or ip-address - port - username - password In add... | from pymongo import MongoClient
client = MongoClient(host='18.219.151.47', #host is the hostname for the database
port=27017, #port is the port number that mongo is running on
username='student', #username for the db
password='emse6992pass', #password for ... | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
***NOTE: NEVER hard encode your password!!!*** Verify the connection is working: | client.server_info() | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Accessing Databases and CollectionsEven if we have authenticated oursevles, we still need to tell Mongo what database and collections we are interested. Once connected those attributes are name addressable: - `conn['database_name']` or `conn.database_name` - `database['coll_name']` or `database.coll_name` **Connecting... | db = client.emse6992
# db = client['emse6992'] - Alternative method | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Proof we're connected: | db.list_collection_names() | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
**Connecting to the Collections:** | favs_coll = db.twitter_favorites
# favs_coll = db['twitter_favorites'] | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Proof this works: | doc = favs_coll.find_one({})
doc
doc['favorited_by_screen_name'] | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
QueryingOnce connected, we are ready to start querying the database.The great thing about Python is it's integration with both JSON and Mongo, meaning that the Python Mongo API is almost exactly the same as Monog's own query API. find_one()This method works exactly the same as the Mongo equivelant. In addition the in... | doc = favs_coll.find_one({"favorited_by_screen_name": "elonmusk"})
doc | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
In Class Excercise:Using the **twitter_favorites** collection, find a **singular status** with a **tesla hashtag** | #Room for in-class work
doc = favs_coll.find_one({"hashtags.text": "tesla"},
{'hashtags': 1, 'user.screen_name': 1, 'user.description': 1})
print(doc) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
find()Likewise pymongo's **find()** works exactly like mongo's console find() command. One thing to note `find({})` returns a cursor (iterable), not an actual document.**In Class Questions:** 1. What is the advantage to using a generator/iterable in this instance? 2. What is the benefit of being able to query for one ... | docs = favs_coll.find({})
print(docs) # notice this is cursor, no actual data
print(docs[600]) # By indexing we can extract results from the query | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Iterating Through Our CursorWe can prove the query executed correctly by iterating through all of the documents | # Our query
docs = favs_coll.find({"favorited_by_screen_name": "elonmusk"})
# Variable to store the state of the test
worked = True
# Iterate through each of the docs looking for an invalid state
for doc in docs:
if doc['favorited_by_screen_name'] != 'elonmusk':
worked = False
break
# If worked is... | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Instead of iterating through the documents, we can also extract all of the documents at once by calling `list(docs)`. This approach though comes with some drawbacks. - The code will have to wait for all of the records to be pulled (unless threaded) - You'll need to ensure that you have the memory to store all of the re... | docs = favs_coll.find({"favorited_by_screen_name": "elonmusk"})
doc_lst = list(docs)
print(len(doc_lst))
docs.count() | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
In Class Excercise:Using the **twitter_statuses** collection, calculate the **total number of favorites** that **elonmusk** has received | stats_coll = db.twitter_statuses
#Room for in-class work
docs = stats_coll.find({'user.screen_name': 'elonmusk'})
tot = sum([doc.get('favorite_count', 0) for doc in docs])
print(tot) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Would we get the same result if we ran this processes against the **twitter_favorites** collection? Exception to the RuleWhile pymongo's pattern system effectively parallels the mongo shell, there is one key exception: - The use of the **$** In mongo shell the following is valid: - **`db.coll_name.find({"attr": {$exi... | # Space for work
from datetime import datetime
date = datetime(2021, 1, 1)
docs = favs_coll.find({"created_at": {"$gte": date}}).sort([('favorite_count', -1)])
user = docs[0].get('user').get('screen_name')
friends_coll = db.twitter_friends
doc = friends_coll.find_one({
"$and": [
{"screen_name": user},
... | not friends
| CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
insert_one() and insert_many()These methods enable us to insert one or more documents into the collection**Do not run the following sections!****Question**:Will the following cell cause an error? | test_coll = db.test_collection
doc = test_coll.find_one({"test": "passed!"})
print(doc) | None
| CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
We can insert any valid object by simply calling: - **`coll_name.insert_one(doc)`** *Note: If we do not provide a `_id` field in the document mongo will automatically create one. This means that there is nothing stopping us from inserting duplicate records* | doc = {"test": "passed!"}
result = test_coll.insert_one(doc)
result.inserted_id | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
We can verify on the python side by querying for the record | doc = test_coll.find_one({"test": "passed!"})
print(doc) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
We can also insert many documents at once: - **`coll_name.insert_many(docs)`** - where docs is a list of valid BSON documents | #Don't run this - just for demonstration
docs = [{'test': 'passed-' + str(x)} for x in range(5)]
test_coll.insert_many(docs) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Verification: | # Since it's a sample collection it only has our inserted docs
docs = test_coll.find({})
docs_lst = list(docs)
for doc in docs_lst:
# This will simply help the formatting on the output
print(doc)
| _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
update_one() and update_many()As discussed in the slides, these methods are used to modify an existing record.While they are a bit more complexed than the other methods, I did want to provide a little example.**`coll_name.update_one(find_pattern, update_pattern)`** 1. We find the documnet(s) that match the find_patter... | # Here we will be adding an attribute that indicates the document has been updated
test_coll.update_one({"test": "passed!"}, {"$set": {"updated": True}})
doc = test_coll.find_one({"test": "updated"})
print(doc) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Works the same way for **`coll_name.update_many(find_pattern, update_pattern)`** | test_coll.update_many({"test": {"$exists": True}}, {"$set": {"updated": True}})
docs = test_coll.find({})
for doc in docs:
# This will simply help the formatting on the output
print(doc) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
delete_one() and delete_many()Deleting records works almost the same was as updating, except we only provide a **find_pattern** to the method.**`coll_name.delete_one(find_pattern)`** | result = test_coll.delete_one({"test": "updated"}) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Now we shouldn't be able to find that document: | doc = test_coll.find_one({"test": "updated"})
print(doc) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
We can also inspect the **DeleteResult** from the command: | print(result.raw_result)
print(result.deleted_count)
print(result.acknowledged) | _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Small example using **`coll_name.delete_many()`** | def num_field(field):
docs = test_coll.find({field: {"$exists": True}})
count = sum(1 for x in docs)
return(count)
print(num_field('test'))
test_coll.delete_many({'test': {"$exists": True}})
print(num_field('test'))
| _____no_output_____ | CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
In Class Excercise: 1. Insert a JSON document into the test_collection with the following structure: ```JSON { "name": `your_name`, "favorite_movie": `movie_name`, "favorite_bands": [ `band_name_1`, `band_name_2`, `etc.` ] }``` 2. Review the response o... | # Space for work
resp = test_coll.insert_one(
{
"name": "Joel",
"favorite_movie": 'Big Fish',
"favorite_bands": [
'Jon Bellion',
'Blink-182'
]
}
)
if resp.acknowledged:
print("Inserted")
_id = resp.inserted_id
test_coll.find_one({"_id": _id})
resp = te... | 1 documents removed
| CC-BY-3.0 | assets/EMSE6586/PyMongo_Complete.ipynb | ngau9567/ngau9567.github.io |
Introduction In this notebook you will learn about the **AR-CNN** - a novel self-correcting, autoregressive model that uses a convolutional neural network in its architecture. By the end of this notebook, you will have trained and ran inference on your very own custom model. This notebook dives into details on the mod... | # The MIT-Zero License
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limit... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Dataset SummaryIn this tutorial, we use the [`JSB-Chorales-dataset`](http://www-etud.iro.umontreal.ca/~boulanni/icml2012), comprising 229 chorale snippets. A chorale is a hymn that is usually sung with a single voice playing a simple melody and three lower voices providing harmony. In this dataset, these voices are re... | # Get The List Of Midi Files
data_dir = 'data/*.mid'
midi_files = glob.glob(data_dir)
random_midi = randrange(len(midi_files))
play_midi(midi_files[random_midi]) | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Data Format - Piano Roll For the purpose of this tutorial, we represent music from the JSB-Chorales dataset in the piano roll format.A **piano roll** is a discrete, image-like representation of music which can be viewed as a two-dimensional grid with **"Time"** on the horizontal axis and **"Pitch"** on the vertical ax... | # Generate Midi File Samples
def generate_samples(midi_files, bars, beats_per_bar, beat_resolution, bars_shifted_per_sample):
"""
dataset_files: All files in the dataset
return: piano roll samples sized to X bars
"""
timesteps_per_nbars = bars * beats_per_bar * beat_resolution
time_steps_shifted... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Training AugmentationThe augmented **input piano roll** is created by adding and removing notes from the original piano roll. By keeping the original piano roll as the target, the model learns what edit events (i.e. notes to add and remove) are needed to recreate from the augmented piano roll. The augmented piano roll... | sampling_lower_bound_remove = 0
sampling_upper_bound_remove = 100
sampling_lower_bound_add = 1
sampling_upper_bound_add = 1.5 | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Loss FunctionRather than using a traditional loss function such as binary crossentropy, we calculate a custom loss function for our model. In our augmentation we both add extraneous notes and remove existing notes from the piano roll. Our end goal is to have the model pick the next **edit event**(i.e. the next note to... | # Customized Loss function
class Loss():
@staticmethod
def built_in_softmax_kl_loss(target, output):
'''
Custom Loss Function
:param target: ground truth values
:param output: predicted values
:return kullback_leibler_divergence loss
'''
target = K.flatten... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Model Architecture Our Model architecture is adapted from the U-Net architecture (a popular CNN that is used extensively in the computer vision domain), consisting of an **“encoder”** that maps the single track music data (represented as piano roll images) to a relatively lower dimensional “latent space“ and a **”deco... | # Build The Model
class ArCnnModel():
def __init__(self,
input_dim,
num_filters,
growth_factor,
num_layers,
dropout_rate_encoder,
dropout_rate_decoder,
batch_norm_encoder,
batch_no... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
TrainingWe split the dataset into training and validation sets. The default training-validation split is 0.9, but this can be changed with the parameter **“training_validation_split”** in **constants.py**.During training, the data generator creates (input, target) pairs by applying augmentations on the piano rolls pre... | dataset_size = len(dataset_samples)
dataset_split = math.floor(dataset_size * Constants.training_validation_split)
print(0, dataset_split, dataset_split + 1, dataset_size)
training_samples = dataset_samples[0:dataset_split]
print("training samples length: {}".format(len(training_samples)))
validation_samples = dataset... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
All the ArCnn model related hyperparameters can be changed from below. For instance, to decrease the model size, change the default value of num_layers from 5, and update the dropout_rate_encoder, dropout_rate_deoder, batch_norm_encoder and batch_norm_decoder lists accordingly. | # Piano Roll Input Dimensions
input_dim = (Constants.bars * Constants.beats_per_bar * Constants.beat_resolution,
Constants.number_of_pitches,
Constants.number_of_channels)
# Number of Filters In The Convolution
num_filters = 32
# Growth Rate Of Number Of Filters At Each Convolution
growth_fa... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Build The Data GeneratorsNow let's build the training and validation data generators to create data on the fly during training. | ## Training Data Generator
training_data_generator = PianoRollGenerator(sample_list=training_samples,
sampling_lower_bound_remove = sampling_lower_bound_remove,
sampling_upper_bound_remove = sampling_upper_bound_remove,
... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Create Callbacks for the model. 1. Create **Training Vs Validation** loss plots during training.2. Save model checkpoints based on the **Best Validation Loss**. | # Callback For Loss Plots
plot_losses = GenerateTrainingPlots()
## Checkpoint Path
checkpoint_filepath = 'checkpoints/-best-model-epoch:{epoch:04d}.hdf5'
# Callback For Saving Model Checkpoints
model_checkpoint_callback = keras.callbacks.ModelCheckpoint(
filepath=checkpoint_filepath,
save_weights_only=False... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Inference Generating Bach Like Enhanced Melody For Custom InputCongratulations! You have trained your very own AutoRegressive model to generate music. Let us see how our music model performs on a custom input.Before loading the model, we need to load inference related parameters. After that, we load our pretrained m... | # Load The Inference Related Parameters
with open('inference_parameters.json') as json_file:
inference_params = json.load(json_file)
# Create An Inference Object
inference_obj = Inference()
# Load The Checkpoint
inference_obj.load_model('checkpoints/-best-model-epoch:0001.hdf5')
| _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Please navigate to **sample_inputs** directory to find different input melodies we have already created for you to help generating novel compositions.To download the novel compositions, you have created using the model we just trained, please navigate to **outputs** directory and download the midi file. | # Generate The Composition
inference_obj.generate_composition('sample_inputs/twinkle_twinkle.midi', inference_params) | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Now, Let's Play The Generated Output And Listen To It | play_midi("outputs/output_0.mid") | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Evaluate ResultsNow that we have finished generating our enhanced melody, let's find out how we did. We will analyze our output using below three metrics and compare them with the sample input:- **Empty Bar Rate:** The ratio of empty bars to total number of bars.- **Pitch Histogram Distance:** A metric that captures t... | # Input Midi Metrics:
print("The input midi metrics are:")
get_music_metrics("sample_inputs/twinkle_twinkle.midi", beat_resolution=4)
print("\n")
# Generated Output Midi Metrics:
print("The generated output midi metrics are:")
get_music_metrics("outputs/output_0.mid", beat_resolution=4)
# Convert The Input and Generat... | _____no_output_____ | MIT-0 | ar-cnn/ AutoRegressiveCNN.ipynb | byhqsr/aws-samples-aws-deepcomposer-samples |
Redshift fittingJavier Sánchez, 06/09/2016 A big part of the astrophysical and cosmological information comes from geometry, i.e., we can infer a lot of properties of our observable Universe using the positions of stars, galaxies and other objects. The sky appears to us as a 2D projection of our 3D Universe. The angul... | %pylab inline
import time
import os
import urllib2
import numpy as np
import pylab as pl
from matplotlib.patches import Arrow
REFSPEC_URL = 'http://www.astro.washington.edu/users/ivezic/DMbook/data/1732526_nic_002.ascii'
URL = 'http://www.sdss.org/dr7/instruments/imager/filters/%s.dat'
def fetch_filter(filt):
as... | _____no_output_____ | MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
Idea: Measure light at different wavelengths from the sources to determine their redshift Spectra If we measure the spectra at different wavelengths with certain resolution we can compare with an object with the same characteristics and a known redshift and compute it. Photometry Instead of using a spectrograph we u... | """
Photometric Redshifts via Linear Regression
-------------------------------------------
Linear Regression for photometric redshifts
We could use sklearn.linear_model.LinearRegression, but to be more
transparent, we'll do it by hand using linear algebra.
"""
# Author: Jake VanderPlas
# License: BSD
# The figure pr... | /Users/javiers/anaconda/lib/python2.7/site-packages/scipy/linalg/basic.py:884: RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.
warnings.warn(mes... | MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
Decision trees | """
Photometric Redshifts by Decision Trees
---------------------------------------
Figure 9.14
Photometric redshift estimation using decision-tree regression. The data is
described in Section 1.5.5. The training set consists of u, g , r, i, z
magnitudes of 60,000 galaxies from the SDSS spectroscopic sample.
Cross-vali... | _____no_output_____ | MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
Boosted decision trees | """
Photometric Redshifts by Random Forests
---------------------------------------
Figure 9.16
Photometric redshift estimation using gradient-boosted decision trees, with 100
boosting steps. As with random forests (figure 9.15), boosting allows for
improved results over the single tree case (figure 9.14). Note, howeve... | @pickle_results: using precomputed results from 'photoz_boosting.pkl'
| MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
KNN | """
K-Neighbors for Photometric Redshifts
-------------------------------------
Estimate redshifts from the colors of sdss galaxies and quasars.
This uses colors from a sample of 50,000 objects with SDSS photometry
and ugriz magnitudes. The example shows how far one can get with an
extremely simple machine learning ap... | RMS error = 0.024
| MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
Neural Network In this case I am going to use a Recurrent Neural Network (Long Short Term Memory). More info on: http://colah.github.io/posts/2015-08-Understanding-LSTMs/ | from keras.models import Sequential
model = Sequential()
from keras.layers import Dense, Activation
from keras.layers.recurrent import GRU, SimpleRNN
from keras.layers.recurrent import LSTM
from keras.layers import Embedding
model.add(LSTM(64,input_dim=4, return_sequences=False, activation='tanh'))
model.add(Dense(64))... | RMS error = 0.072
| MIT | Extra/Redshift Fitting -- Bayez.ipynb | dkirkby/astroml-study |
Lecture 06: Recap and overview [Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2021)[](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2021/master?urlpath=lab/tree/06/Examples_and_overview.ipynb) 1. [Lecture 02: Fundamentals](Lecture-02:-Fundamentals)2. [Lecture 03: Optimize, print and plot](L... | import itertools as it
import numpy as np
from scipy import optimize
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid') | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
1. Lecture 02: Fundamentals **Abstract:** You will be given an in-depth introduction to the **fundamentals of Python** (objects, variables, operators, classes, methods, functions, conditionals, loops). You learn to discriminate between different **types** such as integers, floats, strings, lists, tuples and dictionari... | np.random.seed(1917)
Nx = 10
x = np.random.uniform(0,1,size=(Nx,))
for i in range(Nx):
print(x[i]) | 0.15451797797720246
0.20789496806883712
0.0027198495778043563
0.1729632542127988
0.855555830200955
0.584099749650399
0.011903025078194518
0.0682582385196221
0.24917894776796679
0.8936630858183269
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**While loop**: A loop which continues until some condition is met. | i = 0
while i < Nx:
print(x[i])
i += 1 | 0.15451797797720246
0.20789496806883712
0.0027198495778043563
0.1729632542127988
0.855555830200955
0.584099749650399
0.011903025078194518
0.0682582385196221
0.24917894776796679
0.8936630858183269
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Find first number less than 0.1:** | i = 0
while i < Nx and x[i] >= 0.1:
i += 1
print(x[i]) | 0.0027198495778043563
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
Using a break: | i = 0
while i < Nx:
i += 1
if x[i] < 0.1:
break
print(x[i])
for i in range(Nx):
if x[i] < 0.1:
break
print(x[i]) | 0.0027198495778043563
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Conclusion:** When you can use a for-loop it typically gives you more simple code. 1.2 Nested loops | Nx = 5
Ny = 5
Nz = 5
x = np.random.uniform(0,1,size=(Nx))
y = np.random.uniform(0,1,size=(Ny))
z = np.random.uniform(0,1,size=(Nz))
mysum = 0
for i in range(Nx):
for j in range(Ny):
mysum += x[i]*y[j]
print(mysum)
mysum = 0
for i,j in it.product(range(Nx),range(Ny)):
mysum += x[i]*y[j]
print(mysum) | 4.689237201743941
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Meshgrid:** | xmat,ymat = np.meshgrid(x,y,indexing='ij')
mysum = xmat*ymat
print(np.sum(mysum))
I,J = np.meshgrid(range(Nx),range(Ny),indexing='ij')
mysum = x[I]*y[J]
print(np.sum(mysum)) | 4.689237201743942
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
1.3 Classes | class Fraction:
def __init__(self,numerator,denominator): # called when created
self.num = numerator
self.denom = denominator
def __str__(self): # called when using print
return f'{self.num}/{self.denom}' # string = self.nom/self.denom
def __add__... | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
In `__add__` we use$$\frac{a}{b}+\frac{c}{d}=\frac{a \cdot d+c \cdot b}{b \cdot d}$$ | x = Fraction(1,3)
print(x)
x = Fraction(1,3) # 1/3 = 5/15
y = Fraction(3,9) # 2/5 = 6/15
z = x+y # 5/15 + 6/15 = 11/15
print(z)
z.reduce()
print(z) | 2/3
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Check which methods a class have:** | dir(Fraction) | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
1.4 A consumer class $$\begin{aligned}V(p_{1},p_{2},I) & = \max_{x_{1},x_{2}}x_1^{\alpha}x_2^{1-\alpha}\\ \text{s.t.}\\p_{1}x_{1}+p_{2}x_{2} & \leq I,\,\,\,p_{1},p_{2},I>0\\x_{1},x_{2} & \geq 0\end{aligned}$$ **Goal:** Create a model-class to solve this problem. **Utility function:** | def u_func(model,x1,x2):
return x1**model.alpha*x2**(1-model.alpha) | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Solution function:** | def solve(model):
# a. objective function (to minimize)
obj = lambda x: -model.u_func(x[0],x[1]) # minimize -> negtive of utility
# b. constraints and bounds
con = lambda x: model.I-model.p1*x[0]-model.p2*x[1] # violated if negative
constraints = ({'type':'ineq','fun':con})
bo... | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Create consumer class:** | class ConsumerClass:
def __init__(self):
self.alpha = 0.5
self.p1 = 1
self.p2 = 2
self.I = 10
u_func = u_func
solve = solve | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Solve consumer problem**: | jeppe = ConsumerClass()
jeppe.alpha = 0.75
jeppe.solve()
print(f'(x1,x2) = ({jeppe.x1:.3f},{jeppe.x2:.3f}), u = {jeppe.u:.3f}') | (x1,x2) = (7.500,1.250), u = 4.792
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
Easy to loop over: | for alpha in np.linspace(0.1,0.9,10):
jeppe.alpha = alpha
jeppe.solve()
print(f'alpha = {alpha:.3f} -> (x1,x2) = ({jeppe.x1:.3f},{jeppe.x2:.3f}), u = {jeppe.u:.3f}') | alpha = 0.100 -> (x1,x2) = (1.000,4.500), u = 3.872
alpha = 0.189 -> (x1,x2) = (1.890,4.055), u = 3.510
alpha = 0.278 -> (x1,x2) = (2.778,3.611), u = 3.357
alpha = 0.367 -> (x1,x2) = (3.667,3.167), u = 3.342
alpha = 0.456 -> (x1,x2) = (4.554,2.723), u = 3.442
alpha = 0.544 -> (x1,x2) = (5.446,2.277), u = 3.661
alpha = ... | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
2. Lecture 03: Optimize, print and plot **Abstract:** You will learn how to work with numerical data (**numpy**) and solve simple numerical optimization problems (**scipy.optimize**) and report the results both in text (**print**) and in figures (**matplotlib**). 2.1 Numpy | x = np.random.uniform(0,1,size=6)
print(x) | [0.50162377 0.58786823 0.6692749 0.67937905 0.87084325 0.30623102]
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
Consider the following code with loop: | y = np.empty(x.size*2)
for i in range(x.size):
y[i] = x[i]
for i in range(x.size):
y[x.size + i] = x[i]
print(y) | [0.50162377 0.58786823 0.6692749 0.67937905 0.87084325 0.30623102
0.50162377 0.58786823 0.6692749 0.67937905 0.87084325 0.30623102]
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Vertical extension of vector** (more columns) | y = np.tile(x,2) # tiling (same x repated)
print(y)
y = np.hstack((x,x)) # stacking
print(y)
y = np.insert(x,0,x) # insert vector at place 0
print(y)
y = np.insert(x,6,x) # insert vector at place 0
print(y)
print(y.shape) | [0.50162377 0.58786823 0.6692749 0.67937905 0.87084325 0.30623102
0.50162377 0.58786823 0.6692749 0.67937905 0.87084325 0.30623102]
(12,)
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Horizontal extension of vector** (more columns) | y = np.vstack((x,x)) # stacking
print(y)
print(y.shape)
z = y.ravel()
print(z)
print(z.shape)
y_ = np.tile(x,2) # tiling (same x repated)
print(y_)
print(y_.shape)
print('')
y = np.reshape(y_,(2,6))
print(y)
print(y.shape)
y_ = np.repeat(x,2) # repeat each element
print(y_)
print('')
y__ = np.reshape(y_,(6,2))
print(y_... | [0.50162377 0.50162377 0.58786823 0.58786823 0.6692749 0.6692749
0.67937905 0.67937905 0.87084325 0.87084325 0.30623102 0.30623102]
[[0.50162377 0.50162377]
[0.58786823 0.58786823]
[0.6692749 0.6692749 ]
[0.67937905 0.67937905]
[0.87084325 0.87084325]
[0.30623102 0.30623102]]
[[0.50162377 0.58786823 0.6692749... | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
2.2 Numpy vs. dictionary vs. list vs. tuple | x_np = np.zeros(0)
x_list = []
x_dict = {}
x_tuple = () | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
1. If you data is **numeric**, and is changing on the fly, use **numpy**2. If your data is **heterogenous**, and is changing on the fly, use a **list** or a **dictionary**3. If your data is **fixed** use a tuple 2.3 Optimizers All **optimization problems** are characterized by:1. Control vector (choices), $\boldsymbol... | def f(x):
return np.sin(x)+0.05*x**2 | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Solution with loop:** | N = 100
x_vec = np.linspace(-10,10,N)
f_vec = np.empty(N)
f_best = np.inf # initial maximum
x_best = np.nan # not-a-number
for i,x in enumerate(x_vec):
f_now = f_vec[i] = f(x)
if f_now < f_best:
x_best = x
f_best = f_now
print(f'best with loop is {f_best:.8f} at x = {x_best:.8f}') | best with loop is -0.88366802 at x = -1.51515152
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Solution with scipy optimize:** | x_guess = [0]
obj = lambda x: f(x[0])
res = optimize.minimize(obj, x_guess, method='Nelder-Mead')
x_best_scipy = res.x[0]
f_best_scipy = res.fun
print(f'best with scipy.optimize is {f_best_scipy:.8f} at x = {x_best_scipy:.8f}') | best with scipy.optimize is -0.88786283 at x = -1.42756250
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Link:** [Scipy on the choice of optimizer](https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html) **Comparison:** | fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x_vec,f_vec,ls='--',lw=2,color='black',label='$f(x)$')
ax.plot(x_best,f_best,ls='',marker='s',label='loop')
ax.plot(x_best_scipy,f_best_scipy,ls='',marker='o',
markeredgecolor='red',label='scipy.optimize')
ax.set_xlabel('x')
ax.set_ylabel('f')
ax.legend(l... | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
2.5 Gradient descent optimizer **Algorithm:** `minimize_gradient_descent()`1. Choose tolerance $\epsilon>0$, step size $\alpha > 0$, and guess on $x_0$, set $n=0$.2. Compute $f(x_n)$ and $f^\prime(x_n) \approx \frac{f(\boldsymbol{x}_{n}+\Delta)-f(\boldsymbol{x}_{n})}{\Delta}$.3. If $|f^\prime(x_n)| < \epsilon$ then s... | def gradient_descent(f,x0,alpha=1,Delta=1e-8,max_iter=500,eps=1e-8):
""" minimize function with gradient descent
Args:
f (callable): function
x0 (float): initial value
alpha (float,optional): step size factor in search
Delta (float,optional): step size in numerical deri... | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Call the optimizer:** | x0 = 0
alpha = 0.5
x,fx,trials = gradient_descent(f,x0,alpha)
print(f'best with gradient_descent is {fx:.8f} at x = {x:.8f}') | n = 0: x = 0.00000000, f = 0.00000000, fp = 1.00000000
n = 1: x = -0.50000000, f = -0.46692554, fp = 0.82758257
n = 2: x = -0.91379128, f = -0.75007422, fp = 0.51936899
n = 3: x = -1.17347578, f = -0.85324884, fp = 0.26960144
n = 4: x = -1.30827650, f = -0.88015974, fp = 0.12868722
n = ... | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Illusstration:** | fig = plt.figure(figsize=(10,10))
# a. main figure
ax = fig.add_subplot(2,2,(1,2))
trial_x_vec = [trial['x'] for trial in trials]
trial_f_vec = [trial['fx'] for trial in trials]
trial_fp_vec = [trial['fp'] for trial in trials]
ax.plot(x_vec,f_vec,ls='--',lw=2,color='black',label='$f(x)$')
ax.plot(trial_x_vec,trial_f... | _____no_output_____ | MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
3. Lecture 04: Random numbers and simulation **Abstract:** You will learn how to use a random number generator with a seed and produce simulation results (**numpy.random**, **scipy.stats**), and calcuate the expected value of a random variable through Monte Carlo integration. You will learn how to save your results fo... | def f(x,y):
return (np.var(x)-np.var(y))**2
np.random.seed(1917)
x = np.random.normal(0,1,size=100)
print(f'mean(x) = {np.mean(x):.3f}')
for sigma in [0.5,1.0,0.5]:
y = np.random.normal(0,sigma,size=x.size)
print(f'sigma = {sigma:2f}: f = {f(x,y):.4f}') | mean(x) = -0.007
sigma = 0.500000: f = 0.5522
sigma = 1.000000: f = 0.0001
sigma = 0.500000: f = 0.4985
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**Question:** How can we make the loop give the same result for the same value of `sigma`? **Option 1:** Reset seed | np.random.seed(1917)
x = np.random.normal(0,1,size=100)
print(f'var(x) = {np.var(x):.3f}')
for sigma in [0.5,1.0,0.5]:
np.random.seed(1918)
y = np.random.normal(0,sigma,size=x.size)
print(f'sigma = {sigma:2f}: f = {f(x,y):.4f}') | var(x) = 0.951
sigma = 0.500000: f = 0.4908
sigma = 1.000000: f = 0.0025
sigma = 0.500000: f = 0.4908
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
**BAD SOLUTION:** Never reset the seed. Variables `x` and `y` are not ensured to be random relative to each other with this method. **Option 2:** Set and get state | np.random.seed(1917)
x = np.random.normal(0,1,size=100)
print(f'var(x) = {np.var(x):.3f}')
state = np.random.get_state()
for sigma in [0.5,1.0,0.5]:
np.random.set_state(state)
y = np.random.normal(0,sigma,size=x.size)
print(f'sigma = {sigma:2f}: f = {f(x,y):.4f}') | var(x) = 0.951
sigma = 0.500000: f = 0.5522
sigma = 1.000000: f = 0.0143
sigma = 0.500000: f = 0.5522
| MIT | web/06/Examples_and_overview.ipynb | Jovansam/lectures-2021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.