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 |
|---|---|---|---|---|---|
Class RecommenderEvaluatorIn order to become easier to evaluate the metrics, I created a class that receives all the original ratings and predicted ratings for every recommender system and defined functions to extract all the metrics established in section 1 of the capstone report. Lets take a look at a summary of the... | class RecommenderEvaluator:
def __init__(self, items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias):
self.items = items
self.actual_ratings = actual_ratings
# static data containing the average score given by each user
self.average_rating_... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test methods:Just to have an idea of the output of each method, lets call all them with a test user. At the next section we will calculate these metrics for all users. | userId = '64'
re = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test RMSE | re.rmse(userId) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test nDCG | re.nDCG(userId) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test Diversity - Price and Availability | re.price_diversity(userId)
re.availability_diversity(userId) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test Popularity | re.popularity(userId) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Test Precision@N | re.precision_at_n(userId) | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Average metrics by all usersEspefically for user 907, the recommendations from the user user came with all nulls (original dataset). This specifically impacted the RMSE calculation, as one Nan damaged the entire average calculation. So specifically for RMSE we did a separate calculation section. All the other metrics ... | re = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias)
i = 0
count = np.array([0,0,0,0,0])
for userId in actual_ratings.columns:
if(userId == '907'):
rmse_recommenders = re.rmse(userId).fillna(0)
else:
rmse_recommenders = re.rmse(userId)
... |
---
Average nDCG
---
content_based 0.136505
item_item 0.146798
matrix_fact 0.155888
pers_bias 0.125180
user_user 0.169080
Name: nDCG, dtype: float64
---
Average Price - Diversity Measure
---
mean std
content_based 19.286627 19.229536
user_user 21.961776... | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Final AnalysisIn terms of **RMSE**, the user-user collaborative filtering showed to be the most effective, despite it not being significantly better.For nDCG rank score, again user user and now item item collaborative filtering were the best.In terms of price diversity, the item item algorith was the most diverse, pro... | obs_ratings_list = []
content_based_list = []
user_user_list = []
item_item_list = []
matrix_fact_list = []
pers_bias_list = []
re = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias)
for userId in actual_ratings.columns:
observed_ratings = re.get_observed... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
In order to have an idea of the results, let's choose 3 users randomly to show the predictions using the new hybrid models | np.random.seed(42)
sample_users = np.random.choice(actual_ratings.columns, 3).astype(str)
print('sample_users: ' + str(sample_users)) | sample_users: ['1528' '3524' '417']
| MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Get recommenders' predictions for sample users in order to create input for ensemble models (hybridization I and II) | from collections import OrderedDict
df_sample = pd.DataFrame()
for user in sample_users:
content_based_ = re.content_based[user]
user_user_ = re.user_user[user]
item_item_ = re.item_item[user]
matrix_fact_ = re.matrix_fact[user]
pers_bias_ = re.pers_bias[user]
df_sample = df_sample.append(pd.Da... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Focus on Performance (RMSE) I - Linear Model | from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
linear = LinearRegression()
print('RMSE for linear ensemble of recommender systems:')
np.mean(cross_val_score(linear, dataset.drop('rating', axis=1), dataset['rating'], cv=5)) | RMSE for linear ensemble of recommender systems:
| MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Predictions for sample users: Creating top 5 recommendations for sample users | pred_cols = ['content_based','user_user','item_item','matrix_fact','pers_bias']
predictions = linear.fit(dataset.drop('rating', axis=1), dataset['rating']).predict(df_sample[pred_cols])
recommendations = pd.DataFrame(OrderedDict({'user':df_sample['user'], 'item':df_sample['item'], 'predictions':predictions}))
recommend... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Focus on Performance (RMSE) II - Emsemble | from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(random_state=42)
print('RMSE for non linear ensemble of recommender systems:')
np.mean(cross_val_score(rf, dataset.drop('rating', axis=1), dataset['rating'], cv=5)) | RMSE for non linear ensemble of recommender systems:
| MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Predictions for sample users: | predictions = rf.fit(dataset.drop('rating', axis=1), dataset['rating']).predict(df_sample[pred_cols])
recommendations = pd.DataFrame(OrderedDict({'user':df_sample['user'], 'item':df_sample['item'], 'predictions':predictions}))
recommendations.groupby('user').apply(lambda df_user : df_user.loc[df_user['predictions'].sor... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Focus on Recommendations - Top 1 from each RecommenderWith the all top 1 recommender, we can evaluate its performance not just with RMSE, but all the list metrics we evaluated before. As a business constraint, we will also pay more attention to the *precision@5* metric, as a general information on how good is the reco... | count_nDCG = np.array([0])
count_diversity_price = np.ndarray([1,2])
count_diversity_availability = np.ndarray([1,2])
count_popularity = np.array([0])
count_precision = np.array([0])
for userId in actual_ratings.columns:
top_n_1 = re.get_top_n(userId,1)
user_items = {}
user_items['top_1_all'] = [a[0] ... |
---
Average nDCG
---
top_1_all 0.159211
Name: nDCG, dtype: float64
---
Average Price - Diversity Measure
---
mean std
top_1_all 16.4625 14.741783
---
Average Availability - Diversity Measure
---
mean std
top_1_all 0.575683 0.161168
---
Average Popularity
---
top_... | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Predictions for sample users: | results = {}
for user_sample in sample_users:
results[user_sample] = [a[0] for a in list(re.get_top_n(user_sample, 1).values())]
results | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Focus on Recommendations - Switching algorithm Can we use a Content Based Recommender for items with less evaluations?We can see in the cumulative histogram that only around 20% of the rated items had 10 or more ratings. This signals us that maybe we can prioritize the use of a content based recommender or even a non... | import matplotlib.pyplot as plt
item_nbr_ratings = actual_ratings.apply(lambda col: np.sum(~np.isnan(col)), axis=1)
item_max_nbr_ratings = item_nbr_ratings.max()
range_item_max_nbr_ratings = range(item_max_nbr_ratings+1)
plt.figure(figsize=(15,3))
plt.subplot(121)
nbr_ratings_items = []
for i in range_item_max_nbr_ra... | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Geometric operations Overlay analysisIn this tutorial, the aim is to make an overlay analysis where we create a new layer based on geometries from a dataset that `intersect` with geometries of another layer. As our test case, we will select Polygon grid cells from `TravelTimes_to_5975375_RailwayStation_Helsinki.shp` t... | import geopandas as gpd
import matplotlib.pyplot as plt
import shapely.speedups
%matplotlib inline
# File paths
border_fp = "data/Helsinki_borders.shp"
grid_fp = "data/TravelTimes_to_5975375_RailwayStation.shp"
# Read files
grid = gpd.read_file(grid_fp)
hel = gpd.read_file(border_fp) | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
- Visualize the layers: | # Plot the layers
ax = grid.plot(facecolor='gray')
hel.plot(ax=ax, facecolor='None', edgecolor='blue') | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
Here the grey area is the Travel Time Matrix grid (13231 grid squares) that covers the Helsinki region, and the blue area represents the municipality of Helsinki. Our goal is to conduct an overlay analysis and select the geometries from the grid polygon layer that intersect with the Helsinki municipality polygon.When c... | # Ensure that the CRS matches, if not raise an AssertionError
assert hel.crs == grid.crs, "CRS differs between layers!" | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
Indeed, they do. Hence, the pre-requisite to conduct spatial operations between the layers is fullfilled (also the map we plotted indicated this).- Let's do an overlay analysis and create a new layer from polygons of the grid that `intersect` with our Helsinki layer. We can use a function called `overlay()` to conduct ... | intersection = gpd.overlay(grid, hel, how='intersection') | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
- Let's plot our data and see what we have: | intersection.plot(color="b") | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
As a result, we now have only those grid cells that intersect with the Helsinki borders. As we can see **the grid cells are clipped based on the boundary.**- Whatabout the data attributes? Let's see what we have: | print(intersection.head()) | car_m_d car_m_t car_r_d car_r_t from_id pt_m_d pt_m_t pt_m_tt \
0 29476 41 29483 46 5876274 29990 76 95
1 29456 41 29462 46 5876275 29866 74 95
2 36772 50 36778 56 5876278 33541 116 137
3 36898 49 ... | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
As we can see, due to the overlay analysis, the dataset contains the attributes from both input layers.- Let's save our result grid as a GeoJSON file that is commonly used file format nowadays for storing spatial data. | # Output filepath
outfp = "data/TravelTimes_to_5975375_RailwayStation_Helsinki.geojson"
# Use GeoJSON driver
intersection.to_file(outfp, driver="GeoJSON") | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
There are many more examples for different types of overlay analysis in [Geopandas documentation](http://geopandas.org/set_operations.html) where you can go and learn more. Aggregating dataData aggregation refers to a process where we combine data into groups. When doing spatial data aggregation, we merge the geometri... | # Conduct the aggregation
dissolved = intersection.dissolve(by="car_r_t")
# What did we get
print(dissolved.head()) | geometry car_m_d car_m_t \
car_r_t
-1 MULTIPOLYGON (((388000.000 6668750.000, 387750... -1 -1
0 POLYGON ((386000.000 6672000.000, 385750.000 6... 0 0
... | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
- Let's compare the number of cells in the layers before and after the aggregation: | print('Rows in original intersection GeoDataFrame:', len(intersection))
print('Rows in dissolved layer:', len(dissolved)) | Rows in original intersection GeoDataFrame: 3826
Rows in dissolved layer: 51
| MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
Indeed the number of rows in our data has decreased and the Polygons were merged together.What actually happened here? Let's take a closer look. - Let's see what columns we have now in our GeoDataFrame: | print(dissolved.columns) | Index(['geometry', 'car_m_d', 'car_m_t', 'car_r_d', 'from_id', 'pt_m_d',
'pt_m_t', 'pt_m_tt', 'pt_r_d', 'pt_r_t', 'pt_r_tt', 'to_id', 'walk_d',
'walk_t', 'GML_ID', 'NAMEFIN', 'NAMESWE', 'NATCODE'],
dtype='object')
| MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
As we can see, the column that we used for conducting the aggregation (`car_r_t`) can not be found from the columns list anymore. What happened to it?- Let's take a look at the indices of our GeoDataFrame: | print(dissolved.index) | Int64Index([-1, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
56],
dtype='int64', name='car_r_t')
| MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
Aha! Well now we understand where our column went. It is now used as index in our `dissolved` GeoDataFrame. - Now, we can for example select only such geometries from the layer that are for example exactly 15 minutes away from the Helsinki Railway Station: | # Select only geometries that are within 15 minutes away
dissolved.iloc[15]
# See the data type
print(type(dissolved.iloc[15]))
# See the data
print(dissolved.iloc[15].head()) | geometry (POLYGON ((388250.0001354316 6668750.000042891...
car_m_d 12035
car_m_t 18
car_r_d 11997
from_id 5903886
Name: 20, ... | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
As we can see, as a result, we have now a Pandas `Series` object containing basically one row from our original aggregated GeoDataFrame.Let's also visualize those 15 minute grid cells.- First, we need to convert the selected row back to a GeoDataFrame: | # Create a GeoDataFrame
selection = gpd.GeoDataFrame([dissolved.iloc[15]], crs=dissolved.crs) | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
- Plot the selection on top of the entire grid: | # Plot all the grid cells, and the grid cells that are 15 minutes a way from the Railway Station
ax = dissolved.plot(facecolor='gray')
selection.plot(ax=ax, facecolor='red') | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
Simplifying geometries Sometimes it might be useful to be able to simplify geometries. This could be something to consider for example when you have very detailed spatial features that cover the whole world. If you make a map that covers the whole world, it is unnecessary to have really detailed geometries because it ... | import geopandas as gpd
# File path
fp = "data/Amazon_river.shp"
data = gpd.read_file(fp)
# Print crs
print(data.crs)
# Plot the river
data.plot(); | PROJCS["Mercator_2SP",GEOGCS["GCS_GRS 1980(IUGG, 1980)",DATUM["D_unknown",SPHEROID["GRS80",6378137,298.257222101]],PRIMEM["Unknown",0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator_2SP"],PARAMETER["standard_parallel_1",-2],PARAMETER["central_meridian",-43],PARAMETER["false_easting",5000000],PARAMETER["false_n... | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
The LineString that is presented here is quite detailed, so let's see how we can generalize them a bit. As we can see from the coordinate reference system, the data is projected in a metric system using [Mercator projection based on SIRGAS datum](http://spatialreference.org/ref/sr-org/7868/). - Generalization can be do... | # Generalize geometry
data2 = data.copy()
data2['geom_gen'] = data2.simplify(tolerance=20000)
# Set geometry to be our new simlified geometry
data2 = data2.set_geometry('geom_gen')
# Plot
data2.plot()
# plot them side-by-side
%matplotlib inline
import matplotlib.pyplot as plt
#basic config
fig, (ax1,ax2) = plt.subp... | _____no_output_____ | MIT | geometric-operations.ipynb | AdrianKriger/Automating-GIS-Processess |
GNN Implementation- Name: Abhishek Aditya BS- SRN: PES1UG19CS019- VI Semester 'A' Section- Date: 27-04-2022 | import sys
if 'google.colab' in sys.modules:
%pip install -q stellargraph[demos]==1.2.1
import pandas as pd
import os
import stellargraph as sg
from stellargraph.mapper import FullBatchNodeGenerator
from stellargraph.layer import GCN
from tensorflow.keras import layers, optimizers, losses, metrics, Model
from sklear... | _____no_output_____ | MIT | Topics of Deep Learning Lab/Lab-3/GNN.ipynb | Abhishek-Aditya-bs/Lab-Projects-and-Assignments |
Within repo | import pandas as pd
train_file = ["mesos", "usergrid", "appceleratorstudio", "appceleratorstudio", "titanium", "aptanastudio", "mule", "mulestudio"]
test_file = ["usergrid", "mesos", "aptanastudio", "titanium", "appceleratorstudio", "titanium", "mulestudio", "mule"]
mae = [1.07, 1.14, 2.75, 1.99, 2.85, 3.41, 3.14, 2.3... | _____no_output_____ | MIT | abe0/ignore_process_csv.ipynb | awsm-research/gpt2sp |
Cross repo | import pandas as pd
train_file = ["clover", "talendesb", "talenddataquality", "mule", "talenddataquality", "mulestudio", "appceleratorstudio", "appceleratorstudio"]
test_file = ["usergrid", "mesos", "aptanastudio", "titanium", "appceleratorstudio", "titanium", "mulestudio", "mule"]
mae = [1.57, 2.08, 5.37, 6.36, 5.55,... | _____no_output_____ | MIT | abe0/ignore_process_csv.ipynb | awsm-research/gpt2sp |
Solution to puzzle number 5 | import pandas as pd
import numpy as np
data = pd.read_csv('../inputs/puzzle5_input.csv')
data = [val for val in data.columns]
data[:10] | _____no_output_____ | MIT | puzzle_notebooks/puzzle5.ipynb | fromdatavistodatascience/adventofcode2019 |
Part 5.1 After providing 1 to the only input instruction and passing all the tests, what diagnostic code does the program produce? More Rules: - Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. - Opcode 4 outputs the value of its only parameter. Functions now... | user_ID = 1
numbers = 1002,4,3,4,33
def opcode_instructions(intcode):
"Function that breaks the opcode instructions into pieces"
str_intcode = str(intcode)
opcode = str_intcode[-2:]
int_opcode = int(opcode)
return int_opcode
def extract_p_modes(intcode):
"Function that extracts the p_modes"
... | _____no_output_____ | MIT | puzzle_notebooks/puzzle5.ipynb | fromdatavistodatascience/adventofcode2019 |
Selecting the first speech to see what we need to clean. | filename = os.path.join(path, dirs[0]) # dirs is a list, and we are going to study the first element dirs[0]
text_file = open(filename, 'r') #open the first file dirs[0]
lines = text_file.read() # read the file
lines # print what is in the file
lines.replace('\n', ' ') # remove the \n symbols by replacing with an empty... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Putting all the speeches into a list, after cleaning them | #The filter() function returns an iterator were the items are filtered
#through a function to test if the item is accepted or not.
# str.isalpha : checks if it is an alpha character.
# lower() : transform everything to lower case
# split() : Split a string into a list where each word is a list item
# loop over all ... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Count Vectorize | #from notebook
#vectorizer = CountVectorizer(stop_words='english') #remove stop words: a, the, and, etc.
vectorizer = TfidfVectorizer(stop_words='english', max_df = 0.42, min_df = 0.01) #remove stop words: a, the, and, etc.
doc_word = vectorizer.fit_transform(sotu_data) #transform into sparse matrix (0, 1, 2, etc. for... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Compare how similar speeches are to one another | df_similarity = pd.DataFrame(pairwise_similarity.toarray(), index = dirs, columns = dirs)
df_similarity.head() #similarity dataframe, compares each document to eachother
df_similarity.to_pickle("df_similarity.pkl") #pickle file
df_similarity['Speech_str'] = dirs #matrix comparing speech similarity
df_similarity['Yea... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Transforming the doc into a dataframe | # We have to convert `.toarray()` because the vectorizer returns a sparse matrix.
# For a big corpus, we would skip the dataframe and keep the output sparse.
#pd.DataFrame(doc_word.toarray(), index=sotu_data, columns=vectorizer.get_feature_names()).head(10) #doc_word.toarray() makes 7x19 table, otherwise it would be
#... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Topic Modeling using nmf | n_topics = 8 # number of topics
nmf_model = NMF(n_topics) # create an object
doc_topic = nmf_model.fit_transform(doc_word) #break into 10 components like SVD
topic_word = pd.DataFrame(nmf_model.components_.round(3), #,"component_9","component_10","component_11","component_12"
index = ["component_1","compon... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Top 15 words in each component | n_top_words = 15
feature_names = vectorizer.get_feature_names()
print_top_words(nmf_model, feature_names, n_top_words)
#Component x Speech
H = pd.DataFrame(doc_topic.round(5), index=dirs, #,"component_9","component_10"
columns = ["component_1","component_2", "component_3","component_4","compo... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Use NMF to plot top 15 words for each of 8 components def plot_top_words(model, feature_names, n_top_words, title): fig, axes = plt.subplots(2, 4, figsize=(30, 15), sharex=True) axes = axes.flatten() for topic_idx, topic in enumerate(model.components_): top_features_ind = topic.argsort()[:-n_top_words ... | n_top_words = 12
feature_names = vectorizer.get_feature_names()
plot_top_words(nmf_model, feature_names, n_top_words,
'Topics in NMF model') #title
| _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Sort speeches Chronologically | H1 = H
H1['Speech_str'] = dirs
H1['Year'] = H1['Speech_str'].replace('[^0-9]', '', regex=True)
H1 = H1.sort_values(by = ['Year'])
H1.to_csv("Data_H1.csv", index = False) #Save chronologically sorted speeches in this csv
H1.head()
H1.to_pickle("H1.pkl") #pickle chronological csv file | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Plots of Components over Time (check Powerpoint/Readme for more insights) | plt.subplots(4, 2, figsize=(30, 15), sharex=True)
plt.rcParams.update({'font.size': 20})
plt.subplot(4, 2, 1)
plt.plot(H1['Year'], H1['component_1'] ) #Label axis and titles for all plots
plt.title("19th Century Economic Terms")
plt.xlabel("Year")
plt.ylabel("Component_1")
plt.axhline(y=0.0, color='k', linestyle='... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 1: 19th Century Economics | H1.iloc[75:85] #Starts 1831. Peak starts 1868 (apex=1894), Nosedive in 1901 w/ Teddy. 4 Yr resurgence under Taft (1909-1912) | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 2: Modern Economic Language | H1.iloc[205:215] #1960s: Starts under JFK in 1961, peaks w/ Clinton, dips post 9/11 Bush, resurgence under Obama | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 3: Growth of US Government and Federal Programs | H1.iloc[155:165] #1921, 1929-1935. Big peak in 1946-1950 (1951 Cold War). 1954-1961 Eisenhower. Low after Reagan Revolution (1984) | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 4: Early Foreign Policy and War | H1.iloc[30:40] #Highest from 1790-1830, Washington to Jackson | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 5: Progressive Era, Roaring 20s | H1.iloc[115:125] #Peaks in 1900-1930.Especially Teddy Roosevelt. Dip around WW1 | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 6: War Before, During, and After the Civil War | H1.iloc[70:80] #Starts w/ Jackson 1829, Peaks w/ Mexican-American War (1846-1848). Drops 60% w/ Lincoln. Peak ends w/ Johnson 1868. Remains pretty low after 1876 (Reconstruction ends) | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 7: World Wars and Korean War | H1.iloc[155:165] #Minor Peak around WW1. Masssive spike a response of Cold War, Korean War (1951). Eisenhower drops (except 1960 U2). Johnson Vietnam. Peaks again 1980 (Jimmy Carter foreign policy crises) | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Component 8: Iraq War and Terrorism | H1.iloc[210:220] #Minor peak w/ Bush 1990. BIG peak w/ Bush 2002. Ends w/ Obama 2009. Resurgence in 2016/18 (ISIS?) | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Word Cloud | from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
speech_name = 'Lincoln_1864.txt'
sotu_dict[path + '\\' + speech_name]
#example = sotu_data[0]
example = sotu_dict[path + '\\' + speech_name]
wordcloud = WordCloud(max_words=100).generate(example)
plt.title("WordCloud of " + speech_name)
plt.imshow(wordclou... | _____no_output_____ | MIT | state_of_union_main.ipynb | gequitz/State_of_The_Union_Analysis_NLP |
Average Monthly Temperatures, 1970-2004**Date:** 2021-12-02**Reference:** | library(TTR)
options(
jupyter.plot_mimetypes = "image/svg+xml",
repr.plot.width = 7,
repr.plot.height = 5
) | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
SummaryThe aim of this notebook was to show how to decompose seasonal time series data using **R** so the trend, seasonal and irregular components can be estimated.Data on the average monthly temperatures in central England from January 1970 to December 2004 was plotted.The series was decomposed using the `decompose` ... | monthlytemps <- read.csv("..\\..\\data\\moderntemps.csv")
head(monthlytemps)
modtemps <- monthlytemps$temperature | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
Plot the time series | ts_modtemps <- ts(modtemps, start = c(1970, 1), frequency = 12)
plot.ts(ts_modtemps, xlab = "year", ylab = "temperature") | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
The time series is highly seasonal with little evidence of a trend.There appears to be a constant level of approximately 10$^{\circ}$C. Decompose the dataUse the `decompose` function from `R.stats` to return estimates of the trend, seasonal, and irregular components of the time series. | decomp_ts <- decompose(ts_modtemps) | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
Seasonal factorsCalculate the seasonal factors of the decomposed time series.Cast the `seasonal` time series object held in `decomp_ts` to a `vector`, slice the new vector to isolate a single period, and then cast the sliced vector to a named `matrix`. | sf <- as.vector(decomp_ts$seasonal)
(matrix(sf[1:12], dimnames = list(month.abb, c("factors")))) | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
_Add a comment_ Plot the componentsPlot the trend, seasonal, and irregular components in a single graphic. | plot(decomp_ts, xlab = "year") | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
Plot the individual components of the decomposition by accessing the variables held in the `tsdecomp`.This will generally make the components easier to understand. | plot(decomp_ts$trend, xlab = "year", ylab = "temperature (Celsius)")
title(main = "Trend component")
plot(decomp_ts$seasonal, xlab = "year", ylab = "temperature (Celsius)")
title(main = "Seasonal component")
plot(decomp_ts$random, xlab = "year", ylab = "temperature (Celsius)")
title(main = "Irregular component") | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
_Add comment on trend, seasonal, and irregular components.__Which component dominates the series?_ Seasonal adjusted plotPlot the seasonally adjusted series by subtracting the seasonal factors from the original series. | adjusted_ts <- ts_modtemps - decomp_ts$seasonal
plot(adjusted_ts, xlab = "year", ylab = "temperature (Celsius)")
title(main = "Seasonally adjusted series") | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
This new seasonally adjusted series only contains the trend and irregular components, so it can be treated as if it is non-seasonal data.Estimate the trend component by taking the simple moving order of order 35. | sma35_adjusted_ts <- SMA(adjusted_ts, n = 35)
plot.ts(sma35_adjusted_ts, xlab = "year", ylab = "temperature (Celsius)")
title(main = "Trend component (ma35)") | _____no_output_____ | MIT | jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb | ljk233/R249 |
PySchools without Thomas High School 9th graders Dependencies and data | # Dependencies
import os
import numpy as np
import pandas as pd
# School data
school_path = os.path.join('data', 'schools.csv') # school data path
school_df = pd.read_csv(school_path)
# Student data
student_path = os.path.join('data', 'students.csv') # student data path
student_df = pd.read_csv(student_path)
school_d... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Clean student names | # Prefixes to remove: "Miss ", "Dr. ", "Mr. ", "Ms. ", "Mrs. "
# Suffixes to remove: " MD", " DDS", " DVM", " PhD"
fixes_to_remove = ['Miss ', '\w+\. ', ' [DMP]\w?[DMS]'] # regex for prefixes and suffixes
str_to_remove = r'|'.join(fixes_to_remove) # join into a single raw str
# Remove inappropriate prefixes and suffix... | ['Juan', 'Noah', 'Cory', 'Omar', 'Eric', 'Ryan', 'Sean', 'Jon', 'Cody', 'Todd', 'Erik', 'Greg', 'Adam', 'Seth', 'Tony', 'Mark'] ['V', 'IV', 'Jr.', 'III', 'II']
| MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Merge data | # Add binary vars for passing score
student_df['pass_read'] = (student_df.reading_score >= 70).astype(int) # passing reading score
student_df['pass_math'] = (student_df.math_score >= 70).astype(int) # passing math score
student_df['pass_both'] = np.min([student_df.pass_read, student_df.pass_math], axis=0) # passing bot... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 39170 entries, 0 to 39169
Data columns (total 17 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Student ID 39170 non-null int64
1 student_name 39170 non-null object
2 gender... | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
District summary | # District summary
district_summary = pd.DataFrame(school_df[['size', 'budget']].sum(), columns=['District']).T
district_summary['Total Schools'] = school_df.shape[0]
district_summary = district_summary[['Total Schools', 'size', 'budget']]
district_summary_cols = ['Total Schools', 'Total Students', 'Total Budget']
dist... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
School summary | # School cols
school_cols = ['type', 'size', 'budget', 'budget_per_student',
'reading_score', 'math_score', 'pass_read', 'pass_math', 'pass_both']
school_cols_new = ['School Type', 'Total Students', 'Total Budget', 'Budget Per Student']
school_cols_new += score_cols_new
# School summary
school_summary ... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Scores by grade | # Reading scores by grade of each school
grade_read_scores = pd.pivot_table(df, index='school_name', columns='grade',
values='reading_score', aggfunc='mean').round(2)
grade_read_scores.index.name = None
grade_read_scores.columns.name = 'Reading scores'
grade_read_scores = grade_read_... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Scores by budget per student | # Scores by spending
spending_scores = df.groupby('spending_lvl')[score_cols].mean().round(2)
for col in spending_scores.columns:
if "pass" in col:
spending_scores[col] = (spending_scores[col] * 100).astype(int)
spending_scores
# Formatting
spending_scores.index.name = 'Spending Level'
spending_scores.colum... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Scores by school size | # Scores by school size
size_scores = df.groupby('school_size')[score_cols].mean().round(2)
for col in size_scores.columns:
if "pass" in col:
size_scores[col] = (size_scores[col] * 100).astype(int)
size_scores
# Formatting
size_scores.index.name = 'School Size'
size_scores.columns = score_cols_new
size_scor... | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
Scores by school type | # Scores by school type
type_scores = df.groupby('type')[score_cols].mean().round(2)
for col in type_scores.columns:
if "pass" in col:
type_scores[col] = (type_scores[col] * 100).astype(int)
type_scores
# Formatting
type_scores.index.name = 'School Type'
type_scores.columns = score_cols_new
type_scores | _____no_output_____ | MIT | pyschools/analysis2.ipynb | tri-bui/sandbox-analytics |
InstructionsImplement multi output cross entropy loss in pytorch.Throughout this whole problem we use multioutput models:* predicting 4 localization coordinates* predicting 4 keypoint coordinates + whale id and callosity pattern* predicting whale id and callosity patternIn order for that to work your loss function nee... | def solution(outputs, targets):
"""
Args:
outputs: list of torch.autograd.Variables containing model outputs
targets: list of torch.autograd.Variables containing targets for each output
Returns:
loss_value: torch.autograd.Variable object
"""
return loss_value | _____no_output_____ | MIT | resources/whales/tasks/task5.ipynb | pknut/minerva |
**ANALYSIS OF FINANCIAL INCLUSION IN EAST AFRICA BETWEEN 2016 TO 2018** DEFINING QUESTION The research problem is to figure out how we can predict which individuals are most likely to have or use a bank account. METRIC FOR SUCCESS My solution procedure will be to help provide an indication of the state of financial ... | # importing libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
READING AND CHECKING DATA | # loading and viewing variable definitions dataset
url = "http://bit.ly/VariableDefinitions"
vb_df = pd.read_csv(url)
vb_df
# loading and viewing financial dataset
url2 = "http://bit.ly/FinancialDataset"
fds = pd.read_csv(url2)
fds
fds.shape
fds.head()
fds.tail()
fds.dtypes
fds.columns
fds.info()
fds.describe()
fds.d... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
EXTERNAL DATA SOURCE VALIDATION FinAccess Kenya 2018: https://fsdkenya.org/publication/finaccess2019/Finscope Rwanda 2016: http://www.statistics.gov.rw/publication/finscope-rwanda-2016 Finscope Tanzania 2017: http://www.fsdt.or.tz/finscope/Finscope Uganda 2018: http://fsduganda.or.ug/finscope-2018-survey-report/ CLEA... | fds.head(2)
# CHECKING FOR OUTLIERS IN YEAR COLUMN
sns.boxplot(x=fds['year'])
fds.shape
# dropping year column outliers
fds1= fds[fds['year']<2020]
fds1.shape
# CHECKING FOR OUTLIERS IN HOUSEHOLD SIZE COLUMN
sns.boxplot(x=fds1['household_size'])
# dropping household size outliers
fds2 =fds1[fds1['ho... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
**EXPLORATORY ANALYSIS** 1.UNIVARIATE ANALYSIS a. NUMERICAL VARIABLES MODE |
fds5['year'].mode()
fds5['household_size'].mode()
fds5['age_of_respondent'].mode() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
MEAN | fds5['age_of_respondent'].mean()
fds5['household_size'].mean()
fds5.mean() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
MEDIAN | fds5['age_of_respondent'].median()
fds5['household_size'].median()
fds5.median() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
RANGE | a = fds5['age_of_respondent'].max()
b = fds5['age_of_respondent'].min()
c = a-b
print('The range of the age for the respondents is', c)
d = fds5['household_size'].max()
e = fds5['household_size'].min()
f = d-e
print('The range of the household_sizes is', f) | The range of the household_sizes is 8.0
| MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
QUANTILE AND INTERQUANTILE | fds5.quantile([0.25,0.5,0.75])
# FINDING THE INTERQUANTILE RANGE = IQR
Q3 = fds5['age_of_respondent'].quantile(0.75)
Q2 = fds5['age_of_respondent'].quantile(0.25)
IQR= Q3-Q2
print('The IQR for the respondents age is', IQR)
q3 = fds5['household_size'].quantile(0.75)
q2 = fds5['household_size'].quantile(0.25)
iqr = q3-q2... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
STANDARD DEVIATION | fds5.std() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
VARIANCE | fds5.var() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
KURTOSIS | fds5.kurt() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
SKEWNESS | fds5.skew()
| _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
b. CATEGORICAL MODE | fds5.mode().head(1)
fds5['age_of_respondent'].plot(kind="hist")
plt.xlabel('ages of respondents')
plt.ylabel('frequency')
plt.title(' Frequency of the ages of the respondents')
country=fds5['country'].value_counts()
print(country)
# Plotting the pie chart
colors=['pink','white','cyan','yellow']
country.plot(kind='pie'... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
CONCLUSION AND RECOMMENDATION Most of the data was collected in Rwanda.Most of the data was collected in Rural areas.Most of those who were interviewed were women.Most of the population has mobile phones.There were several outliers.Since 75% of the population has phones, phones should be used as the main channel for i... | fds5.head()
#@title Since i am predicting the likelihood of the respondents using the bank,I shall be comparing all variables against the bank account column.
| _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
NUMERICAL VS NUMERICAL | sns.pairplot(fds5)
plt.show()
# pearson correlation of numerical variables
sns.heatmap(fds5.corr(),annot=True)
plt.show()
# possible weak correlation
fds5.corr() | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
CATEGORICAL VS CATEGORICAL | # Grouping bank usage by country
country1 = fds5.groupby('country')['bank account'].value_counts(normalize=True).unstack()
colors= ['lightpink', 'skyblue']
country1.plot(kind='bar', figsize=(8, 6), color=colors, stacked=True)
plt.title('Bank usage by country', fontsize=15, y=1.015)
plt.xlabel('country', fontsize=14, ... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
NUMERICAL VS CATEGORICAL IMPLEMENTING AND CHALLENGING SOLUTION | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT | |
Most of those interviewed do not have bank accounts of which 80% is the uneducated.Most of the population that participated is married,followed by single/never married.Most of the population has primary school education level.Most of the population is involved in farming followed by self employment.Bank usage has more ... | # Multivariate analysis - This is a statistical analysis that involves observation and analysis of more than one statistical outcome variable at a time
# LETS MAKE A COPY
fds_new = fds5.copy()
fds_new.columns
fds_new.dtypes
# IMPORTING THE LABEL ENCODER
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
FACTOR ANALYSIS |
# Installing factor analyzer
!pip install factor_analyzer==0.2.3
from factor_analyzer.factor_analyzer import calculate_bartlett_sphericity
chi_square_value,p_value=calculate_bartlett_sphericity(fds_new)
chi_square_value, p_value
# In Bartlett ’s test, the p-value is 0. The test was statistically significant,
# in... | _____no_output_____ | MIT | Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb | MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT |
Configure | sample_size = 0
max_closure_size = 10000
max_distance = 0.22
cluster_distance_threshold = 0.155
super_cluster_distance_threshold = 0.205
num_candidates = 1000
eps = 0.000001
model_filename = '../data/models/anc-triplet-bilstm-100-512-40-05.pth'
# process_nicknames = True
# werelate_names_filename = 'givenname_similar_... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Read WeRelate names into all_namesLater, we'll want to read frequent FS names into all_names | # TODO rewrite this in just a few lines using pandas
def load_werelate_names(path, is_surname):
name_variants = defaultdict(set)
with fopen(path, mode="r", encoding="utf-8") as f:
is_header = True
for line in f:
if is_header:
is_header = False
continue... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Read nicknames and remove from names | def load_nicknames(path):
nicknames = defaultdict(set)
with fopen(path, mode="r", encoding="utf-8") as f:
for line in f:
names = line.rstrip().split(" ")
# normalize should only return a single name piece, but loop just in case
for name_piece in normalize(names[0], Fa... | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Map names to ids | def map_names_to_ids(names):
ids = range(len(names))
return dict(zip(names, ids)), dict(zip(ids, names))
name_ids, id_names = map_names_to_ids(all_names)
print(next(iter(name_ids.items())), next(iter(id_names.items()))) | _____no_output_____ | MIT | reports/80_cluster_anc_triplet-initial.ipynb | rootsdev/nama |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.