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 after, even just a few training iterations, we can already see that the model is making progress on the task. | plt.figure()
plt.ylabel("Loss")
plt.xlabel("Training Steps")
plt.ylim([0,2])
plt.plot(batch_stats_callback.batch_losses)
plt.figure()
plt.ylabel("Accuracy")
plt.xlabel("Training Steps")
plt.ylim([0,1])
plt.plot(batch_stats_callback.batch_acc) | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Check the predictionsTo redo the plot from before, first get the ordered list of class names: | class_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1])
class_names = np.array([key.title() for key, value in class_names])
class_names | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Run the image batch through the model and convert the indices to class names. | predicted_batch = model.predict(image_batch)
predicted_id = np.argmax(predicted_batch, axis=-1)
predicted_label_batch = class_names[predicted_id] | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Plot the result | label_id = np.argmax(label_batch, axis=-1)
plt.figure(figsize=(10,9))
plt.subplots_adjust(hspace=0.5)
for n in range(30):
plt.subplot(6,5,n+1)
plt.imshow(image_batch[n])
color = "green" if predicted_id[n] == label_id[n] else "red"
plt.title(predicted_label_batch[n].title(), color=color)
plt.axis('off')
_ = pl... | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Export your modelNow that you've trained the model, export it as a SavedModel for use later on. | t = time.time()
export_path = "/tmp/saved_models/{}".format(int(t))
model.save(export_path)
export_path | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
Now confirm that we can reload it, and it still gives the same results: | reloaded = tf.keras.models.load_model(export_path)
result_batch = model.predict(image_batch)
reloaded_result_batch = reloaded.predict(image_batch)
abs(reloaded_result_batch - result_batch).max() | _____no_output_____ | Apache-2.0 | site/en/tutorials/images/transfer_learning_with_hub.ipynb | miried/tensorflow-docs |
any function that's passed to a multiprocessing function must be defined globally, even the callback function size decompressed = 3.7 * compressed Config | # Reload all src modules every time before executing the Python code typed
%load_ext autoreload
%autoreload 2
import os
import sys
import json
import cProfile
import pandas as pd
import geopandas as geopd
import numpy as np
import multiprocessing as mp
try:
import cld3
except ModuleNotFoundError:
pass
import py... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Getting the data Places, area and grid | shapefile_dict = make_config.shapefile_dict(area_dict, cc, region=region)
shapefile_path = os.path.join(
external_data_dir, shapefile_dict['name'], shapefile_dict['name'])
shape_df = geopd.read_file(shapefile_path)
shape_df = geo.extract_shape(
shape_df, shapefile_dict, xy_proj=xy_proj, min_area=min_poly_a... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Places can be a point too -> treat them like tweets with coords in this case | places_files_paths = [
os.path.join(data_dir_path, places_files_format.format(2015, 2018, cc)),
os.path.join(data_dir_path, places_files_format.format(2019, 2019, cc))]
all_raw_places_df = []
for file in places_files_paths:
raw_places_df = data_access.return_json(file,
ssh_domain=ssh_domain, ssh_use... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Reading the data | def profile_pre_process(tweets_file_path, chunk_start, chunk_size):
cProfile.runctx(
'''data_access.read_data(
tweets_file_path, chunk_start, chunk_size, dfs_to_join=[places_geodf])''',
globals(), locals())
tweets_access_res = []
def collect_tweets_access_res(res):
global tweets_access... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Filtering out users Filters: user-based imply a loop over all the raw_tweets_df, and must be applied before getting tweets_lang_df and even tweets_loc_df, because these don't interest us at all. This filter requires us to loop over all files and aggregate the results to get the valid UIDs out | if tweets_access_res is None:
def get_df_fun(arg0):
return data_access.read_json_wrapper(*arg0)
else:
def get_df_fun(arg0):
return arg0
def chunk_users_months(df_access, get_df_fun, places_geodf,
cols=None, ref_year=2015):
raw_tweets_df = get_df_fun(df_access)
raw... | There are 66972 users with at least 3 months of activity in the dataset.
There are 36284 users considered local in the dataset, as they have been active for 3 consecutive months in this area at least once.
0 users have been found to be bots because of their excessive activity, tweeting more than 3 times per minute.
Thi... | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Then we have to loop over all files once again to apply the speed filter, which is expensive, thus done last (we thus benefit from having some users already filtered out, so smaller tweets dataframes) | if tweets_access_res is None:
def get_df_fun(arg0):
return data_access.read_json_wrapper(*arg0)
else:
def get_df_fun(arg0):
return arg0
def speed_filter(df_access, get_df_fun, valid_uids, places_in_xy, max_distance,
cols=None):
tweets_df = get_df_fun(df_access)
tweets_d... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Processing We don't filter out tweets with a useless place (one too large) here, because these tweets can still be useful for language detection. So this filter is only applied later on. Similarly, we keep tweets with insufficient text to make a reliable language detection, because they can still be useful for residen... | valid_uids = pd.read_csv(valid_uids_path, index_col='uid', header=0)
if tweets_access_res is None:
def get_df_fun(arg0):
return data_access.read_json_wrapper(*arg0)
else:
def get_df_fun(arg0):
return arg0
tweets_process_res = []
def collect_tweets_process_res(res):
global tweets_proces... | /home/thomaslouf/Documents/code/multiling-twitter/.venv/lib/python3.6/site-packages/pandas/core/indexing.py:1418: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
https://pandas.pydata.org/p... | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Study at the tweet level Make tweet counts data | tweet_level_label = 'tweets in {}'
plot_langs_dict = make_config.langs_dict(area_dict, tweet_level_label) | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Why sjoin so slow? It tests on every cell, even though it's exclusive: if one cell matches no other will. Solution: loop over cells, ordered by the counts obtained from places, and stop at first match, will greatly reduce the number of 'within' operations -> update: doesn't seem possible, deleting from spatial index is... | def get_langs_counts(tweets_lang_df, max_place_area, cells_in_area_df):
tweets_df = tweets_lang_df.copy()
relevant_area_mask = tweets_df['area'] < max_place_area
tweets_df = tweets_df.loc[relevant_area_mask]
# The following mask accounts for both tweets with GPS coordinates and
# tweets within place... | entering the loop
109 tweets have been found outside of the grid and filtered out as a result.
123 tweets have been found outside of the grid and filtered out as a result.
119 tweets have been found outside of the grid and filtered out as a result.
149 tweets have been found outside of the grid and filtered out as a re... | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Places -> cells | # We count the number of users speaking a local language in each cell and place
# of residence.
local_langs = [lang for lang in plot_langs_dict]
places_local_counts = places_langs_counts.reset_index(level='cld_lang')
local_langs_mask = places_local_counts['cld_lang'].isin(local_langs)
places_local_counts = (places_loc... | There are 9010159 tweets in Spanish.
There are 5035352 tweets in Catalan.
| RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Plots | # cell_size = 20000
cell_data_path = cell_data_path_format.format('tweets', cc, cell_size)
cell_plot_df = geopd.read_file(cell_data_path)
cell_plot_df.index = cell_plot_df['cell_id']
cell_plot_df, plot_langs_dict = metrics.calc_by_cell(cell_plot_df, plot_langs_dict)
for plot_lang, plot_dict in plot_langs_dict.items():
... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Study at the user level Users who have tagged their tweets with gps coordinates seem to do it regularly, as the median of the proportion of tweets they geo tag is at more than 75% on the first chunk -> it's worth it to try and get their cell of residence | a = tweets_process_res[0].copy()
a['has_gps'] = a['area'] == 0
gps_uids = a.loc[a['has_gps'], 'uid'].unique()
a = a.loc[a['uid'].isin(gps_uids)].groupby(['uid', 'has_gps']).size().rename('count').to_frame()
a = a.join(a.groupby('uid')['count'].sum().rename('sum'))
b = a.reset_index()
b = b.loc[b['has_gps']]
b['ratio'] ... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
If there's one or more cells where a user tweeted in proportion more than relevant_th of the time, we take among these cells the one where they tweeted the most outside work hours. Otherwise, we take the relevant place where they tweeted the most outside work hours, or we default to the place where they tweeted the mos... | user_level_label = '{}-speaking users'
lang_relevant_prop = 0.1
lang_relevant_count = 5
cell_relevant_th = 0.1
plot_langs_dict = make_config.langs_dict(area_dict, user_level_label) | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
If valid_uids is already generated, we only loop once over the tweets df and do the whole processing in one go on each file, thus keeping very little in memory | valid_uids = pd.read_csv(valid_uids_path, index_col='uid', header=0)
cells_df_list = [cells_in_area_df]
if tweets_access_res is None:
def get_df_fun(arg0):
return data_access.read_json_wrapper(*arg0)
else:
def get_df_fun(arg0):
return arg0
user_agg_res = []
def collect_user_agg_res(res):
... | 1000MB read, 846686 tweets unpacked.
487136 tweets remaining after filters.
1000MB read, 852716 tweets unpacked.
477614 tweets remaining after filters.
1000MB read, 844912 tweets unpacked.
starting lang detect
471237 tweets remaining after filters.
starting lang detect
1000MB read, 841957 tweets unpacked.
starting lang... | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Language(s) attribution very few users are actually filtered out by language attribution: not more worth it to generate user_langs_counts, user_cells_habits and user_places_habits inside of tweets_lang_df loop, so as to drop tweets_langs_df, and only return these user level, lightweight DFs Here we get rid of users w... | # Residence attribution is the longest to run, and by a long shot, so we'll start
# with language to filter out uids in tweets_df before doing it
groupby_cols = ['uid', 'cld_lang']
user_langs_counts = None
for res in tweets_process_res:
tweets_lang_df = res.copy()
# Here we don't filter out based on max_place_a... | We were able to attribute at least one language to 33779 users
| RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Attribute users to a group: mono, bi, tri, ... lingualProblem: need more tweets to detect multilingualism, eg users with only three tweets in the dataset are very unlikely to be detected as multilinguals | users_ling_grp = uagg.get_ling_grp(
user_langs_agg, area_dict, lang_relevant_prop=lang_relevant_prop,
lang_relevant_count=lang_relevant_count, fig_dir=fig_dir, show_fig=True) | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Pre-residence attribution | with mp.Pool(8) as pool:
map_parameters = [(res, cells_in_area_df,
max_place_area, cc_timezone)
for res in tweets_process_res]
print('entering the loop')
tweets_pre_resid_res = (
pool.starmap_async(data_process.prep_resid_attr, map_parameters).get())
... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Here we took number of speakers, whether they're multilingual or monolingual, if they speak a language, they count as one in that language's count Residence attribution | user_home_cell, user_only_place = uagg.get_residence(
user_cells_habits, user_places_habits, place_relevant_th=cell_relevant_th,
cell_relevant_th=cell_relevant_th) | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Generate cell data | cell_plot_df = data_process.from_users_area_and_lang(
cells_in_area_df, places_geodf, user_only_place,
user_home_cell, user_langs_agg, users_ling_grp,
plot_langs_dict, multiling_grps, cell_data_path_format) | There are 9012 German-speaking users.
There are 7927 French-speaking users.
There are 1887 Italian-speaking users.
| RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
GeoJSON should always be in lat, lon, WGS84 to be read by external programs, so in plotly for instance we need to make sure we come back to latlon_proj Plots | cell_size = 10000
cell_data_path = cell_data_path_format.format(
'users_cell_data', cc, cell_size, 'geojson')
cell_plot_df = geopd.read_file(cell_data_path)
cell_plot_df.index = cell_plot_df['cell_id']
cell_plot_df, plot_langs_dict = metrics.calc_by_cell(cell_plot_df,
... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Generate cell data files in loops In all the above, the cell size and cc are supposed constant, defined in config. Here we first assume the cell size is not constant, then the cc | import sys
import logging
import logging.config
import traceback
import IPython
# logger = logging.getLogger(__name__)
# load config from file
logging.config.fileConfig('logging.ini', disable_existing_loggers=False)
def showtraceback(self):
traceback_lines = traceback.format_exception(*sys.exc_info())
del tra... | _____no_output_____ | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
Countries loop | cc = 'PY'
regions = ()
# regions = ('New York City', 'Puerto Rico')
# regions = ('Catalonia', 'Balearic islands', 'Galicia', 'Valencian Community',
# 'Basque country')
# regions = ('Louisiana', 'Texas', 'New Mexico', 'Arizona', 'Nevada',
# 'California')
valid_uids_path_format = os.path.join(interi... | 2020-06-04 11:38:43,882 - src.data.cells_results - INFO - starting on chunk 0
2020-06-04 11:38:53,009 - src.data.cells_results - INFO - starting on chunk 1
2020-06-04 11:39:02,469 - src.data.cells_results - INFO - starting on chunk 2
2020-06-04 11:39:11,418 - src.data.cells_results - INFO - starting on chunk 3
2020-06-... | RSA-MD | notebooks/1.1.first_whole_analysis.ipynb | TLouf/multiling-twitter |
EvalutaionTo be able to make a statement about the performance of a question-asnwering system, it is important to evalute it. Furthermore, evaluation allows to determine which parts of the system can be improved. Start an Elasticsearch serverYou can start Elasticsearch on your local machine instance using Docker. If ... | # Recommended: Start Elasticsearch using Docker
#! docker run -d -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
# In Colab / No Docker environments: Start Elasticsearch from source
! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.6.2-linux-x86_64.tar.gz -q
! tar -xzf elastic... | 06/05/2020 16:11:30 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:1.613s]
06/05/2020 16:11:31 - INFO - elasticsearch - POST http://localhost:9200/_bulk [status:200 request:0.453s]
| Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | arthurbarros/haystack |
Initialize components of QA-System | # Initialize Retriever
from haystack.retriever.elasticsearch import ElasticsearchRetriever
retriever = ElasticsearchRetriever(document_store=document_store)
# Initialize Reader
from haystack.reader.farm import FARMReader
reader = FARMReader("deepset/roberta-base-squad2")
# Initialize Finder which sticks together Read... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | arthurbarros/haystack |
Evaluation of Retriever | # Evaluate Retriever on its own
retriever_eval_results = retriever.eval()
## Retriever Recall is the proportion of questions for which the correct document containing the answer is
## among the correct documents
print("Retriever Recall:", retriever_eval_results["recall"])
## Retriever Mean Avg Precision rewards retrie... | 06/05/2020 16:12:46 - INFO - elasticsearch - POST http://localhost:9200/feedback/_search?scroll=5m&size=1000 [status:200 request:0.170s]
06/05/2020 16:12:46 - INFO - elasticsearch - POST http://localhost:9200/eval_document/_search [status:200 request:0.069s]
06/05/2020 16:12:46 - INFO - haystack.retriever.elasticse... | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | arthurbarros/haystack |
Evaluation of Reader | # Evaluate Reader on its own
reader_eval_results = reader.eval(document_store=document_store, device=device)
# Evaluation of Reader can also be done directly on a SQuAD-formatted file
# without passing the data to Elasticsearch
#reader_eval_results = reader.eval_on_file("../data/natural_questions", "dev_subset.json", ... | 06/05/2020 16:12:47 - INFO - elasticsearch - POST http://localhost:9200/feedback/_search?scroll=5m&size=1000 [status:200 request:0.022s]
06/05/2020 16:12:47 - INFO - elasticsearch - POST http://localhost:9200/_search/scroll [status:200 request:0.005s]
06/05/2020 16:12:47 - INFO - elasticsearch - DELETE http://loc... | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | arthurbarros/haystack |
Evaluation of Finder | # Evaluate combination of Reader and Retriever through Finder
finder_eval_results = finder.eval()
print("\n___Retriever Metrics in Finder___")
print("Retriever Recall:", finder_eval_results["retriever_recall"])
print("Retriever Mean Avg Precision:", finder_eval_results["retriever_map"])
# Reader is only evaluated wit... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | arthurbarros/haystack |
ML Pipeline PreparationFollow the instructions below to help you create your ML pipeline. 1. Import libraries and load data from database.- Import Python libraries- Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)- Define feature and ... | # import libraries
import pandas as pd
from sqlalchemy import create_engine
import re
import nltk
import string
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline ... | Engine(sqlite:///DisasterResponse.db)
| MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
2. Write a tokenization function to process your text data | stop_words = nltk.corpus.stopwords.words("english")
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
remove_punc_table = str.maketrans('', '', string.punctuation)
def tokenize(text):
# normalize case and remove punctuation
text = text.translate(remove_punc_table).lower()
# tokenize text
tokens = ... | _____no_output_____ | MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
3. Build a machine learning pipelineThis machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) h... | forest_clf = RandomForestClassifier(n_estimators=10)
pipeline = Pipeline([
('tfidf', TfidfVectorizer(tokenizer=tokenize)),
('forest', MultiOutputClassifier(forest_clf))
]) | _____no_output_____ | MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
4. Train pipeline- Split data into train and test sets- Train pipeline | X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=42)
#X_train
pipeline.fit(X_train, Y_train) | _____no_output_____ | MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
5. Test your modelReport the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each. | Y_pred = pipeline.predict(X_test)
for i, col in enumerate(Y_test):
print(col)
print(classification_report(Y_test[col], Y_pred[:, i])) | related
precision recall f1-score support
0.0 0.31 0.14 0.20 2096
1.0 0.76 0.90 0.82 6497
accuracy 0.71 8593
macro avg 0.54 0.52 0.51 8593
weighted avg 0.65 0.71 0... | MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
6. Improve your modelUse grid search to find better parameters. | '''
parameters = {
'tfidf__ngram_range': ((1, 1), (1, 2)),
'tfidf__max_df': (0.8, 1.0),
'tfidf__max_features': (None, 10000),
'forest__estimator__n_estimators': [50, 100],
'forest__estimator__min_samples_split': [2, 4]
}
'''
parameters = {
'tfidf__ngram_range': ((1, 1), (1, 2))
}
cv = GridSear... | Fitting 3 folds for each of 2 candidates, totalling 6 fits
[CV] tfidf__ngram_range=(1, 1) .......................................
[CV] ........... tfidf__ngram_range=(1, 1), score=0.139, total= 48.2s
[CV] tfidf__ngram_range=(1, 1) .......................................
| MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
7. Test your modelShow the accuracy, precision, and recall of the tuned model. Since this project focuses on code quality, process, and pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - esp... | def evaluate_model(model, X_test, Y_test):
Y_pred = model.predict(X_test)
print(classification_report(Y_test, Y_pred, target_names=category_names))
# print('Accuracy: ', accuracy_score(Y_test, Y_pred))
# print('Precision: ', precision_score(Y_test, Y_pred, average='weighted'))
# print('Recall: ', re... | Accuracy: 0.144652624229
Precision: 0.400912141504
Recall: 0.277450871544
| MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
8. Try improving your model further. Here are a few ideas:* try other machine learning algorithms* add other features besides the TF-IDF | from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.model_selection import train_test_split
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier,AdaBoostClassifier
from sklearn.feature_extraction.text import CountVectoriz... | Fitting 5 folds for each of 2 candidates, totalling 10 fits
[CV] features__text_pipeline__vect__ngram_range=(1, 1) ...............
[CV] features__text_pipeline__vect__ngram_range=(1, 1), total= 1.9min
[CV] features__text_pipeline__vect__ngram_range=(1, 1) ...............
| MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
9. Export your model as a pickle file | import joblib
joblib.dump(cv.best_estimator_, 'disaster_model.pkl') | _____no_output_____ | MIT | notepads/ML Pipeline Preparation.ipynb | ranjeetraj2005/Disaster_Response_System |
TensorFlow实现VGG16 导入需要使用的库 | import inspect
import os
import numpy as np
import tensorflow as tf | D:\anaconda\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
| Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义卷积层 | '''Convolution op wrapper, use RELU activation after convolution
Args:
layer_name: e.g. conv1, pool1...
x: input tensor, [batch_size, height, width, channels]
out_channels: number of output channels (or comvolutional kernels)
kernel_size: the size of convolutional kernel, VGG paper u... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义池化层 | '''Pooling op
Args:
x: input tensor
kernel: pooling kernel, VGG paper used [1,2,2,1], the size of kernel is 2X2
stride: stride size, VGG paper used [1,2,2,1]
padding:
is_max_pool: boolen
if True: use max pooling
else: use avg pooling
''... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义全连接层 | '''Wrapper for fully connected layers with RELU activation as default
Args:
layer_name: e.g. 'FC1', 'FC2'
x: input feature map
out_nodes: number of neurons for current FC layer
'''
def fc_layer(layer_name, x, out_nodes,keep_prob=0.8):
shape = x.get_shape()
# 处理没有预先做flatten的输入
if ... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义VGG16网络 | def vgg16_net(x, n_classes, is_pretrain=True):
with tf.name_scope('VGG16'):
x = conv_layer('conv1_1', x, 64, kernel_size=[3,3], stride=[1,1,1,1], is_pretrain=is_pretrain)
x = conv_layer('conv1_2', x, 64, kernel_size=[3,3], stride=[1,1,1,1], is_pretrain=is_pretrain)
with tf.name_scope('pool1'... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义损失函数采用交叉熵计算损失 | '''Compute loss
Args:
logits: logits tensor, [batch_size, n_classes]
labels: one-hot labels
'''
def loss(logits, labels):
with tf.name_scope('loss') as scope:
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels,name='cross-entropy')
loss = tf... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义准确率 | '''
Evaluate the quality of the logits at predicting the label.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor,
'''
def accuracy(logits, labels):
with tf.name_scope('accuracy') as scope:
correct = tf.equal(tf.arg_max(logits, 1), tf.arg_max(lab... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义优化函数 | def optimize(loss, learning_rate, global_step):
'''optimization, use Gradient Descent as default
'''
with tf.name_scope('optimizer'):
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
#optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op =... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义加载模型函数 | def load_with_skip(data_path, session, skip_layer):
data_dict = np.load(data_path, encoding='latin1').item()
for key in data_dict:
if key not in skip_layer:
with tf.variable_scope(key, reuse=True):
for subkey, data in zip(('weights', 'biases'), data_dict[key]):
... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义训练图片读取函数 | def read_cifar10(data_dir, is_train, batch_size, shuffle):
"""Read CIFAR10
Args:
data_dir: the directory of CIFAR10
is_train: boolen
batch_size:
shuffle:
Returns:
label: 1D tensor, tf.int32
image: 4D tensor, [batch_size, height, width, 3], tf.float... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
定义训练函数 | IMG_W = 32
IMG_H = 32
N_CLASSES = 10
BATCH_SIZE = 32
learning_rate = 0.01
MAX_STEP = 10 # it took me about one hour to complete the training.
IS_PRETRAIN = False
image_size = 224 # 输入图像尺寸
images = tf.Variable(tf.random_normal([batch_size, image_size, image_size, 3], dtype=tf.float32, stddev=1e-1))
vgg16_net(images,k... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
VGG16使用 | def time_tensorflow_run(session, target, feed, info_string):
num_steps_burn_in = 10 # 预热轮数
total_duration = 0.0 # 总时间
total_duration_squared = 0.0 # 总时间的平方和用以计算方差
for i in range(num_batches + num_steps_burn_in):
start_time = time.time()
_ = session.run(target,feed_dict=feed)
d... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
其他参数 | # Construct model
pred = conv_net(x, weights, biases, keep_prob)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1... | _____no_output_____ | Apache-2.0 | VGG16/TensorFlow/.ipynb_checkpoints/vgg16_tensorflow-checkpoint.ipynb | user-ZJ/deep-learning |
Project: Part of Speech Tagging with Hidden Markov Models --- IntroductionPart of speech tagging is the process of determining the syntactic category of a word from the words in its surrounding context. It is often used to help disambiguate natural language phrases because it can be done quickly with high accuracy. Ta... | # Jupyter "magic methods" -- only need to be run once per kernel restart
%load_ext autoreload
%aimport helpers, tests
%autoreload 1
# import python modules -- this cell needs to be run again if you make changes to any of the files
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.display import HTML... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Step 1: Read and preprocess the dataset---We'll start by reading in a text corpus and splitting it into a training and testing dataset. The data set is a copy of the [Brown corpus](https://en.wikipedia.org/wiki/Brown_Corpus) (originally from the [NLTK](https://www.nltk.org/) library) that has already been pre-processe... | data = Dataset("tags-universal.txt", "brown-universal.txt", train_test_split=0.8)
print("There are {} sentences in the corpus.".format(len(data)))
print("There are {} sentences in the training set.".format(len(data.training_set)))
print("There are {} sentences in the testing set.".format(len(data.testing_set)))
asser... | There are 57340 sentences in the corpus.
There are 45872 sentences in the training set.
There are 11468 sentences in the testing set.
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
The Dataset InterfaceYou can access (mostly) immutable references to the dataset through a simple interface provided through the `Dataset` class, which represents an iterable collection of sentences along with easy access to partitions of the data for training & testing. Review the reference below, then run and review... | key = 'b100-38532'
print("Sentence: {}".format(key))
print("words:\n\t{!s}".format(data.sentences[key].words))
print("tags:\n\t{!s}".format(data.sentences[key].tags)) | Sentence: b100-38532
words:
('Perhaps', 'it', 'was', 'right', ';', ';')
tags:
('ADV', 'PRON', 'VERB', 'ADJ', '.', '.')
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
**Note:** The underlying iterable sequence is **unordered** over the sentences in the corpus; it is not guaranteed to return the sentences in a consistent order between calls. Use `Dataset.stream()`, `Dataset.keys`, `Dataset.X`, or `Dataset.Y` attributes if you need ordered access to the data. Counting Unique ElementsY... | print("There are a total of {} samples of {} unique words in the corpus."
.format(data.N, len(data.vocab)))
print("There are {} samples of {} unique words in the training set."
.format(data.training_set.N, len(data.training_set.vocab)))
print("There are {} samples of {} unique words in the testing set."
... | There are a total of 1161192 samples of 56057 unique words in the corpus.
There are 928458 samples of 50536 unique words in the training set.
There are 232734 samples of 25112 unique words in the testing set.
There are 5521 words in the test set that are missing in the training set.
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Accessing word and tag SequencesThe `Dataset.X` and `Dataset.Y` attributes provide access to ordered collections of matching word and tag sequences for each sentence in the dataset. | # accessing words with Dataset.X and tags with Dataset.Y
for i in range(2):
print("Sentence {}:".format(i + 1), data.X[i])
print()
print("Labels {}:".format(i + 1), data.Y[i])
print() | Sentence 1: ('Mr.', 'Podger', 'had', 'thanked', 'him', 'gravely', ',', 'and', 'now', 'he', 'made', 'use', 'of', 'the', 'advice', '.')
Labels 1: ('NOUN', 'NOUN', 'VERB', 'VERB', 'PRON', 'ADV', '.', 'CONJ', 'ADV', 'PRON', 'VERB', 'NOUN', 'ADP', 'DET', 'NOUN', '.')
Sentence 2: ('But', 'there', 'seemed', 'to', 'be', 'som... | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Accessing (word, tag) SamplesThe `Dataset.stream()` method returns an iterator that chains together every pair of (word, tag) entries across all sentences in the entire corpus. | # use Dataset.stream() (word, tag) samples for the entire corpus
print("\nStream (word, tag) pairs:\n")
for i, pair in enumerate(data.stream()):
print("\t", pair)
if i > 5: break |
Stream (word, tag) pairs:
('Mr.', 'NOUN')
('Podger', 'NOUN')
('had', 'VERB')
('thanked', 'VERB')
('him', 'PRON')
('gravely', 'ADV')
(',', '.')
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
For both our baseline tagger and the HMM model we'll build, we need to estimate the frequency of tags & words from the frequency counts of observations in the training corpus. In the next several cells you will complete functions to compute the counts of several sets of counts. Step 2: Build a Most Frequent Class tag... | def pair_counts(sequences_A, sequences_B):
"""Return a dictionary keyed to each unique value in the first sequence list
that counts the number of occurrences of the corresponding value from the
second sequences list.
For example, if sequences_A is tags and sequences_B is the corresponding
words... | dict_keys(['NOUN', 'VERB', 'PRON', 'ADV', '.', 'CONJ', 'ADP', 'DET', 'PRT', 'ADJ', 'X', 'NUM'])
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
IMPLEMENTATION: Most Frequent Class TaggerUse the `pair_counts()` function and the training dataset to find the most frequent class label for each word in the training data, and populate the `mfc_table` below. The table keys should be words, and the values should be the appropriate tag string.The `MFCTagger` class is ... | # Create a lookup table mfc_table where mfc_table[word] contains the tag label most frequently assigned to that word
from collections import namedtuple
FakeState = namedtuple("FakeState", "name")
class MFCTagger:
# NOTE: You should not need to modify this class or any of its methods
missing = FakeState(name="... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Making Predictions with a ModelThe helper functions provided below interface with Pomegranate network models & the mocked MFCTagger to take advantage of the [missing value](http://pomegranate.readthedocs.io/en/latest/nan.html) functionality in Pomegranate through a simple sequence decoding function. Run these function... | def replace_unknown(sequence):
"""Return a copy of the input sequence where each unknown word is replaced
by the literal string value 'nan'. Pomegranate will ignore these values
during computation.
"""
return [w if w in data.training_set.vocab else 'nan' for w in sequence]
def simplify_decoding(X, ... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Example Decoding Sequences with MFC Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, mfc_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Evaluating Model AccuracyThe function below will evaluate the accuracy of the MFC tagger on the collection of all sentences from a text corpus. | def accuracy(X, Y, model):
"""Calculate the prediction accuracy by using the model to decode each sequence
in the input X and comparing the prediction with the true labels in Y.
The X should be an array whose first dimension is the number of sentences to test,
and each element of the array should b... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Evaluate the accuracy of the MFC taggerRun the next cell to evaluate the accuracy of the tagger on the training and test corpus. | mfc_training_acc = accuracy(data.training_set.X, data.training_set.Y, mfc_model)
print("training accuracy mfc_model: {:.2f}%".format(100 * mfc_training_acc))
mfc_testing_acc = accuracy(data.testing_set.X, data.testing_set.Y, mfc_model)
print("testing accuracy mfc_model: {:.2f}%".format(100 * mfc_testing_acc))
assert ... | training accuracy mfc_model: 95.72%
testing accuracy mfc_model: 93.01%
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Step 3: Build an HMM tagger---The HMM tagger has one hidden state for each possible tag, and parameterized by two distributions: the emission probabilties giving the conditional probability of observing a given **word** from each hidden state, and the transition probabilities giving the conditional probability of movi... | def unigram_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequence list that
counts the number of occurrences of the value in the sequences list. The sequences
collection should be a 2-dimensional array.
For example, if the tag NOUN appears 275558 times over all ... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
IMPLEMENTATION: Bigram CountsComplete the function below to estimate the co-occurrence frequency of each pair of symbols in each of the input sequences. These counts are used in the HMM model to estimate the bigram probability of two tags from the frequency counts according to the formula: $$P(tag_2|tag_1) = \frac{C(t... | def bigram_counts(sequences):
"""Return a dictionary keyed to each unique PAIR of values in the input sequences
list that counts the number of occurrences of pair in the sequences list. The input
should be a 2-dimensional array.
For example, if the pair of tags (NOUN, VERB) appear 61582 times, then... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
IMPLEMENTATION: Sequence Starting CountsComplete the code below to estimate the bigram probabilities of a sequence starting with each tag. | def starting_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the beginning of
a sequence.
For example, if 8093 sequences start with NOUN, then you should return a
dictionary such that y... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
IMPLEMENTATION: Sequence Ending CountsComplete the function below to estimate the bigram probabilities of a sequence ending with each tag. | def ending_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the end of
a sequence.
For example, if 18 sequences end with DET, then you should return a
dictionary such that your_starting_... | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
IMPLEMENTATION: Basic HMM TaggerUse the tag unigrams and bigrams calculated above to construct a hidden Markov tagger.- Add one state per tag - The emission distribution at each state should be estimated with the formula: $P(w|t) = \frac{C(t, w)}{C(t)}$- Add an edge from the starting state `basic_model.start` to ea... | basic_model = HiddenMarkovModel(name="base-hmm-tagger")
# TODO: create states with emission probability distributions P(word | tag) and add to the model
# (Hint: you may need to loop & create/add new states)
states = []
for tag in data.training_set.tagset:
tag_distribution = {word: emission_counts[tag][word]/tag... | training accuracy basic hmm model: 97.54%
testing accuracy basic hmm model: 96.16%
| MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Example Decoding Sequences with the HMM Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, basic_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Finishing the project---**Note:** **SAVE YOUR NOTEBOOK**, then run the next cell to generate an HTML copy. You will zip & submit both this file and the HTML copy for review. | !!jupyter nbconvert *.ipynb | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
Step 4: [Optional] Improving model performance---There are additional enhancements that can be incorporated into your tagger that improve performance on larger tagsets where the data sparsity problem is more significant. The data sparsity problem arises because the same amount of data split over more tags means there ... | import nltk
from nltk import pos_tag, word_tokenize
from nltk.corpus import brown
nltk.download('brown')
training_corpus = nltk.corpus.brown
training_corpus.tagged_sents()[0] | _____no_output_____ | MIT | HMM Tagger.ipynb | DeepanshKhurana/udacityproject-hmm-tagger-nlp |
**READING IN KINESSO DATA** | imp = pd.read_csv('impressions_one_hour.csv')
imp = imp[imp['country'] == 'Germany']
imp = imp[~imp['zip_code'].isna()]
imp['zip_code'] = imp['zip_code'].astype(str) | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**READING IN 2011 GERMANY CENSUS DATA** | # data from: https://www.suche-postleitzahl.org/downloads
zip_codes = pd.read_csv("plz_einwohner.csv")
def add_zero(x):
if len(x) == 4:
return '0'+ x
else:
return x | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**CORRECTING FORMATTING ERROR THAT REMOVED INITIAL '0' FROM ZIPCODES** | zip_codes['zipcode'] = zip_codes['zipcode'].astype(str).apply(add_zero)
zip_codes.head() | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
Real Population of Germany is 83.02 million | np.sum(zip_codes['population']) | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**CALCULATING VALUE COUNTS FROM KINESSO DATA** | val_cou = imp['zip_code'].value_counts()
val_counts = pd.DataFrame(columns=['zipcode', 'count'], data=val_cou)
val_counts['zipcode'] = val_cou.index.astype(str)
val_counts['count'] = val_cou.values.astype(int)
val_counts | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**MERGING TOGETHER KINESSO VALUE COUNTS WITH KINESSO DATA***ONLY 19 ZIPCODES DO NOT HAVE CENSUS DATA* | population_count = val_counts.merge(right=zip_codes, right_on='zipcode', left_on='zipcode', how='outer')
population_count_f = population_count.dropna()
#only 19 zipcodes without data
len(population_count[population_count['population'].isna()]) | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
Here count is the observed number from the Kinesso dataset and population is the expected number from census dataset | population_count_f | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**CALCULATING DEVICE FREQUENCIES FOR EACH ZIPCODE** | imp['count'] = [1] * len(imp)
device_model_make_counts = imp.groupby(['zip_code', 'device_make', 'device_model'], as_index=False).count()[['zip_code', 'device_make', 'device_model', 'count']]
total_calc = device_model_make_counts.groupby(['zip_code']).sum()
percent_calc = []
for i in device_model_make_counts.index:
... | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**CALCULATING PERCENT DIFFERENCE BETWEEN EXPECTED AND OBSERVED POPULATIONS FOR EACH ZIPCODE** | population_count_f['population % expected'] = (population_count_f['population']/sum(population_count_f['population']))*100
population_count_f['population % observed'] = (population_count_f['count']/sum(population_count_f['count']))*100
population_count_f['% difference'] = population_count_f['population % observed'] - p... | <ipython-input-46-cfa73adf08fd>:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-co... | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
*MERGING TOGETHER WITH DEVICE FREQUENCY DATA* | combo = device_model_make_counts.merge(right=population_count_f, right_on='zipcode', left_on='zip_code', how='outer').drop(['count', 'device_make', 'device_model'], axis=1)
combined_impressions = combo.sort_values('% difference', ascending=False)
combined_impressions | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
*GROUPING TO IDENTIFY MOST COMMONLY USED DEVICE* | most_common_device = combined_impressions.groupby(['zip_code']).max()
most_common_device | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
*IDENTIFYING MOST UNDER REPRESENTED ZIP CODES* | underrepresented = most_common_device.sort_values('% difference').head(1000)
underrepresented.head(10)
underrepresented['combined'].value_counts() | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
*IDENTIFYING MOST OVER REPRESENTED ZIP CODES* | overrepresented = most_common_device.sort_values('% difference', ascending=False).head(1000)
overrepresented.head(10)
overrepresented['combined'].value_counts() | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
**I actually decided not to look to closely into the device frequency numbers because for the underrepresented zipcodes there's only like 8-9 people Kinesso advertised to-- and mostly to Apple users interestingly. Instead I did some digging into the top 10 and bottom 10 in a seperate google docs titled: top 10 zipcode ... | sns.distplot(most_common_device['% difference']) | _____no_output_____ | Apache-2.0 | student-projects/fall-2020/Kinesso-AdShift-Diversifies-Marketing-Audiences/eda/[DEPRECATED] international_eda/germany/germany_eda.ipynb | UCBerkeley-SCET/DataX-Berkeley |
Fetching Twitter dataThis is a simple notebook containing a simple demonstration on how to fetch tweets using a Twitter Sanbox Environment. The sample data is saved in the form of a json file, which must then be preprocessed. | import os
from os.path import join
from searchtweets import load_credentials, gen_rule_payload, ResultStream, collect_results
import json
project_dir = join(os.getcwd(), os.pardir)
raw_dir = join(project_dir, 'data', 'raw')
twitter_creds_path = join(project_dir, 'twitter_creds.yaml')
search_args = load_credentials(twi... | done
| MIT | notebooks/1.0-jf-fetching-tweets-example.ipynb | joaopfonseca/solve-iwmi |
Count existing tweets for a given request | search_args = load_credentials(twitter_creds_path, yaml_key='search_tweets_api')
query = "(cyclone amphan)"
count_rule = gen_rule_payload(query, from_date="2020-05-14", to_date="2020-06-15", count_bucket="day", results_per_call=500)
counts = collect_results(count_rule, result_stream_args=search_args)
counts
tweets =... | _____no_output_____ | MIT | notebooks/1.0-jf-fetching-tweets-example.ipynb | joaopfonseca/solve-iwmi |
https://pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/why : reads image directly as np.array -> to directly image processNeeds : to add steps for saving (1 step for the orig capture and one for the processed image) | # import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
rawCapture = PiRGBArray(camera)
# allow the camera to warmup
time.sleep(0.1)
# grab an image from the came... | _____no_output_____ | CC0-1.0 | capture_array.ipynb | trucabrac/Blob-process---tests |
**This notebook is an exercise in the [Python](https://www.kaggle.com/learn/python) course. You can reference the tutorial at [this link](https://www.kaggle.com/colinmorris/hello-python).**--- Welcome to your first set of Python coding problems. If this is your first time using Kaggle Notebooks, welcome! Notebooks ar... | print("You've successfully run some Python code")
print("Congratulations!") | You've successfully run some Python code
Congratulations!
| MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
Try adding another line of code in the cell above and re-running it. Now let's get a little fancier: Add a new code cell by clicking on an existing code cell, hitting the escape key, and then hitting the `a` or `b` key. The `a` key will add a cell above the current cell, and `b` adds a cell below.Great! Now you know ... | from learntools.core import binder; binder.bind(globals())
from learntools.python.ex1 import *
print("Setup complete! You're ready to start question 0.") | Setup complete! You're ready to start question 0.
| MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
0.*This is a silly question intended as an introduction to the format we use for hands-on exercises throughout all Kaggle courses.***What is your favorite color? **To complete this question, create a variable called `color` in the cell below with an appropriate value. The function call `q0.check()` (which we've alread... | # create a variable called color with an appropriate value on the line below
# (Remember, strings in Python must be enclosed in 'single' or "double" quotes)
color = "blue"
# Check your answer
q0.check() | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
Didn't get the right answer? How do you not even know your own favorite color?!Delete the `` in the line below to make one of the lines run. You can choose between getting a hint or the full answer by choosing which line to remove the `` from. Removing the `` is called uncommenting, because it changes that line from a ... | # q0.hint()
# q0.solution() | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
The upcoming questions work the same way. The only thing that will change are the question numbers. For the next question, you'll call `q1.check()`, `q1.hint()`, `q1.solution()`, for question 2, you'll call `q2.check()`, and so on. 1.Complete the code below. In case it's helpful, here is the table of available arithme... | pi = 3.14159 # approximate
diameter = 3
# Create a variable called 'radius' equal to half the diameter
radius = diameter/2
# Create a variable called 'area', using the formula for the area of a circle: pi times the radius squared
area = pi * (radius ** 2)
# Check your answer
q1.check()
# Uncomment and run the lines ... | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
2.Add code to the following cell to swap variables `a` and `b` (so that `a` refers to the object previously referred to by `b` and vice versa). | ########### Setup code - don't touch this part ######################
# If you're curious, these are examples of lists. We'll talk about
# them in depth a few lessons from now. For now, just know that they're
# yet another type of Python object, like int or float.
a = [1, 2, 3]
b = [3, 2, 1]
q2.store_original_ids()
##... | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
3a.Add parentheses to the following expression so that it evaluates to 1. | (5 - 3) // 2
#q3.a.hint()
# Check your answer (Run this code cell to receive credit!)
q3.a.solution() | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
3b. 🌶️Questions, like this one, marked a spicy pepper are a bit harder.Add parentheses to the following expression so that it evaluates to 0. | (8 - (3 * 2)) - (1 + 1)
#q3.b.hint()
# Check your answer (Run this code cell to receive credit!)
q3.b.solution() | _____no_output_____ | MIT | 1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb | AkashKumarSingh11032001/Kaggle_Course_Repository |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.