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
3) Select the day of the monthCreate a Pandas Series `day_of_month_earthquakes` containing the day of the month from the "date_parsed" column.
# try to get the day of the month from the date column day_of_month_earthquakes = earthquakes['date_parsed'].dt.day # Check your answer q3.check() # Lines below will give you a hint or solution code #q3.hint() #q3.solution()
_____no_output_____
MIT
data_cleaning/03-parsing-dates.ipynb
drakearch/kaggle-courses
4) Plot the day of the month to check the date parsingPlot the days of the month from your earthquake dataset.
# TODO: Your code here! sns.displot(day_of_month_earthquakes, kde=False, bins=31);
_____no_output_____
MIT
data_cleaning/03-parsing-dates.ipynb
drakearch/kaggle-courses
Does the graph make sense to you?
# Check your answer (Run this code cell to receive credit!) q4.check() # Line below will give you a hint #q4.hint()
_____no_output_____
MIT
data_cleaning/03-parsing-dates.ipynb
drakearch/kaggle-courses
(Optional) Bonus ChallengeFor an extra challenge, you'll work with a [Smithsonian dataset](https://www.kaggle.com/smithsonian/volcanic-eruptions) that documents Earth's volcanoes and their eruptive history over the past 10,000 years Run the next code cell to load the data.
volcanos = pd.read_csv("../input/volcanic-eruptions/database.csv")
_____no_output_____
MIT
data_cleaning/03-parsing-dates.ipynb
drakearch/kaggle-courses
Try parsing the column "Last Known Eruption" from the `volcanos` dataframe. This column contains a mixture of text ("Unknown") and years both before the common era (BCE, also known as BC) and in the common era (CE, also known as AD).
volcanos['Last Known Eruption'].sample(5)
_____no_output_____
MIT
data_cleaning/03-parsing-dates.ipynb
drakearch/kaggle-courses
Running on AnyscaleLet's connect to an existing 1GPU/16CPUs cluster via `ray.init(address=...)`.
ray.init( # Connecting to an existing (and running) cluster ("cluster-12" in my account). address="anyscale://cluster-12", # This will upload this directory to Anyscale so that the code can be run on cluster. project_dir=".", #cloud="anyscale_default_cloud", # Our Python dependencies,...
(anyscale +0.1s) Loaded Anyscale authentication token from ~/.anyscale/credentials.json (anyscale +0.1s) Loaded Anyscale authentication token from ~/.anyscale/credentials.json (anyscale +0.9s) .anyscale.yaml found in project_dir. Directory is attached to a project. (anysc...
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Coding/defining our "problem" via an RL environment.We will use the following (adversarial) multi-agent environment throughout this demo.
# Let's code our multi-agent environment. class MultiAgentArena(MultiAgentEnv): def __init__(self, config=None): config = config or {} # Dimensions of the grid. self.width = config.get("width", 10) self.height = config.get("height", 10) # End an episode after this many time...
_____no_output_____
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Configuring our Trainer
TRAINER_CFG = { # Using our environment class defined above. "env": MultiAgentArena, # Use `framework=torch` here for PyTorch. "framework": "tf", # Run on 1 GPU on the "learner". "num_gpus": 1, # Use 15 ray-parallelized environment workers, # which collect samples to learn from. Each wo...
_____no_output_____
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Training our 2 Policies (agent1 and agent2)
results = tune.run( # RLlib Trainer class (we use the "PPO" algorithm today). PPOTrainer, # Give our experiment a name (we will find results/checkpoints # under this name on the server's `~ray_results/` dir). name=f"CUJ-RL", # The RLlib config (defined in a cell above). config=TRAINER_CFG, ...
(run pid=None) == Status == (run pid=None) Current time: 2021-12-01 09:24:41 (running for 00:00:00.14) (run pid=None) Memory usage on this node: 4.7/119.9 GiB (run pid=None) Using FIFO scheduling algorithm. (run pid=None) Resources requested: 0/16 CPUs, 0...
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Restoring from a checkpoint
local_checkpoint = "/Users/sven/Downloads/checkpoint-20-2" if os.path.isfile(local_checkpoint): print("yes, checkpoint files are on local machine ('Downloads' folder)") # We'll restore the trained PPOTrainer locally on this laptop here and have it run # through a new environment to demonstrate it has learnt useful...
2021-12-01 18:34:51,615 WARNING deprecation.py:38 -- DeprecationWarning: `SampleBatch['is_training']` has been deprecated. Use `SampleBatch.is_training` instead. This will raise an error in the future! 2021-12-01 18:34:54,804 WARNING trainer_template.py:185 -- `execution_plan` functions should accept `trainer`, `worker...
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Running inference locally
env = MultiAgentArena(config={"render": True}) with env.out: obs = env.reset() env.render() while True: a1 = new_trainer.compute_single_action(obs["agent1"], policy_id="policy1", explore=True) a2 = new_trainer.compute_single_action(obs["agent2"], policy_id="policy2", explore=False) ...
_____no_output_____
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
Inference using Ray Serve
@serve.deployment(route_prefix="/multi-agent-arena") class ServeRLlibTrainer: def __init__(self, config, checkpoint_path): # Link to our trainer. self.trainer = PPOTrainer(cpu_config) self.trainer.restore(checkpoint_path) async def __call__(self, request: Request): json_input =...
_____no_output_____
Apache-2.0
rllib_industry_webinar_20211201/demo_dec1.ipynb
sven1977/rllib_tutorials
**_Note: This notebook contains ALL the code for Sections 13.7 through 13.11, including the Self Check snippets because all the snippets in these sections are consecutively numbered in the text._** 13.7 Authenticating with Twitter Via Tweepy
import tweepy import keys
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Creating and Configuring an `OAuthHandler` to Authenticate with Twitter
auth = tweepy.OAuthHandler(keys.consumer_key, keys.consumer_secret) auth.set_access_token(keys.access_token, keys.access_token_secret)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Creating an API Object
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.7 Self Check**1. _(Fill-In)_** Authenticating with Twitter via Tweepy involves two steps. First, create an object of the Tweepy module’s `________` class, passing your API key and API secret key to its constructor. **Answer:** `OAuthHandler`.**2. _(True/F...
nasa = api.get_user('nasa')
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting Basic Account Information
nasa.id nasa.name nasa.screen_name nasa.description
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting the Most Recent Status Update
nasa.status.text
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting the Number of Followers
nasa.followers_count
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting the Number of Friends
nasa.friends_count
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting Your Own Account’s Information ![Self Check Exercises check mark image](files/art/check.png) 13.8 Self Check**1. _(Fill-In)_** After authenticating with Twitter, you can use the Tweepy `API` object’s `________` method to get a tweepy.models.User object containing information about a user’s Twitter account.**An...
nasa_kepler = api.get_user('NASAKepler') nasa_kepler.followers_count nasa_kepler.status.text
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
13.9 Introduction to Tweepy `Cursor`s: Getting an Account’s Followers and Friends 13.9.1 Determining an Account’s Followers
followers = []
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Creating a Cursor
cursor = tweepy.Cursor(api.followers, screen_name='nasa')
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Getting Results
for account in cursor.items(10): followers.append(account.screen_name) print('Followers:', ' '.join(sorted(followers, key=lambda s: s.lower())))
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Automatic Paging Getting Follower IDs Rather Than Followers ![Self Check Exercises check mark image](files/art/check.png) 13.9.1 Self Check**1. _(Fill-In)_** Each Twitter API method’s documentation discusses the maximum number of items the method can return in one call—this is known as a `________` of results. **Answe...
kepler_followers = [] cursor = tweepy.Cursor(api.followers, screen_name='NASAKepler') for account in cursor.items(10): kepler_followers.append(account.screen_name) print(' '.join(kepler_followers))
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
13.9.2 Determining Whom an Account Follows
friends = [] cursor = tweepy.Cursor(api.friends, screen_name='nasa') for friend in cursor.items(10): friends.append(friend.screen_name) print('Friends:', ' '.join(sorted(friends, key=lambda s: s.lower())))
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.9.2 Self Check**1. _(Fill-In)_** The `API` object’s `friends` method calls the Twitter API’s `________` method to get a list of User objects representing an account’s friends. **Answer:** `friends/list`. 13.9.3 Getting a User’s Recent Tweets
nasa_tweets = api.user_timeline(screen_name='nasa', count=3) for tweet in nasa_tweets: print(f'{tweet.user.screen_name}: {tweet.text}\n')
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Grabbing Recent Tweets from Your Own Timeline ![Self Check Exercises check mark image](files/art/check.png) 13.9.3 Self Check**1. _(Fill-In)_** You can call the `API` method `home_timeline` to get tweets from your home timeline, that is, your tweets and tweets from `________`. **Answer:** the people you follow.**2. _(...
kepler_tweets = api.user_timeline( screen_name='NASAKepler', count=2) for tweet in kepler_tweets: print(f'{tweet.user.screen_name}: {tweet.text}\n')
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
13.10 Searching Recent Tweets Tweet Printer
from tweetutilities import print_tweets
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Searching for Specific Words
tweets = api.search(q='Mars Opportunity Rover', count=3) print_tweets(tweets)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Searching with Twitter Search Operators
tweets = api.search(q='from:nasa since:2018-09-01', count=3) print_tweets(tweets)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
Searching for a Hashtag
tweets = api.search(q='#collegefootball', count=20) print_tweets(tweets)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.10 Self Check**1. _(Fill-In)_** The Tweepy `API` method `________` returns tweets that match a query string.**Answer:** search.**2. _(True/False)_** If you plan to request more results than can be returned by one call to search, you should use an `API` ob...
tweets = api.search(q='astronaut from:nasa', count=1) print_tweets(tweets)
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
13.11 Spotting Trends with the Twitter Trends API 13.11.1 Places with Trending Topics
trends_available = api.trends_available() len(trends_available) trends_available[0] trends_available[1]
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.11.1 Self Check**1. _(Fill-In)_** If a topic “goes viral,” you could have thousands or even millions of people tweeting about that topic at once. Twitter refers to these as `________` topics.**Answer:** trending.**2. _(True/False)_** The Twitter Trends AP...
world_trends = api.trends_place(id=1) trends_list = world_trends[0]['trends'] trends_list[0] trends_list = [t for t in trends_list if t['tweet_volume']] from operator import itemgetter trends_list.sort(key=itemgetter('tweet_volume'), reverse=True) for trend in trends_list[:5]: print(trend['name'])
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
New York City Trending Topics
nyc_trends = api.trends_place(id=2459115) # New York City WOEID nyc_list = nyc_trends[0]['trends'] nyc_list = [t for t in nyc_list if t['tweet_volume']] nyc_list.sort(key=itemgetter('tweet_volume'), reverse=True) for trend in nyc_list[:5]: print(trend['name'])
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.11.2 Self Check**1. _(Fill-In)_** You also can look up WOEIDs programmatically using Yahoo!’s web services via Python libraries like `________`.**Answer:** `woeid`.**2. _(True/False)_** The statement `todays_trends = api.trends_place(id=1)` gets today’s U...
us_trends = api.trends_place(id='23424977') us_list = us_trends[0]['trends'] us_list = [t for t in us_list if t['tweet_volume']] us_list.sort(key=itemgetter('tweet_volume'), reverse=True) for trend in us_list[:3]: print(trend['name'])
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
13.11.3 Create a Word Cloud from Trending Topics
topics = {} for trend in nyc_list: topics[trend['name']] = trend['tweet_volume'] from wordcloud import WordCloud wordcloud = WordCloud(width=1600, height=900, prefer_horizontal=0.5, min_font_size=10, colormap='prism', background_color='white') wordcloud = wordcloud.fit_word...
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
![Self Check Exercises check mark image](files/art/check.png) 13.11.3 Self Check**1. _(IPython Session)_** Create a word cloud using the `us_list` list from the previous section’s Self Check.**Answer:**
topics = {} for trend in us_list: topics[trend['name']] = trend['tweet_volume'] wordcloud = wordcloud.fit_words(topics) wordcloud = wordcloud.to_file('USTrendingTwitter.png') ########################################################################## # (C) Copyright 2019 by Deitel & Associates, Inc. and ...
_____no_output_____
MIT
examples/ch13/snippets_ipynb/13_07-11withSelfChecks.ipynb
edson-gomes/Intro-to-Python
$ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcommand{\braket}[2]{\langle 1|2\rangle} $$ \newcommand{\dot}[2]{ 1 \cdot 2} $$ \newcommand{\biginner}[2]{\left\langle 1,2\right\rangle} $$ \newcommand{\mymatrix}[2]{\left( \begin{array}{1} 2\end{array} \right)} $$ \newcommand{\myvector}[1]{\my...
import os, webbrowser webbrowser.open(os.path.abspath("Exercises_Probabilistic_Systems.html"))
_____no_output_____
Apache-2.0
classical-systems/Exercises_Probabilistic_Systems.ipynb
jaorduz/QWorld2021_QMexico
7. Share the Insight > “The goal is to turn data into insight” - Why do we need to communicate insight?- Types of communication - Exploration vs. Explanation- Explanation: Telling a story with data- Exploration: Building an interface for people to find storiesThere are two main insights we want to communicate. - Bang...
# Import the library we need, which is Pandas and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # import seaborn as sns # Set some parameters to get good visuals - style to ggplot and size to 15,10 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (15, 10) #...
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
Let us plot the Cities in a Geographic Map
# Load the geocode file dfGeo = pd.read_csv('city_geocode.csv') dfGeo.head()
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
PRINCIPLE: Joining two data framesThere will be many cases in which your data is in two different dataframe and you would like to merge them in to one dataframe. Let us look at one example of this - which is called left join![](../img/left_merge.png)
dfCityGeo = pd.merge(df2016City, dfGeo, how='left', on=['city', 'city']) dfCityGeo.head() dfCityGeo.isnull().describe() dfCityGeo.plot(kind = 'scatter', x = 'lon', y = 'lat', s = 100)
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
We can do a crude aspect ratio adjustment to make the cartesian coordinate systesm appear like a mercator map
dfCityGeo.plot(kind = 'scatter', x = 'lon', y = 'lat', s = 100, figsize = [10,11]) # Let us at quanitity as the size of the bubble dfCityGeo.plot(kind = 'scatter', x = 'lon', y = 'lat', s = dfCityGeo.quantity, figsize = [10,11]) # Let us scale down the quantity variable dfCityGeo.plot(kind = 'scatter', x...
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
Exercise Can you plot all the States by quantity in (pseudo) geographic map? Plotting on a Map
import folium # Getting an India Map map_osm = folium.Map(location=[20.5937, 78.9629]) map_osm # Using any map provider map_stamen = folium.Map(location=[20.5937, 78.9629], tiles='Stamen Toner', zoom_start=5) map_stamen
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
Adding markers on the map
folium.CircleMarker(location=[20.5937, 78.9629], radius=50000, popup='Central India', color='#3186cc', fill_color='#3186cc', ).add_to(map_stamen) map_stamen
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
Add markers from a dataframe
length = dfCityGeo.shape[0] length map_india = folium.Map(location=[20.5937, 78.9629], tiles='Stamen Toner', zoom_start=5) for i in range(length): lon = dfCityGeo.iloc[i, 2] lat = dfCityGeo.iloc[i, 3] location = [lat, lon] radius = dfCityGeo.iloc[i, 1]/25 name = dfCityGeo.iloc[i,0] folium.C...
_____no_output_____
MIT
notebook/onion/7-Insight.ipynb
narnaik/art-data-science
Thanks for:* https://www.kaggle.com/sishihara/moa-lgbm-benchmarkPreprocessing* https://www.kaggle.com/ttahara/osic-baseline-lgbm-with-custom-metric* https://zenn.dev/fkubota/articles/2b8d46b11c178ac2fa2d* https://qiita.com/ryouta0506/items/619d9ac0d80f8c0aed92* https://github.com/nejumi/tools_for_kaggle/blob/master/sem...
# Version = "v1" # starter model # Version = "v2" # Compare treat Vs. ctrl and minor modifications, StratifiedKFold # Version = "v3" # Add debug mode and minor modifications # Version = "v4" # Clipping a control with an outlier(25-75) # Version = "v5" # Clipping a control with an outlier(20-80) # Version = "v6" # under...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Library
import lightgbm as lgb from lightgbm import LGBMClassifier import imblearn from imblearn.over_sampling import SMOTE from logging import getLogger, INFO, StreamHandler, FileHandler, Formatter import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os import random from skl...
lightgbm Version: 2.3.1 imblearn Version: 0.7.0 numpy Version: 1.18.5 pandas Version: 1.1.3
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Utils
def get_logger(filename='log'): logger = getLogger(__name__) logger.setLevel(INFO) handler1 = StreamHandler() handler1.setFormatter(Formatter("%(message)s")) handler2 = FileHandler(filename=f"{filename}.{Version}.log") handler2.setFormatter(Formatter("%(message)s")) logger.addHandler(handler...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Config
if DEBUG: N_FOLD = 2 Num_boost_round=1000 Early_stopping_rounds=10 Learning_rate = 0.03 else: N_FOLD = 4 Num_boost_round=10000 Early_stopping_rounds=30 Learning_rate = 0.01 SEED = 42 seed_everything(seed=SEED) Max_depth = 7
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Data Loading
train = pd.read_csv("../input/lish-moa/train_features.csv") test = pd.read_csv("../input/lish-moa/test_features.csv") train_targets_scored = pd.read_csv("../input/lish-moa/train_targets_scored.csv") train_targets_nonscored = pd.read_csv("../input/lish-moa/train_targets_nonscored.csv") sub = pd.read_csv("../input/lish-m...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Training Utils
def get_target(target_col, annot_sig): if target_col in annot_sig: t_cols = [] for t_col in list(annot[annot.sig_id == target_col].iloc[0]): if t_col is not np.nan: t_cols.append(t_col) target = train_target[t_cols] target = target.sum(axis...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
PreprocessingWe have to convert some categorical features into numbers in train and test. We can identify categorical features by `pd.DataFrame.select_dtypes`.
train.head() train.select_dtypes(include=['object']).columns train, test = label_encoding(train, test, ['cp_type', 'cp_time', 'cp_dose']) train['WHERE'] = 'train' test['WHERE'] = 'test' data = train.append(test) data = data.reset_index(drop=True) data # Select control data ctl = train[(train.cp_type==0)].copy() ctl = ...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Modeling
cv = StratifiedKFold(n_splits=N_FOLD, shuffle=True, random_state=SEED) params = { 'objective': 'binary', 'metric': 'binary_logloss', 'learning_rate': Learning_rate, 'num_threads': 2, 'verbose': -1, 'max_depth': Max_depth, 'num_leaves': int((Max_depth**2)*0.7), 'feature_fraction':0.4, # ...
_____no_output_____
MIT
notebooks/20201103-moa-lgbm-v38.ipynb
KFurudate/kaggle_MoA
Before adding any more features, let's check the performance with the initial set.
#Use the following predictors predictors = ['compilation','number for sale', 'number have', 'number of ratings', 'number of tracks', 'number of versions', 'number on label', 'number on label for sale', 'number want'] #Randomly shuffle the row order new_albums = albums.sample(frac=1) #Generate prediction...
Random forest regression on initial features gives £19.64 mean difference and 0.3423 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Let's monitor how these (hopefully) improve as we add more features.
mean_diff_each_step = [mean_diff] score_each_step = [score] each_step = ['Initial features']
_____no_output_____
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Year of releaseThis should have a large bearing on the price, but the years of some releases are unknown. Let's make some assumptions about these to generate the feature.
#Convert the known years to integers albums['integer year'] = [int(year[-4:]) if not pd.isnull(year) else year for year in albums['year']] #For the unknown years for index in albums[albums['year'].isnull()].index: ave_artist_year = np.round(albums.ix[albums['artist'] == albums.ix[index,'artist'],'integer year'].me...
Random forest regression with year added gives £18.29 mean difference and 0.4012 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
So knowing the year helps a lot. Average ratingA lot of releases also have a rating given by users.
albums[~albums['average rating'].isnull()]['average rating'].hist(bins=100) plt.xlabel('Average Rating') plt.ylabel('Count') plt.title('Distribution of average ratings'); for i in range(1,6): print(str(i) + '* rated albums have mean price £{0:.2f}'.format(albums.ix[(albums['average rating'] <= i) ...
1* rated albums have mean price £38.79 2* rated albums have mean price £32.74 3* rated albums have mean price £36.40 4* rated albums have mean price £24.29 5* rated albums have mean price £37.11 Unrated albums have mean price £41.45
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
These are distributed towards the high end (as expected: we're looking at the most wanted records), but a higher rating does not necessarily correspond to a more expensive record.Let's first try giving the unrated records the mean rating.
#If no rating is given, set it to be the average albums['new rating'] = albums['average rating'] albums.ix[albums['new rating'].isnull(),'new rating'] = albums['new rating'].mean() predictors = ['compilation','number for sale', 'number have', 'number of ratings', 'number of tracks', 'number of versions',...
Assuming the mean rating for those releases unrated gives £18.33 mean difference and 0.4007 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
What about setting the unrated records to 0, or 6?
#If no rating is given, set it to be the average albums['new rating'] = albums['average rating'] albums.ix[albums['new rating'].isnull(),'new rating'] = 0 predictors = ['compilation','number for sale', 'number have', 'number of ratings', 'number of tracks', 'number of versions', 'number on label', 'numbe...
Assuming a rating of 6 for those releases unrated gives £18.33 mean difference and 0.4021 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
So assigning a 6 for the unrated items gives the best score.
albums.ix[albums['average rating'].isnull(),'average rating'] = 6 predictors = ['compilation','number for sale', 'number have', 'number of ratings', 'number of tracks', 'number of versions', 'number on label', 'number on label for sale', 'number want', 'integer year', 'average rating'] #R...
_____no_output_____
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Number of records Obviously all the records are LPs, but some may be double or even triple, let's add a feature of the number of records.
albums['format'].unique() mean_diff = get_mean_diff(np.array(new_albums['median price sold'][new_albums['format']!='Vinyl']), predictions[np.array(new_albums['format']!='Vinyl')]) score = get_score(np.array(new_albums['median price sold'][new_albums['format']!='Vinyl']), pred...
For boxsets we have £15.45 mean difference and 0.3669 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
So these boxsets are not being served well by the current predictor.
#If the format is 'Vinyl', assume one record #Otherwise extract the number albums['number of records'] = [1 if format_str == 'Vinyl' else [s for s in format_str.split() if s.isdigit()][0] if '×' in format_str else None for form...
For boxsets we now have £14.33 mean difference and 0.4546 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
So adding the number of records doesn't affect the score much, but offers a great improvement for boxsets themselves. Limited editionsSome records are described as 'limited edition' in either the format details or release notes. This could correlate with higher prices so let's add a binary variable for it.
#Pick out if limited edition is specified in format details or notes albums.ix[albums['notes'].isnull(),'notes'] = '' albums['limited edition'] = [(('Limited Edition' in albums.ix[index,'format details']) or ('Limited Edition' in albums.ix[index,'notes'])) for...
Random forest with limited edition added gives £18.08 mean difference and 0.4018 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Seems to make it worse. ReissuesReissues are likely to be cheaper, while the original records that have been reissued will be more in demand, and so more expensive. Some reissues are specified in the format details and notes.
#Pick out if reissue is specified in format details or notes albums.ix[albums['notes'].isnull(),'notes'] = '' albums['reissue'] = [(('Reissue' in albums.ix[index,'format details']) or ('Reissue' in albums.ix[index,'notes'])) for index in albums.index] print('Reissue albums have mean price £{0:.2f}...
Random forest with reissue added gives £18.03 mean difference and 0.4012 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Not a great difference, and makes no distinction whether a record has itself been reissued. We could perhaps get a better grasp of reissues if we look at the difference between year of release between versions.
#If other versions have been released, find the difference to the earliest and latest versions albums.ix[albums['years of versions'].isnull(),'years of versions'] = '' albums['list version years'] = [[int(s) for s in albums.ix[index,'years of versions'].split('; ') if s.isdigit()] + [i...
Random forest with years to reissues added gives £17.86 mean difference and 0.4075 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Together these improve both the mean difference and score. CountriesThere are lots of different countries, many with few entries. First let's try binary variables for countries with more (>10) entries than the likely min leaf size in the random forest regressor (as otherwise they won't be used in the regressor).
albums.ix[albums['country'].isnull(),'country'] = '' #Find all the countries country_list = albums['country'].unique() #Create a binary variable for each country for country in country_list: albums['c_'+country] = 0 #Populate the binary variable albums.ix[albums['country'] == country, 'c_'+country...
Random forest with countries added gives £17.44 mean difference and 0.4231 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Now let's try using k-means to cluster together the countries into a few groups, and using these as features.
from sklearn.cluster import KMeans #Make a dataframe with the price statistics for each country country_stats = pd.DataFrame(albums.groupby(by = 'country') .describe()['median price sold']).reset_index().pivot(index = 'country', ...
_____no_output_____
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
The six groups are:1) Red: low mean/min, middling max; uniformly cheap countries places where major labels release records with fewer small pressings e.g. Australia, Canada, Cuba, Poland, plus hybrid 'countries' like Europe2) Green: high mean/min, low max; uniformly expensive countries places with only a few, sought...
#Reassign Mongolia country_stats.ix['Mongolia', 'label'] = country_stats.ix['Lebanon', 'label'] #Create binary variables for each label count = 1 for label in country_stats['label'].unique(): albums['country label ' + str(count)] = 0 for country in country_stats[country_stats['label'] == label].index: ...
Random forest with countries added gives £17.84 mean difference and 0.4017 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
This isn't as good as the binary variables. GenresGenre may affect price: bebop collectors will probably pay more for originals than smooth jazz collectors, for example.
#Extract all the genres genre_list = [] for genres in albums['genre'].unique(): for genre in genres.split('; '): if genre not in genre_list: genre_list.append(genre) #Create a binary variable for each genre for genre in genre_list: albums['g_'+genre] = 0 #Populate the binary va...
Electronic: 2474, £32.80 Jazz: 23124, £35.27 Hip Hop: 365, £24.21 Stage & Screen: 1865, £51.57 Funk / Soul: 6067, £34.71 Rock: 3636, £35.45 Latin: 1763, £37.27 Folk, World, & Country: 1262, £46.08 Pop: 1131, £33.75 Classical: 388, £49.13 Non-Music: 284, £43.94 Reggae: 153, £30.66 Blues: 521, £30.02 Children's: 19, £22....
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Hip hop records are invariably newer, so less expensive. Stage & Screen is more expensive (perhaps less popular upon initial release, at least in the realms of jazz). Folk, World, & Country will be pressings from more 'exotic' locations, so more expensive. Classical/non-music is more expensive (perhaps less popular ...
predictors = ['compilation','number for sale', 'number have', 'number of ratings', 'number of tracks', 'number of versions', 'number on label', 'number on label for sale', 'number want', 'integer year', 'average rating', 'number of records', 'limited edition', 'reissue', 'dif...
Random forest with genres added gives £17.45 mean difference and 0.4155 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Little difference. StylesSlightly more specific categorisations, but may have a similar effect to genres.
albums.ix[albums['style'].isnull(),'style'] = '' #Extract all the styles style_list = [] for styles in albums['style'].unique(): for style in styles.split('; '): if style not in style_list: style_list.append(style) #Create a binary variable for each style for style in style_list: ...
Random forest with styles added gives £17.27 mean difference and 0.4179 score
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Improves mean difference a little at least.
xticks = list(range(0,len(score_each_step))) fig = plt.figure(figsize=(12,3)) ax1 = fig.add_subplot(121) ax1.plot(xticks,mean_diff_each_step,'-or') ax1.set_title('mean diff') ax1.set_xticks(xticks) ax1.set_xticklabels(each_step, rotation=90) ax1.set_ylabel('mean diff (£)') ax2 = fig.add_subplot(122) ax2.plot(xticks,sco...
_____no_output_____
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
Although there's obviously some noise in both the mean difference and score associated with the random partitioning of the data into train and test sets, there's still a clear improvement in both measures as features have been added.
albums.to_csv('../data/interim/albums.csv',encoding='utf-8')
_____no_output_____
MIT
notebooks/02-20_9_16-generating_features.ipynb
sfblake/Record_Price_Predictor
2020년 6월 24일 수요일 BaekJoon - 11052 : 카드 구매하기 (Python) 문제 : https://www.acmicpc.net/problem/11052 블로그 : https://somjang.tistory.com/entry/BaekJoon-11052%EB%B2%88-%EC%B9%B4%EB%93%9C-%EA%B5%AC%EB%A7%A4%ED%95%98%EA%B8%B0-Python 첫번째 시도
cardNum = int(input()) NC = [0]*(cardNum+1) cardPrice = [0]+list(map(int, input().split())) def answer(): NC[0], NC[1] = 0, cardPrice[1] for i in range(2, cardNum+1): for j in range(1, i+1): NC[i] = max(NC[i], NC[i-j]+cardPrice[j]) print(NC[cardNum]) answer()
_____no_output_____
MIT
DAY 101 ~ 200/DAY139_[BaekJoon] 카드 구매하기 (Python).ipynb
SOMJANG/CODINGTEST_PRACTICE
This code uses the Brian2 neuromorphic simulator code to implement a version of role/filler binding and unbinding based on the paper :High-Dimensional Computing with Sparse Vectors" by Laiho et al 2016. The vector representation is a block structure comprising slots_per_vector where the number of slots_per_vector is th...
# Init base vars show_bound_vecs_slot_detail = False slots_per_vector = 100 # This is the number of neurons used to represent a vector bits_per_slot = 100 # This is the number of bit positions mem_size = 500 # The number of vectors against which the resulting unbound vector is compared Num_bound = 5 # The number of ve...
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Create a set of sparse VSA vectorsGenerate a random matrix (P_matrix) which represents all of the sparse vectors that are to be used.This matrix has columns equal to the number of slots_per_vector in each vector with the number of rows equal to the memory size (mem_size)
P_matrix = np.random.randint(0, bits_per_slot, size=(mem_size,slots_per_vector)) Role_matrix = P_matrix[::2] Val_matrix = P_matrix[1::2]
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Demonstration of modulo addition binding
test_target_neuron = target_neuron # Change this to try different columns e.g. 0, 1, 2.... print(f"Showing modulo {bits_per_slot} addition role+filler bind/unbind for target column {test_target_neuron}\n") for n in range(0,2*Num_bound,2): bind_val = (P_matrix[n][test_target_neuron]+P_matrix[n+1][test_target_neuro...
Showing modulo 100 addition role+filler bind/unbind for target column 1 10+51=61 % 100 = 61 Bind 61-51=10 % 100 = 10 Unbind 0+69=69 % 100 = 69 Bind 69-69= 0 % 100 = 0 Unbind 22+77=99 % 100 = 99 Bind 99-77=22 % 100 = 22 Unbind 30+31=61 % 100 = 61 Bind 61-31=30 % 100 = 30 Unbind 27+63=90 % 100 = 90 Bind ...
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Empirical calc This section of the code computes the theoretical values for the sparse vector (which can then be compared withthe output of the net1 neuromorphic circuit. It then computes the expected number of bits_per_slot that will align in the clean-up memory operation (which can then be compared with the net2 neu...
# print the cyclically shifted version of the vectors that are to be bound np.set_printoptions(threshold=24) np.set_printoptions(edgeitems=11) for n in range(0, Num_bound): print(np.roll(P_matrix[n], n)) np.set_printoptions() # Init sparse bound vector (s_bound) with zeros s_bound = np.zeros((slots_per_vector, b...
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Make s_bound sparse using the argmax function which finds the bit position with the highest random value.
# Make s_bound sparse using the argmax function which finds the bit position with the highest random value. np.set_printoptions(threshold=24) np.set_printoptions(edgeitems=11) print("\nResultant Sparse vector, value indicates 'SET' bit position in each slot. " "\n(Note, a value of '0' means bit zero is set).\n") ...
Resultant Sparse vector, value indicates 'SET' bit position in each slot. (Note, a value of '0' means bit zero is set). [81 61 19 21 68 3 12 9 8 62 17 ... 6 15 15 64 1 53 1 1 24 16 9]
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Perform the unbinding Unbind the vector sparse_bound vector and compare with each of the vectors in the P_matrix couting thenumber of slots_per_vector that have matching bit positions. This gives the number of spikes that should line up in the clean up memory operation.
np.set_printoptions(threshold=24) np.set_printoptions(edgeitems=11) hd_threshold = 0.1 results_set = [] results = None miss_matches = [] min_match = slots_per_vector for nn in range(0, len(Role_matrix)): # for pvec in P_matrix: pvec = Role_matrix[nn] results = [] for test_vec in Val_matrix: unb...
Showing failed matches: Role_vec_idx[05], Val_match_idx[94]: [3 2 1 0 1 0 0 0 2 2 0 ... 0 2 0 1 0 0 1 3 1 1 1] Role_vec_idx[06], Val_match_idx[116]: [0 0 0 2 0 1 1 0 1 0 0 ... 1 1 1 0 1 2 1 0 0 2 2] Role_vec_idx[07], Val_match_idx[27]: [0 1 0 1 1 1 3 1 1 2 2 ... 0 0 2 0 1 2 0 3 0 1 3] Role_vec_idx[08], Val_match_idx[...
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Binding: Brian 2 Code - SIMPLIFIED CIRCUIT ================== ![title](img/Fig10.png) Generate the time delay data_matrix from the so that the input vector time delay in each slot plus the delay matrix line up at the number of bits_per_slot per slot (e.g. a time delay in slot 0 of the input vector of say 10 will have ...
net1=Network() #We first create an array of time delays which will be used to select the first Num_bound vectors from # the P_matrix with a time delay (input_delay) between each vector. #Calculate the array for the input spike generator array1 = np.ones(mem_size) * slots_per_vector * bits_per_slot # The input spik...
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
UnBinding: Brian 2 Code ===================================== ![title](img/Fig9.png)
#-------------------------------------------------------------------------------------------------------- #This section of the code implements the Brian2 neuromorphic circuit which unbinds the vector. #The unbound vector and a selected role vector are processed to give the corresponding 'noisy' filler vector. # which ...
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
The G6 neuron group is stimulated from the P spike generator group with and the G7 neuron group. The P spike generator generates a role vector role using the time delay on the G6 dendrites obtained from the P_matrix (S5.delay) and the G6 neuron group produces the sparse bound vector.The G6 neurons perform the subtracti...
G6 = NeuronGroup(slots_per_vector, equ3, threshold='v>=1.0', reset=reset3, method='euler', refractory ='2*Num_bound*ms') G6.v =0.0 G6.I = 1.0 G6.tau = bits_per_slot * ms net2.add(G6) S5 = Synapses(P2, G6, 'w : 1',on_pre= 'I = (I-1)%2') range_array2 = range(0, slots_per_vector) for n in range(0,mem_size): S5.c...
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
This final NeuronGroup,G8, stage is the clean up memory operation using the transpose of the data_matrix to set the synaptic delays on the G8 dendrites. We only produce one output spike per match by using the refractory operator to suppress any further spikes. This could be improved to choose the larget matching spike.
G8 = NeuronGroup(mem_size, equ2, threshold='v >= 13.0', reset='v=0.0', method='euler') G8.v = 1.0 G8.tau = 2.0*ms net2.add(G8) range_array3 = range(0,mem_size) S8 = Synapses(G6, G8, on_pre='v += 1.0') for n in range(0, slots_per_vector): S8.connect(i=n,j=range_array3) data_matrix2 = np.transpose(data_matrix...
_____no_output_____
MIT
Simplified-Role-Filler-net1.ipynb
vsapy/DTIN07
Latest point anomaly detection with the Anomaly Detector API Use this Jupyter notebook to start visualizing anomalies as a batch with the Anomaly Detector API in Python.While you can detect anomalies as a batch, you can also detect the anomaly status of the last data point in the time series. This notebook iterativel...
# To start sending requests to the Anomaly Detector API, paste your subscription key below, # and replace the endpoint variable with the endpoint for your region. subscription_key = '' endpoint_latest = 'https://westus2.api.cognitive.microsoft.com/anomalydetector/v1.0/timeseries/last/detect' import requests import jso...
_____no_output_____
MIT
ipython-notebook/Latest point detection with the Anomaly Detector API.ipynb
Tapasgt/AnomalyDetector
Detect latest anomaly of sample timeseries The following cells call the Anomaly Detector API with an example time series data set and different sensitivities for anomaly detection. Varying the sensitivity of the Anomaly Detector API can improve how well the response fits your data.
def detect_anomaly(sensitivity): sample_data = json.load(open('sample.json')) points = sample_data['series'] skip_point = 29 result = {'expectedValues': [None]*len(points), 'upperMargins': [None]*len(points), 'lowerMargins': [None]*len(points), 'isNegativeAnomaly': [False]*len(points), ...
_____no_output_____
MIT
ipython-notebook/Latest point detection with the Anomaly Detector API.ipynb
Tapasgt/AnomalyDetector
A review of 2 decades of correlation, hierarchies, netowrks and clustering AimThe aim of this project is to review state of the art clustering algorithms for financial time series and to study their correlation in complicated networks. This will form the basis of an open toolbox to study correlations, hierarchies, n...
# set parameters here start = '2019-01-01' end = '2019-12-31' mst = MinimumSpanningTrees(start=start, end=end) # create a graph from distance computed from mst # share prices are the vertices and edges are the distance from two share prices g = mst.create_graph() # get the minimum spanning tree from the graph mst_tree ...
_____no_output_____
Apache-2.0
marketlearn/network_spanning_trees/mst_example.ipynb
mrajancsr/QuantEquityManagement
Observation- All the shares are strongly correlated with SPY which makes sense since SPY is an index that contains all the other shares Note: - Following is the edge weights associated with the spanning tree
mst_tree def create_graph(): from itertools import combinations g = Graph() input_vertices = range(1, 8) vertices = [g.insert_vertex(v) for v in input_vertices] g.insert_edge(vertices[0], vertices[1], 28) g.insert_edge(vertices[1], vertices[2], 16) g.insert_edge(vertices[2], vertices[3], 12)...
_____no_output_____
Apache-2.0
marketlearn/network_spanning_trees/mst_example.ipynb
mrajancsr/QuantEquityManagement
Lesson 4: Model TrainingAt last, it's time to build our models! It might seem like it took us a while to get here, but professional data scientists actually spend the bulk of their time on the 3 steps leading up to this one: * Exploratory Analysis* Data Cleaning* Feature EngineeringThat's because the biggest jumps in m...
# NumPy for numerical computing import numpy as np # Pandas for DataFrames import pandas as pd pd.set_option('display.max_columns', 100) pd.set_option('display.float_format', lambda x: '%.3f' % x) # Matplotlib for visualization from matplotlib import pyplot as plt # display plots in the notebook %matplotlib inline ...
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Next, let's import 5 algorithms we introduced in the previous lesson.
# Import Elastic Net, Ridge Regression, and Lasso Regression from sklearn.linear_model import ElasticNet, Ridge, Lasso # Import Random Forest and Gradient Boosted Trees from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Quick note about this lesson. In this lesson, we'll be relying heavily on Scikit-Learn, which has many helpful functions we can take advantage of. However, we won't import everything right away. Instead, we'll be importing each function from Scikit-Learn as we need it. That way, we can point out where you can find each...
# Load cleaned dataset from lesson 3 df = pd.read_csv('project_files/analytical_base_table.csv') print(df.shape)
(1863, 41)
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
1. Split your datasetLet's start with a crucial but sometimes overlooked step: **Splitting** your data.First, let's import the train_test_split() function from Scikit-Learn.
# Function for splitting training and test set from sklearn.model_selection import train_test_split
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Next, separate your dataframe into separate objects for the target variable (y) and the input features (X).
# Create separate object for target variable y = df.tx_price # Create separate object for input features X = df.drop('tx_price', axis=1)
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Exercise 5.1**First, split X and y into training and test sets using the train_test_split() function.** * **Tip:** Its first two arguments should be X and y.* **Pass in the argument test_size=0.2 to set aside 20% of our observations for the test set.*** **Pass in random_state=1234 to set the random state for replicabl...
# Split X and y into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Let's confirm we have the right number of observations in each subset.**Next, run this code to confirm the size of each subset is correct.**
print( len(X_train), len(X_test), len(y_train), len(y_test) )
1490 373 1490 373
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Next, when we train our models, we can fit them on the X_train feature values and y_train target values.Finally, when we're ready to evaluate our models on our test set, we would use the trained models to predict X_test and evaluate the predictions against y_test.[**Back to Contents**](toc) 2. Build model pipelinesIn ...
# Summary statistics of X_train X_train.describe()
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Next, standardize the training data manually, creating a new X_train_new object.
# Standardize X_train X_train_new = (X_train - X_train.mean()) / X_train.std()
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer
Let's look at the summary statistics for X_train_new to confirm standarization worked correctly.* How can you tell?
# Summary statistics of X_train_new X_train_new.describe()
_____no_output_____
MIT
Day_7/Lesson 4 - Real Estate Model Training.ipynb
SoftStackFactory/DSML_Primer