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
Lab 1: Markov Decision Processes - Problem 3 Lab InstructionsAll your answers should be written in this notebook. You shouldn't need to write or modify any other files.**You should execute every block of code to not miss any dependency.***This project was developed by Peter Chen, Rocky Duan, Pieter Abbeel for the Ber...
import numpy as np, numpy.random as nr, gym import matplotlib.pyplot as plt %matplotlib inline np.set_printoptions(precision=3)
_____no_output_____
MIT
Lab 1/ Problem 3 genouadr.ipynb
AdrianGScorp/deeprlbootcamp
Problem 3: Sampling-based Tabular Q-LearningSo far we have implemented Value Iteration and Policy Iteration, both of which require access to an MDP's dynamics model. This requirement can sometimes be restrictive - for example, if the environment is given as a blackbox physics simulator, then we won't be able to read o...
from crawler_env import CrawlingRobotEnv env = CrawlingRobotEnv() print("We can inspect the observation space and action space of this Gym Environment") print("-----------------------------------------------------------------------------") print("Action space:", env.action_space) print("It's a discrete space with %i ...
_____no_output_____
MIT
Lab 1/ Problem 3 genouadr.ipynb
AdrianGScorp/deeprlbootcamp
You will see the random controller can sometimes make progress but it won't get very far. Let's implement Tabular Q-Learning with $\epsilon$-greedy exploration to find a better policy piece by piece.
from collections import defaultdict import random # dictionary that maps from state, s, to a numpy array of Q values [Q(s, a_1), Q(s, a_2) ... Q(s, a_n)] # and everything is initialized to 0. q_vals = defaultdict(lambda: np.array([0. for _ in range(env.action_space.n)])) print("Q-values for state (0, 0): %s" % q_va...
Test1 passed Test2 passed
MIT
Lab 1/ Problem 3 genouadr.ipynb
AdrianGScorp/deeprlbootcamp
Next we will implement Q learning update. After we observe a transition $s, a, s', r$,$$\textrm{target}(s') = R(s,a,s') + \gamma \max_{a'} Q_{\theta_k}(s',a')$$$$Q_{k+1}(s,a) \leftarrow (1-\alpha) Q_k(s,a) + \alpha \left[ \textrm{target}(s') \right]$$
def q_learning_update(gamma, alpha, q_vals, cur_state, action, next_state, reward): """ Inputs: gamma: discount factor alpha: learning rate q_vals: q value table cur_state: current state action: action taken in current state next_state: next state results from tak...
Itr 0 # Average speed: 0.05 Itr 50000 # Average speed: 2.03 Itr 100000 # Average speed: 3.37 Itr 150000 # Average speed: 3.37 Itr 200000 # Average speed: 3.37 Itr 250000 # Average speed: 3.37
MIT
Lab 1/ Problem 3 genouadr.ipynb
AdrianGScorp/deeprlbootcamp
After the learning is successful, we can visualize the learned robot controller. Remember we learn this just from interacting with the environment instead of peeking into the dynamics model!
env = CrawlingRobotEnv(render=True, horizon=500) prev_state = env.reset() ret = 0. done = False while not done: action = np.argmax(q_vals[prev_state]) state, reward, done, info = env.step(action) ret += reward prev_state = state # you can close the visualization GUI with the following method env.close_...
_____no_output_____
MIT
Lab 1/ Problem 3 genouadr.ipynb
AdrianGScorp/deeprlbootcamp
Exercise 6-3 LSTMThe following two cells will create a LSTM cell with one neuron.We scale the output of the LSTM linear and add a bias.Then the output will be wrapped by a sigmoid activation.The goal is to predict a time series where every $n^{th}$ ($5^{th}$ in the current example) element is 1 and all others are 0.a)...
import tensorflow as tf import numpy as np from matplotlib import pyplot as plt tf.reset_default_graph() tf.set_random_seed(12314) epochs=50 zero_steps = 5 learning_rate = 0.01 lstm_neurons = 1 out_dim = 1 num_features = 1 batch_size = zero_steps window_size = zero_steps*2 time_steps = 5 x = tf.placeholder(tf.float3...
loss 0.00001 input: [0 0 0 0 1 0 0 0 0 1] forget 0.0135 input gate 0.9997 cell cands 0.9994 out gate sig 1.0000 out gate tanh 0.7586 hidden state 0.7586 cell state 0.9928 pred 0.0000 input: [0 0 0 1 0 0 0 0 1 0] forget 0.8747 input gate 0.9860 cell cands -0.0476 out gate sig 1.0000 out gate tanh 0.6759 hidden st...
MIT
week6/lstm.ipynb
changkun/ws-18-19-deep-learning-tutorial
2020L-WUM Praca domowa 2 Kod: **Bartłomiej Eljasiak** Załadowanie bibliotek Z tych bibliotek będziemy korzystać w wielu miejscach, jednak w niektórych fragmentach kodu znajdą się dodatkowe importowania, lecz w takich sytuacjach użytek załadowanej biblioteki jest ograniczony do 'chunku', w którym została załadowana.
import pandas as pd import seaborn as sns import numpy as np import sklearn
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Wczytanie danych
# local version _data=pd.read_csv('allegro-api-transactions.csv') #online version #_data = pd.read_csv('https://www.dropbox.com/s/360xhh2d9lnaek3/allegro-api-transactions.csv?dl=1') cdata=_data.copy()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Przyjrzenie się danym
cdata.head()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Obróbka danych
len(cdata.it_location.unique()) cdata.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 420020 entries, 0 to 420019 Data columns (total 14 columns): lp 420020 non-null int64 date 420020 non-null object item_id 420020 non-null int64 categories 420020 non-null object pay_option_on_d...
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Na pierwszy rzut oka nie mamy żadnych braków w danych, co znacznie ułatwia nam prace. Kodowanie zmiennych kategorycznych Wiemy, że naszym targetem będzie `price`, chcemy więc w tym akapicie zamienić wszystkie zmienne kategoryczne, z których w dalszej części kodu będziemy korzystać, na zmienne liczbowe. Skuteczna zam...
import category_encoders y=cdata.price te = category_encoders.target_encoder.TargetEncoder(cdata.it_location, smoothing=100) encoded = te.fit_transform(cdata.it_location,y) encoded
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Różne rodzaje zakodowania kolumny `main_category` One-hot Coding
from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder # integer encode le = LabelEncoder() integer_encoded = le.fit_transform(cdata.main_category) print(integer_encoded) # binary encode onehot_encoder = OneHotEncoder(categories='auto',sparse=False) integer_encoded = integer_en...
[12 18 6 ... 18 5 15] [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] ... [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.]]
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Zamieniliśmy w ten sposób kolumnę kategoryczną na 26 kolumn o wartościach 0 lub 1. Nie jest to złe rozwiązanie, jednak stanowczo zwiększa rozmiar naszej ramki i wydłża czas uczenia się modelu. Prawdopodobnie może istnieć lepsze rozwiązanie. Helmert CodingDocumentation: [scikit-learn](http://contrib.scikit-learn.org/ca...
# Pobieramy go z category_encoders helmert_encoder = category_encoders.HelmertEncoder() helmert_encoded = helmert_encoder.fit_transform(cdata.main_category) #showing only first 5 encoded rows print(helmert_encoded.loc[1:5,:].transpose())
1 2 3 4 5 intercept 1.0 1.0 1.0 1.0 1.0 main_category_0 1.0 0.0 0.0 1.0 1.0 main_category_1 -1.0 2.0 0.0 -1.0 -1.0 main_category_2 -1.0 -1.0 3.0 -1.0 -1.0 main_category_3 -1.0 -1.0 -1.0 -1.0 -1.0 main_category_4 -1.0 -1.0 -1.0 -1.0 -1.0 main_category_5 -1.0 -1.0...
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Backward Difference CodingDocumentation: [scikit-learn](http://contrib.scikit-learn.org/categorical-encoding/backward_difference.htmlbackward-difference-coding)
# Pobieramy go z category_encoders back_diff_encoder = category_encoders.BackwardDifferenceEncoder() back_diff_encoded = back_diff_encoder.fit_transform(cdata.main_category) #showing only first 5 encoded rows print(back_diff_encoded.loc[1:5,:].transpose())
1 2 3 4 5 intercept 1.000000 1.000000 1.000000 1.000000 1.000000 main_category_0 0.037037 0.037037 0.037037 0.037037 0.037037 main_category_1 -0.925926 0.074074 0.074074 -0.925926 -0.925926 main_category_2 -0.888889 -0.888889 0.111111 -0.88...
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Uzupełnianie braków Wybranie danych z ramkiDalej będziemy pracowac tylko na 3 kolumnach danych, ograniczę więc je dla przejżystości poczynań.
data_selected= cdata.loc[:,['price','it_seller_rating','it_quantity']] data_selected.head()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Usunięcie danych z kolumny Dane z kolumny będziemy usuwać funkcją `df.column.sample(frac)` gdzie `frac` będzie oznaczać procent danych, które chcemy zatrzymać. Gwarantuje nam to w miarę losowe usunięcie danych, które powinno być wystarczające do dalszych działań.
cdata.price.sample(frac=0.9)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Ocena skutecznosci imputacjiDo oceny skuteczności podanych algorytmów imputacji danych musimy przyjąć jakis sposób liczenia ich. Zgodnie z sugestią prowadzącej skorszystam z [RMSE](https://en.wikipedia.org/wiki/Root_mean_square) czyli root mean square error. Nazwa powinna przybliżyć sposób, którm RMSE jest wyznaczane,...
from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer from sklearn.metrics import mean_squared_error def test_imputation(imputer,iterations=10): _resoults=[] # we always use the same data, so it's taken globally for i in range(iterations): test_data ...
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
I to niech będzie przykład działania takiej funkcji
imputer = IterativeImputer(max_iter=10,random_state=0) RMSE_list = test_imputation(imputer,20) print("Średnie RMSE wynosi", round(np.mean(RMSE_list))) print('Odchylenie standardowe RMSE wynosi: ', round(np.std(RMSE_list))) RMSE_list
Średnie RMSE wynosi 6659.0 Odchylenie standardowe RMSE wynosi: 64.0
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Odchylenie standardowe jest dosyć małe, więc metodę imputacji uważam za skuteczną. Chętnym polecam przetestowanie tej funkcji dla innych typów imputacji oraz zmiennej liczbie iteracji. Usuwanie danych z wielu kolumn Powtórzmy uprzedni przykład dodając drobną modyfikacje. Tym razem będziemy usuwali dane zarówno z `it_...
def test_imputation2(imputer,iterations=10): _resoults=[] # we always use the same data, so it's taken globally for i in range(iterations): test_data = data_selected.copy() test_data.it_seller_rating = test_data.it_seller_rating.sample(frac = 0.9) test_data.it_quantity = test_data.i...
Średnie RMSE wynosi 7953.0 Odchylenie standardowe RMSE wynosi: 60.0
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Tak jak moglibyśmy się spodziewać, średni błąd jest większy w przypadku gdy usuneliśmy więcej danych. Ponownie zachęcam do powtórzenia obliczeń i sprawdzenia wyników. Spojrzenie na imputacje typu `IterativeImputer` Wykorzystałem pewien szczególny sposób imputacji danych tzn `IterativeImputer`, o którym nie wspomniałe...
upper_iter_limit = 30 lower_iter_limit = 5 imputation_iterations = 10 mean_RMSE ={ "single": [], "multi": [], } for imputer_iterations in range(lower_iter_limit,upper_iter_limit,2): _resoults_single = [] _resoults_multi = [] imputer = IterativeImputer(max_iter=imputer_iterations,random_state=0) ...
max_iter: 5 / 30 max_iter: 7 / 30 max_iter: 9 / 30 max_iter: 11 / 30 max_iter: 13 / 30 max_iter: 15 / 30 max_iter: 17 / 30 max_iter: 19 / 30 max_iter: 21 / 30 max_iter: 23 / 30 max_iter: 25 / 30 max_iter: 27 / 30 max_iter: 29 / 30
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Przyjrzyjmy się wynikom.
mean_RMSE
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa2/Grupa1/EljasiakBartlomiej/main.ipynb
niladrem/2020L-WUM
Classifying Fashion-MNISTNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% ...
import torch from torchvision import datasets, transforms import helper # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Download and load the training data trainset = datasets.Fa...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
GeoffKriston/deep-learning-v2-pytorch
Here we can see one of the images.
image, label = next(iter(trainloader)) helper.imshow(image[0,:]);
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
GeoffKriston/deep-learning-v2-pytorch
Building the networkHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up t...
# TODO: Define your network architecture here from torch import nn n_hidden1 = 1024 n_hidden2 = 128 n_hidden3 = 64 model = nn.Sequential(nn.Linear(784,n_hidden1), nn.ReLU(), nn.Linear(n_hidden1,n_hidden2), nn.ReLU(), nn.Linear(n_hid...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
GeoffKriston/deep-learning-v2-pytorch
Train the networkNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.htmlloss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).Then write t...
# TODO: Create the network, define the criterion and optimizer from torch import optim criterion = nn.NLLLoss() optimizer = optim.SGD(model.parameters(),lr=0.007) # TODO: Train the network here data = iter(trainloader) epochs = 10 for e in range(epochs): running_loss = 0 for images,labels in trainloader: ...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb
GeoffKriston/deep-learning-v2-pytorch
differential_privacy.analysis.rdp_accountant
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_____no_output_____
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
dp query
# Copyright 2018, The TensorFlow Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
_____no_output_____
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
gausian query
# Copyright 2018, The TensorFlow Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0. For more information, please see: * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md * https://github.com/tensorflow/addons If you depend on functionality not listed there, please file an issue.
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
our_dp_optimizer
# Copyright 2018, The TensorFlow Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
_____no_output_____
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
gan.ops
""" Most codes from https://github.com/carpedm20/DCGAN-tensorflow """ import math import numpy as np import tensorflow as tf if "concat_v2" in dir(tf): def concat(tensors, axis, *args, **kwargs): return tf.concat_v2(tensors, axis, *args, **kwargs) else: def concat(tensors, axis, *args, **kwargs): ...
_____no_output_____
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
OUR DP CGAN
# -*- coding: utf-8 -*- from __future__ import division from keras.datasets import cifar10 from mlxtend.data import loadlocal_mnist from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import roc_curve, auc from sklearn.linear_model import LogisticRe...
Using TensorFlow backend.
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
gan.utils
""" Most codes from https://github.com/carpedm20/DCGAN-tensorflow """ from __future__ import division import scipy.misc import numpy as np from six.moves import xrange import matplotlib.pyplot as plt import os, gzip import tensorflow as tf import tensorflow.contrib.slim as slim from keras.datasets import cifar1...
_____no_output_____
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
Main
import tensorflow as tf import os base_dir = "./" out_dir = base_dir + "mnist_clip1_sigma0.6_lr0.55" if not os.path.exists(out_dir): os.mkdir(out_dir) gpu_options = tf.GPUOptions(visible_device_list="0") with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, gpu_o...
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz 11493376/11490434 [==============================] - 1s 0us/step WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and ...
Apache-2.0
Advanced_DP_CGAN/AdvancedDPCGAN.ipynb
reihaneh-torkzadehmahani/DP-CGAN
URL: http://matplotlib.org/examples/pylab_examples/quiver_demo.htmlMost examples work across multiple plotting backends, this example is also available for:* [Matplotlib - quiver_demo](../matplotlib/quiver_demo.ipynb)
import numpy as np import holoviews as hv from holoviews import opts hv.extension('bokeh')
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/quiver_demo.ipynb
ppwadhwa/holoviews
Define data
xs, ys = np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2) X, Y = np.meshgrid(xs, ys) U = np.cos(X) V = np.sin(Y) # Convert to magnitude and angle mag = np.sqrt(U**2 + V**2) angle = (np.pi/2.) - np.arctan2(U/mag, V/mag)
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/quiver_demo.ipynb
ppwadhwa/holoviews
Plot
label = 'Arrows scale with plot width, not view' opts.defaults(opts.VectorField(height=400, width=500)) vectorfield = hv.VectorField((xs, ys, angle, mag)) vectorfield.relabel(label) label = "pivot='mid'; every third arrow" vf_mid = hv.VectorField((xs[::3], ys[::3], angle[::3, ::3], mag[::3, ::3], )) points = hv.Poin...
_____no_output_____
BSD-3-Clause
examples/gallery/demos/bokeh/quiver_demo.ipynb
ppwadhwa/holoviews
**PINN eikonal solver for a portion of the Marmousi model**
from google.colab import drive drive.mount('/content/gdrive') cd "/content/gdrive/My Drive/Colab Notebooks/Codes/PINN_isotropic_eikonal_R1" !pip install sciann==0.5.4.0 !pip install tensorflow==2.2.0 #!pip install keras==2.3.1 import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.axe...
0.005852164264049101 0.19346281698941364
MIT
codes/script5.ipynb
umairbinwaheed/PINN_eikonal
GRIP June'21 - The Sparks Foundation Data Science and Business Analytics Author: Smriti Gupta Task 1: **Prediction using Supervised ML** * Predict the percentage of an student based on the no. of study hours. * What will be predicted score if a student studies for 9.25 hrs/ day? * _LANGUAGE:_ Python* _DATASET:_ http:...
# Importing Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline %config Completer.use_jedi = False # Reading data from remote link url = "https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv" df =...
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Data Visualization
# 2-D graph to establish relationship between the Data and checking for linearity sns.set_style('darkgrid') df.plot(x='Hours', y='Scores', style='o') plt.title('Hours vs Percentage') plt.xlabel('Hours Studied') plt.ylabel('Percentage Score') plt.show()
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Data Preprocessing
X = df.iloc[:, :-1].values y = df.iloc[:, 1].values
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
LINEAR REGRESSION MODEL Splitting Dataset into training and test sets:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Training the Model
from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) print('TRAINING COMPLETED.')
TRAINING COMPLETED.
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Predicting the Score
y_predict = regressor.predict(X_test) prediction = pd.DataFrame({'Hours': [i[0] for i in X_test], 'Predicted Scores': [k for k in y_predict]}) prediction print(regressor.intercept_) print(regressor.coef_) # Plotting the regression line line = regressor.coef_*X+regressor.intercept_ # Plotting for the test data plt.sc...
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Checking the Accuracy Scores for training and test set
print('Test Score') print(regressor.score(X_test, y_test)) print('Training Score') print(regressor.score(X_train, y_train))
Test Score 0.9480612939203932 Training Score 0.953103139564599
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Comparing Actual Scores and Predicted Scores
data= pd.DataFrame({'Actual': y_test,'Predicted': y_predict}) data # Visualization comparing Actual Scores and Predicted Scores plt.scatter(X_test, y_test, color = colors[1]) plt.plot(X_test, y_predict, color = colors[0]) plt.title("Hours Studied Vs Percentage (Test Dataset)") plt.xlabel("Hour") plt.ylabel...
_____no_output_____
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
Model Evaluation Metrics
#Checking the efficiency of model from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict)))
Mean Absolute Error: 4.451593449522768 Mean Squared Error: 25.188194900366135 Root Mean Squared Error: 5.018784205399365
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
What will be predicted score if a student studies for 9.25 hrs/ day?
hours = 9.25 ans = regressor.predict([[hours]]) print("No of Hours = {}".format(hours)) print("Predicted Score = {}".format(ans[0]))
No of Hours = 9.25 Predicted Score = 93.71476919815156
MIT
Task 1- Prediction using Supervised ML/Linear Regression.ipynb
smritig19/GRIP_Internship_Tasks
import pandas as pd import time import os.path import warnings warnings.filterwarnings('ignore') # install DenMune clustering algorithm using pip command from the offecial Python repository, PyPi # from https://pypi.org/project/denmune/ !pip install denmune # now import it from denmune import DenMune # clone datasets...
Plotting train data
BSD-3-Clause
kaggle/detecting-non-groundtruth-datasets.ipynb
fossabot/denmune-clustering-algorithm
import numpy as np import matplotlib.pyplot as plt import pandas as pd !git clone https://github.com/yohanesnuwara/ccs-gundih
Cloning into 'ccs-gundih'... remote: Enumerating objects: 94, done. remote: Counting objects: 1% (1/94) remote: Counting objects: 2% (2/94) remote: Counting objects: 3% (3/94) remote: Counting objects: 4% (4/94) remote: Counting objects: 5% (5/94) remote: Counting objects: 6% (6/94) rem...
MIT
main/00_gundih_historical_production_data.ipynb
yohanesnuwara/bsc-thesis-carbon-capture-storage
Visualize the Historical Production Data
# Read simulation result col = np.array(['Date', 'Days', 'WSAT', 'OSAT', 'GSAT', 'GMT', 'OMR', 'GMR', 'GCDI', 'GCDM', 'WCD', 'WGR', 'WCT', 'VPR', 'VPT', 'VIR', 'VIT', 'WPR', 'OPR', 'GPR', 'WPT', 'OPT', 'GPT', 'PR', 'GIR', 'GIT', 'GOR']) case1 = pd.read_excel(r'/content/ccs-gundih/data/CASE...
_____no_output_____
MIT
main/00_gundih_historical_production_data.ipynb
yohanesnuwara/bsc-thesis-carbon-capture-storage
Dry-Gas Reservoir Analysis
!git clone https://github.com/yohanesnuwara/reservoir-engineering # calculate gas z factor and FVF import os, sys sys.path.append('/content/reservoir-engineering/Unit 2 Review of Rock and Fluid Properties/functions') from pseudoprops import pseudoprops from dranchuk_aboukassem import dranchuk from gasfvf import gasfv...
_____no_output_____
MIT
main/00_gundih_historical_production_data.ipynb
yohanesnuwara/bsc-thesis-carbon-capture-storage
1A.1 - Deviner un nombre aléatoire (correction)On reprend la fonction introduite dans l'énoncé et qui permet de saisir un nombre.
import random nombre = input("Entrez un nombre") nombre
_____no_output_____
MIT
_doc/notebooks/td1a/pp_exo_deviner_un_nombre_correction.ipynb
Jerome-maker/ensae_teaching_cs
**Q1 :** Ecrire une jeu dans lequel python choisi aléatoirement un nombre entre 0 et 100, et essayer de trouver ce nombre en 10 étapes.
n = random.randint(0,100) appreciation = "?" while True: var = input("Entrez un nombre") var = int(var) if var < n : appreciation = "trop bas" print(var, appreciation) else : appreciation = "trop haut" print(var, appreciation) if var == n: appreciat...
Entrez un nombre7 7 trop bas Entrez un nombre10 10 trop bas Entrez un nombre100 100 trop haut Entrez un nombre50 50 trop bas Entrez un nombre75 75 trop haut Entrez un nombre60 60 trop haut Entrez un nombre55 55 trop haut Entrez un nombre53 53 trop haut Entrez un nombre52 52 trop haut Entrez un nombre51 51 trop haut 51 ...
MIT
_doc/notebooks/td1a/pp_exo_deviner_un_nombre_correction.ipynb
Jerome-maker/ensae_teaching_cs
**Q2 :** Transformer ce jeu en une fonction ``jeu(nVies)`` où ``nVies`` est le nombre d'itérations maximum.
import random n = random.randint(0,100) vies = 10 appreciation = "?" while vies > 0: var = input("Entrez un nombre") var = int(var) if var < n : appreciation = "trop bas" print(vies, var, appreciation) else : appreciation = "trop haut" print(vies, var, appreciation) ...
Entrez un nombre50 10 50 trop bas Entrez un nombre75 9 75 trop haut Entrez un nombre60 8 60 trop bas Entrez un nombre65 7 65 trop bas Entrez un nombre70 6 70 trop bas Entrez un nombre73 5 73 trop haut Entrez un nombre72 4 72 trop haut Entrez un nombre71 3 71 trop haut 3 71 bravo !
MIT
_doc/notebooks/td1a/pp_exo_deviner_un_nombre_correction.ipynb
Jerome-maker/ensae_teaching_cs
**Q3 :** Adapter le code pour faire une classe joueur avec une méthode jouer, où un joueur est défini par un pseudo et son nombre de vies. Faire jouer deux joueurs et déterminer le vainqueur.
class joueur: def __init__(self, vies, pseudo): self.vies = vies self.pseudo = pseudo def jouer(self): appreciation = "?" n = random.randint(0,100) while self.vies > 0: message = appreciation + " -- " + self.pseudo + " : " + str(self.vies) + " vies restan...
? -- joueur 1 : 10 vies restantes. Nombre choisi : 50 3 50 trop haut trop haut -- joueur 1 : 9 vies restantes. Nombre choisi : 25 3 25 trop haut trop haut -- joueur 1 : 8 vies restantes. Nombre choisi : 10 3 10 trop haut trop haut -- joueur 1 : 7 vies restantes. Nombre choisi : 5 3 5 trop bas trop bas -- joueur 1 : 6 v...
MIT
_doc/notebooks/td1a/pp_exo_deviner_un_nombre_correction.ipynb
Jerome-maker/ensae_teaching_cs
Run sims to understand sensitivity of 'contact_tracing_constant'
ctc_range = [0.1 * x for x in range(11)] dfs_ctc_pre_reopen = run_sensitivity_sims(pre_reopen_params, param_to_vary='contact_tracing_constant', param_values = ctc_range, trajectories_per_config=250, time_horizon=100) dfs_ctc_post_reopen = run_sensitivity_sims(reopen_params, param_to...
_____no_output_____
MIT
boqn/group_testing/notebooks/.ipynb_checkpoints/cornell_reopen_analysis_sensitivity_contact_tracing_effectiveness-checkpoint.ipynb
RaulAstudillo06/BOQN
Artificial Intelligence Nanodegree Machine Translation ProjectIn this notebook, sections that end with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully! IntroductionIn this not...
%load_ext autoreload %aimport helper, tests %autoreload 1 import collections import helper import numpy as np import project_tests as tests from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Model from keras.layers import GRU, Input, Dense, T...
Using TensorFlow backend.
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Verify access to the GPUThe following test applies only if you expect to be using a GPU, e.g., while running in a Udacity Workspace or using an AWS instance with GPU support. Run the next cell, and verify that the device_type is "GPU".- If the device is not GPU & you are running from a Udacity Workspace, then save you...
from tensorflow.python.client import device_lib print(device_lib.list_local_devices())
[name: "/cpu:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 15440441665772238793 , name: "/gpu:0" device_type: "GPU" memory_limit: 357433344 locality { bus_id: 1 } incarnation: 3061658136091710780 physical_device_desc: "device: 0, name: Tesla K80, pci bus id: 0000:00:04.0" ]
MIT
machine_translation.ipynb
jay-thakur/machine_translation
DatasetWe begin by investigating the dataset that will be used to train and evaluate your pipeline. The most common datasets used for machine translation are from [WMT](http://www.statmt.org/). However, that will take a long time to train a neural network on. We'll be using a dataset we created for this project tha...
# Load English data english_sentences = helper.load_data('data/small_vocab_en') # Load French data french_sentences = helper.load_data('data/small_vocab_fr') print('Dataset Loaded')
Dataset Loaded
MIT
machine_translation.ipynb
jay-thakur/machine_translation
FilesEach line in `small_vocab_en` contains an English sentence with the respective translation in each line of `small_vocab_fr`. View the first two lines from each file.
for sample_i in range(2): print('small_vocab_en Line {}: {}'.format(sample_i + 1, english_sentences[sample_i])) print('small_vocab_fr Line {}: {}'.format(sample_i + 1, french_sentences[sample_i]))
small_vocab_en Line 1: new jersey is sometimes quiet during autumn , and it is snowy in april . small_vocab_fr Line 1: new jersey est parfois calme pendant l' automne , et il est neigeux en avril . small_vocab_en Line 2: the united states is usually chilly during july , and it is usually freezing in november . small...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
From looking at the sentences, you can see they have been preprocessed already. The puncuations have been delimited using spaces. All the text have been converted to lowercase. This should save you some time, but the text requires more preprocessing. VocabularyThe complexity of the problem is determined by the comple...
english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()]) french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()]) print('{} English words.'.format(len([word for sentence in english_sentences for word in se...
1823250 English words. 227 unique English words. 10 Most common words in the English dataset: "is" "," "." "in" "it" "during" "the" "but" "and" "sometimes" 1961295 French words. 355 unique French words. 10 Most common words in the French dataset: "est" "." "," "en" "il" "les" "mais" "et" "la" "parfois"
MIT
machine_translation.ipynb
jay-thakur/machine_translation
For comparison, _Alice's Adventures in Wonderland_ contains 2,766 unique words of a total of 15,500 words. PreprocessFor this project, you won't use text data as input to your model. Instead, you'll convert the text into sequences of integers using the following preprocess methods:1. Tokenize the words into ids2. Add p...
def tokenize(x): """ Tokenize x :param x: List of sentences/strings to be tokenized :return: Tuple of (tokenized x data, tokenizer used to tokenize x) """ # TODO: Implement tokenizer = Tokenizer() tokenizer.fit_on_texts(x) return tokenizer.texts_to_sequences(x), tokenizer tests....
{'the': 1, 'quick': 2, 'a': 3, 'brown': 4, 'fox': 5, 'jumps': 6, 'over': 7, 'lazy': 8, 'dog': 9, 'by': 10, 'jove': 11, 'my': 12, 'study': 13, 'of': 14, 'lexicography': 15, 'won': 16, 'prize': 17, 'this': 18, 'is': 19, 'short': 20, 'sentence': 21} Sequence 1 in x Input: The quick brown fox jumps over the lazy dog . ...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Padding (IMPLEMENTATION)When batching the sequence of word ids together, each sequence needs to be the same length. Since sentences are dynamic in length, we can add padding to the end of the sequences to make them the same length.Make sure all the English sequences have the same length and all the French sequences h...
def pad(x, length=None): """ Pad x :param x: List of sequences. :param length: Length to pad the sequence to. If None, use length of longest sequence in x. :return: Padded numpy array of sequences """ # TODO: Implement if length is None: length = max([len(sentence) for sentence ...
Sequence 1 in x Input: [1 2 4 5 6 7 1 8 9] Output: [1 2 4 5 6 7 1 8 9 0] Sequence 2 in x Input: [10 11 12 2 13 14 15 16 3 17] Output: [10 11 12 2 13 14 15 16 3 17] Sequence 3 in x Input: [18 19 3 20 21] Output: [18 19 3 20 21 0 0 0 0 0]
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Preprocess PipelineYour focus for this project is to build neural network architecture, so we won't ask you to create a preprocess pipeline. Instead, we've provided you with the implementation of the `preprocess` function.
def preprocess(x, y): """ Preprocess x and y :param x: Feature List of sentences :param y: Label List of sentences :return: Tuple of (Preprocessed x, Preprocessed y, x tokenizer, y tokenizer) """ preprocess_x, x_tk = tokenize(x) preprocess_y, y_tk = tokenize(y) preprocess_x = pad(pr...
Data Preprocessed Max English sentence length: 15 Max French sentence length: 21 English vocabulary size: 199 French vocabulary size: 344
MIT
machine_translation.ipynb
jay-thakur/machine_translation
ModelsIn this section, you will experiment with various neural network architectures.You will begin by training four relatively simple architectures.- Model 1 is a simple RNN- Model 2 is a RNN with Embedding- Model 3 is a Bidirectional RNN- Model 4 is an optional Encoder-Decoder RNNAfter experimenting with the four si...
def logits_to_text(logits, tokenizer): """ Turn logits from a neural network into text using the tokenizer :param logits: Logits from a neural network :param tokenizer: Keras Tokenizer fit on the labels :return: String that represents the text of the logits """ index_to_words = {id: word for...
`logits_to_text` function loaded.
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Model 1: RNN (IMPLEMENTATION)![RNN](images/rnn.png)A basic RNN model is a good baseline for sequence data. In this model, you'll build a RNN that translates English to French.
def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a basic RNN on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the ...
Train on 110288 samples, validate on 27573 samples Epoch 1/10 110288/110288 [==============================] - 12s 109us/step - loss: 2.5907 - acc: 0.4812 - val_loss: nan - val_acc: 0.5582 Epoch 2/10 110288/110288 [==============================] - 10s 91us/step - loss: 1.6567 - acc: 0.5862 - val_loss: nan - val_acc: 0...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Model 2: Embedding (IMPLEMENTATION)![RNN](images/embedding.png)You've turned the words into ids, but there's a better representation of a word. This is called word embeddings. An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of...
def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a RNN model using word embedding on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique E...
Train on 110288 samples, validate on 27573 samples Epoch 1/10 110288/110288 [==============================] - 12s 104us/step - loss: 3.3620 - acc: 0.4088 - val_loss: nan - val_acc: 0.4603 Epoch 2/10 110288/110288 [==============================] - 11s 102us/step - loss: 2.5504 - acc: 0.4842 - val_loss: nan - val_acc: ...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Model 3: Bidirectional RNNs (IMPLEMENTATION)![RNN](images/bidirectional.png)One restriction of a RNN is that it can't see the future input, only the past. This is where bidirectional recurrent neural networks come in. They are able to see the future data.
def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a bidirectional RNN model on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English wor...
Train on 110288 samples, validate on 27573 samples Epoch 1/10 110288/110288 [==============================] - 12s 106us/step - loss: 3.3402 - acc: 0.4192 - val_loss: nan - val_acc: 0.4769 Epoch 2/10 110288/110288 [==============================] - 11s 101us/step - loss: 2.4795 - acc: 0.4908 - val_loss: nan - val_acc: ...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Model 4: Encoder-Decoder (OPTIONAL)Time to look at encoder-decoder models. This model is made up of an encoder and decoder. The encoder creates a matrix representation of the sentence. The decoder takes this matrix as input and predicts the translation as output.Create an encoder-decoder model in the cell below.
def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train an encoder-decoder model on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English ...
Train on 110288 samples, validate on 27573 samples Epoch 1/10 110288/110288 [==============================] - 12s 106us/step - loss: 3.3761 - acc: 0.4076 - val_loss: nan - val_acc: 0.4515 Epoch 2/10 110288/110288 [==============================] - 11s 100us/step - loss: 2.5353 - acc: 0.4798 - val_loss: nan - val_acc: ...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Model 5: Custom (IMPLEMENTATION)Use everything you learned from the previous models to create a model that incorporates embedding and a bidirectional rnn into one model.
def model_final(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a model that incorporates embedding, encoder-decoder, and bidirectional RNN on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :p...
Final Model Loaded Train on 110288 samples, validate on 27573 samples Epoch 1/10 110288/110288 [==============================] - 91s 824us/step - loss: 2.4410 - acc: 0.4865 - val_loss: nan - val_acc: 0.5841 Epoch 2/10 110288/110288 [==============================] - 89s 807us/step - loss: 1.4055 - acc: 0.6253 - val_lo...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Prediction (IMPLEMENTATION)
def final_predictions(x, y, x_tk, y_tk): """ Gets predictions using the final model :param x: Preprocessed English data :param y: Preprocessed French data :param x_tk: English tokenizer :param y_tk: French tokenizer """ # TODO: Train neural network using model_final model = model_fin...
Train on 110288 samples, validate on 27573 samples Epoch 1/12 110288/110288 [==============================] - 81s 733us/step - loss: 2.3220 - acc: 0.5011 - val_loss: nan - val_acc: 0.5999 Epoch 2/12 110288/110288 [==============================] - 79s 713us/step - loss: 1.3477 - acc: 0.6375 - val_loss: nan - val_acc: ...
MIT
machine_translation.ipynb
jay-thakur/machine_translation
SubmissionWhen you're ready to submit, complete the following steps:1. Review the [rubric](https://review.udacity.com/!/rubrics/1004/view) to ensure your submission meets all requirements to pass2. Generate an HTML version of this notebook - Run the next cell to attempt automatic generation (this is the recommended m...
# Save before you run this cell! !!jupyter nbconvert *.ipynb
_____no_output_____
MIT
machine_translation.ipynb
jay-thakur/machine_translation
Unit 5 - Financial Planning
# Initial imports import os import requests import pandas as pd from dotenv import load_dotenv import alpaca_trade_api as tradeapi from MCForecastTools import MCSimulation # date here from datetime import date %matplotlib inline # Load .env enviroment variables load_dotenv()
_____no_output_____
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Part 1 - Personal Finance Planner Collect Crypto Prices Using the `requests` Library
# Set current amount of crypto assets # YOUR CODE HERE! my_btc = 1.2 my_eth = 5.3 # Crypto API URLs btc_url = "https://api.alternative.me/v2/ticker/Bitcoin/?convert=CAD" eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=CAD" # response_data = requests.get(create_deck_url).json() # response_data btc_re...
The current value of your 1.2 BTC is $60097.20 The current value of your 5.3 ETH is $11897.07
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Collect Investments Data Using Alpaca: `SPY` (stocks) and `AGG` (bonds)
# Current amount of shares # Create two variables named my_agg and my_spy and set them equal to 200 and 50, respectively. # YOUR CODE HERE! my_agg = 200 my_spy = 50 # Set Alpaca API key and secret # YOUR CODE HERE! alpaca_api_key = os.getenv("ALPACA_API_KEY") alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY") # Create...
The current value of your 50 SPY shares is $20865.50 The current value of your 200 AGG shares is $22908.00
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Savings Health Analysis
# Set monthly household income # YOUR CODE HERE! monthly_income = 12000 # Create savings DataFrame # YOUR CODE HERE! df_savings = pd.DataFrame([my_btc_value+ my_eth_value, my_spy_value + my_agg_value], columns = ['amount'], index = ['crypto', 'shares']) # Display savings DataFrame display(df_savings) # Plot savings p...
Congratulations! You have enough money in your emergency fund.
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Part 2 - Retirement Planning Monte Carlo Simulation Hassan's Note for some reason AlPaca would not let me get more than 1000 records. To get 5 years data (252 * 5), I had to break it up into two reads and concat the data.
# Set start and end dates of five years back from today. # Sample results may vary from the solution based on the time frame chosen start_date1 = pd.Timestamp('2015-08-07', tz='America/New_York').isoformat() end_date1 = pd.Timestamp('2017-08-07', tz='America/New_York').isoformat() start_date2 = pd.Timestamp('2017-08-08...
_____no_output_____
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Retirement Analysis
# delete # Fetch summary statistics from the Monte Carlo simulation results # YOUR CODE HERE! # Print summary statistics # YOUR CODE HERE! # Fetch summary statistics from the Monte Carlo simulation results # YOUR CODE HERE! tbl = MC_even_dist.summarize_cumulative_return() # Print summary statistics print (tbl)
count 500.000000 mean 9.683146 std 6.514698 min 1.320640 25% 5.124632 50% 8.047245 75% 12.513634 max 51.017155 95% CI Lower 2.421887 95% CI Upper 25.440141 Name: 7560, dtype: float64
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Calculate the expected portfolio return at the 95% lower and upper confidence intervals based on a `$20,000` initial investment.
# delete # # Set initial investment # initial_investment = 20000 # # Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $20,000 # # YOUR CODE HERE! # # Print results # print(f"There is a 95% chance that an initial investment of ${initial_investment} in the portfo...
There is a 95% chance that an initial investment of $20000 in the portfolio over the next 30 years will end within in the range of $48437.75 and $508802.81
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Calculate the expected portfolio return at the `95%` lower and upper confidence intervals based on a `50%` increase in the initial investment.
# delete # # Set initial investment # initial_investment = 20000 * 1.5 # # Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $30,000 # # YOUR CODE HERE! # # Print results # print(f"There is a 95% chance that an initial investment of ${initial_investment} in the ...
There is a 95% chance that an initial investment of $30000.0 in the portfolio over the next 30 years will end within in the range of $72656.62 and $763204.22
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Optional Challenge - Early Retirement Five Years Retirement Option
# Configuring a Monte Carlo simulation to forecast 5 years cumulative returns # YOUR CODE HERE! MC_even_dist = MCSimulation( portfolio_data = df_stock_data, weights = [.4, .6], num_simulation = 500, num_trading_days = 252*5 ) # Running a Monte Carlo simulation to forecast 5 years cumulative returns # YO...
There is a 95% chance that an initial investment of $60000 in the portfolio over the next 5 years will end within in the range of $51278.36 and $141959.07
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
Ten Years Retirement Option
# Configuring a Monte Carlo simulation to forecast 10 years cumulative returns # YOUR CODE HERE! MC_even_dist = MCSimulation( portfolio_data = df_stock_data, weights = [.4, .6], num_simulation = 500, num_trading_days = 252*10 ) # Running a Monte Carlo simulation to forecast 10 years cumulative returns #...
There is a 95% chance that an initial investment of $60000 in the portfolio over the next 10 years will end within in the range of $55174.9 and $241011.77
Apache-2.0
Scratch Folder/financial-planner-v4.ipynb
HassanAlam55/ColumbiaFintechHW5API
!pip install h5py pyyaml import tensorflow as tf from tensorflow import keras import urllib.request print('Beginning file download with urllib2...') url = 'https://drive.google.com/file/d/1Z0dlwhtS03lYhHv-f3ZT7nf_PgbIXBMB/view?usp=sharing' urllib.request.urlretrieve(url, 'basic_CNN.h5') basic_CNN = keras.models.load...
_____no_output_____
Apache-2.0
mBSUS_XRay_Test_Program.ipynb
rjthompson22/bMSUS_XRay_Model
Abstract Factory Design Pattern >An abstract factory is a generative design pattern that allows you to create families of related objects without getting attached to specific classes of created objects. The pattern is being implemented by creating an abstract class (for example - Factory), which is represented as an i...
class AbstractFactory: def create_chair(self): raise NotImplementedError() def create_sofa(self): raise NotImplementedError() def create_table(self): raise NotImplementedError() class Chair: def __init__(self, name): self._name = name def __...
victorian chair victorian sofa victorian table modern chair modern sofa modern table futuristic chair futuristic sofa futuristic table
MIT
Other/Creational Design Pattern - Abstract Factory.ipynb
deepaksood619/Python-Competitive-Programming
Example - https://py.checkio.org/mission/army-units/solve/
class Army: def train_swordsman(self, name): return NotImplementedError() def train_lancer(self, name): return NotImplementedError() def train_archer(self, name): return NotImplementedError() class Swordsman: def __init__(self, soldier_type, name, army_type): ...
Knight Jaks, European swordsman Knight Jaks, European swordsman Raubritter Harold, European lancer Ranger Robin, European archer Coding complete? Let's try tests!
MIT
Other/Creational Design Pattern - Abstract Factory.ipynb
deepaksood619/Python-Competitive-Programming
Cosine prediction Data preparationIn this notebook, we will use fost to predict a cosine curve. Let's import `pandas` and `numpy` first.
import pandas as pd import numpy as np
_____no_output_____
MIT
examples/1. Cosine prediction.ipynb
meng-zha/FOST
Next, generate cosine data.
train_df = pd.DataFrame() #we don't have actual timestamp in this case, use a default one train_df['Date'] = [pd.datetime(year=2000,month=1,day=1)+pd.Timedelta(days=i) for i in range(2000)] train_df['TARGET'] = [np.cos(i/2) for i in range(2000)] #there is not a 'Node' concept in this dataset, thus all the Node are 0 t...
_____no_output_____
MIT
examples/1. Cosine prediction.ipynb
meng-zha/FOST
FOST only supports file path as input, save the data to `train.csv`
train_df.to_csv('train.csv',index=False)
_____no_output_____
MIT
examples/1. Cosine prediction.ipynb
meng-zha/FOST
Load fost to predict future
import fostool from fostool.pipeline import Pipeline #predict future 10 steps lookahead = 10 fost = Pipeline(lookahead=lookahead, train_path='train.csv') #fit in one line fost.fit() #get predict result res = fost.predict() #plot prediction fost.plot(res, lookback_size=lookahead)
_____no_output_____
MIT
examples/1. Cosine prediction.ipynb
meng-zha/FOST
Pytorch Basic
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt from IPython.display import clear_output torch.cuda.is_available()
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Hyper Parameter
input_size = 784 hidden_size = 500 num_class = 10 epochs = 5 batch_size = 100 lr = 0.001
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Load MNIST Dataset
train_dataset = torchvision.datasets.MNIST(root='../data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST(root='../data', ...
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Simple Model
class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size, num_class): super(NeuralNet, self).__init__() self.fc1 = nn.Linear(input_size,hidden_size) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size, num_class) def forward(self, x): out = self....
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Loss and Optimizer
criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr)
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Train
total_step = len(train_loader) for epoch in range(epochs): for i, (images, labels) in enumerate(train_loader): images = images.reshape(-1,28*28).to(device) labels = labels.to(device) outputs = model(images) loss = criterion(outputs, labels) optimizer.zero_g...
EPOCH [5/5] STEP [600/600] Loss 0.0343)
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Test
with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: images = images.reshape(-1, 28*28).to(device) labels = labels.to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predic...
Accuracy of the network on the 10000 test images: 97.85 %
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
save
torch.save(model.state_dict(), 'model.ckpt')
_____no_output_____
MIT
my_notebook/1_basic_forward.ipynb
jjeamin/pytorch-tutorial
Importar librerías y series de datos
import time start = time.time() #importar datos y librerias import numpy as np import pandas as pd from datetime import datetime import matplotlib.pyplot as plt from scipy import signal from sklearn.linear_model import LinearRegression from statsmodels.tsa.seasonal import seasonal_decompose from scipy.stats import box...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier
Establecer las funciones a utilizar
def kronecker(data1:'Dataframe 1',data2:'Dataframe 2'): x=0 data1_kron=data1[x:x+1] data2_kron=data2[x:x+1] Combinacion=np.kron(data1_kron,data2_kron) Combinacion=pd.DataFrame(Combinacion) for x in range(1,len(data1)): data1_kron=data1[x:x+1] data2_kron=data2[x:x+1] kron=...
_____no_output_____
MIT
Efecto Arima en final.ipynb
ramirezdiana/Forecast-with-fourier