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
Now let's compare the posterior computed by the Diagonal Normal guide vs the Multivariate Normal guide. Note that the multivariate distribution is more dispresed than the Diagonal Normal.
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 6)) fig.suptitle("Cross-sections of the Posterior Distribution", fontsize=16) sns.kdeplot(svi_samples["bA"], svi_samples["bR"], ax=axs[0], label="SVI (Diagonal Normal)") sns.kdeplot(svi_mvn_samples["bA"], svi_mvn_samples["bR"], ax=axs[0], shade=True, label="SVI (Mu...
_____no_output_____
MIT
examples/bayesian_regression_ii.ipynb
fehiepsi/website
and the Multivariate guide with the posterior computed by HMC. Note that the Multivariate guide better captures the true posterior.
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12, 6)) fig.suptitle("Cross-sections of the Posterior Distribution", fontsize=16) sns.kdeplot(hmc_samples["bA"], hmc_samples["bR"], ax=axs[0], shade=True, label="HMC") sns.kdeplot(svi_mvn_samples["bA"], svi_mvn_samples["bR"], ax=axs[0], label="SVI (Multivariate Normal)...
_____no_output_____
MIT
examples/bayesian_regression_ii.ipynb
fehiepsi/website
1. Google Play Store apps and reviewsMobile apps are everywhere. They are easy to create and can be lucrative. Because of these two factors, more and more apps are being developed. In this notebook, we will do a comprehensive analysis of the Android app market by comparing over ten thousand apps in Google Play across ...
# Read in dataset import pandas as pd apps_with_duplicates = pd.read_csv('datasets/apps.csv') # Drop duplicates apps = apps_with_duplicates.drop_duplicates() # Print the total number of apps print('Total number of apps in the dataset = ', len(apps['App'])) # Have a look at a random sample of 5 rows n = 5 apps.sample...
Total number of apps in the dataset = 9659
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
2. Data cleaningThe four features that we will be working with most frequently henceforth are Installs, Size, Rating and Price. The info() function (from the previous task) told us that Installs and Price columns are of type object and not int64 or float64 as we would expect. This is because the column contains some ...
# List of characters to remove chars_to_remove = ['+' , ',' , '$'] # List of column names to clean cols_to_clean = ['Installs' , 'Price'] # Loop for each column for col in cols_to_clean: # Replace each character with an empty string for char in chars_to_remove: apps[col] = apps[col].str.replace(char, '...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
3. Exploring app categoriesWith more than 1 billion active users in 190 countries around the world, Google Play continues to be an important distribution platform to build a global audience. For businesses to get their apps in front of users, it's important to make them more quickly and easily discoverable on Google P...
import plotly plotly.offline.init_notebook_mode(connected=True) import plotly.graph_objs as go # Print the total number of unique categories num_categories = len(apps["Category"].unique()) print('Number of categories = ', num_categories) # Count the number of apps in each 'Category' and sort them in descending order ...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
4. Distribution of app ratingsAfter having witnessed the market share for each category of apps, let's see how all these apps perform on an average. App ratings (on a scale of 1 to 5) impact the discoverability, conversion of apps as well as the company's overall brand image. Ratings are a key performance indicator of...
# Average rating of apps avg_app_rating = apps['Rating'].mean() print('Average app rating = ', avg_app_rating) # Distribution of apps according to their ratings data = [go.Histogram( x = apps['Rating'] )] # Vertical dashed line to indicate the average app rating layout = {'shapes': [{ 'type' :'l...
Average app rating = 4.173243045387994
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
5. Size and price of an appLet's now examine app size and app price. For size, if the mobile app is too large, it may be difficult and/or expensive for users to download. Lengthy download times could turn users off before they even experience your mobile app. Plus, each user's device has a finite amount of disk space....
%matplotlib inline import seaborn as sns sns.set_style("darkgrid") apps_with_size_and_rating_present = apps[(apps['Rating'].notnull()) & (apps["Size"].notnull())] # Subset for categories with at least 250 apps large_categories = apps_with_size_and_rating_present.groupby('Category').filter(lambda x: len(x) >= 250).rese...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
6. Relation between app category and app priceSo now comes the hard part. How are companies and developers supposed to make ends meet? What monetization strategies can companies use to maximize profit? The costs of apps are largely based on features, complexity, and platform.There are many factors to consider when sel...
import matplotlib.pyplot as plt fig, ax = plt.subplots() fig.set_size_inches(15, 8) # Select a few popular app categories popular_app_cats = apps[apps.Category.isin(['GAME', 'FAMILY', 'PHOTOGRAPHY', 'MEDICAL', 'TOOLS', 'FINANCE', '...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
7. Filter out "junk" appsIt looks like a bunch of the really expensive apps are "junk" apps. That is, apps that don't really have a purpose. Some app developer may create an app called I Am Rich Premium or most expensive app (H) just for a joke or to test their app development skills. Some developers even do this with...
# Select apps priced below $100 apps_under_100 = popular_app_cats[popular_app_cats['Price'] < 100] fig, ax = plt.subplots() fig.set_size_inches(15, 8) # Examine price vs category with the authentic apps ax = sns.stripplot(x=apps_under_100['Price'], y=apps_under_100['Category'], data=apps_under_100, ...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
8. Popularity of paid apps vs free appsFor apps in the Play Store today, there are five types of pricing strategies: free, freemium, paid, paymium, and subscription. Let's focus on free and paid apps only. Some characteristics of free apps are:Free to download.Main source of income often comes from advertisements.Ofte...
trace0 = go.Box( # Data for paid apps y=apps[apps['Type'] == 'Paid']['Installs'], name = 'Paid' ) trace1 = go.Box( # Data for free apps y=apps[apps['Type'] == 'Free']['Installs'], name = 'Free' ) layout = go.Layout( title = "Number of downloads of paid apps vs. free apps", yaxis = dict...
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
9. Sentiment analysis of user reviewsMining user review data to determine how people feel about your product, brand, or service can be done using a technique called sentiment analysis. User reviews for apps can be analyzed to identify if the mood is positive, negative or neutral about that app. For example, positive w...
# Load user_reviews.csv reviews_df = pd.read_csv('datasets/user_reviews.csv') # Join and merge the two dataframe merged_df = pd.merge(apps, reviews_df, on = 'App', how = "inner") # Drop NA values from Sentiment and Translated_Review columns merged_df = merged_df.dropna(subset=['Sentiment', 'Translated_Review']) sns....
_____no_output_____
MIT
notebook.ipynb
akh20/The-Android-App-Market-on-Google-Play
# !pip3 install kaggle from google.colab import files files.upload() !mkdir ~/.kaggle !cp kaggle.json ~/.kaggle/ !chmod 600 ~/.kaggle/kaggle.json !kaggle competitions download -c toxic-comments-classification-apdl-2021 !ls import pandas as pd import numpy as np from sklearn.metrics import * from sklearn.model_selectio...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
Bag of words
from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer from nltk import ngrams vec = CountVectorizer(ngram_range=(1, 2)) # строим BoW для слов bow = vec.fit_transform(x_train) vec2 = CountVectorizer(ngram_range=(1, 2)) # строим BoW для слов bow2 = vec2.fit_tran...
Warning: Looks like you're using an outdated API Version, please consider updating (server 1.5.12 / client 1.5.4) 100% 23.6k/23.6k [00:09<00:00, 2.45kB/s] Successfully submitted to Toxic comments classification
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer vec = TfidfVectorizer(ngram_range=(1, 1)) bow = vec.fit_transform(x_train) clf2 = LogisticRegression(random_state=1, max_iter = 500) clf2.fit(bow, y_train) pred = clf2.predict(vec.transform(x_test)) print(classification_report(pred, y_test)) tf_idf = test.copy...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
Symbol n-Grams
vec = CountVectorizer(analyzer='char', ngram_range=(1, 5)) bowsimb = vec.fit_transform(x_train) from sklearn.preprocessing import MaxAbsScaler scaler = MaxAbsScaler() scaler.fit(bowsimb) bowsimb = scaler.transform(bowsimb) clf3 = LogisticRegression(random_state=0, max_iter=1000) clf3.fit(bowsimb, y_train) pred = clf...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
FastText
!pip3 install fasttext import fasttext with open('ft_train_data.txt', 'w') as f: for pair in list(zip(x_train, y_train)): text, label = pair f.write(f'__label__{int(label)} {text.lower()}\n') with open('ft_test_data.txt', 'w') as f: for pair in list(zip(x_test, y_test)): text, l...
Warning: Looks like you're using an outdated API Version, please consider updating (server 1.5.12 / client 1.5.4) 100% 23.6k/23.6k [00:07<00:00, 3.36kB/s] Successfully submitted to Toxic comments classification
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
CNN
from torchtext.legacy import data pd.read_csv('train_data.csv.zip', compression='zip') !unzip train_data.csv.zip !unzip test_data.csv.zip # классы Field и LabelField отвечают за то, как данные будут храниться и обрабатываться при считывании TEXT = data.Field(tokenize='spacy') # spacy -- значит, токенизацию будет делат...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
word2vec> not done, skip this model
! wget https://nlp.stanford.edu/data/glove.6B.zip with open("alice.txt", 'r', encoding='utf-8') as f: text = f.read() text = re.sub('\n', ' ', text) sents = sent_tokenize(text) punct = '!"#$%&()*+,-./:;<=>?@[\]^_`{|}~„“«»†*—/\-‘’' clean_sents = [] for sent in sents: s = [w.lower().strip(punct) for w in sent....
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
bow on random forest![photo_2021-10-24_13-09-26.jpg](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHR...
! pip install pymystem3 ! pip install --force-reinstall pymorphy2 !pip install pymorphy2-dicts-ru import pymorphy2 import re morph = pymorphy2.MorphAnalyzer() # убираем все небуквенные символы regex = re.compile("[А-Яа-яA-z]+") def words_only(text, regex=regex): try: return regex.findall(text.lower(...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
nor run -too slow
# rnd_reg = RandomForestClassifier( ) # # hyper-parameter space # param_grid_RF = { # 'n_estimators' : [10,20,50,100,200,500,1000], # 'max_features' : [0.6,0.8,"auto","sqrt"], # } # search_two = HalvingGridSearchCV(rnd_reg, param_grid_RF, factor=5, scoring='accuracy', # n_jobs=-1, random...
_____no_output_____
MIT
07 NLP/kaggle hw/solution.ipynb
ksetdekov/HSE_DS
Looping with WhileNow let us look at looping with `while` in Python, one of the ways in which we can repeatedly perform some action(s). While loops continue
n = 43 while n > 2: n -= 1 if n % 2 == 0: continue print("n = ", n, "; Testing if number is prime.")
n = 41 ; Testing if number is prime. n = 39 ; Testing if number is prime. n = 37 ; Testing if number is prime. n = 35 ; Testing if number is prime. n = 33 ; Testing if number is prime. n = 31 ; Testing if number is prime. n = 29 ; Testing if number is prime. n = 27 ; Testing if number is prime. n = 25 ; Testin...
Apache-2.0
notebooks/WhileLoop.ipynb
gcallah/IntroPython
else
n = 1 while n < 8: if n == 5: break print("loop1", n ** 2) n += 1 print("Got to 8") n = 1 while n < 8: if n == 5: break print("loop2", n ** 2) n += 1 else: print("Got to 8") def process_station_data(station_no): return station_no % 123 == 121 error = False num_sta...
_____no_output_____
Apache-2.0
notebooks/WhileLoop.ipynb
gcallah/IntroPython
[Surprise · A Python scikit for recommender systems.](http://surpriselib.com/)
# !pip install scikit-surprise # !conda install -c conda-forge scikit-surprise from surprise import SVD from surprise import Dataset from surprise.model_selection import cross_validate # Load the movielens-100k dataset (download it if needed). data = Dataset.load_builtin('ml-100k') # Use the famous SVD algorithm. alg...
_____no_output_____
MIT
surprise/surprise.ipynb
neoville/Kaggle
Satellite sea surface temperatures along the West Coast of the United States during the 2014–2016 northeast Pacific marine heat waveIn 2016 we published a [paper](https://agupubs.onlinelibrary.wiley.com/doi/10.1002/2016GL071039) on the heat wave in the ocean off the California coastThis analysis was the last time I u...
import warnings import numpy as np import pandas as pd import xarray as xr import fsspec import matplotlib.pyplot as plt warnings.simplefilter('ignore') # filter some warning messages xr.set_options(display_style="html") #display dataset nicely dir_out = './../../data/zarr_testing/' file_aws = 'https://mur-sst.s3.us-...
_____no_output_____
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
Just plot a random day to make sure it looks correct
subset.analysed_sst[0,:,:].plot()
_____no_output_____
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
How big is this dataset?- Because xarray uses lazy loading, we have access to this entire dataset but it only loads what it needs to for calculations
print('GB data = ',subset.nbytes/(1024 * 1024 * 1024))
GB data = 201.89575985074043
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
Caluculate the Monthly Sea Surface Temperature Anomalies
sst_monthly = subset.resample(time='1MS').mean('time',keep_attrs=True,skipna=False) climatology_mean_monthly = sst_monthly.sel(time=slice(date1,date2)).groupby('time.month').mean('time',keep_attrs=True,skipna=False) sst_anomaly_monthly = sst_monthly.groupby('time.month')-climatology_mean_monthly #take out annual mea...
_____no_output_____
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
Let's try and re-do figure 2 which uses 5-day average SST anomalies
sst_5day = subset.resample(time='5D').mean('time',keep_attrs=True,skipna=False) climatology_mean_5day = sst_5day.sel(time=slice(date1,date2)).groupby('time.day').mean('time',keep_attrs=True,skipna=False) sst_anomaly_5day = sst_5day.groupby('time.day')-climatology_mean_5day #take out annual mean to remove trends sst...
_____no_output_____
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
Switch to same data, but it is chunked differently- it is optimized for timeseries rather than spatial analysis
ds_sst = xr.open_zarr(file_aws_time,consolidated=True) ds_sst %%time sst_newport_nearshore = ds_sst.analysed_sst.sel(lat=44.6,lon=-124.11,method='nearest').rolling(time=30, center=True).mean().load() sst_newport_offshore = ds_sst.analysed_sst.sel(lat=44.6,lon=-134.11,method='nearest').rolling(time=30, center=True).mean...
_____no_output_____
Apache-2.0
sst_science/West_Coast_HeatWave.ipynb
sevfour/cloud_science
Minimal end-to-end causal analysis with ```cause2e```This notebook shows a minimal example of how ```cause2e``` can be used as a standalone package for end-to-end causal analysis. It illustrates how we can proceed in stringing together many causal techniques that have previously required fitting together various algor...
import os from cause2e import path_mgr, knowledge, discovery
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Set up paths to data and output directoriesThis step is conveniently handled by the ```PathManager``` class, which avoids having to wrestle with paths throughout the multistep causal analysis. If we want to perform the analysis in a directory ```'dirname'``` that contains ```'dirname/data'``` and ```'dirname/output'``...
cwd = os.getcwd() wd = os.path.dirname(cwd) paths = path_mgr.PathManagerQuick(experiment_name='sprinkler', data_name='sprinkler.csv', directory=wd )
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Learn the causal graph from data and domain knowledgeModel-based causal inference leverages qualitative knowledge about pairwise causal connections to obtain unbiased estimates of quantitative causal effects. The qualitative knowledge is encoded in the causal graph, so we must recover this graph before we can start ac...
learner = discovery.StructureLearner(paths)
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Read the dataThe ```StructureLearner``` has reading methods for csv and parquet files.
learner.read_csv(index_col=0)
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
The first step in the analysis should be an assessment of which variables we are dealing with. In the sprinkler dataset, each sample tells us - the current season- whether it is raining- whether our lawn sprinkler is activated- whether our lawn is slippery- whether our lawn is wet.
learner.variables
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Preprocess the dataAs mentioned above, currently there are problems in the estimation step with categorical data, so we use this occasion to showcase ```cause2e```'s built-in preprocessing functionalities. We define a function that replaces instances of ```'Summer'``` by 1, and instances of ```'Spring'``` by 0. Afterw...
def is_summer(data, col_name): return (data[col_name] == 'Summer').apply(int) learner.combine_variables(name='Season_binary', func=is_summer, input_cols=['Season'], keep_old=False)
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
It necessary to communicate to the ```StructureLearner``` if the variables are discrete, continuous, or both. We check how many unique values each variable takes on in our sample and deduce that all variables are discrete.
learner.data.nunique()
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
This information is passed to the ```StructureLearner``` by indicating the exact sets of discrete and continuous variables.
learner.discrete = learner.variables learner.continuous = set()
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Provide domain knowledgeHumans can often infer parts of the causal graph from domain knowledge. The nodes are always just the variables in the data, so the problem of finding the right graph comes down to selecting the right edges between them. As a reminder: The correct causal graph has an edge from variable A to var...
edge_creator = knowledge.EdgeCreator() edge_creator.forbid_edges_from_groups({'Season_binary'}, incoming=learner.variables) edge_creator.forbid_edges_from_groups({'Slippery'}, outgoing=learner.variables) edge_creator.require_edge('Sprinkler', 'Wet') edge_creator.forbid_edge('Sprinkler', 'Rain')
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
There is a fourth way of passing knowledge which is not used in learning the graph, but in validating the quantitative estimates resulting from our end-to-end causal analysis. We often know beforehand what some of the quantitative effects should look like, e.g.- turning the sprinkler on should have a positive overall e...
validation_creator = knowledge.ValidationCreator() validation_creator.add_expected_effect(('Sprinkler', 'Wet', 'nonparametric-ate'), ('greater', 0)) validation_creator.add_expected_effect(('Wet', 'Slippery', 'nonparametric-ate'), ('greater', 0)) validation_creator.add_expected_effect(('Sprinkler', 'Rain', 'nonparametri...
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
We pass the knowledge to the ```StructureLearner``` and check if it has been correctly received.
learner.set_knowledge(edge_creator=edge_creator, validation_creator=validation_creator)
==================== Showing knowledge for graph search. Causal graph constructed from domain knowledge: (Edges required by domain knowledge in red, remaining allowed edges dotted)
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
Apply a structure learning algorithmNow that the ```StructureLearner``` has received the data and the domain knowledge, we can try to recover the original graph using causal discovery methods provided by the internally called ```py-causal``` package. There are many parameters that can be tuned (choice of algorithm, se...
learner.run_quick_search()
Remember to stop the JVM after you are completely done. Proposed causal graph (edges required by domain knowledge in red, undirected edges in blue):
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
The output of the search is a proposed causal graph. We can ignore the warning about stopping the Java Virtual Machine (needed by ```py-causal``` which is a wrapper around the ```TETRAD``` software that is written in Java) if we do not run into any problems. If the algorithm cannot orient all edges, we need to do this ...
learner.run_all_quick_analyses()
Showing and saving heatmaps of the causal estimates.
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
The output consists of a detailed analysis of the causal effects in our system. HeatmapsThe first three images are heatmaps, where the (i, j)-entry shows the causal effect of variable i on variable j. The three heatmaps differ in the type of causal effect that they are describing: - **Average Treatment Effect (ATE)**:...
1 - sum(learner.data['Rain']) / len(learner.data)
_____no_output_____
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
We recover the same number of 0.638. Additionally, we can change our data to consist only of the instances where it is not raining. If we now repeat the causal analysis, the effect is indeed 1 (skip after the warnings that are caused by the now degenerate dataset). This procedure can be generalized to analyzing other c...
learner.data = learner.data[learner.data['Rain']==0] learner.run_all_quick_analyses()
C:\Users\D.Gruenbaum\Anaconda3\envs\test\lib\site-packages\statsmodels\regression\linear_model.py:1830: RuntimeWarning: divide by zero encountered in double_scalars return np.sqrt(eigvals[0]/eigvals[-1]) C:\Users\D.Gruenbaum\Anaconda3\envs\test\lib\site-packages\statsmodels\base\model.py:1362: RuntimeWarning: invalid...
MIT
examples/minimal_end_to_end_causal_analysis.ipynb
MLResearchAtOSRAM/cause2e
The data and the description:https://archive.ics.uci.edu/ml/datasets/APS+Failure+at+Scania+TrucksAbstract: The datasets' positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS.
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder pd.options.display.max_columns = None import warnings warnings.filterwarnings('ignore') df_original = p...
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
The set is very unbalanced with one label (0) being more frequent than the other (1). The algorithm needs to adjust for that. It is done using 'class_weight' hyperparameter which is the ratio of number of 0s to 1s in the label.
df = df_original.copy() from sklearn.model_selection import train_test_split X, y = df.iloc[:,1:], df.iloc[:,0] X_tr, X_t, y_tr, y_t = train_test_split(X, y, test_size = 0.2, random_state = 0) weight = sum(y_tr == 0)/sum(y_tr == 1) lr_full = LogisticRegression(C = 1, class_weight={1:weight}, random_state = 0) lr_full....
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
13632 is our basic score. We'll use it as a reference for further optimizations.The data seemed to be scaled but let's apply scaling to the data just in case.
#testing scaling df = df_original.copy() from sklearn.preprocessing import MinMaxScaler scaler_minmax = MinMaxScaler() X, y = df.iloc[:,1:], df.iloc[:,0] X_scaled = scaler_minmax.fit_transform(X.values) X_tr, X_t, y_tr, y_t = train_test_split(X_scaled, y, test_size = 0.2, random_state = 0) weight = sum(y_tr == 0)/sum...
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
MinMaxScaler slightly improved the result. Let's tune the 'C', a hyperparameter (parameter) of the Logistic Regression algorithm.
#tuning hyperparameters for Logistic Regression df = df_original.copy() X, y = df.iloc[:,1:], df.iloc[:,0] X_tr, X_t, y_tr, y_t = train_test_split(X, y, test_size = 0.2, random_state = 0) Cs = list(np.arange(0.1, 0.5, 0.1)) weight = sum(y_tr == 0)/sum(y_tr == 1) for C_ in Cs: lr_full = LogisticRegression(C = C_, ...
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
C = 0.1 gives the best score. Let's try another algorithm. Maybe Random Forest will perfom better.
#check algorithm with all NAs replaced with mean column values (none rows/columns dropped) df = df_original.copy() X, y = df.iloc[:,1:], df.iloc[:,0] #split into train and test from sklearn.model_selection import train_test_split X_tr, X_t, y_tr, y_t = train_test_split(X, y, test_size = 0.2, random_state = 0) from skl...
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
61938 is significanlty worse. It seems Logistic Regression gives us the best score.We need to train it on the full training data set and fit the actual test set to get the final score.
df = df_original.copy() X_train, y_train = df.iloc[:,1:], df.iloc[:,0] X_train_scaled = scaler_minmax.fit_transform(X_train.values) #calculation of the score for the actual test set weight = sum(y_train == 0)/sum(y_train == 1) log_reg = LogisticRegression(class_weight = {1:weight}, C = 0.2, random_state=1) log_reg.fit...
_____no_output_____
MIT
Raw Codes/.ipynb_checkpoints/basic -2-checkpoint.ipynb
masudurHimel/ML---APS-Failure-at-Scania-Trucks-Data-Set
stripplot() and swarmplot()Many datasets have categorical data and Seaborn supports several useful plot types for this data. In this example, we will continue to look at the 2010 School Improvement data and segment the data by the types of school improvement models used.As a refresher, here is the KDE distribution of ...
# Import packages import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Import dataset df = pd.read_csv('grant_file.csv') # Create the stripplot sns.stripplot(data=df, x='Award_Amount', y='Model Selected', jitter=True) plt.show() # Create and display a s...
/home/victor/.local/lib/python3.8/site-packages/seaborn/categorical.py:1296: UserWarning: 34.8% of the points cannot be placed; you may want to decrease the size of the markers or use stripplot. warnings.warn(msg, UserWarning) /home/victor/.local/lib/python3.8/site-packages/seaborn/categorical.py:1296: UserWarning: 9...
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
boxplots, violinplots and lvplotsSeaborn's categorical plots also support several abstract representations of data. The API for each of these is the same so it is very convenient to try each plot and see if the data lends itself to one over the other.In this exercise, we will use the color palette options presented in...
# Create a boxplot sns.boxplot(data=df, x='Award_Amount', y='Model Selected') plt.show() plt.clf() # Create a violinplot with the husl palette sns.violinplot(data=df, x='Award_Amount', y='Model Selected', palette='husl') plt.show() plt.clf() # Creat...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
barplots, pointplots and countplotsThe final group of categorical plots are `barplots`, `pointplots` and `countplot` which create statistical summaries of the data. The plots follow a similar API as the other plots and allow further customization for the specific problem at hand.Instructions1. Create a `countplot` wit...
# Show a countplot with the number of models used with each region a different color sns.countplot(data=df, y='Model Selected', hue='Region') plt.show() plt.clf() # Create a pointplot and include the capsize in order to show caps on the error bars sns.pointplot(data=df, x='Mod...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Regression and residual plotsLinear regression is a useful tool for understanding the relationship between numerical variables. Seaborn has simple but powerful tools for examining these relationships.For these exercises, we will look at some details from the US Department of Education on 4 year college tuition informa...
# Import dataset college = pd.read_csv('college_datav3.csv') # Display a regression plot for Tuition sns.regplot(data=college, y='Tuition', x='SAT_AVG_ALL', marker='^', color='g') plt.show() plt.clf() # Display the residual plot sns.residplot(data=college, ...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Regression plot parametersSeaborn's regression plot supports several parameters that can be used to configure the plots and drive more insight into the data.For the next exercise, we can look at the relationship between tuition and the percent of students that receive Pell grants. A Pell grant is based on student fina...
# Plot a regression plot of Tuition and the Percentage of Pell Grants sns.regplot(data=college, y='Tuition', x='PCTPELL') plt.show() plt.clf() # Create another plot that estimates the tuition by PCTPELL sns.regplot(data=college, y='Tuition', x='PCTPELL', x_bi...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Binning dataWhen the data on the x axis is a continuous value, it can be useful to break it into different bins in order to get a better visualization of the changes in the data.For this exercise, we will look at the relationship between tuition and the Undergraduate population abbreviated as `UG` in this data. We wil...
# Create a scatter plot by disabling the regression line sns.regplot(data=college, y='Tuition', x='UG', fit_reg=False) plt.show() plt.clf() # Create a scatter plot and bin the data into 5 bins sns.regplot(data=college, y='Tuition', x='UG', x_bins=...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Creating heatmapsA heatmap is a common matrix plot that can be used to graphically summarize the relationship between two variables. For this exercise, we will start by looking at guests of the Daily Show from 1999 - 2015 and see how the occupations of the guests have changed over time.The data includes the date of ea...
# Import dataset daily_show = pd.read_csv('daily_show_guests_cleaned.csv') # Create a crosstab table of the data pd_crosstab = pd.crosstab(daily_show['Group'], daily_show['YEAR']) pd_crosstab # Plot a heatmap of the table sns.heatmap(pd_crosstab) # Rotate tick marks for visibility plt.yticks(rotation=0) plt.xticks(rot...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Customizing heatmapsSeaborn supports several types of additional customizations to improve the output of a heatmap. For this exercise, we will continue to use the Daily Show data that is stored in the `daily_show` variable but we will customize the output.Instructions1. Create a crosstab table of `Group` and `YEAR`.2....
# Create the crosstab DataFrame pd_crosstab = pd.crosstab(daily_show['Group'], daily_show['YEAR']) # Plot a heatmap of the table with no color bar and using the BuGn palette sns.heatmap(pd_crosstab, cbar=False, cmap='BuGn', linewidths=0.3) # Rotate tick marks for visibility plt.yticks(rotation=0) plt.xticks(rotation=...
_____no_output_____
MIT
intermediate_data_visualization_with_seaborn/3_additional_plot_types.ipynb
vhsenna/datacamp-courses
Syllables
# http://docs.cltk.org/en/latest/latin.html#syllabifier from cltk.stem.latin.syllabifier import Syllabifier cato_agri_praef = "Est interdum praestare mercaturis rem quaerere, nisi tam periculosum sit, et item foenerari, si tam honestum. Maiores nostri sic habuerunt et ita in legibus posiverunt: furem dupli condemnari,...
est ['est'] interdum ['in', 'ter', 'dum'] praestare ['praes', 'ta', 're'] mercaturis ['mer', 'ca', 'tu', 'ris'] rem ['rem'] quaerere ['quae', 're', 're'] nisi ['ni', 'si'] tam ['tam'] periculosum ['pe', 'ri', 'cu', 'lo', 'sum'] sit ['sit'] et ['et'] item ['i', 'tem'] foenerari ['foe', 'ne', 'ra', 'ri'] si ['si'] tam ['...
MIT
7 Syllabification, prosody, phonetics.ipynb
cs145442/gsoc2018Practice
ProsodyTakes two steps: first find long vowels, then scan actual meter
# macronizer # http://docs.cltk.org/en/latest/latin.html#macronizer from cltk.prosody.latin.macronizer import Macronizer macronizer = Macronizer('tag_ngram_123_backoff') text = 'Quo usque tandem, O Catilina, abutere nostra patientia?' scanned_text = macronizer.macronize_text(text) # scanner # http://docs.cltk.org/en...
[('quō', None, 'quō'), ('usque', 'd--------', 'usque'), ('tandem', 'd--------', 'tandem'), (',', 'u--------', ','), ('ō', None, 'ō'), ('catilīnā', None, 'catilīnā'), (',', 'u--------', ','), ('abūtēre', None, 'abūtēre'), ('nostrā', None, 'nostrā'), ('patientia', 'n-s---fn-', 'patientia'), ('?', None, '?')]
MIT
7 Syllabification, prosody, phonetics.ipynb
cs145442/gsoc2018Practice
Lambda School Data Science - A First Look at Data Lecture - let's explore Python DS libraries and examples!The Python Data Science ecosystem is huge. You've seen some of the big pieces - pandas, scikit-learn, matplotlib. What parts do you want to see more of?
import numpy as np import matplotlib.pyplot as plt import pandas as pd
_____no_output_____
MIT
module1-afirstlookatdata/LS_DSPT3_111_A_First_Look_at_Data.ipynb
elcoreano/DS-Unit-1-Sprint-1-Dealing-With-Data
Assignment - now it's your turnPick at least one Python DS library, and using documentation/examples reproduce in this notebook something cool. It's OK if you don't fully understand it or get it 100% working, but do put in effort and look things up.
# TODO - your code here # Use what we did live in lecture as an example np.random.randint(0, 10, size=10) np.random.randint(0, 10, size=10) x = [9, 4, 9, 9, 6, 2, 2, 5, 0, 3] y = [0, 5, 8, 8, 5, 2, 1, 0, 7, 9] df = pd.DataFrame ({'set 1': x, "set 2": y}) df df['set 1'] df.shape df['set 3'] = df['set 1'] + 2*df['set 2'...
_____no_output_____
MIT
module1-afirstlookatdata/LS_DSPT3_111_A_First_Look_at_Data.ipynb
elcoreano/DS-Unit-1-Sprint-1-Dealing-With-Data
Training Keyword SpottingThis notebook builds on the Colab in which we used the pre-trained [micro_speech](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/micro_speech) example as well as the HarvardX [3_5_18_TrainingKeywordSpotting.ipynb](https://github.com/tinyMLx/colabs) and [4_5...
%%bash rm -rf tensorflow log v2.4.1.zip logs models train dataset extract_loudest_section apt-get update -qq && apt-get install -y wget unzip wget https://github.com/tensorflow/tensorflow/archive/v2.4.1.zip unzip v2.4.1.zip &> log mv tensorflow-2.4.1/ tensorflow/ rm -rf v2.4.1.zip log
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Import PackagesImport standard packages as well as the additional packages from the cloned Github Repo.
import tensorflow as tf import sys # We add this path so we can import the speech processing modules. sys.path.append("./tensorflow/tensorflow/examples/speech_commands/") import input_data import models import numpy as np import pickle import shutil import os
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Check GPU availabilityThe code will also work without GPU acceleration, but it will be significantly slower.
tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None)
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Configure Your Model!Select your keywords and model settings with which to train!**This is where you need to make choices and input data!**```WANTED_WORDS``` = A comma-delimited string of the words you want to train for (e.g., "yes,no"). All the other words you do not select will be used to train an "unknown" label so...
WANTED_WORDS = "stop,go"
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
The number of training steps and learning rates can be specified as comma-separated strings to define the amount/rate at each stage. For example, ```TRAINING_STEPS="12000,3000"``` and ```LEARNING_RATE="0.001,0.0001"``` will run 12,000 training steps with a rate of 0.001 followed by 3,000 final steps with a learning rat...
TRAINING_STEPS = "12000,3000" LEARNING_RATE = "0.001,0.0001"
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
We suggest you leave the ```MODEL_ARCHITECTURE``` as tiny_conv the first time but if you would like to do this again and explore additional models some options are: ```single_fc, conv, low_latency_conv, low_latency_svdf, tiny_embedding_conv```
MODEL_ARCHITECTURE = 'tiny_conv' # Calculate the total number of steps, which is used to identify the checkpoint # file name. TOTAL_STEPS = str(sum(map(lambda string: int(string), TRAINING_STEPS.split(",")))) # Print the configuration to confirm it print("Training these words: %s" % WANTED_WORDS) print("Training steps...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
**DO NOT MODIFY** the following constants as they include filepaths used in this notebook and data that is shared during training and inference.
# Calculate the percentage of 'silence' and 'unknown' training samples required # to ensure that we have equal number of samples for each label. number_of_labels = WANTED_WORDS.count(',') + 1 number_of_total_labels = number_of_labels + 2 # for 'silence' and 'unknown' label equal_percentage_of_training_samples = int(100...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Train the model Load in TensorBoard to visulaize the training process.As training progresses you should see the training status show up in the Tensorboard area. If this works it is very helpful for analyzing your training progress. Unfortunately, the staff has found that it sometimes doesn't start showing data for a ...
%load_ext tensorboard logs_base_dir='./logs/' os.makedirs(logs_base_dir, exist_ok=True) %tensorboard --logdir {logs_base_dir} --host 0.0.0.0 --port 6006
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Launch TrainingIf you would like to get more information on the training script you can find the source code for the script [here](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/speech_commands/train.py). In short it sets up the optimizer and preprocessor based on all of the flags we pass in!...
!python tensorflow/tensorflow/examples/speech_commands/train.py \ --data_dir={DATASET_DIR} \ --wanted_words={WANTED_WORDS} \ --silence_percentage={SILENT_PERCENTAGE} \ --unknown_percentage={UNKNOWN_PERCENTAGE} \ --preprocess={PREPROCESS} \ --window_stride={WINDOW_STRIDE} \ --model_architecture={MODEL_ARCHITECTURE} \ --...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Generating your ModelJust like with the pre-trained model we will now take the final checkpoint and convert it into a quantized TensorFlow Lite model. Generate a TensorFlow Model for InferenceCombine relevant training results (graph, weights, etc) into a single file for inference. This process is known as freezing a ...
!rm -rf {SAVED_MODEL} !python tensorflow/tensorflow/examples/speech_commands/freeze.py \ --wanted_words=$WANTED_WORDS \ --window_stride_ms=$WINDOW_STRIDE \ --preprocess=$PREPROCESS \ --model_architecture=$MODEL_ARCHITECTURE \ --start_checkpoint=$TRAIN_DIR$MODEL_ARCHITECTURE'.ckpt-'{TOTAL_STEPS} \ --save_format=saved_mo...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Generate a TensorFlow Lite ModelConvert the frozen graph into a TensorFlow Lite model, which is fully quantized for use with embedded devices.The following cell will also print the model size, which will be under 20 kilobytes.We download the dataset to use as a representative dataset for more thoughtful post training ...
model_settings = models.prepare_model_settings( len(input_data.prepare_words_list(WANTED_WORDS.split(','))), SAMPLE_RATE, CLIP_DURATION_MS, WINDOW_SIZE_MS, WINDOW_STRIDE, FEATURE_BIN_COUNT, PREPROCESS) audio_processor = input_data.AudioProcessor( DATA_URL, DATASET_DIR, SILENT_PERCENTAGE, UNKNOWN_PER...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Testing the accuracy after QuantizationVerify that the model we've exported is still accurate, using the TF Lite Python API and our test set.
# Helper function to run inference def run_tflite_inference_testSet(tflite_model_path, model_type="Float"): # # Load test data # np.random.seed(0) # set random seed for reproducible test results. with tf.Session() as sess: test_data, test_labels = audio_processor.get_data( -1, 0, model_settings, B...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Testing the model with your own data!Now comes the fun part. It's time to test your model with your own realworld data. We'll proceed in the same way we tested the pre-trained model. Have fun! Importing packages
!apt-get update -qqq && apt-get -y -qqq install apt-utils gcc libpq-dev libsndfile-dev git !python3 -m pip install --upgrade --no-cache-dir --quiet pip ffmpeg-python scipy librosa google-colab from IPython.display import HTML, Audio from google.colab.output import eval_js from base64 import b64decode import numpy as np...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Define the helper function to run inference
# Helper function to run inference (on a single input this time) # Note: this also includes additional manual pre-processing TF_SESS = tf.compat.v1.InteractiveSession() def run_tflite_inference_singleFile(tflite_model_path, custom_audio, sr_custom_audio, model_type="Float"): # # Preprocess the sample to get the fea...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Define the audio importing functionAdapted from: https://ricardodeazambuja.com/deep_learning/2019/03/09/audio_and_video_google_colab/ and https://colab.research.google.com/drive/1Z6VIRZ_sX314hyev3Gm5gBqvm1wQVo-ascrollTo=RtMcXr3o6gxN
def get_audio(): """Records audio from your local microphone inside a colab notebook Returns ------- tuple audio (numpy.ndarray), sample rate (int) Obs: To write this piece of code I took inspiration/code from a lot of places. It was late night, so I'm not sure how much I created or just...
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Record your own audio and test the model!After you run the record cell wait for the stop button to appear then start recording and then press the button to stop the recording once you have said the word!
custom_audio, sr_custom_audio = get_audio() print("DONE") # Then test the model run_tflite_inference_singleFile(MODEL_TFLITE, custom_audio, sr_custom_audio, model_type="Quantized")
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Generate a TensorFlow Lite for Microcontrollers ModelTo convert the TensorFlow Lite quantized model into a C source file that can be loaded by TensorFlow Lite for Microcontrollers on Arduino we simply need to use the ```xxd``` tool to convert the ```.tflite``` file into a ```.cc``` file.
!apt-get update -qqq && apt-get -qqq install xxd MODEL_TFLITE = './models/model.tflite' MODEL_TFLITE_MICRO = './models/model.cc' !xxd -i {MODEL_TFLITE} > {MODEL_TFLITE_MICRO} REPLACE_TEXT = MODEL_TFLITE.replace('/', '_').replace('.', '_') !sed -i 's/'{REPLACE_TEXT}'/g_model/g' {MODEL_TFLITE_MICRO}
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
The generated Tensorflow Lite for Microcontroller model can now be used in the Arduino IDE. There are **two options** to do this:1. Copy the screen output directly from the Jupyter Notebook into the **micro_features_model.cpp** file (in the Arduino IDE)2. Download the **model.cc** file for later use to copy its content...
!cat {MODEL_TFLITE_MICRO}
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Option 2: Download Model File
from IPython.display import FileLink local_file = FileLink('./models/model.cc', result_html_prefix="Click here to download: ") display(local_file)
_____no_output_____
MIT
02_projects/keyword_spotting/2words/TrainKeywordSpottingModel2words.ipynb
KlausPuchner/tinyml
Based on this: * https://scikit-optimize.github.io/stable/auto_examples/bayesian-optimization.htmlsphx-glr-auto-examples-bayesian-optimization-py
import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt from skopt.plots import plot_gaussian_process from skopt import Optimizer import matplotlib.pyplot as plt import matplotlib.image as mpimg from skopt import gp_minimize import numpy as np %matplotlib inline from sklearn.gaussian_process import Ga...
_____no_output_____
MIT
bayes-opt.ipynb
chappers/chappers.github.io
How do we pick the next point to evaluate?From here there are several way to pick the next point. Two common approaches are around:* Upper confidence bound (exploration vs exploitation)* Expected improvement
plt.plot(X_, y_mean, 'r', X, y, 'ro') plt.grid(True) plt.fill_between(X_, y_mean - y_std, y_mean + y_std, alpha=0.5, color='k') # for example, let's just consider the lower bound # kappa controls the exploration/exploitation. kappa = 0.5 plt.plot(X_, y_mean, 'r', X, y, 'ro', X_, y_mean - y_std, 'b', X_...
_____no_output_____
MIT
bayes-opt.ipynb
chappers/chappers.github.io
Let's use scikit optimise instead...
res = gp_minimize(objective_wo_noise, # the function to minimize [(-2.0, 2.0)], # the bounds on each dimension of x acq_func="EI", # the acquisition function n_calls=10, # the number of evaluations of f n_random_starts=1, # the n...
_____no_output_____
MIT
bayes-opt.ipynb
chappers/chappers.github.io
Reaction features
features_reactions = pd.DataFrame(index=cc.index) features_reactions['n_up'] = cc['Actions.Agree.Total'] features_reactions['n_down'] = cc['Actions.Disagree.Total'] features_reactions['n_reply'] = cc['Actions.Comment.Total'] sns.pairplot(features_reactions)
_____no_output_____
MIT
notebooks/explore_models.ipynb
HofmannZ/global-ai-hackathon--truth-coin
Post date features
features_date = pd.DataFrame(index=cc.index) features_date['t_week'] = cc.Timestamp.dt.week features_date['t_dow'] = cc.Timestamp.dt.dayofweek features_date['t_hour'] = cc.Timestamp.dt.hour features_date['t_day'] = cc.Timestamp.dt.day sns.pairplot(features_date)
_____no_output_____
MIT
notebooks/explore_models.ipynb
HofmannZ/global-ai-hackathon--truth-coin
Spacy NLP ...
import spacy # See "Installing spaCy" nlp = spacy.load('en') # You are here. spacy_docs = pd.DataFrame(index=cc.index) docs = cc.Body.apply(nlp) vec = docs.apply(lambda x: x.vector) feature_word_vec = pd.DataFrame(vec.tolist(), columns=['spacy_%s'%i for i in range(300)]) featu...
_____no_output_____
MIT
notebooks/explore_models.ipynb
HofmannZ/global-ai-hackathon--truth-coin
Target
targets = pd.read_csv('./btc-ind.csv') targets['date'] = pd.to_datetime(targets['Date']) targets = targets.set_index('date') del targets['Date'] targets.tail() join_by_date = pd.DataFrame(index=cc.index) join_by_date['date'] = cc.Timestamp.dt.round(freq="d") Y_all = join_by_date.join(targets, on='date').dropna() groups...
_____no_output_____
MIT
notebooks/explore_models.ipynb
HofmannZ/global-ai-hackathon--truth-coin
Combine features
#features = pd.concat([features_date, features_tfidf, features_reactions, feature_word_vec], axis=1) features = pd.concat([features_date, features_reactions, feature_word_vec], axis=1) X_all = features.ix[Y_all.index] X_all.shape from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomFor...
_____no_output_____
MIT
notebooks/explore_models.ipynb
HofmannZ/global-ai-hackathon--truth-coin
Shapefile
with open(os.path.join('..', 'data','shapefiles','Nakhon-Si-Thammarat.geojson')) as f: data = json.load(f) for i, feature in enumerate(data['features']): prop = feature['properties'] province = prop['PV_TN'] district = prop['AP_TN'] subdist = prop['TB_TN'] df_tmp = df_larval.loc[(df_larval...
_____no_output_____
MIT
src/preprocess/translator.ipynb
pcrete/dengue_dash
Dictonary file
province_entry = [] for feature in data['features']: prop = feature['properties'] province_entry.append([ prop['PV_TN'], prop['AP_TN'], prop['TB_TN'], prop['PV_EN'], prop['AP_EN'], prop['TB_EN'], ]) province_entry = pd.DataFrame.from_records(province...
_____no_output_____
MIT
src/preprocess/translator.ipynb
pcrete/dengue_dash
Detection file
with open(os.path.join('..', 'data','breeding-sites','detection.geojson')) as f: detection = json.load(f) for feature in tqdm_notebook(detection['features']): prop = feature['properties'] province = prop['province'] district = prop['district'] subdist = prop['subdist'] df_tmp = province_en...
_____no_output_____
MIT
src/preprocess/translator.ipynb
pcrete/dengue_dash
Partie 1 : Code de César Implementation Le code suivant contient deux fonctions principales : `encryptMessage` et `decryptMessage`.Ces fonctions permet d'encoder et de decoder un string donnée. L'encryption se fait de facon classique par decalage d'alphabet. La clé donnée est le nombre de decalage. La fonction `conv...
alphabet_string = string.printable alphabetListOrdered = list(alphabet_string) numberListOrdered = list(map(ord, alphabetListOrdered)) def convertAlphabets(messageCharNumList, numList, numListToConvert, encrypt = True) : index = 0 newList = [] for val in messageCharNumList: indexOfLetter = numListT...
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
Pour la fonction d'encryption, on utilisera l'alphabet de tout les caracteres imprimable en ascii donnée par `string.printable`.
string.printable def encryptMessage(m, shiftKey): alphabet_string = string.printable alphabetListOrdered = list(alphabet_string) numberListOrdered = list(map(ord, alphabetListOrdered)) alphabetListShuffled = shiftAlphabet(list(alphabetListOrdered), shiftKey) numberListShuffled = list(map(ord, alphabetLis...
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
En dessous est un exemple d'encryption et de decryption.
m = "Vous savez, moi je ne crois pas qu'il y ait de bonne ou de mauvaise situation. Moi, si je devais resumer ma vie aujourd'hui avec vous, je dirais que c'est d'abord des rencontres. Des gens qui m'ont tendu la main, peut-etre a un moment ou je ne pouvais pas, ou j'etais seul chez moi" m
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
On encrypte le texte plus haut au moins d'une clé de valeur `4051`
e = encryptMessage(m, 4501) e
[49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, ...
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
On verifie que la decryption marche bien quand on remet la clé.
d = decryptMessage(e, 4501) d
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
Exercice : Cracker un cypher par décalage avec l'analyse de fréquence Voici un cypher généré avec l'algorithme d'encryption de cypher encryptMessage.Le but est d'arriver a decrypter le message grace a l'analyse de frequence des caracteres du message. Le message code est en anglais, donc un morceau de texte anglais vou...
# Ceci est le message codé à cracker. # Des espaces sont laissés expres pour permettre de bien reconnaitre les caracteres # Attention aux caracteres speciaux d'ascii. E.g. `\r` est bien compté comme 1 caractere de lalphabet. cypher = "Z C D M P C i W M S i B G Q A S Q Q i R F C i P C Q M J S R G M L \r i J C R i K C ...
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
Pour vous aider, voici un morceau de discours en anglais sur lequel vous pouvez faire une premiere analyse de frequences de caracteres.Le texte est assez long pour etre representatif d'une distribution classique de la langue anglaise.Votre histogramme devrait ressembler a celui sur la page web suivante : https://www3.n...
englishText = "I am the First Accused.I hold a Bachelor's Degree in Arts and practised as an attorney in Johannesburg for a number of years in partnership with Oliver Tambo. I am a convicted prisoner serving five years for leaving the country without a permit and for inciting people to go on strike at the end of May 19...
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor
**Consigne** :Comparer la frequence d'apparition des caracteres du cypher et du discours.Par simplicité, triez les tableaux dans l'ordre alphabetique.Il faut ensuite que vous decaliez l'alphabet du cypher jusqu'a que les deux distributions se superposent.Vous pouvez utiliser la fonction `shiftAlphabet` donnée plus haut...
# Zone a coder en dessous
_____no_output_____
BSD-3-Clause
Exercises/Hands_on_Cypher/Hands_on_Cypher.ipynb
AGuyNextDoor/AProfNextDoor