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 2 - Define Model Here is a diagram of the model we'll use: -->Now we'll define the model. See how our model consists of three blocks of `Conv2D` and `MaxPool2D` layers (the base) followed by a head of `Dense` layers. We can translate this diagram more or less directly into a Keras `Sequential` model just by filli...
import tensorflow.keras as keras import tensorflow.keras.layers as layers model = keras.Sequential([ # First Convolutional Block layers.Conv2D(filters=32, kernel_size=5, activation="relu", padding='same', # give the input dimensions in the first layer # [height, width, colo...
_____no_output_____
Apache-2.0
notebooks/computer_vision/raw/tut5.ipynb
guesswhohaha/learntools
Notice in this definition is how the number of filters doubled block-by-block: 64, 128, 256. This is a common pattern. Since the `MaxPool2D` layer is reducing the *size* of the feature maps, we can afford to increase the *quantity* we create. Step 3 - Train We can train this model just like the model from Lesson 1: com...
model.compile( optimizer=tf.keras.optimizers.Adam(epsilon=0.01), loss='binary_crossentropy', metrics=['binary_accuracy'] ) history = model.fit( ds_train, validation_data=ds_valid, epochs=40, ) import pandas as pd history_frame = pd.DataFrame(history.history) history_frame.loc[:, ['loss', 'val...
_____no_output_____
Apache-2.0
notebooks/computer_vision/raw/tut5.ipynb
guesswhohaha/learntools
Cascade FilesOpenCV comes with these pre-trained cascade files, we've relocated the .xml files for you in our own DATA folder. Face Detection¶
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def detect_face(img): face_img = img.copy() face_rects = face_cascade.detectMultiScale(face_img) for (x, y, w, h) in face_rects: cv2.rectangle(face_img, (x, y), (x + w, y + h), (255, 255, 255), 10) ...
_____no_output_____
Apache-2.0
11_Face_Detection.ipynb
EliasPapachristos/Computer_Vision_with_OpenCV
Conjunction with Video
cap = cv2.VideoCapture(0) while True: ret, frame = cap.read(0) frame = detect_face(frame) cv2.imshow('Video Face Detection', frame) c = cv2.waitKey(1) if c == 27: break cap.release() cv2.destroyAllWindows()
_____no_output_____
Apache-2.0
11_Face_Detection.ipynb
EliasPapachristos/Computer_Vision_with_OpenCV
Looking up Trig RatiosThere are three ways you could find the value of a trig function at a particular angle.**1. Use a table** - This is how engineers used to find trig ratios before the days of computers. For example, from the table below I can see that $\sin(60)=0.866$| angle | sin | cos | tan || :---: | :---: | :-...
# Python's math module has functions called sin, cos, and tan # as well as the constant "pi" (which we will find useful shortly) from math import sin, cos, tan, pi # Run this cell. What do you expect the output to be? print(sin(60))
-0.3048106211022167
MIT
3-object-tracking-and-localization/activities/8-vehicle-motion-and-calculus/Looking up Trig Ratios.ipynb
S1lv10Fr4gn4n1/udacity-cv
Did the output match what you expected?If not, it's probably because we didn't convert our angle to radians. EXERCISE 1 - Write a function that converts degrees to radiansImplement the following math in code:$$\theta_{\text{radians}} = \theta_{\text{degrees}} \times \frac{\pi}{180}$$
from math import pi def deg2rad(theta): """Converts degrees to radians""" return theta * (pi/180) # TODO - implement this function (solution # code at end of notebook) assert(deg2rad(45.0) == pi / 4) assert(deg2rad(90.0) == pi / 2) print("Nice work! Your degrees to radians function works!") for the...
Nice work! Your degrees to radians function works! sin( 0 degrees) = 0.0 sin( 30 degrees) = 0.49999999999999994 sin( 45 degrees) = 0.7071067811865475 sin( 60 degrees) = 0.8660254037844386 sin( 90 degrees) = 1.0
MIT
3-object-tracking-and-localization/activities/8-vehicle-motion-and-calculus/Looking up Trig Ratios.ipynb
S1lv10Fr4gn4n1/udacity-cv
EXERCISE 2 - Make plots of cosine and tangent
import numpy as np from matplotlib import pyplot as plt def plot_sine(min_theta, max_theta): """ Generates a plot of sin(theta) between min_theta and max_theta (both of which are specified in degrees). """ angles_degrees = np.linspace(min_theta, max_theta) angles_radians = deg2rad(angles_degrees...
_____no_output_____
MIT
3-object-tracking-and-localization/activities/8-vehicle-motion-and-calculus/Looking up Trig Ratios.ipynb
S1lv10Fr4gn4n1/udacity-cv
In this notebook, we'll look at entry points for G10 vol, look for crosses with the largest downside sensivity to SPX, indicatively price several structures and analyze their carry profile.* [1: FX entry point vs richness](1:-FX-entry-point-vs-richness)* [2: Downside sensitivity to SPX](2:-Downside-sensitivity-to-SPX)*...
def format_df(data_dict): df = pd.concat(data_dict, axis=1) df.columns = data_dict.keys() return df.fillna(method='ffill').dropna() g10 = ['USDJPY', 'EURUSD', 'AUDUSD', 'GBPUSD', 'USDCAD', 'USDNOK', 'NZDUSD', 'USDSEK', 'USDCHF', 'AUDJPY'] start_date = date(2005, 8, 26) end_date = business_day_offset(date.t...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
2: Downside sensitivity to SPXLet's now look at beta and correlation with SPX across G10.
spx_spot = Dataset('TREOD').get_data(start_date, end_date, bbid='SPX')[['closePrice']] spx_spot = spx_spot.fillna(method='ffill').dropna() df = pd.DataFrame(spx_spot) #FX Spot data fx_spots = format_df(spot_fx) data = pd.concat([spx_spot, fx_spots], axis=1).dropna() data.columns = ['SPX'] + g10 beta_spx, corr_spx = {}...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
Part 3: AUDJPY conditional relationship with SPXLet's focus on AUDJPY and look at its relationship with SPX when SPX is significantly up and down.
# resample data to weekly from daily & get weekly returns wk_data = data.resample('W-FRI').last() rets = returns(wk_data, 1) sns.set(style='white', color_codes=True) spx_returns = [-.1, -.05, .05, .1] r2 = lambda x,y: stats.pearsonr(x,y)[0]**2 betas = pd.DataFrame(index=spx_returns, columns=g10) for ret in spx_returns...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
Let's use the beta for all S&P returns to price a structure
sns.jointplot(x='SPX', y='AUDJPY', data=rets, kind='reg', stat_func=r2)
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
4: Price structures Let's now look at a few AUDJPY structures as potential hedges* Buy 4m AUDJPY put using spx beta to size. Max loss limited to premium paid.* Buy 4m AUDJPY put spread (4.2%/10.6% OTMS). Max loss limited to premium paid.For more info on this trade, check out our market strats piece [here](https://m...
#buy 4m AUDJPY put audjpy_put = FXOption(option_type='Put', pair='AUDJPY', strike_price= 's-4.2%', expiration_date='4m', buy_sell='Buy') print('cost in bps: {:,.2f}'.format(audjpy_put.premium / audjpy_put.notional_amount * 1e4)) #buy 4m AUDJPY put spread (5.3%/10.6% OTMS) from gs_quant.markets.portfolio import Port...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
...And some rates ideas* Sell straddle. Max loss unlimited.* Sell 3m30y straddle, buy 2y30y straddle in a 0 pv package. Max loss unlimited.
leg = IRSwaption('Straddle', '30y', notional_currency='USD', expiration_date='3m', buy_sell='Sell') print('PV in USD: {:,.2f}'.format(leg.dollar_price())) leg1 = IRSwaption('Straddle', '30y', notional_currency='USD', expiration_date='3m', buy_sell='Sell',name='3m30y ATM Straddle') leg2 = IRSwaption('Straddle', '30y', n...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
5: Analyse rates package
dates = pd.bdate_range(date(2020, 6, 8), leg1.expiration_date, freq='5B').date.tolist() with BackToTheFuturePricingContext(dates=dates, roll_to_fwds=True): future = rates_package.price() rates_future = future.result().aggregate() rates_future.plot(figsize=(10, 6), title='Historical PV and carry for rates package'...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
Let's focus on the next 3m and how the calendar carries in different rates shocks.
dates = pd.bdate_range(dt.date.today(), leg1.expiration_date, freq='5B').date.tolist() shocked_pv = pd.DataFrame(columns=['Base', '5bp per week', '50bp instantaneous'], index=dates) p1, p2, p3 = [], [], [] with PricingContext(is_batch=True): for t, d in enumerate(dates): with CarryScenario(date=d, roll_to_...
_____no_output_____
Apache-2.0
gs_quant/content/events/00_virtual_event/0003_trades.ipynb
KabbalahOracle/gs-quant
💡 SolutionsBefore trying out these solutions, please start the [gqlalchemy-workshop notebook](../workshop/gqlalchemy-workshop.ipynb) to import all data. Also, this solutions manual is here to help you out, and it is recommended you try solving the exercises first by yourself. Exercise 1**Find out how many genres ther...
from gqlalchemy import match total_genres = ( match() .node(labels="Genre", variable="g") .return_({"count(g)": "num_of_genres"}) .execute() ) results = list(total_genres) for result in results: print(result["num_of_genres"])
22084
MIT
solutions/gqlalchemy-solutions.ipynb
pyladiesams/graphdatabases-gqlalchemy-beginner-mar2022
Exercise 2**Find out to how many genres movie 'Matrix, The (1999)' belongs to.**The correct Cypher query is:```MATCH (:Movie {title: 'Matrix, The (1999)'})-[:OF_GENRE]->(g:Genre)RETURN count(g) AS num_of_genres;```You can try it out in Memgraph Lab at `localhost:3000`.With GQLAlchemy's query builder, the solution is:
matrix = ( match() .node(labels="Movie", variable="m") .to("OF_GENRE") .node(labels="Genre", variable="g") .where("m.title", "=", "Matrix, The (1999)") .return_({"count(g)": "num_of_genres"}) .execute() ) results = list(matrix) for result in results: print(result["num_of_genres"])
3
MIT
solutions/gqlalchemy-solutions.ipynb
pyladiesams/graphdatabases-gqlalchemy-beginner-mar2022
Exercise 3**Find out the title of the movies that the user with `id` 1 rated.**The correct Cypher query is:```MATCH (:User {id: 1})-[:RATED]->(m:Movie)RETURN m.title;```You can try it out in Memgraph Lab at `localhost:3000`.With GQLAlchemy's query builder, the solution is:
movies = ( match() .node(labels="User", variable="u") .to("RATED") .node(labels="Movie", variable="m") .where("u.id", "=", 1) .return_({"m.title": "movie"}) .execute() ) results = list(movies) for result in results: print(result["movie"])
Toy Story (1995) Grumpier Old Men (1995) Heat (1995) Seven (a.k.a. Se7en) (1995) Usual Suspects, The (1995) From Dusk Till Dawn (1996) Bottle Rocket (1996) Braveheart (1995) Rob Roy (1995) Canadian Bacon (1995) Desperado (1995) Billy Madison (1995) Clerks (1994) Dumb & Dumber (Dumb and Dumber) (1994) Ed Wood (1994) Sta...
MIT
solutions/gqlalchemy-solutions.ipynb
pyladiesams/graphdatabases-gqlalchemy-beginner-mar2022
Exercise 4**List 15 movies of 'Documentary' and 'Comedy' genres and sort them by title descending.**The correct Cypher query is:```MATCH (m:Movie)-[:OF_GENRE]->(:Genre {name: "Documentary"})MATCH (m)-[:OF_GENRE]->(:Genre {name: "Comedy"})RETURN m.titleORDER BY m.title DESCLIMIT 15;```You can try it out in Memgraph Lab...
movies = ( match() .node(labels="Movie", variable="m") .to("OF_GENRE") .node(labels="Genre", variable="g1") .where("g1.name", "=", "Documentary") .match() .node(labels="Movie", variable="m") .to("OF_GENRE") .node(labels="Genre", variable="g2") .where("g2.name", "=", "Comedy") ...
What the #$*! Do We Know!? (a.k.a. What the Bleep Do We Know!?) (2004) Union: The Business Behind Getting High, The (2007) Super Size Me (2004) Super High Me (2007) Secret Policeman's Other Ball, The (1982) Richard Pryor Live on the Sunset Strip (1982) Religulous (2008) Paper Heart (2009) Original Kings of Comedy, The ...
MIT
solutions/gqlalchemy-solutions.ipynb
pyladiesams/graphdatabases-gqlalchemy-beginner-mar2022
Exercise 5**Find out the minimum rating of the 'Star Wars: Episode I - The Phantom Menace (1999)' movie.**The correct Cypher query is:```MATCH (:User)-[r:RATED]->(:Movie {title: 'Star Wars: Episode I - The Phantom Menace (1999)'})RETURN min(r.rating);```You can try it out in Memgraph Lab at `localhost:3000`.With GQLAl...
rating = ( match() .node(labels="User") .to("RATED", variable="r") .node(labels="Movie", variable="m") .where("m.title", "=", "Star Wars: Episode I - The Phantom Menace (1999)") .return_({"min(r.rating)": "min_rating"}) .execute() ) results = list(rating) for result in results: print(r...
0.5
MIT
solutions/gqlalchemy-solutions.ipynb
pyladiesams/graphdatabases-gqlalchemy-beginner-mar2022
Can We Predict If a PGA Tour Player Won a Tournament in a Given Year?Golf is picking up popularity, so I thought it would be interesting to focus my project here. I set out to find what sets apart the best golfers from the rest. I decided to explore their statistics and to see if I could predict which golfers would win...
# Player Name: Name of the golfer # Rounds: The number of games that a player played # Fairway Percentage: The percentage of time a tee shot lands on the fairway # Year: The year in which the statistic was collected # Avg Distance: The average distance of the tee-shot # gir: (Green in Regulation) is met if any pa...
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
2. Data CleaningAfter looking at the dataframe, the data needs to be cleaned:-For the columns Top 10 and Wins, convert the NaNs to 0s-Change Top 10 and Wins into an int -Drop NaN values for players who do not have the full statistics-Change the columns Rounds into int-Change points to int-Remove the dollar sign ($) and...
# Replace NaN with 0 in Top 10 df['Top 10'].fillna(0, inplace=True) df['Top 10'] = df['Top 10'].astype(int) # Replace NaN with 0 in # of wins df['Wins'].fillna(0, inplace=True) df['Wins'] = df['Wins'].astype(int) # Drop NaN values df.dropna(axis = 0, inplace=True) # Change Rounds to int df['Rounds'] = df['Rounds']....
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
3. Exploratory Data Analysis
#collapse_output # Looking at the distribution of data f, ax = plt.subplots(nrows = 6, ncols = 3, figsize=(20,20)) distribution = df.loc[:,df.columns!='Player Name'].columns rows = 0 cols = 0 for i, column in enumerate(distribution): p = sns.distplot(df[column], ax=ax[rows][cols]) cols += 1 if cols == 3: ...
/usr/local/lib/python3.7/dist-packages/seaborn/distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms). war...
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From the distributions plotted, most of the graphs are normally distributed. However, we can observe that Money, Points, Wins, and Top 10s are all skewed to the right. This could be explained by the separation of the best players and the average PGA Tour player. The best players have multiple placings in the Top 10 wit...
#collapse_output # Looking at the number of players with Wins for each year win = df.groupby('Year')['Wins'].value_counts() win = win.unstack() win.fillna(0, inplace=True) # Converting win into ints win = win.astype(int) print(win)
Wins 0 1 2 3 4 5 Year 2010 166 21 5 0 0 0 2011 156 25 5 0 0 0 2012 159 26 4 1 0 0 2013 152 24 3 0 0 1 2014 142 29 3 2 0 0 2015 150 29 2 1 1 0 2016 152 28 4 1 0 0 2017 156 30 0 3 1 0 2018 158 26 5 3 0 0
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From this table, we can see that most players end the year without a win. It's pretty rare to find a player that has won more than once!
# Looking at the percentage of players without a win in that year players = win.apply(lambda x: np.sum(x), axis=1) percent_no_win = win[0]/players percent_no_win = percent_no_win*100 print(percent_no_win) #collapse_output # Plotting percentage of players without a win each year fig, ax = plt.subplots() bar_width = 0....
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From the box plot above, we can observe that the percentages of players without a win are around 80%. There was very little variation in the percentage of players without a win in the past 8 years.
#collapse_output # Plotting the number of wins on a bar chart fig, ax = plt.subplots() index = np.arange(2010, 2019) bar_width = 0.2 opacity = 0.7 def plot_bar(index, win, labels): plt.bar(index, win, bar_width, alpha=opacity, label=labels) # Plotting the bars rects = plot_bar(index, win[0], labels = '0 Wins') ...
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
By looking at the distribution of Wins each year, we can see that it is rare for most players to even win a tournament in the PGA Tour. Majority of players do not win, and a very few number of players win more than once a year.
# Percentage of people who did not place in the top 10 each year top10 = df.groupby('Year')['Top 10'].value_counts() top10 = top10.unstack() top10.fillna(0, inplace=True) players = top10.apply(lambda x: np.sum(x), axis=1) no_top10 = top10[0]/players * 100 print(no_top10)
Year 2010 17.187500 2011 25.268817 2012 23.157895 2013 18.888889 2014 16.477273 2015 18.579235 2016 20.000000 2017 15.789474 2018 17.187500 dtype: float64
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
By looking at the percentage of players that did not place in the top 10 by year, We can observe that only approximately 20% of players did not place in the Top 10. In addition, the range for these player that did not place in the Top 10 is only 9.47%. This tells us that this statistic does not vary much on a yearly ba...
# Who are some of the longest hitters distance = df[['Year','Player Name','Avg Distance']].copy() distance.sort_values(by='Avg Distance', inplace=True, ascending=False) print(distance.head())
Year Player Name Avg Distance 162 2018 Rory McIlroy 319.7 1481 2011 J.B. Holmes 318.4 174 2018 Trey Mullinax 318.3 732 2015 Dustin Johnson 317.7 350 2017 Rory McIlroy 316.7
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
Rory McIlroy is one of the longest hitters in the game, setting the average driver distance to be 319.7 yards in 2018. He was also the longest hitter in 2017 with an average of 316.7 yards.
# Who made the most money money_ranking = df[['Year','Player Name','Money']].copy() money_ranking.sort_values(by='Money', inplace=True, ascending=False) print(money_ranking.head())
Year Player Name Money 647 2015 Jordan Spieth 12030465.0 361 2017 Justin Thomas 9921560.0 303 2017 Jordan Spieth 9433033.0 729 2015 Jason Day 9403330.0 520 2016 Dustin Johnson 9365185.0
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
We can see that Jordan Spieth has made the most amount of money in a year, earning a total of 12 million dollars in 2015.
#collapse_output # Who made the most money each year money_rank = money_ranking.groupby('Year')['Money'].max() money_rank = pd.DataFrame(money_rank) indexs = np.arange(2010, 2019) names = [] for i in range(money_rank.shape[0]): temp = df.loc[df['Money'] == money_rank.iloc[i,0],'Player Name'] names.append(str(...
Money Player Name Year 2010 4910477.0 Matt Kuchar 2011 6683214.0 Luke Donald 2012 8047952.0 Rory McIlroy 2013 8553439.0 Tiger Woods 2014 8280096.0 Rory McIlroy 2015 12030465.0 Jordan Spieth 2016 9365185.0 Dustin Johnson 2017 9921560.0 Just...
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
With this table, we can examine the earnings of each player by year. Some of the most notable were Jordan Speith's earning of 12 million dollars and Justin Thomas earning the most money in both 2017 and 2018.
#collapse_output # Plot the correlation matrix between variables corr = df.corr() sns.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values, cmap='coolwarm') df.corr()['Wins']
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From the correlation matrix, we can observe that Money is highly correlated to wins along with the FedExCup Points. We can also observe that the fairway percentage, year, and rounds are not correlated to Wins. 4. Machine Learning Model (Classification)To predict winners, I used multiple machine learning models to explo...
#collapse # Importing the Machine Learning modules from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_curve, roc_auc_score from sklearn.metrics import confusion_matrix from sklearn.feature_selection import RFE from sklearn.metrics imp...
_____no_output_____
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
Preparing the Data for ClassificationWe know from the calculation above that the data for wins is skewed. Even without machine learning we know that approximately 83% of the players does not lead to a win. Therefore, we will be utilizing ROC AUC as the metric of these models
# Adding the Winner column to determine if the player won that year or not df['Winner'] = df['Wins'].apply(lambda x: 1 if x>0 else 0) # New DataFrame ml_df = df.copy() # Y value for machine learning is the Winner column target = df['Winner'] # Removing the columns Player Name, Wins, and Winner from the dataframe t...
Accuracy of Logistic regression classifier on training set: 0.90 Accuracy of Logistic regression classifier on test set: 0.91 0 1 0 345 8 1 28 38 precision recall f1-score support 0 0.92 0.98 0.95 353 1 0.83 0.58 0.68 6...
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From the logisitic regression, we got an accuracy of 0.9 on the training set and an accuracy of 0.91 on the test set. This was surprisingly accurate for a first run. However, the ROC AUC Score of 0.78 could be improved. Therefore, I decided to add more features as a way of possibly improving the model.
## Feature Engineering # Adding Domain Features ml_d = ml_df.copy() # Top 10 / Money might give us a better understanding on how well they placed in the top 10 ml_d['Top10perMoney'] = ml_d['Top 10'] / ml_d['Money'] # Avg Distance / Fairway Percentage to give us a ratio that determines how accurate and far a player h...
Accuracy of Logistic regression classifier on training set: 0.90 Accuracy of Logistic regression classifier on test set: 0.91 0 1 0 346 7 1 32 34 precision recall f1-score support 0 0.92 0.98 0.95 353 1 0.83 0.52 0.64 6...
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
From feature engineering, there were no improvements in the ROC AUC Score. In fact as I added more features, the accuracy and the ROC AUC Score decreased. This could signal to us that another machine learning algorithm could better predict winners.
#collapse_show ## Randon Forest Model def random_forest(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 10) clf = RandomForestClassifier(n_estimators=200).fit(X_train, y_train) y_pred = clf.predict(X_test) print('Accurac...
Accuracy of Random Forest classifier on training set: 1.00 Accuracy of Random Forest classifier on test set: 0.94 0 1 0 340 13 1 14 52 precision recall f1-score support 0 0.96 0.96 0.96 353 1 0.80 0.79 0.79 66 accur...
Apache-2.0
_notebooks/2021_04_28_PGA_Wins.ipynb
brennanashley/lambdalost
Monte Carlo MethodsIn this notebook, you will write your own implementations of many Monte Carlo (MC) algorithms. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. Part 0: Explore BlackjackEnvWe begin by importing the necessary packages.
import sys import gym import numpy as np from collections import defaultdict from plot_utils import plot_blackjack_values, plot_policy
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Use the code cell below to create an instance of the [Blackjack](https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py) environment.
env = gym.make('Blackjack-v0')
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Each state is a 3-tuple of:- the player's current sum $\in \{0, 1, \ldots, 31\}$,- the dealer's face up card $\in \{1, \ldots, 10\}$, and- whether or not the player has a usable ace (`no` $=0$, `yes` $=1$).The agent has two potential actions:``` STICK = 0 HIT = 1```Verify this by running the code cell below.
print(f"Observation space: \t{env.observation_space}") print(f"Action space: \t\t{env.action_space}")
Observation space: Tuple(Discrete(32), Discrete(11), Discrete(2)) Action space: Discrete(2)
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Execute the code cell below to play Blackjack with a random policy. (_The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to get some experience with the output that is returned as the agent interacts with the environment._)
for i_episode in range(3): state = env.reset() while True: print(state) action = env.action_space.sample() state, reward, done, info = env.step(action) if done: print('End game! Reward: ', reward) print('You won :)\n') if reward > 0 else print('You lost :(...
(19, 10, False) End game! Reward: 1.0 You won :) (14, 6, False) (15, 6, False) End game! Reward: 1.0 You won :) (16, 3, False) End game! Reward: 1.0 You won :)
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Part 1: MC PredictionIn this section, you will write your own implementation of MC prediction (for estimating the action-value function). We will begin by investigating a policy where the player _almost_ always sticks if the sum of her cards exceeds 18. In particular, she selects action `STICK` with 80% probability ...
def generate_episode_from_limit_stochastic(bj_env): episode = [] state = bj_env.reset() while True: probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8] action = np.random.choice(np.arange(2), p=probs) next_state, reward, done, info = bj_env.step(action) ...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Execute the code cell below to play Blackjack with the policy. (*The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to gain some familiarity with the output of the `generate_episode_from_limit_stochastic` function.*)
for i in range(5): print(generate_episode_from_limit_stochastic(env))
[((18, 2, True), 0, 1.0)] [((16, 5, False), 1, 0.0), ((18, 5, False), 1, -1.0)] [((13, 5, False), 1, 0.0), ((17, 5, False), 1, -1.0)] [((14, 4, False), 1, 0.0), ((17, 4, False), 1, -1.0)] [((20, 10, False), 0, -1.0)]
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Now, you are ready to write your own implementation of MC prediction. Feel free to implement either first-visit or every-visit MC prediction; in the case of the Blackjack environment, the techniques are equivalent.Your algorithm has three arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episo...
def mc_prediction_q(env, num_episodes, generate_episode, gamma=1.0): # initialize empty dictionaries of arrays returns_sum = defaultdict(lambda: np.zeros(env.action_space.n)) N = defaultdict(lambda: np.zeros(env.action_space.n)) Q = defaultdict(lambda: np.zeros(env.action_space.n)) R = defaultdict(l...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Use the cell below to obtain the action-value function estimate $Q$. We have also plotted the corresponding state-value function.To check the accuracy of your implementation, compare the plot below to the corresponding plot in the solutions notebook **Monte_Carlo_Solution.ipynb**.
# obtain the action-value function Q, R, N = mc_prediction_q(env, 500000, generate_episode_from_limit_stochastic) # obtain the corresponding state-value function V_to_plot = dict((k,(k[0]>18)*(np.dot([0.8, 0.2],v)) + (k[0]<=18)*(np.dot([0.2, 0.8],v))) \ for k, v in Q.items()) # plot the state-value function ...
Episode 500000/500000.
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Part 2: MC ControlIn this section, you will write your own implementation of constant-$\alpha$ MC control. Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`: Th...
def generate_episode_from_Q(env, Q, epsilon, n): """ generates an episode following the epsilon-greedy policy""" episode = [] state = env.reset() while True: if state in Q: action = np.random.choice(np.arange(n), p=get_props(Q[state], epsilon, n)) else: actio...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Use the cell below to obtain the estimated optimal policy and action-value function. Note that you should fill in your own values for the `num_episodes` and `alpha` parameters.
# obtain the estimated optimal policy and action-value function policy, Q = mc_control(env, 500000, 0.02)
Episode 500000/500000.
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Next, we plot the corresponding state-value function.
# obtain the corresponding state-value function V = dict((k,np.max(v)) for k, v in Q.items()) # plot the state-value function plot_blackjack_values(V)
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Finally, we visualize the policy that is estimated to be optimal.
# plot the policy plot_policy(policy)
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
jbdekker/deep-reinforcement-learning
Carregando dados dos usuários premium
df = pd.read_csv("../data/processed/premium_students.csv",parse_dates=[1,2],index_col=[0]) print(df.shape) df.head()
(6260, 2)
MIT
notebooks/1_0_EDA_BASE_A.ipynb
teoria/PD_datascience
--- Novas colunas auxiliares
df['diffDate'] = (df.SubscriptionDate - df.RegisteredDate) df['diffDays'] = [ item.days for item in df['diffDate']] df['register_time'] = df.RegisteredDate.map( lambda x : int(x.strftime("%H")) ) df['register_time_AM_PM'] = df.register_time.map( lambda x : 1 if x>=12 else 0) df['register_num_week'] = df.RegisteredD...
_____no_output_____
MIT
notebooks/1_0_EDA_BASE_A.ipynb
teoria/PD_datascience
--- Verificando distribuições
df.register_time.hist() df.subscription_time.hist() df.register_time_AM_PM.value_counts() df.subscription_time_AM_PM.value_counts() df.subscription_week_day.value_counts() df.diffDays.hist() df.diffDays.quantile([.25,.5,.75,.95])
_____no_output_____
MIT
notebooks/1_0_EDA_BASE_A.ipynb
teoria/PD_datascience
Separando os dados em 2 momentos.
lt_50 = df.loc[(df.diffDays <50) & (df.diffDays >3)] lt_50.diffDays.hist() lt_50.diffDays.value_counts() lt_50.diffDays.quantile([.25,.5,.75,.95]) range_0_3 = df.loc[(df.diffDays < 3)] range_3_18 = df.loc[(df.diffDays >= 3)&(df.diffDays < 18)] range_6_11 = df.loc[(df.diffDays >= 6) & (df.diffDays < 11)] range_11_18 = ...
_____no_output_____
MIT
notebooks/1_0_EDA_BASE_A.ipynb
teoria/PD_datascience
NumPy Operations ArithmeticYou can easily perform array with array arithmetic, or scalar with array arithmetic. Let's see some examples:
import numpy as np arr = np.arange(0,10) arr + arr arr * arr arr - arr arr**3
_____no_output_____
Apache-2.0
Numpy/Numpy Operations.ipynb
aaavinash85/100-Days-of-ML-
Universal Array Functions
#Taking Square Roots np.sqrt(arr) #Calcualting exponential (e^) np.exp(arr) np.max(arr) #same as arr.max() np.sin(arr) np.log(arr)
<ipython-input-3-a67b4ae04e95>:1: RuntimeWarning: divide by zero encountered in log np.log(arr)
Apache-2.0
Numpy/Numpy Operations.ipynb
aaavinash85/100-Days-of-ML-
シンプルなBERTの実装訓練済みのモデルを使用し、文章の一部の予測、及び2つの文章が連続しているかどうかの判定を行います。 ライブラリのインストールPyTorch-Transformers、および必要なライブラリのインストールを行います。
!pip install folium==0.2.1 !pip install urllib3==1.25.11 !pip install transformers==4.13.0
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
文章の一部の予測文章における一部の単語をMASKし、それをBERTのモデルを使って予測します。
import torch from transformers import BertForMaskedLM from transformers import BertTokenizer text = "[CLS] I played baseball with my friends at school yesterday [SEP]" tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") words = tokenizer.tokenize(text) print(words)
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
文章の一部をMASKします。
msk_idx = 3 words[msk_idx] = "[MASK]" # 単語を[MASK]に置き換える print(words)
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
単語を対応するインデックスに変換します。
word_ids = tokenizer.convert_tokens_to_ids(words) # 単語をインデックスに変換 word_tensor = torch.tensor([word_ids]) # テンソルに変換 print(word_tensor)
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
BERTのモデルを使って予測を行います。
msk_model = BertForMaskedLM.from_pretrained("bert-base-uncased") msk_model.cuda() # GPU対応 msk_model.eval() x = word_tensor.cuda() # GPU対応 y = msk_model(x) # 予測 result = y[0] print(result.size()) # 結果の形状 _, max_ids = torch.topk(result[0][msk_idx], k=5) # 最も大きい5つの値 result_words = tokenizer.convert_ids_to_tokens(ma...
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
文章が連続しているかどうかの判定BERTのモデルを使って、2つの文章が連続しているかどうかの判定を行います。 以下の関数`show_continuity`では、2つの文章の連続性を判定し、表示します。
from transformers import BertForNextSentencePrediction def show_continuity(text, seg_ids): words = tokenizer.tokenize(text) word_ids = tokenizer.convert_tokens_to_ids(words) # 単語をインデックスに変換 word_tensor = torch.tensor([word_ids]) # テンソルに変換 seg_tensor = torch.tensor([seg_ids]) nsp_model = BertForN...
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
`show_continuity`関数に、自然につながる2つの文章を与えます。
text = "[CLS] What is baseball ? [SEP] It is a game of hitting the ball with the bat [SEP]" seg_ids = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1, 1] # 0:前の文章の単語、1:後の文章の単語 show_continuity(text, seg_ids)
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
`show_continuity`関数に、自然につながらない2つの文章を与えます。
text = "[CLS] What is baseball ? [SEP] This food is made with flour and milk [SEP]" seg_ids = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1] # 0:前の文章の単語、1:後の文章の単語 show_continuity(text, seg_ids)
_____no_output_____
MIT
section_2/03_simple_bert.ipynb
derwind/bert_nlp
Binary Search or Bust> Binary search is useful for searching, but its implementation often leaves us searching for edge cases- toc: true - badges: true- comments: true- categories: [data structures & algorithms, coding interviews, searching]- image: images/binary_search_gif.gif Why should you care?Binary search is us...
#hide from typing import List, Dict, Tuple def binary_search(nums: List[int], target: int) -> int: """Vanilla Binary Search. Given a sorted list of integers and a target value, find the index of the target value in the list. If not present, return -1. """ # Left and right boundaries of the s...
_____no_output_____
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
Here're a few examples of running our binary search implementation on a list and target values
#hide_input nums = [1,4,9,54,100,123] targets = [4, 100, 92] for val in targets: print(f"Result of searching for {val} in {nums} : \ {binary_search(nums, val)}\n")
Result of searching for 4 in [1, 4, 9, 54, 100, 123] : 1 Result of searching for 100 in [1, 4, 9, 54, 100, 123] : 4 Result of searching for 92 in [1, 4, 9, 54, 100, 123] : -1
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
> Tip: Using the approach middle = left + (right - left) // 2 helps avoid overflow. While this isn&39;t a concern in Python, it becomes a tricky issue to debug in other programming languages such as C++. For more on overflow, check out this [article](https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearl...
def linear_search(nums: List[int], target: int) -> int: """Linear Search. Given a list of integers and a target value, return find the index of the target value in the list. If not present, return -1. """ for idx, elem in enumerate(nums): # Found the target value if elem == ta...
_____no_output_____
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
Let's see the time it takes linear search and binary search to find $99999$ in a sorted list of numbers from $[1, 1000000]$ - Linear Search
#hide_input %timeit linear_search(large_nums, target)
5.19 ms ± 26.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
- Binary Search
#hide_input %timeit binary_search(large_nums, target)
6.05 µs ± 46.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
Hopefully, that drives the point home :wink:. Naïve Binary Search ProblemsHere's a list of problems that can be solved using vanilla binary search (or slightly modifying it). Anytime you see a problem statement which goes something like _"Given a sorted list.."_ or _"Find the position of an element"_, think of using b...
def find_square_root(n: int) -> int: """Integer square root. Given a positive integer, return its square root. """ left, right = 1, n // 2 + 1 while left <= right: middle = left + (right - left) // 2 if middle * middle == n: return middle # Found an exact match ...
Square root of 1 is: 1 Square root of 4 is: 2 Square root of 8 is: 2 Square root of 33 is: 5 Square root of 100 is: 10
Apache-2.0
_notebooks/2022-05-03-binary-search-or-bust.ipynb
boolean-pandit/non-faangable-tokens
**INITIALIZATION:**- I use these three lines of code on top of my each notebooks because it will help to prevent any problems while reloading the same project. And the third line of code helps to make visualization within the notebook.
#@ INITIALIZATION: %reload_ext autoreload %autoreload 2 %matplotlib inline
_____no_output_____
MIT
06. VGGNet Architecture/Mini VGGNet.ipynb
ThinamXx/ComputerVision
**LIBRARIES AND DEPENDENCIES:**- I have downloaded all the libraries and dependencies required for the project in one particular cell.
#@ IMPORTING NECESSARY LIBRARIES AND DEPENDENCIES: from keras.models import Sequential from keras.layers import BatchNormalization from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.layers.core import Activation from keras.layers.core import Flatten from keras.l...
_____no_output_____
MIT
06. VGGNet Architecture/Mini VGGNet.ipynb
ThinamXx/ComputerVision
**VGG ARCHITECTURE:**- I will define the build method of Mini VGGNet architecture below. It requires four parameters: width of input image, height of input image, depth of image, number of class labels in the classification task. The Sequential class, the building block of sequential networks sequentially stack one lay...
#@ DEFINING VGGNET ARCHITECTURE: class MiniVGGNet: # Defining VGG Network. @staticmethod def build(width, height, depth, classes): # Defining Build Method. model = Sequential() # Initializing Sequential ...
_____no_output_____
MIT
06. VGGNet Architecture/Mini VGGNet.ipynb
ThinamXx/ComputerVision
**VGGNET ON CIFAR10**
#@ GETTING THE DATASET: ((trainX, trainY), (testX, testY)) = cifar10.load_data() # Loading Dataset. trainX = trainX.astype("float") / 255.0 # Normalizing Dataset. testX = testX.astype("float") / 255.0 # Normalizing Dataset. #@ PREPARING THE DATASE...
Epoch 1/40 782/782 [==============================] - 29s 21ms/step - loss: 1.6339 - accuracy: 0.4555 - val_loss: 1.1509 - val_accuracy: 0.5970 - lr: 0.0100 Epoch 2/40 782/782 [==============================] - 16s 21ms/step - loss: 1.1813 - accuracy: 0.5932 - val_loss: 0.9222 - val_accuracy: 0.6733 - lr: 0.0100 Epoch ...
MIT
06. VGGNet Architecture/Mini VGGNet.ipynb
ThinamXx/ComputerVision
**MODEL EVALUATION:**
#@ INITIALIZING MODEL EVALUATION: predictions = model.predict(testX, batch_size=64) # Getting Model Predictions. print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=labelNames)) # Inspecting Classification R...
_____no_output_____
MIT
06. VGGNet Architecture/Mini VGGNet.ipynb
ThinamXx/ComputerVision
내가 닮은 연예인은?사진 모으기얼굴 영역 자르기얼굴 영역 Embedding 추출연예인들의 얼굴과 거리 비교하기시각화회고1. 사진 모으기2. 얼굴 영역 자르기이미지에서 얼굴 영역을 자름image.fromarray를 이용하여 PIL image로 변환한 후, 추후에 시각화에 사용
# 필요한 모듈 불러오기 import os import re import glob import glob import pickle import pandas as pd import matplotlib.pyplot as plt import matplotlib.image as img import face_recognition %matplotlib inline from PIL import Image import numpy as np import face_recognition import os from PIL import Image dir_path = o...
_____no_output_____
MIT
celebrity.ipynb
peter1505/AIFFEL
Step3. 얼굴 영역의 임베딩 추출하기
# 얼굴 영역을 가지고 얼굴 임베딩 벡터를 구하는 함수 def get_face_embedding(face): return face_recognition.face_encodings(face, model='cnn') # 파일 경로를 넣으면 embedding_dict를 리턴하는 함수 def get_face_embedding_dict(dir_path): file_list = os.listdir(dir_path) embedding_dict = {} for file in file_list: try: ...
_____no_output_____
MIT
celebrity.ipynb
peter1505/AIFFEL
Step4. 모은 연예인들과 비교하기
# 이미지 간 거리를 구하는 함수 def get_distance(name1, name2): return np.linalg.norm(embedding_dict[name1]-embedding_dict[name2], ord=2) # 본인 사진의 거리를 확인해보자 print('내 사진끼리의 거리는?:', get_distance('이원재_01', '이원재_02')) # name1과 name2의 거리를 비교하는 함수를 생성하되, name1은 미리 지정하고, name2는 호출시에 인자로 받도록 합니다. def get_sort_key_func(name1): de...
순위 1 : 이름(이원재_01), 거리(0.27525162596989655) 순위 2 : 이름(euPhemia), 거리(0.38568278214648233) 순위 3 : 이름(공명), 거리(0.445581489047543) 순위 4 : 이름(김동완), 거리(0.44765017085662295) 순위 5 : 이름(강성필), 거리(0.4536061116328271)
MIT
celebrity.ipynb
peter1505/AIFFEL
Step5. 다양한 재미있는 시각화 시도해 보기
# 사진 경로 설정 mypicture1 = os.getenv('HOME')+'/aiffel/EXP_07_face_embedding/data/이원재_01.jpg' mypicture2 = os.getenv('HOME')+'/aiffel/EXP_07_face_embedding/data/이원재_02.jpg' mc= os.getenv('HOME')+'/aiffel/EXP_07_face_embedding/data/MC몽.jpg' gahee = os.getenv('HOME')+'/aiffel/EXP_07_face_embedding/data/가희.jpg' seven = os....
mypicture의 순위 순위 1 : 이름(사쿠라), 거리(0.36107689719729225) 순위 2 : 이름(트와이스나연), 거리(0.36906292012955577) 순위 3 : 이름(아이유), 거리(0.3703590842312735) 순위 4 : 이름(유트루), 거리(0.3809516850126146) 순위 5 : 이름(지호), 거리(0.3886670633997685)
MIT
celebrity.ipynb
peter1505/AIFFEL
5. Arbitrary Value Imputation this technique was derived from kaggle competition It consists of replacing NAN by an arbitrary value
import pandas as pd df=pd.read_csv("titanic.csv", usecols=["Age","Fare","Survived"]) df.head() def impute_nan(df,variable): df[variable+'_zero']=df[variable].fillna(0) df[variable+'_hundred']=df[variable].fillna(100) df['Age'].hist(bins=50)
_____no_output_____
Apache-2.0
Feature - Handling missing Values/5. Arbitrary Value Imputation.ipynb
deepakkum21/Feature-Engineering
Advantages Easy to implement Captures the importance of missingess if there is one Disadvantages Distorts the original distribution of the variable If missingess is not important, it may mask the predictive power of the original variable by distorting its distribution Hard to decide which value to use
impute_nan(df,'Age') df.head() print(df['Age'].std()) print(df['Age_zero'].std()) print(df['Age_hundred'].std()) print(df['Age'].mean()) print(df['Age_zero'].mean()) print(df['Age_hundred'].mean()) import matplotlib.pyplot as plt %matplotlib inline fig = plt.figure() ax = fig.add_subplot(111) df['Age'].plot(kind='kde',...
_____no_output_____
Apache-2.0
Feature - Handling missing Values/5. Arbitrary Value Imputation.ipynb
deepakkum21/Feature-Engineering
loading the libraries
import os import sys import pyvista as pv import trimesh as tm import numpy as np import topogenesis as tg import pickle as pk sys.path.append(os.path.realpath('..\..')) # no idea how or why this is not working without adding this to the path TODO: learn about path etc. from notebooks.resources import RES as res
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
loading the configuration of the test
# load base lattice CSV file lattice_path = os.path.relpath('../../data/macrovoxels.csv') macro_lattice = tg.lattice_from_csv(lattice_path) # load random configuration for testing config_path = os.path.relpath('../../data/random_lattice.csv') configuration = tg.lattice_from_csv(config_path) # load environment environ...
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
during optimization, arrays like these will be passed to the function:
variable = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0,...
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
calling the objective function
# input is the decision variables, a referenca lattice, the visibility vectors, their magnitude (i.e. direct normal illuminance for daylight), and a mesh of the environment # output is the total objective score in 100s of lux on the facade, and 100s of lux per each surface (voxel roofs) crit, voxcrit = res.crit_2_DL(va...
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
generating mesh
meshes, _, _ = res.construct_vertical_mesh(configuration, configuration.unit) facademesh = tm.util.concatenate(meshes)
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
visualisation
p = pv.Plotter(notebook=True) configuration.fast_vis(p,False,False,opacity=0.1) # p.add_arrows(ctr_per_ray, -ray_per_ctr, mag=5, show_scalar_bar=False) # p.add_arrows(ctr_per_ray, nrm_per_ray, mag=5, show_scalar_bar=False) # p.add_mesh(roof_mesh) p.add_mesh(environment_mesh) p.add_mesh(facademesh, cmap='fire', scalars...
_____no_output_____
MIT
notebooks/Toy_problem/Tp4_criterium_2_daylighting_potential.ipynb
Maxketelaar/thesis
Módulo e pacote
# importando módulo, math para operações matemáticas import math # verificando todos os metodos do modulo dir(math) # usando um dos metódos do módulo, sqrt, raiz quadrada print(math.sqrt(25)) # importando apenas uma função do módulo math from math import sqrt # usando este método, como importou somente a função do mód...
_____no_output_____
Apache-2.0
Cap04/.ipynb_checkpoints/modulos_pacotes-checkpoint.ipynb
carlos-freitas-gitHub/python-analytics
Notebook Content1. [Import Packages](1)1. [Helper Functions](2)1. [Input](3)1. [Model](4)1. [Prediction](5)1. [Complete Figure](6) 1. Import PackagesImporting all necessary and useful packages in single cell.
import numpy as np import keras import tensorflow as tf from numpy import array from keras.models import Sequential from keras.layers import LSTM from keras.layers import Dense from keras.layers import Flatten from keras.layers import TimeDistributed from keras.layers.convolutional import Conv1D from keras.layers.convo...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
2. Helper FunctionsDefining Some helper functions which we will need later in code
# split a univariate sequence into samples def split_sequence(sequence, n_steps, look_ahead=0): X, y = list(), list() for i in range(len(sequence)-look_ahead): # find the end of this pattern end_ix = i + n_steps # check if we are beyond the sequence if end_ix > len(sequence)-1-lo...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
3. Input3-1. Sequence PreProcessingSplitting and Reshaping
n_features = 1 n_seq = 20 n_steps = 1 def sequence_preprocessed(values, sliding_window, look_ahead=0): # Normalization normalized,scaler = normalize(values) # Try the following if randomizing the sequence: # random.seed('sam') # set the seed # raw_seq = random.sample(raw_seq, 100) ...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
3-2. Providing SequenceDefining a raw sequence, sliding window of data to consider and look ahead future timesteps
# define input sequence sequence_val = [i for i in range(5000,7000)] sequence_train = [i for i in range(1000,2000)] sequence_test = [i for i in range(10000,14000)] # choose a number of time steps for sliding window sliding_window = 20 # choose a number of further time steps after end of sliding_window till target sta...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
4. Model4-1. Defining LayersAdding 1D Convolution, Max Pooling, LSTM and finally Dense (MLP) layer
# define model model = Sequential() model.add(TimeDistributed(Conv1D(filters=64, kernel_size=1, activation='relu'), input_shape=(None, n_steps, n_features) )) model.add(TimeDistributed(MaxPooling1D(pool_size=1))) model.add(TimeDistributed(Flatten())) model.add(LSTM(5...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
4-2. Training ModelDefined early stop, can be used in callbacks param of model fit, not using for now since it's not recommended at first few iterations of experimentation with new data
# Defining multiple metrics, leaving it to a choice, some may be useful and few may even surprise on some problems metrics = ['mean_squared_error', 'mean_absolute_error', 'mean_absolute_percentage_error', 'mean_squared_logarithmic_error', 'logcosh'] # Compiling Model model.c...
Train on 960 samples, validate on 1960 samples Epoch 1/100 Epoch 2/100 Epoch 3/100 Epoch 4/100 Epoch 5/100 Epoch 6/100 Epoch 7/100 Epoch 8/100 Epoch 9/100 Epoch 10/100 Epoch 11/100 Epoch 12/100 Epoch 13/100 Epoch 14/100 Epoch 15/100 Epoch 16/100 Epoch 17/100 Epoch 18/100 Epoch 19/100 Epoch 20/100 Epoch 21/100 Epoch 22/...
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
4-3. Evaluating ModelPlotting Training and Validation mean square error
# Plot Errors for metric in metrics: xAxis = history.epoch yAxes = {} yAxes["Training"]=history.history[metric] yAxes["Validation"]=history.history['val_'+metric] plot_multi_graph(xAxis,yAxes, title=metric,xAxisLabel='Epochs')
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
5. Prediction5-1. Single Value PredictionPredicting a single value slided 20 (our provided figure for look_ahead above) values ahead
# demonstrate prediction x_input = array([i for i in range(100,120)]) print(x_input) x_input = x_input.reshape((1, n_seq, n_steps, n_features)) yhat = model.predict(x_input) print(yhat)
[100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119] [[105.82992]]
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
5-2. Sequence PredictionPredicting complete sequence (determining closeness to target) based on data change variable for any other sequence though
# Prediction from Training Set predict_train = model.predict(X_train) # Prediction from Test Set predict_test = model.predict(X_test) """ df = pd.DataFrame(({"normalized y_train":y_train.flatten(), "normalized predict_train":predict_train.flatten(), "actual y_train":scaler_trai...
_____no_output_____
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
6. Complete FigureData, Target, Prediction - all in one single graph
xAxis = [i for i in range(len(y_train))] yAxes = {} yAxes["Data"]=sequence_train[sliding_window:len(sequence_train)-look_ahead] yAxes["Target"]=scaler_train.inverse_transform(y_train) yAxes["Prediction"]=scaler_train.inverse_transform(predict_train) plot_multi_graph(xAxis,yAxes,title='') xAxis = [i for i in range(len(...
['mean_squared_error', 'mean_absolute_error', 'mean_absolute_percentage_error', 'mean_squared_logarithmic_error', 'logcosh'] 3960/3960 [==============================] - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: - ETA: ...
MIT
BareBones 1D CNN LSTM MLP - Sequence Prediction.ipynb
codeWhim/Sequence-Prediction
**Libraries**
from google.colab import drive drive.mount('/content/drive') # *********************** # *****| LIBRARIES |***** # *********************** %tensorflow_version 2.x import pandas as pd import numpy as np import os import json from sklearn.model_selection import train_test_split import tensorflow as tf from keras.preproc...
_____no_output_____
MIT
models/Character_Level_CNN.ipynb
TheBlueEngineer/Serene-1.0
**Utility functions**
# ***************** # *** GET FILES *** # ***************** def getFiles( driverPath, directory, basename, extension): # Define a function that will return a list of files pathList = [] # Declare an empty array directory = os.path.join( driverPath, directory) # ...
_____no_output_____
MIT
models/Character_Level_CNN.ipynb
TheBlueEngineer/Serene-1.0
**Gather the path to files**
# *********************************** # *** GET THE PATHS FOR THE FILES *** # *********************************** # Path to the content of the Google Drive driverPath = "/content/drive/My Drive" # Sub-directories in the driver paths = ["processed/depression/submission", "processed/depression/comment", ...
Gathered 750 files from processed/depression/submission. Gathered 2892 files from processed/depression/comment. Gathered 1311 files from processed/AskReddit/submission. Gathered 5510 files from processed/AskReddit/comment.
MIT
models/Character_Level_CNN.ipynb
TheBlueEngineer/Serene-1.0
**Gather the data from files**
# ************************************ # *** GATHER THE DATA AND SPLIT IT *** # ************************************ # Local variables rand_state_splitter = 1000 test_size = 0.2 min_files = [ 750, 0, 1300, 0] max_words = [ 50, 0, 50, 0] limit_packets = [300, 0, 300, 0] message = ["Depression submissions", "Depression...
Build the Pandas DataFrames for each category. Word min set to: 50. Lists created with 300000/349305 (85.88%) data objects. Rest ignored due to minimum words limit of 50 or the limit of 300000 data objects maximum. Added 300000 samples to data list: Depression submissions. Word min set to: 0. Lists created with 0/0 (0...
MIT
models/Character_Level_CNN.ipynb
TheBlueEngineer/Serene-1.0
**Process the data at a character-level**
# ******************************* # *** CONVERT STRING TO INDEX *** # ******************************* print("Convert the strings to indexes.") tk = Tokenizer(num_words = None, char_level = True, oov_token='UNK') tk.fit_on_texts(x_train) print("Original:", x_train[0]) # ********************************* # *** CONSTRUCT ...
Convert the strings to indexes. Original: i did not think i had have to post in this subreddit i just feel empty and completely alone i am hanging out with friends but nothing makes me feel happy as i used to be i know people generally have it worse i just want someone to talk to and just be silly with Construct a new...
MIT
models/Character_Level_CNN.ipynb
TheBlueEngineer/Serene-1.0