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
Step 6 (again) - Deploy the model for the web appNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.As we saw above, by default the estimator which we created, w...
!pygmentize serve/predict.py
import argparse import json import os import pickle import sys import sagemaker_containers ...
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.**TODO**: Complete th...
from sagemaker.predictor import RealTimePredictor from sagemaker.pytorch import PyTorchModel class StringPredictor(RealTimePredictor): def __init__(self, endpoint_name, sagemaker_session): super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain') model = PyTorchMod...
Parameter image will be renamed to image_uri in SageMaker Python SDK v2. 'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
Testing the modelNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is t...
import glob def test_reviews(data_dir='../data/aclImdb', stop=250): results = [] ground = [] # We make sure to test both positive and negative reviews for sentiment in ['pos', 'neg']: path = os.path.join(data_dir, 'test', sentiment, '*.txt') files = glob.glob(path...
_____no_output_____
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
As an additional test, we can try sending the `test_review` that we looked at earlier.
predictor.predict(test_review)
_____no_output_____
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back. Step 7 (again): Use the model for th...
predictor.endpoint
_____no_output_____
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function. Setting up API GatewayNow that our Lambda function is set up, it is time to create a new API using API Gateway that wi...
predictor.delete_endpoint()
_____no_output_____
MIT
Project/SageMaker Project.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project1
Statistics Questions ```{admonition} Problem: JOIN Dataframes:class: dropdown, tipCan you tell me the ways in which 2 pandas data frames can be joined?``` ```{admonition} Solution::class: dropdownA very high level difference is that merge() is used to combine two (or more) dataframes on the basis of values of common ...
import numpy as np import matplotlib.pyplot as plt from scipy import stats def normal_sample_generator(N): # can be done using np.random.randn or stats.norm.rvs #x = np.random.randn(N) x = stats.norm.rvs(size=N) num_bins = 20 plt.hist(x, bins=num_bins, facecolor='blue', alpha=0.5) y = np.linsp...
_____no_output_____
MIT
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
```{admonition} Problem: [UBER] Bernoulli trial generator:class: dropdown, tipGiven a random Bernoulli trial generator, write a function to return a value sampled from a normal distribution.``` ```{admonition} Solution::class: dropdownSolution pending, [Reference material link](Given a random Bernoulli trial generator,...
# Interquartile distance is the difference between first and third quartile # first let's generate a list of random numbers import random import numpy as np li = [round(random.uniform(33.33, 66.66), 2) for i in range(50)] print(li) qtl_1 = np.quantile(li,.25) qtl_3 = np.quantile(li,.75) print("Interquartile distan...
[54.81, 65.68, 63.85, 58.29, 60.14, 53.23, 52.58, 51.62, 61.6, 57.85, 51.37, 38.7, 35.87, 33.95, 61.65, 33.59, 61.33, 44.97, 62.49, 39.67, 51.03, 45.79, 60.99, 60.49, 64.8, 46.16, 46.61, 34.06, 37.78, 56.72, 39.62, 61.38, 55.27, 40.53, 49.31, 58.95, 37.49, 34.39, 60.47, 56.12, 61.41, 34.56, 58.18, 56.35, 63.59, 50.59, ...
MIT
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
````{admonition} Problem: [GENENTECH] Imputing the mdeian:class: dropdown, tipWrite a function cheese_median to impute the median price of the selected California cheeses in place of the missing values. You may assume at least one cheese is not missing its price.Input:```pythonimport pandas as pdcheeses = {"Name": ["Bo...
import pandas as pd cheeses = {"Name": ["Bohemian Goat", "Central Coast Bleu", "Cowgirl Mozzarella", "Cypress Grove Cheddar", "Oakdale Colby"], "Price" : [15.00, None, 30.00, None, 45.00]} df_cheeses = pd.DataFrame(cheeses) df_cheeses['Price'] = df_cheeses['Price'].fillna(df_cheeses['Price'].median()) df_cheeses.hea...
_____no_output_____
MIT
_sources/contents/Python/Statistics.ipynb
mulaab/datasains
Real Estate Price Prediction
import pandas as pd df = pd.read_csv("data.csv") df.head() df['CHAS'].value_counts() df.info() df.describe() %matplotlib inline import matplotlib.pyplot as plt df.hist(bins=50, figsize=(20,15))
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
train_test_split
import numpy as np def split_train_test(data, test_ratio): np.random.seed(42) shuffled = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled[:test_set_size] train_indices = shuffled[test_set_size:] return data.iloc[train_indices], data.iloc[test_i...
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
train_test_split from sklearn
from sklearn.model_selection import train_test_split train_set, test_set = train_test_split(df, test_size = 0.2, random_state = 42) print(f"The length of train dataset is: {len(train_set)}") print(f"The length of train dataset is: {len(test_set)}") from sklearn.model_selection import StratifiedShuffleSplit split = Stra...
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Stratified learning equal splitting of zero and ones
95/7 376/28 df = strat_train_set.copy()
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Corelations
from pandas.plotting import scatter_matrix attributes = ["MEDV", "RM", "ZN" , "LSTAT"] scatter_matrix(df[attributes], figsize = (12,8)) df.plot(kind="scatter", x="RM", y="MEDV", alpha=1)
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Trying out attribute combinations
df["TAXRM"] = df["TAX"]/df["RM"] df.head() corr_matrix = df.corr() corr_matrix['MEDV'].sort_values(ascending=False) # 1 means strong positive corr and -1 means strong negative corr. # EX: if RM will increase our final result(MEDV) in prediction will also increase. df.plot(kind="scatter", x="TAXRM", y="MEDV", alpha=1) d...
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Pipeline
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer my_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy="median")), ('std_scaler', StandardScaler()), ]) df_numpy = my_pipeline.fit_transform(df) df_numpy #Numpy array of df as m...
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Model Selection
from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor # model = LinearRegression() # model = DecisionTreeRegressor() model = RandomForestRegressor() model.fit(df_numpy, df_labels) some_data = df.iloc[:5] some_labels = df_label...
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Evaluating the model
from sklearn.metrics import mean_squared_error df_predictions = model.predict(df_numpy) mse = mean_squared_error(df_labels, df_predictions) rmse = np.sqrt(mse) rmse # from sklearn.metrics import accuracy_score # accuracy_score(some_data, some_labels, normalize=False)
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Cross Validation
from sklearn.model_selection import cross_val_score scores = cross_val_score(model, df_numpy, df_labels, scoring="neg_mean_squared_error", cv=10) rmse_scores = np.sqrt(-scores) rmse_scores def print_scores(scores): print("Scores:", scores) print("\nMean:", scores.mean()) print("\nStandard deviation:", score...
Scores: [2.79289168 2.69441597 4.40018895 2.56972379 3.33073436 2.62687167 4.77007351 3.27403209 3.38378214 3.16691711] Mean: 3.3009631251857217 Standard deviation: 0.7076841067486248
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Saving Model
from joblib import dump, load dump(model, 'final_model.joblib') dump(model, 'final_model.sav')
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
Testing model on test data
X_test = strat_test_set.drop("MEDV", axis=1) Y_test = strat_test_set["MEDV"].copy() X_test_prepared = my_pipeline.transform(X_test) final_predictions = model.predict(X_test_prepared) final_mse = mean_squared_error(Y_test, final_predictions) final_rmse = np.sqrt(final_mse) final_rmse
_____no_output_____
MIT
.ipynb_checkpoints/real_estate-checkpoint.ipynb
shhubhxm/HousePricePrediction-ML_model
In-Place Waveform Library UpdatesThis example notebook shows how one can update pulses data in-place without recompiling.© Raytheon BBN Technologies 2020 Set the `SAVE_WF_OFFSETS` flag in order that QGL will output a map of the waveform data within the compiled binary waveform library.
from QGL import * import QGL import os.path import pickle QGL.drivers.APS2Pattern.SAVE_WF_OFFSETS = True
_____no_output_____
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Create the usual channel library with a couple of AWGs.
cl = ChannelLibrary(":memory:") q1 = cl.new_qubit("q1") aps2_1 = cl.new_APS2("BBNAPS1", address="192.168.5.101") aps2_2 = cl.new_APS2("BBNAPS2", address="192.168.5.102") dig_1 = cl.new_X6("X6_1", address=0) h1 = cl.new_source("Holz1", "HolzworthHS9000", "HS9004A-009-1", power=-30) h2 = cl.new_source("Holz2", "Holzwor...
Creating engine...
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Compile a simple sequence.
mf = RabiAmp(cl["q1"], np.linspace(-1, 1, 11)) plot_pulse_files(mf, time=True)
Compiled 11 sequences. <module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'> <module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Open the offsets file (in the same directory as the `.aps2` files, one per AWG slice.)
offset_f = os.path.join(os.path.dirname(mf), "Rabi-BBNAPS1.offsets") with open(offset_f, "rb") as FID: offsets = pickle.load(FID) offsets
_____no_output_____
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Let's replace every single pulse with a fixed amplitude `Utheta`
pulses = {l: Utheta(q1, amp=0.1, phase=0) for l in offsets} wfm_f = os.path.join(os.path.dirname(mf), "Rabi-BBNAPS1.aps2") QGL.drivers.APS2Pattern.update_wf_library(wfm_f, pulses, offsets)
_____no_output_____
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
We see that the data in the file has been updated.
plot_pulse_files(mf, time=True)
<module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'> <module 'QGL.drivers.APS2Pattern' from '/Users/growland/workspace/QGL/QGL/drivers/APS2Pattern.py'>
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Profiling How long does this take?
%timeit mf = RabiAmp(cl["q1"], np.linspace(-1, 1, 100))
Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. Compiled 100 sequences. 317 ms ± 6.15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Getting the offsets is fast, and only needs to be done once
def get_offsets(): offset_f = os.path.join(os.path.dirname(mf), "Rabi-BBNAPS1.offsets") with open(offset_f, "rb") as FID: offsets = pickle.load(FID) return offsets %timeit offsets = get_offsets() %timeit pulses = {l: Utheta(q1, amp=0.1, phase=0) for l in offsets} wfm_f = os.path.join(os.path.dirnam...
1.25 ms ± 19.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Apache-2.0
doc/ex4_update_in_place.ipynb
gribeill/QGL
Tutorial 09: InflowsThis tutorial walks you through the process of introducing inflows of vehicles into a network. Inflows allow us to simulate open networks where vehicles may enter (and potentially exit) the network. This exercise is organized as follows: in section 1 we prepare our inflows variables to support infl...
from flow.scenarios.merge import MergeScenario
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
A schematic of the above network is availabe in the figure below. As we can see, the edges at the start of the main highway and the on-merge are named "inflow_highway" and "inflow_merge" respectively. These names will be important to us when we begin specifying our inflows into the network.We will also define the types...
from flow.core.vehicles import Vehicles from flow.controllers import IDMController # create an empty vehicles object vehicles = Vehicles() # add some vehicles to this object of type "human" vehicles.add("human", acceleration_controller=(IDMController, {}), speed_mode="no_collide", # we use...
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
Next, we are ready to import and create an empty inflows object.
from flow.core.params import InFlows inflow = InFlows()
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
The `InFlows` object is provided as an input during the scenario creation process via the `NetParams` parameter. Introducing these inflows into the network is handled by the backend scenario generation processes during instantiation of the scenario object.In order to add new inflows of vehicles of pre-defined types ont...
inflow.add(veh_type="human", edge="inflow_highway", vehs_per_hour=2000, departSpeed=10, departLane="random")
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
Next, we specify a second inflow of vehicles through the on-merge lane at a rate of only 100 veh/hr.
inflow.add(veh_type="human", edge="inflow_merge", vehs_per_hour=100, departSpeed=10, departLane="random")
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
2. Running Simulations with InflowsWe are now ready to test our inflows in simulation. As mentioned in section 1, the inflows are specified in the `NetParams` object, in addition to all other network-specific parameters. For the merge network, this is done as follows:
from flow.scenarios.merge import ADDITIONAL_NET_PARAMS from flow.core.params import NetParams additional_net_params = ADDITIONAL_NET_PARAMS.copy() # we choose to make the main highway slightly longer additional_net_params["pre_merge_length"] = 500 net_params = NetParams(inflows=inflow, # our inflows ...
_____no_output_____
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
Finally, we execute the simulation following simulation creation techniques we learned from exercise 1 using the below code block. Running this simulation, we see an excessive number of vehicles entering from the main highway, but only a sparse number of vehicles entering from the on-merge. Nevertheless, this volume of...
from flow.core.params import SumoParams, EnvParams, InitialConfig from flow.envs.loop.loop_accel import AccelEnv, ADDITIONAL_ENV_PARAMS from flow.core.experiment import SumoExperiment sumo_params = SumoParams(render=True, sim_step=0.2) env_params = EnvParams(additional_params=ADDITIONAL_ENV_P...
********************************************************** ********************************************************** ********************************************************** WARNING: Inflows will cause computational performance to significantly decrease after large number of rollouts. In order to avoid this, set Su...
MIT
tutorials/tutorial09_inflows.ipynb
nskh/flow
IPython magicsThis notebook is used for testing nbqa with ipython magics.
from random import randint from IPython import get_ipython
_____no_output_____
MIT
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
Cell magics
%%bash for n in {1..10} do echo -n "$n " done %%time import operator def compute(operand1,operand2, bin_op): """Perform input binary operation over the given operands.""" return bin_op(operand1, operand2) compute(5,1, operator.add)
CPU times: user 31 µs, sys: 4 µs, total: 35 µs Wall time: 37.9 µs
MIT
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
Help Magics
str.split?? # would this comment also be considered as magic? str.split? ?str.splitlines
Signature: str.splitlines(self, /, keepends=False) Docstring: Return a list of the lines in the string, breaking at line boundaries. Line breaks are no...
MIT
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
Shell magics
!grep -r '%%HTML' . | wc -l flake8_version = !pip list 2>&1 | grep flake8 if flake8_version: print(flake8_version)
['flake8 3.8.4']
MIT
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
Line magics
%time randint(5,10) if __debug__: %time compute(5,1, operator.mul) %time get_ipython().run_line_magic("lsmagic", "") import pprint import sys %time pretty_print_object = pprint.PrettyPrinter(\ indent=4, width=80, stream=sys.stdout, compact=True, depth=5\ )
CPU times: user 29 µs, sys: 0 ns, total: 29 µs Wall time: 33.4 µs
MIT
tests/data/notebook_with_indented_magics.ipynb
girip11/nbQA
$BA_i \sim Beta(81,219)$$y_i \sim Bin(AB_i,BA_i)$$i=1,2,...,8$
#https://mc-stan.org/users/documentation/case-studies/rstan_workflow.html #https://people.duke.edu/~ccc14/sta-663/PyStan.html #http://varianceexplained.org/statistics/beta_distribution_and_baseball/ model_code = ''' data { int<lower=0> N; int<lower=0> at_bats[N]; int<lower=0> hits[N]; real<lower=0> A; real<l...
_____no_output_____
MIT
beta_binomial_baseball.ipynb
thomasmartins/pystan_misc
Introduction to Pandas
import pandas pandas.__version__ import pandas as pd
_____no_output_____
MIT
code_listings/03.00-Introduction-to-Pandas.ipynb
cesar-rocha/PythonDataScienceHandbook
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ourownstory/neural_prophet/blob/master/example_notebooks/sub_daily_data_yosemite_temps.ipynb) Sub-daily dataNeuralProphet can make forecasts for time series with sub-daily observations by passing in a ...
if 'google.colab' in str(get_ipython()): !pip install git+https://github.com/ourownstory/neural_prophet.git # may take a while #!pip install neuralprophet # much faster, but may not have the latest upgrades/bugfixes data_location = "https://raw.githubusercontent.com/ourownstory/neural_prophet/master/" else:...
_____no_output_____
MIT
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
Now we will attempt to forecast the next 7 days. The `5min` data resulution means that we have `60/5*24=288` daily values. Thus, we want to forecast `7*288` periods ahead.Using some common sense, we set:* First, we disable weekly seasonality, as nature does not follow the human week's calendar.* Second, we disable chan...
m = NeuralProphet( n_changepoints=0, weekly_seasonality=False, ) metrics = m.fit(df, freq='5min') future = m.make_future_dataframe(df, periods=7*288, n_historic_predictions=len(df)) forecast = m.predict(future) fig = m.plot(forecast) # fig_comp = m.plot_components(forecast) fig_param = m.plot_parameters()
INFO - (NP.forecaster._handle_missing_data) - 12 NaN values in column y were auto-imputed. INFO - (NP.utils.set_auto_seasonalities) - Disabling yearly seasonality. Run NeuralProphet with yearly_seasonality=True to override this. INFO - (NP.config.set_auto_batch_epoch) - Auto-set batch_size to 128 INFO - (NP.config.set_...
MIT
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
The daily seasonality seems to make sense, when we account for the time being recorded in GMT, while Yosemite local time is GMT-8. Improving trend and seasonality As we have `288` daily values recorded, we can increase the flexibility of `daily_seasonality`, without danger of overfitting. Further, we may want to re-vis...
m = NeuralProphet( changepoints_range=0.95, n_changepoints=50, trend_reg=1.5, weekly_seasonality=False, daily_seasonality=10, ) metrics = m.fit(df, freq='5min') future = m.make_future_dataframe(df, periods=60//5*24*7, n_historic_predictions=len(df)) forecast = m.predict(future) fig = m.plot(forecast...
INFO - (NP.config.__post_init__) - Note: Trend changepoint regularization is experimental. INFO - (NP.forecaster._handle_missing_data) - 12 NaN values in column y were auto-imputed. INFO - (NP.utils.set_auto_seasonalities) - Disabling yearly seasonality. Run NeuralProphet with yearly_seasonality=True to override this. ...
MIT
example_notebooks/sub_daily_data_yosemite_temps.ipynb
aws-kh/neural_prophet
Deep Deterministic Policy Gradients (DDPG)---In this notebook, we train DDPG with OpenAI Gym's Pendulum-v0 environment. 1. Import the Necessary Packages
import gym import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline from ddpg_agent import Agent
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
2. Instantiate the Environment and Agent
env = gym.make('Pendulum-v0') env.seed(2) agent = Agent(state_size=3, action_size=1, random_seed=2)
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
ObservationType: Box(3)|Num |Observation |Min| Max|| --- | --- | --- |--- |0 | cos(theta) | -1.0 |1.0|1 | sin(theta) |-1.0 |1.0|2 | theta dot |-8.0 |8.0|ActionsType: Box(1)| Num | Action | Min | Max| | --- | --- | --- |--- || 0 | Joint effort | -2.0 | 2.0| 3. Train the Agent with DDPG
def ddpg(n_episodes=100, max_t=300, print_every=100): scores_deque = deque(maxlen=print_every) scores = [] for i_episode in range(1, n_episodes+1): state = env.reset() agent.reset() score = 0 for t in range(max_t): action = agent.act(state) next_state,...
Episode 100 Average Score: -595.74
MIT
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
4. Watch a Smart Agent!
agent.actor_local.load_state_dict(torch.load('checkpoint_actor.pth')) agent.critic_local.load_state_dict(torch.load('checkpoint_critic.pth')) state = env.reset() for t in range(500): action = agent.act(state, add_noise=False) env.render() state, reward, done, _ = env.step(action) if done: break...
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
6. ExploreIn this exercise, we have provided a sample DDPG agent and demonstrated how to use it to solve an OpenAI Gym environment. To continue your learning, you are encouraged to complete any (or all!) of the following tasks:- Amend the various hyperparameters and network architecture to see if you can get your age...
int(1e5)
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
elexira/deep-reinforcement-learning
Classes and Objects in PythonEstimated time needed: **40** minutes ObjectivesAfter completing this lab you will be able to:- Work with classes and objects- Identify and define attributes and methods Table of Contents Introduction to Classes and Objects Creating...
# Import the library import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
The first step in creating your own class is to use the class keyword, then the name of the class as shown in Figure 4. In this course the class parent will always be object: Figure 4: Creating a class Circle. The next step is a special method called a constructor __init__, which is used to initialize the object. Th...
# Create a class Circle class Circle(object): # Constructor def __init__(self, radius=3, color='blue'): self.radius = radius self.color = color # Method def add_radius(self, r): self.radius = self.radius + r return(self.radius) # Method def drawCi...
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Creating an instance of a class Circle Let’s create the object RedCircle of type Circle to do the following:
# Create an object RedCircle RedCircle = Circle(10, 'red')
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can use the dir command to get a list of the object's methods. Many of them are default Python methods.
# Find out the methods can be used on the object RedCircle dir(RedCircle)
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can look at the data attributes of the object:
# Print the object attribute radius RedCircle.radius # Print the object attribute color RedCircle.color
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can change the object's data attributes:
# Set the object attribute radius RedCircle.radius = 1 RedCircle.radius
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can draw the object by using the method drawCircle():
# Call the method drawCircle RedCircle.drawCircle()
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can increase the radius of the circle by applying the method add_radius(). Let increases the radius by 2 and then by 5:
# Use method to change the object attribute radius print('Radius of object:',RedCircle.radius) RedCircle.add_radius(2) print('Radius of object of after applying the method add_radius(2):',RedCircle.radius) RedCircle.add_radius(5) print('Radius of object of after applying the method add_radius(5):',RedCircle.radius) Re...
Radius of object: 1 Radius of object of after applying the method add_radius(2): 3 Radius of object of after applying the method add_radius(5): 8 Radius of object of after applying the method add radius(6): 14
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Let’s create a blue circle. As the default colour is blue, all we have to do is specify what the radius is:
# Create a blue circle with a given radius BlueCircle = Circle(radius=100)
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
As before we can access the attributes of the instance of the class by using the dot notation:
# Print the object attribute radius BlueCircle.radius # Print the object attribute color BlueCircle.color
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can draw the object by using the method drawCircle():
# Call the method drawCircle BlueCircle.drawCircle()
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Compare the x and y axis of the figure to the figure for RedCircle; they are different. The Rectangle Class Let's create a class rectangle with the attributes of height, width and color. We will only add the method to draw the rectangle object:
# Create a new Rectangle class for creating a rectangle object class Rectangle(object): # Constructor def __init__(self, width=2, height=3, color='r'): self.height = height self.width = width self.color = color # Method def drawRectangle(self): plt.gca().add_p...
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Let’s create the object SkinnyBlueRectangle of type Rectangle. Its width will be 2 and height will be 3, and the color will be blue:
# Create a new object rectangle SkinnyBlueRectangle = Rectangle(2, 10, 'blue')
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
As before we can access the attributes of the instance of the class by using the dot notation:
# Print the object attribute height SkinnyBlueRectangle.height # Print the object attribute width SkinnyBlueRectangle.width # Print the object attribute color SkinnyBlueRectangle.color
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can draw the object:
# Use the drawRectangle method to draw the shape SkinnyBlueRectangle.drawRectangle()
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Let’s create the object FatYellowRectangle of type Rectangle :
# Create a new object rectangle FatYellowRectangle = Rectangle(20, 5, 'yellow')
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can access the attributes of the instance of the class by using the dot notation:
# Print the object attribute height FatYellowRectangle.height # Print the object attribute width FatYellowRectangle.width # Print the object attribute color FatYellowRectangle.color
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
We can draw the object:
# Use the drawRectangle method to draw the shape FatYellowRectangle.drawRectangle()
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Exercises Text Analysis You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class'analysedText' with the following methods - Constructor - Takes argument 'text',makes it lower case and removes all punctuation....
class analysedText(object): def __init__ (self, text): reArrText = text.lower() reArrText = reArrText.replace('.','').replace('!','').replace(',','').replace('?','') self.fmtText = reArrText def freqAll(self): ...
_____no_output_____
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Execute the block below to check your progress.
import sys sampleMap = {'eirmod': 1,'sed': 1, 'amet': 2, 'diam': 5, 'consetetur': 1, 'labore': 1, 'tempor': 1, 'dolor': 1, 'magna': 2, 'et': 3, 'nonumy': 1, 'ipsum': 1, 'lorem': 2} def testMsg(passed): if passed: return 'Test Passed' else : return 'Test Failed' print("Constructor: ") try: s...
Constructor: Test Passed freqAll: Test Passed freqOf: Test Passed
FSFAP
4_Python for Data Science, AI & Development/PY0101EN-3-5-Classes.ipynb
lebinh97/IBM-DataScience-Capstone
Analyzing the Effects of Non-Academic Features on Student Performance
# For reading data sets import pandas # For lots of awesome things import numpy as np # Need this for LabelEncoder from sklearn import preprocessing # For building our net import keras # For plotting import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Read in data Data is seperated by a semicolon (delimiter=";") containing column names as the first row of the file (header = 0).
# Read in student data student_data = np.array(pandas.read_table("./student-por.csv", delimiter=";", header=0)) # Display student data student_data
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Determine what the column labels are...
# Descriptions for each feature (found in the header) feature_descrips = np.array(pandas.read_csv("./student-por.csv", delimiter=";", header=None, nrows=1)) # Display descriptions print(feature_descrips)
[['school' 'sex' 'age' 'address' 'famsize' 'Pstatus' 'Medu' 'Fedu' 'Mjob' 'Fjob' 'reason' 'guardian' 'traveltime' 'studytime' 'failures' 'schoolsup' 'famsup' 'paid' 'activities' 'nursery' 'higher' 'internet' 'romantic' 'famrel' 'freetime' 'goout' 'Dalc' 'Walc' 'health' 'absences' 'G1' 'G2' 'G3']]
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
...and give them clearer descriptions.
# More detailed descriptions feature_descrips = np.array(["School", "Sex", "Age", "Urban or Rural Address", "Family Size", "Parent's Cohabitation status", "Mother's Education", "Father's Education", "Mother's Job", "Father's Job", "Reason for Choosing School", ...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Data Cleanup Shuffle data We sampled 2 schools, and right now our data has each school grouped together. We need to get rid of this grouping for training later down the road.
# Shuffle the data! np.random.shuffle(student_data) student_data
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Alphabetically classify scores Because our data is sampled from Portugal, we have to modify their scoring system a bit to represent something more like ours. 0 = F 1 = D 2 = C 3 = B 4 = A
# Array holding final scores for every student scores = student_data[:,32] # Iterate through list of scores, changing them from a 0-19 value ## to a 0-4 value (representing F-A) for i in range(len(scores)): if(scores[i] > 18): scores[i] = 4 elif(scores[i] > 16): scores[i] = 3 elif(scores[i]...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Encoding non-numeric data to integers
# One student sample student_data[0,:]
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
We have some qualitative data from the questionaire that needs to be converted to represent numbers.
# Label Encoder le = preprocessing.LabelEncoder() # Columns that hold non-numeric data indices = np.array([0,1,3,4,5,8,9,10,11,15,16,17,18,19,20,21,22]) # Transform the non-numeric data in these columns to integers for i in range(len(indices)): column = indices[i] le.fit(student_data[:,column]) student_da...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Encoding 0's to -1 for binomial data. We want our weights to change because 0 represents something! Therefore, we need to encode 0's to -1's so the weights will change with that input.
# Columns that hold binomial data indices = np.array([0,1,3,4,5,15,16,17,18,19,20,21,22]) # Change 0's to -1's for i in range(len(indices)): column = indices[i] # values of current feature feature = student_data[:,column] # change values to -1 if equal to 0 feature = np.where(feature==0, ...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Standardizing the nominal and numerical data. We need our input to matter equally (Everyone is important!). We do this by standardizing our data (get a mean of 0 and a stardard deviation of 1).
scaler = preprocessing.StandardScaler() temp = student_data[:,[2,6,7,8,9,10,11,12,13,14,23,24,25,26,27,28,29,30,31]] print(student_data[0,:]) Standardized = scaler.fit_transform(temp) print('Mean:', round(Standardized.mean())) print('Standard deviation:', Standardized.std()) student_data[:,[2,6,7,8,9,10,11,12,13,14,23,...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Convert results to one-hot encoding
# Final grades results = student_data[:,32] # Take a look at first 5 final grades print("First 5 final grades:", results[0:5]) # All unique values for final grades (0-4 representing F-A) possible_results = np.unique(student_data[:,32]).T print("All possible results:", possible_results) # One-hot encode final grades (...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Model Building Now let's create a function that will build a model for us. This will come in handy later on. Our model will have two hidden layers. The first hidden layer will have an input size of 800, and the second will have an input size of 400. The optimizer that we are using is adamax which is good at ignoring ...
# Function to create network given model def create_network(model): # Specify input/output size input_size = x.shape[1] output_size = y.shape[1] # Create the hidden layer model.add(keras.layers.Dense(800, input_dim = input_size, activation = 'relu')) # Additional hidden layer model.add(ker...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Initial Test of the Network
# Split data into training and testing data x_train = x[0:518,:] x_test = x[519:649,:] y_train = y[0:518,:] y_test = y[519:649,:] # Train on training data! # We're saving this information in the variable -history- so we can take a look at it later history = model.fit(x_train, y_train, batch_size =...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Training and Testing Without Individual Features
# Analyze the effects of removing one feature on training def remove_and_analyze(feature): # Told you those feature descriptions would be useful print("Without feature", feature, ":", feature_descrips[feature]) # Create feed-forward network model = keras.Sequential() create_network(model) ...
Without feature 0 : School Test loss: 0.1621086014179477 Test accuracy: 0.9461538461538461
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Training and Testing Without Five Features
# Delete the five features that most negatively impact accuracy x = np.delete(student_data, 21, axis = 1) x = np.delete(x, 20, axis = 1) x = np.delete(x, 9, axis = 1) x = np.delete(x, 8, axis = 1) x = np.delete(x, 7, axis = 1) # Create feed-forward network model = keras.Sequential() create_network(model) # Split data...
Test loss: 0.1731401116976765 Test accuracy: 0.9307692307692308
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Grade Distribution Analysis
# Function for analyzing the percent of students with each grade [F,D,C,B,A] def analyze(array): # To hold the total number of students with a certain final grade # Index 0 - F. Index 4 - A sums = np.array([0,0,0,0,0]) # Iterate through array. Update sums according to whether a student got a f...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Family Educational Support
# Array holding final grades of all students who have family educational support fam_sup = [] # Array holding final grades of all students who have family educational support no_fam_sup = [] # Iterate through all student samples for i in range(student_data.shape[0]): # Does the student have family educational...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Family Educational Support
analyze(fam_sup)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
No Family Educational Support
analyze(no_fam_sup)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Reason for choosing school
# Each array holds the grades of students who chose to go to their school for that reason # Close to home reason1 = [] # School reputation reason2 = [] # Course prefrence reason3 = [] # Other reason4 = [] # Values that represent these unique reasons. They are not integer numbers like in the previous ## example. They'r...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Reason 1: Close to Home
analyze(reason1)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Reason 2: School Reputation
analyze(reason2)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Reason 3: Course Prefrence
analyze(reason3)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Reason 4: Other
analyze(reason4)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Frequency of Going Out With Friends
# Each array holds the grades of students who go out with friends for that specified amount of time # (1 - very low, 5 - very high) go_out1 = [] go_out2 = [] go_out3 = [] go_out4 = [] go_out5 = [] # Floating point values representing frequency unique = np.unique(student_data[:,25]) # Iterate through all student samp...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Free Time after School
# Each array holds the grades of students who have the specified amount of free time after school # (1 - very low, 5 - very high) free1 = [] free2 = [] free3 = [] free4 = [] free5 = [] # Floating point values representing frequency unique = np.unique(student_data[:,24]) # Iterate through all student samples and appe...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Paid Classes
# Array holding final grades of all students who have extra paid classes paid_class = [] # Array holding final grades of all students who do not have extra paid classes no_paid_class = [] # Iterate through all student samples and append final grades to corresponding arrays for i in range(student_data.shape[0]): ...
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
Extra Paid Classes
analyze(paid_class)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project
No Extra Paid Classes
analyze(no_paid_class)
_____no_output_____
MIT
LSTM1.ipynb
CSCI4850/S19-team3-project