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
The **operator** Module
import operator dir(operator)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Arithmetic Operators A variety of arithmetic operators are implemented.
operator.add(1, 2) operator.mul(2, 3) operator.pow(2, 3) operator.mod(13, 2) operator.floordiv(13, 2) operator.truediv(3, 2)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
These would have been very handy in our previous section:
from functools import reduce reduce(lambda x, y: x*y, [1, 2, 3, 4])
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Instead of defining a lambda, we could simply use **operator.mul**:
reduce(operator.mul, [1, 2, 3, 4])
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Comparison and Boolean Operators Comparison and Boolean operators are also implemented as functions:
operator.lt(10, 100) operator.le(10, 10) operator.is_('abc', 'def')
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
We can even get the truthyness of an object:
operator.truth([1,2]) operator.truth([]) operator.and_(True, False) operator.or_(True, False)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Element and Attribute Getters and Setters We generally select an item by index from a sequence by using **[n]**:
my_list = [1, 2, 3, 4] my_list[1]
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
We can do the same thing using:
operator.getitem(my_list, 1)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
If the sequence is mutable, we can also set or remove items:
my_list = [1, 2, 3, 4] my_list[1] = 100 del my_list[3] print(my_list) my_list = [1, 2, 3, 4] operator.setitem(my_list, 1, 100) operator.delitem(my_list, 3) print(my_list)
[1, 100, 3]
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
We can also do the same thing using the **operator** module's **itemgetter** function.The difference is that this returns a callable:
f = operator.itemgetter(2)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Now, **f(my_list)** will return **my_list[2]**
f(my_list) x = 'python' f(x)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Furthermore, we can pass more than one index to **itemgetter**:
f = operator.itemgetter(2, 3) my_list = [1, 2, 3, 4] f(my_list) x = 'pytyhon' f(x)
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Similarly, **operator.attrgetter** does the same thing, but with object attributes.
class MyClass: def __init__(self): self.a = 10 self.b = 20 self.c = 30 def test(self): print('test method running...') obj = MyClass() obj.a, obj.b, obj.c f = operator.attrgetter('a') f(obj) my_var = 'b' operator.attrgetter(my_var)(obj) my_var = 'c' operator.attrgetter(m...
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Of course, attributes can also be methods.In this case, **attrgetter** will return the object's **test** method - a callable that can then be called using **()**:
f = operator.attrgetter('test') obj_test_method = f(obj) obj_test_method()
test method running...
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Just like lambdas, we do not need to assign them to a variable name in order to use them:
operator.attrgetter('a', 'b')(obj) operator.itemgetter(2, 3)('python')
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Of course, we can achieve the same thing using functions or lambdas:
f = lambda x: (x.a, x.b, x.c) f(obj) f = lambda x: (x[2], x[3]) f([1, 2, 3, 4]) f('python')
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Use Case Example: Sorting Suppose we want to sort a list of complex numbers based on the real part of the numbers:
a = 2 + 5j a.real l = [10+1j, 8+2j, 5+3j] sorted(l, key=operator.attrgetter('real'))
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Or if we want to sort a list of string based on the last character of the strings:
l = ['aaz', 'aad', 'aaa', 'aac'] sorted(l, key=operator.itemgetter(-1))
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Or maybe we want to sort a list of tuples based on the first item of each tuple:
l = [(2, 3, 4), (1, 2, 3), (4, ), (3, 4)] sorted(l, key=operator.itemgetter(0))
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Slicing
l = [1, 2, 3, 4] l[0:2] l[0:2] = ['a', 'b', 'c'] print(l) del l[3:5] print(l)
['a', 'b', 'c']
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
We can do the same thing this way:
l = [1, 2, 3, 4] operator.getitem(l, slice(0,2)) operator.setitem(l, slice(0,2), ['a', 'b', 'c']) print(l) operator.delitem(l, slice(3, 5)) print(l)
['a', 'b', 'c']
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Calling another Callable
x = 'python' x.upper() operator.methodcaller('upper')('python')
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Of course, since **upper** is just an attribute of the string object **x**, we could also have used:
operator.attrgetter('upper')(x)()
_____no_output_____
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
If the callable takes in more than one parameter, they can be specified as additional arguments in **methodcaller**:
class MyClass: def __init__(self): self.a = 10 self.b = 20 def do_something(self, c): print(self.a, self.b, c) obj = MyClass() obj.do_something(100) operator.methodcaller('do_something', 100)(obj) class MyClass: def __init__(self): self.a = 10 self.b = 20 ...
10 20 100
Apache-2.0
dd_1/Part 1/Section 06 - First-Class Functions/10 - The operator Module.ipynb
rebekka-halal/bg
Data types--- **EXERCISES** _1. What type of value is 3.4? How can you find out?_ **Solution**_It is a floating-point number (often abbreviated “float”)._
print(type(3.4))
<class 'float'>
MIT
semester2/notebooks/1.2-data-types-solutions.ipynb
pedrohserrano/global-studies
This is the basic load and clean stuff
# %load ~/dataviz/ExplorePy/clean-divvy-explore.py import pandas as pd import numpy as np import datetime as dt import pandas.api.types as pt import pytz as pytz from astral import LocationInfo from astral.sun import sun from astral.geocoder import add_locations, database, lookup from dateutil import parser as du_pr ...
LocationInfo(name='Chicago', region='USA', timezone='US/Central', latitude=41.833333333333336, longitude=-87.68333333333334) Loading /mnt/d/DivvyDatasets/rev5-divvy_trip_history_201909-202108.csv Converting start_time ID ...1 ride_id rideable_type started_at \ 0 1147482 826...
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Look at the average duration by rider type & day of week average duration by day of week for rider types
type(df_divvy['duration']) df_divvy.info() df_divvy.shape df_rider_by_dow = df_divvy.groupby(['member_casual','day_of_week']).agg(mean_time = ('duration', 'mean')).round(2) df_rider_by_dow df_rider_by_dow.sort_values(by=['member_casual','day_of_week'])
<class 'pandas.core.frame.DataFrame'> RangeIndex: 8190307 entries, 0 to 8190306 Data columns (total 32 columns): # Column Dtype --- ------ ----- 0 ID object 1 ...1 object 2 ride_id ...
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Now we want to plot
%matplotlib inline import matplotlib.pyplot as plt import seaborn as sns
_____no_output_____
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
bar plot of Duration by Rider Type and Day of Week
df_rider_by_dow.unstack('member_casual').plot(kind='bar') df_rider_by_dow.reset_index(inplace=True) sns.set(rc={"figure.figsize":(16,8)}) sns.barplot(data=df_rider_by_dow, x="day_of_week", y="mean_time", hue="member_casual")
_____no_output_____
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Look at the number of riders by type and day of week grouping
df_rider_by_dow = df_divvy.groupby(['member_casual','day_of_week']).agg(num_rides = ('ID', 'count')) df_rider_by_dow #df_rider_by_dow['day_of_week'] = df_rider_by_dow['day_of_week'].astype(cats_type) df_rider_by_dow.sort_values(by=['member_casual','day_of_week'])
_____no_output_____
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
plot of Number of Rids by Rider Type and Day of Week
df_rider_by_dow.unstack('member_casual').plot(kind='bar') df_rider_by_dow.reset_index(inplace=True) sns.set(rc={"figure.figsize":(16,8)}) sns.barplot(data=df_rider_by_dow, x="day_of_week", y="num_rides", hue="member_casual") df_member_by_yr_dow = df_divvy[df_divvy['member_casual'] == 'member'].groupby(['year','day_of_w...
_____no_output_____
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Let's look at starting in the dark by rider
df_rider_count_by_is_dark = df_divvy.groupby(['member_casual','is_dark']).agg(count = ('ID', 'count')) df_rider_count_by_is_dark.unstack('member_casual').plot(kind='bar', title='Rider count by starting in the dark') df_rider_by_time = df_divvy.groupby(['member_casual','start_cat']).agg(count = ('ID', 'count')) df_rider...
_____no_output_____
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Starting stations -- member
df_starting_member = df_divvy[df_divvy['member_casual']=='member'].groupby(['start_station_name']).agg(count=('ID','count')) df_starting_member = df_starting_member.sort_values(by='count', ascending=False) df_starting_member_top = df_starting_member.iloc[0:19] df_starting_member_top.plot(kind='bar', title="Starting Sta...
start_station_name,count Clark St & Elm St,11804 Theater on the Lake,11412 Wells St & Concord Ln,11294 Broadway & Barry Ave,9624 Clark St & Lincoln Ave,9435 Clark St & Armitage Ave,9319 Lake Shore Dr & North Blvd,9245 Wells St & Elm St,8896 Streeter Dr & Grand Ave,8820 Dearborn St & Erie St,8260 Larrabee St & Webster A...
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
Starting Stations - casual
df_starting_casual = df_divvy[df_divvy['member_casual']=='casual'].groupby(['start_station_name']).agg(count=('ID','count')) df_starting_casual = df_starting_casual.sort_values(by='count', ascending=False) df_starting_casual_top = df_starting_casual.iloc[0:19] df_starting_casual_top.head() df_starting_casual_weekday =...
start_station_name,count Streeter Dr & Grand Ave,42683 Lake Shore Dr & Monroe St,24422 Millennium Park,23273 Michigan Ave & Oak St,19327 Theater on the Lake,17348 Lake Shore Dr & North Blvd,14798 Shedd Aquarium,14373 Indiana Ave & Roosevelt Rd,12122 Clark St & Lincoln Ave,11290 Dusable Harbor,10879 Wells St & Concord L...
MIT
Notebook/HereItIs.ipynb
soddencarpenter/dataviz
osumapper: create osu! map using Tensorflow and Colab -- For osu!mania game mode --For mappers who don't know how this colaboratory thing works:- Press Ctrl+Enter in code blocks to run them one by one- It will ask you to upload .osu file and audio.mp3 after the third block of code- .osu file needs to have correct timi...
%cd /content/ !git clone https://github.com/kotritrona/osumapper.git %cd osumapper/v7.0 !apt install -y ffmpeg !apt install -y nodejs !cp requirements_colab.txt requirements.txt !cp package_colab.json package.json !pip install -r requirements.txt !npm install
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Step 2: Choose a pre-trained modelSet the select_model variable to one of:- "default": default model (choose only after training it)- "lowkey": model trained with 4-key and 5-key maps (☆2.5-5.5)- "highkey": model trained with 6-key to 9-key maps (☆2.5-5.5)
from mania_setup_colab import * select_model = "highkey" model_params = load_pretrained_model(select_model);
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Step 3: Upload map and music fileMap file = .osu file with correct timing (**Important:** Set to mania mode and the wished key count!)Music file = the mp3 file in the osu folder
from google.colab import files print("Please upload the map file:") mapfile_upload = files.upload() for fn in mapfile_upload.keys(): uploaded_osu_name = fn print('Uploaded map file: "{name}" {length} bytes'.format(name=fn, length=len(mapfile_upload[fn]))) print("Please upload the music file:") music_upload = files....
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Step 4: Read the map and convert to python readable format
from act_newmap_prep import * step4_read_new_map(uploaded_osu_name);
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Step 5: Use model to calculate map rhythmParameters:"note_density" determines how many notes will be placed on the timeline, ranges from 0 to 1."hold_favor" determines how the model favors holds against circles, ranges from -1 to 1."divisor_favor" determines how the model favors notes to be on X divisors starting from...
from mania_act_rhythm_calc import * model = step5_load_model(model_file=model_params["rhythm_model"]); npz = step5_load_npz(); params = model_params["rhythm_param"] # Or set the parameters here... # params = step5_set_params(note_density=0.6, hold_favor=0.2, divisor_favor=[0] * divisor, hold_max_ticks=8, hold_min_retu...
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Do a little modding to the map.Parameters:- key_fix: remove continuous notes on single key modes (0,1,2,3) 0=inactive 1=remove late note 2=remove early note 3=divert
modding_params = model_params["modding"] # modding_params = { # "key_fix" : 3 # } notes_each_key = mania_modding(notes_each_key, modding_params); notes, key_count = merge_objects_each_key(notes_each_key)
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
Finally, save the data into an .osu file!
from google.colab import files from mania_act_final import * saved_osu_name = step8_save_osu_mania_file(notes, key_count); files.download(saved_osu_name) # clean up if you want to make another map! # colab_clean_up(uploaded_osu_name)
_____no_output_____
Apache-2.0
v7.0/mania_Colab.ipynb
jsstwright/osumapper
First let's figure out how to generate an AR proces
def ar1(phi = .9, n = 100, init = 0): time_series = [init] error = np.random.randn(n) for period in range(n): time_series.append(error[period] + phi*time_series[-1]) return pd.Series(time_series[1:], index = range(n)) def ar2(phi1 = .9, phi2 = .8, n = 100, init = 0): time_series = [init...
_____no_output_____
MIT
TimeSeriesAnalysisWithPython-master/SciPyTimeSeries/.ipynb_checkpoints/09a. AR + MA processes-checkpoint.ipynb
sunny2309/scipy_conf_notebooks
Now let's generate an MA process
def ma1(theta = .5, n = 100): time_series = [] error = np.random.randn(n) for period in range(1,n): time_series.append(error[period] + theta*error[period-1]) return pd.Series(time_series[1:], index = range(1,n-1)) m1 = ma1(theta = -1000) m1.plot()
_____no_output_____
MIT
TimeSeriesAnalysisWithPython-master/SciPyTimeSeries/.ipynb_checkpoints/09a. AR + MA processes-checkpoint.ipynb
sunny2309/scipy_conf_notebooks
Let's look at ACF + PACF for each kind of process
a1 = ar1(phi = .5, n = 1000) a1_acf = acf(a1, nlags = 50) plt.plot(a1_acf) plt.axhline(y=0,linestyle='--', color = 'black') plt.axhline(y=-1.96/np.sqrt(len(a1)),linestyle='--', color = 'red') plt.axhline(y=1.96/np.sqrt(len(a1)),linestyle='--', color = 'red') a1 = ar1(phi = .5, n = 1000) a1_pacf = pacf(a1, nlags = 50) p...
_____no_output_____
MIT
TimeSeriesAnalysisWithPython-master/SciPyTimeSeries/.ipynb_checkpoints/09a. AR + MA processes-checkpoint.ipynb
sunny2309/scipy_conf_notebooks
__Pitfall__: if you get a dimension like `(134,)`, be careful! For linear regression and some models, this works just fine, but for some other models such as CNN/RNN, this dimension will result in sth unexpected and very hard to debug. As a good habit, you should always check your one-dimensional array and make sure th...
df_y.head() df_y = df.filter(items=['survived']) # to get the right shape, use filter() df_y.shape df_y.head() reg = linear_model.LinearRegression() x_train, x_test, y_train, y_test = train_test_split(df_x, df_y, test_size=0.2, random_state=0) reg.fit(x_train, y_train) reg.predict(x_test) mean_squared_error(y_test, re...
_____no_output_____
CC0-1.0
database/MongoDB notebooks/06_linear regression on titanic data set.ipynb
neo-mashiro/BU
Evaluate a privacy policyToday, virtually every organization with which you interact will collect or use some about you. Most typically, the collection and use of these data will be disclosed according to an organization's privacy policy. We encounter these privacy polices all the time, when we create an account on a ...
# run the following commands to install the needed packages """ pip install pandas pip install spacy python -m spacy download en_core_web_lg pip install textacy pip install gensim pip install umap pip install matplotlib """ # load some packages import pandas as pd import json import spacy import textacy import gensim i...
/Users/rfunk/.pyenv/versions/anaconda3-2019.10/lib/python3.7/site-packages/tqdm/std.py:697: FutureWarning: The Panel class is removed from pandas. Accessing it from the top-level namespace will also be removed in the next version from pandas import Panel
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Now, let's go ahead and load the data.
# load the data with open("data/policies.json") as f: policies_df = pd.DataFrame({k:" ".join(v) for k,v in json.load(f).items()}.items(), columns=["url","policy_text"]) # check out the results policies_df.head()
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Looks pretty reasonable. We have one column for the URL and one for the full text of the privacy policy. Note that the orignal data come in a json format, and there, each URL is associated with a set of paragraphs that constitute each privacy policy. In the code above, when we load the data, we concatenate these paragr...
#policies_df = policies_df.sample(frac=0.20) # set frac to some fraction that will run in a reasonable time on your machine policies_df["policy_text_processed"] = policies_df.policy_text.progress_apply(nlp)
100%|██████████| 4062/4062 [09:28<00:00, 7.15it/s]
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
With that simple line of code, spacy has done a bunch of hard work for us, including things like tokenization, part-of-speech tagging, entity parsing, and other stuff that go well beyond our needs today. Let's take a quick look.
policies_df.head()
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Okay, at this point, we've loaded all the packages we need, and we've done some of the basic wrangling necessary to get the data into shape. We'll need to do a little more data wrangling to prepare for a few of the analyses in store below, but we've already done enough to let us get started. So without further ado, let...
# define a processing function process_gensim = lambda tokens: [token.lemma_.lower() for token in tokens if not(token.is_punct or token.is_stop or token.is_space or token.is_digit)] # apply the function policies_df["policy_text_gensim"] = policies_df.policy_text_processed.apply(process_gensim) # create a gensim dictio...
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
As a bonus, we can also check the coherence, essentially a model fit (generally, these measures look at similarity among high scoring words in topics). If you're so inclined, you can re-run the topic model above with different hyperparameters to see if you can get a better fit; I didn't spend a whole lot of time tuning...
# get coherence coherence_model_lda = gensim.models.CoherenceModel(model=lda_model, texts=policies_df["policy_text_gensim"], dictionary=gensim_dict, coherence="c_v") coherence_model_lda.get_coherence()
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Take a look at the topics identified by the models above. Can you assign human-interpretable labels to them? What can you learn about the different topics of discussion in privacy policies? Key words in contextTopic models are nice, but they're a bit abstract. They give us an overview about interesting clusters of wor...
KEYWORD = "right" # "third party" # privacy, right, duty, selling, disclose, trust, inform NUM_FIRMS = 20 with pd.option_context("display.max_colwidth", 100, "display.min_rows", NUM_FIRMS, "display.max_rows", NUM_FIRMS): display( pd.DataFrame(policies_df.sample(n=NUM_FIRMS).apply(lambda row: list(textacy.t...
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Run the code for some different words, not just the ones in my list, but also those that interest you. Can you learn anything about corporate mindsets on privacy? What kind of rights are discussed? Named entitiesAnother way we can gain some insight into the content of privacy policies is by seeing who exactly they dis...
# extract named entities from the privacy policies pull_entities = lambda policy_text: list(set([entity.text.lower() for entity in policy_text.ents if entity.label_ in ("ORG", "PERSON")])) policies_df["named_entities"] = policies_df.policy_text_processed.apply(pull_entities)
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Let's take a quick peek at our data frame and see what the results look like.
# look at the entities with pd.option_context("display.max_colwidth", 100, "display.min_rows", 50, "display.max_rows", 50): display(policies_df[["url","named_entities"]].head(50))
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Now let's add a bit more structure. We'll run a little code to help us identify the most frequently discussed organizations and people in the corporate privacy policies.
# pull the most frequent entities entities = policies_df["named_entities"].explode("named_entities") NUM_WANTED = 50 with pd.option_context("display.min_rows", 50, "display.max_rows", 50): display(entities.groupby(entities).size().sort_values(ascending=False).head(50))
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
What do you make of the most frequent entities? Are you surprised? Do they fit with what you expected? Can we make any inferences about the kind of data sharing companies might be enaging in by looking at these entities? ReadabilityNext, we'll evaluate the privacy policies according to their readability. There are man...
# compute a bunch of text statistics (including readability) policies_df["TextStats"] = policies_df.policy_text_processed.apply(textacy.text_stats.TextStats)
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
You can now access the various statistics for individual documents as follows (e.g., for the document at index 0).
policies_df.iloc[0]["TextStats"].flesch_kincaid_grade_level
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
This tells us that the Flesch-Kinkaid grade level for the policy is just under 12th grade. We're probably not terribly interested in the readability of any given policy. We can do a little wrangling with pandas to extract various metrics for all policies and add them to the data frame. Below, I'll pull out the Flesch-K...
# pull out a few readability metrics policies_df["flesch_kincaid_grade_level"] = policies_df.TextStats.apply(lambda ts: ts.flesch_kincaid_grade_level) policies_df["gunning_fog_index"] = policies_df.TextStats.apply(lambda ts: ts.gunning_fog_index) # let's also clean up some extreme values policies_df.loc[(policies_df.f...
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
I would encourage you to adapt the code above to pull out some other readability-related features that seem interesting. You can find the full list available in our `TextStats` object [here](https://textacy.readthedocs.io/en/stable/api_reference/misc.html), in the textacy documentation. Let's plot the values we just ex...
# plot with matplotlib fig, axes = plt.subplots(1, 2) policies_df["flesch_kincaid_grade_level"].hist(ax=axes[0]) policies_df["gunning_fog_index"].hist(ax=axes[1]) plt.tight_layout()
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
These results are pretty striking, especially when you consider them alongside statistics on the literacy rate in the United States. According to [surveys](https://www.oecd.org/skills/piaac/Country%20note%20-%20United%20States.pdf) by the OECD, about half of adults in the United States can read at an 8th grade level or...
# pull the document embeddings from spacy and format for clustering embeddings_df = policies_df[["url", "policy_text_processed"]] embeddings_df = embeddings_df.set_index("url") embeddings_df["policy_text_processed"] = embeddings_df["policy_text_processed"].apply(lambda text: text.vector) embeddings_df = embeddings_df.p...
_____no_output_____
MIT
sessions/privacy/privacy_policy.ipynb
russellfunk/data_privacy
Colab KSO Tutorial 12: Display movies available on the serverWritten by @jannesgg and @vykantonLast updated: Jun 19, 2022 Set up and requirements Install kso_data_management and its requirements
# Clone koster_data_management repo !git clone --recurse-submodules https://github.com/ocean-data-factory-sweden/koster_data_management.git !pip install -r koster_data_management/requirements.txt # Restart the session to load the latest packages exit()
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Import Python packages
# Set the directory of the libraries import sys, os from pathlib import Path # Enables testing changes in utils %load_ext autoreload %autoreload 2 # Specify the path of the tutorials os.chdir("koster_data_management/tutorials") sys.path.append('..') # Import required modules import kso_utils.tutorials_utils as t_uti...
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Choose your project
project_name = t_utils.choose_project()
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Initiate database
# Initiate db project = p_utils.find_project(project_name = project_name.value) db_info_dict = t_utils.initiate_db(project)
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Retrieve info of movies available on the server
available_movies_df = s_utils.retrieve_movie_info_from_server( project = project, db_info_dict = db_info_dict )
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Select the movie of interest
movie_selected = t_utils.select_movie(available_movies_df)
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Display the movie
movie_display, movie_path = t_utils.preview_movie( project = project, db_info_dict = db_info_dict, available_movies_df = available_movies_df, movie_i = movie_selected.value ) movie_display #END
_____no_output_____
MIT
colab_tutorials/COLAB_12_Display_movies_available_on_the_server.ipynb
ocean-data-factory-sweden/koster_zooniverse
Create a pandas series having values 4, 7, -5, 3, NAN and their index as d, b, a, c, e
# Write a code here import numpy as np import pandas as pd series = pd.Series([4,7,-5,3,np.nan], index=['d','b','a','c','e']) series
_____no_output_____
MIT
Arvind/Introduction to Pandas Series and Creating Series.ipynb
Arvind-collab/Data-Science
Import modules
import numpy as np import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense from handwritten_digits.utils_np import test_prediction from handwritten_digits.data import one_hot
_____no_output_____
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Load data
(X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = tf.keras.utils.normalize(X_train, axis=1) X_test = tf.keras.utils.normalize(X_test, axis=1)
_____no_output_____
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Define model architecture
model = Sequential([ Flatten(), Dense(784, activation=tf.nn.relu), Dense(128, activation=tf.nn.relu), Dense(32, activation=tf.nn.relu), Dense(10, activation=tf.nn.softmax), ])
_____no_output_____
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Train model
model.compile( optimizer="SGD", loss="sparse_categorical_crossentropy", metrics=["accuracy"] ) model.fit(X_train, y_train, epochs=15)
Epoch 1/15 1875/1875 [==============================] - 23s 12ms/step - loss: 0.9401 - accuracy: 0.7679 Epoch 2/15 1875/1875 [==============================] - 22s 12ms/step - loss: 0.3231 - accuracy: 0.9072 Epoch 3/15 1875/1875 [==============================] - 22s 12ms/step - loss: 0.2497 - accuracy: 0.9272 Epoch 4/...
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Evaluate model performance
training_loss, training_accuracy = model.evaluate(x=X_train, y=y_train) test_loss, test_accuracy = model.evaluate(x=X_test, y=y_test)
1875/1875 [==============================] - 14s 7ms/step - loss: 0.0609 - accuracy: 0.9833 313/313 [==============================] - 3s 8ms/step - loss: 0.0963 - accuracy: 0.9692
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Evaluate predictions
# bring preds to same shape as in numpy model probs = model.predict(X_test) preds = probs == np.amax(probs, axis=1, keepdims=True) preds = preds.T.astype(float) # bring data to same shape as in numpy model X_test_reshaped = X_test.reshape(X_test.shape[0], -1).T y_test_reshaped = one_hot(y_test) random_index = np.random...
Prediction: 1 True label: 1
MIT
src/executables/model_tf.ipynb
frederik-schmidt/Handwritten-digits
Copyright 2020 Google LLC.Licensed under the Apache License, Version 2.0 (the "License");
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
DDSP Processor DemoThis notebook provides an introduction to the signal `Processor()` object. The main object type in the DDSP library, it is the base class used for Synthesizers and Effects, which share the methods:* `get_controls()`: inputs -> controls.* `get_signal()`: controls -> signal.* `__call__()`: inputs -> s...
#@title Install and import dependencies %tensorflow_version 2.x !pip install -qU ddsp # Ignore a bunch of deprecation warnings import warnings warnings.filterwarnings("ignore") import ddsp import ddsp.training from ddsp.colab.colab_utils import play, specplot, DEFAULT_SAMPLE_RATE import matplotlib.pyplot as plt impo...
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
Example: additive synthesizerThe additive synthesizer models a sound as a linear combination of harmonic sinusoids. Amplitude envelopes are generated with 50% overlapping hann windows. The final audio is cropped to n_samples. `__init__()`All member variables are initialized in the constructor, which makes it easy to ...
n_frames = 1000 hop_size = 64 n_samples = n_frames * hop_size # Create a synthesizer object. additive_synth = ddsp.synths.Additive(n_samples=n_samples, sample_rate=sample_rate, name='additive_synth')
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
`get_controls()` The outputs of a neural network are often not properly scaled and constrained. The `get_controls` method gives a dictionary of valid control parameters based on neural network outputs. **3 inputs (amps, hd, f0)*** `amplitude`: Amplitude envelope of the synthesizer output.* `harmonic_distribution`: Nor...
# Generate some arbitrary inputs. # Amplitude [batch, n_frames, 1]. # Make amplitude linearly decay over time. amps = np.linspace(1.0, -3.0, n_frames) amps = amps[np.newaxis, :, np.newaxis] # Harmonic Distribution [batch, n_frames, n_harmonics]. # Make harmonics decrease linearly with frequency. n_harmonics = 30 harm...
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
Consider the plots above as outputs of a neural network. These outputs violate the synthesizer's expectations:* Amplitude is not >= 0 (avoids phase shifts)* Harmonic distribution is not normalized (factorizes timbre and amplitude)* Fundamental frequency * n_harmonics > nyquist frequency (440 * 20 > 8000), which will le...
controls = additive_synth.get_controls(amps, harmonic_distribution, f0_hz) print(controls.keys()) # Now let's see what they look like... time = np.linspace(0, n_samples / sample_rate, n_frames) plt.figure(figsize=(18, 4)) plt.subplot(131) plt.plot(time, controls['amplitudes'][0, :, 0]) plt.xticks([0, 1, 2, 3, 4]) plt....
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
Notice that * Amplitudes are now all positive* The harmonic distribution sums to 1.0* All harmonics that are above the Nyquist frequency now have an amplitude of 0. The amplitudes and harmonic distribution are scaled by an "exponentiated sigmoid" function (`ddsp.core.exp_sigmoid`). There is nothing particularly special...
x = tf.linspace(-10.0, 10.0, 1000) y = ddsp.core.exp_sigmoid(x) plt.figure(figsize=(18, 4)) plt.subplot(121) plt.plot(x, y) plt.subplot(122) _ = plt.semilogy(x, y)
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
`get_signal()`Synthesizes audio from controls.
audio = additive_synth.get_signal(**controls) play(audio) specplot(audio)
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
`__call__()` Synthesizes audio directly from the raw inputs. `get_controls()` is called internally to turn them into valid control parameters.
audio = additive_synth(amps, harmonic_distribution, f0_hz) play(audio) specplot(audio)
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
Example: Just for fun... Let's run another example where we tweak some of the controls...
## Some weird control envelopes... # Amplitude [batch, n_frames, 1]. amps = np.ones([n_frames]) * -5.0 amps[:50] += np.linspace(0, 7.0, 50) amps[50:200] += 7.0 amps[200:900] += (7.0 - np.linspace(0.0, 7.0, 700)) amps *= np.abs(np.cos(np.linspace(0, 2*np.pi * 10.0, n_frames))) amps = amps[np.newaxis, :, np.newaxis] #...
_____no_output_____
Apache-2.0
ddsp/colab/tutorials/0_processor.ipynb
kyjohnso/ddsp
Brazil
plot_bra2 = pd.read_csv('sensi_withhold_bra.csv') eff_new = pd.DataFrame( np.array([np.repeat(list(plot_bra2['intervention']),320), plot_bra2[plot_bra2.columns[2:]].values.reshape(1,-1)[0]]).T, columns=['intervention','x']) eff_new['x'] = eff_new['x'].astype(float) eff_new['color'] =([1]*319+[0.1...
_____no_output_____
MIT
plot/plot_robust_sample.ipynb
lunliu454/infect_place
Japan
plot_jp2 = pd.read_csv('sensi_withhold_jp.csv') plot_jp2 eff_new = pd.DataFrame( np.array([np.repeat(list(plot_jp2['intervention']),46), plot_jp2[plot_jp2.columns[2:]].values.reshape(1,-1)[0]]).T, columns=['intervention','x']) eff_new['x'] = eff_new['x'].astype(float) eff_new['color'] =([1]*45+[0...
_____no_output_____
MIT
plot/plot_robust_sample.ipynb
lunliu454/infect_place
UK
plot_uk2 = pd.read_csv('sensi_withhold_uk.csv') eff_new4 = pd.DataFrame( np.array([np.repeat(list(plot_uk2['intervention']),235), plot_uk2[plot_uk2.columns[2:]].values.reshape(1,-1)[0]]).T, columns=['intervention','x']) eff_new4['x'] = eff_new4['x'].astype(float) eff_new4['color'] =([1]*234+[0.1]...
_____no_output_____
MIT
plot/plot_robust_sample.ipynb
lunliu454/infect_place
US
plot_us2 = pd.read_csv('sensi_withhold_us.csv') eff_new = pd.DataFrame( np.array([np.repeat(list(plot_us2['intervention']),310), plot_us2[plot_us2.columns[2:]].values.reshape(1,-1)[0]]).T, columns=['intervention','x']) eff_new['x'] = eff_new['x'].astype(float) eff_new['color'] =([1]*309+[0.1])*9 ...
_____no_output_____
MIT
plot/plot_robust_sample.ipynb
lunliu454/infect_place
Tutorial: Parameterized Hypercomplex Multiplication (PHM) Layer Author: Eleonora GrassucciOriginal paper: Beyond Fully-Connected Layers with Quaternions: Parameterization of Hypercomplex Multiplications with 1/n Parameters.Aston Zhang, Yi Tay, Shuai Zhang, Alvin Chan, Anh Tuan Luu, Siu Cheung Hui, Jie Fu.[ArXiv link](...
# Imports import numpy as np import math import time import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.utils.data as Data from torch.nn import init # Check Pytorch version: torch.kron is available from 1.8.0 torch.__version__ # Define the PHM class cla...
_____no_output_____
MIT
tutorials/PHM tutorial.ipynb
eleGAN23/Hyper
Learn the Hamilton product between two pure quaternionsA pure quaternion is a quaternion with scalar part equal to 0.
# Setup the training set x = torch.FloatTensor([0, 1, 2, 3]).view(4, 1) # Scalar part equal to 0 W = torch.FloatTensor([[0,-1,-1,-1], [1,0,-1,1], [1,1,0,-1], [1,-1,1,0]]) # Scalar parts equal to 0 y = torch.matmul(W, x) num_examples = 1000 batch_size = 1 X = torch.zeros((num_examples, 16)) S = torch.zeros((num_exam...
Ground-truth Hamilton product matrix: tensor([[ 0., -1., -1., -1.], [ 1., 0., -1., 1.], [ 1., 1., 0., -1.], [ 1., -1., 1., 0.]]) Learned A in PHM: Parameter containing: tensor([[[-6.0884e-08, 1.0000e+00, -1.6100e-08, 2.6916e-08], [-1.0000e+00, -1.8684e-08, -2.1245e-08, -8.835...
MIT
tutorials/PHM tutorial.ipynb
eleGAN23/Hyper
Explore feature-to-feature relationship in Boston
import pandas as pd import seaborn as sns from sklearn import datasets import discover import matplotlib.pyplot as plt # watermark is optional - it shows the versions of installed libraries # so it is useful to confirm your library versions when you submit bug reports to projects # install watermark using # %install_ex...
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
Discover non-linear relationships_Github note_ colours for `style` don't show up in Github, you'll have to grab a local copy of the Notebook.* NOX predicts RAD, INDUS, TAX and DIS* RAD predicts DIS poorly, NOX better, TAX better* CRIM predicts RAD but RAD poorly predicts CRIM
%time df_results = discover.discover(df[cols].sample(frac=1), classifier_overrides) fig, ax = plt.subplots(figsize=(12, 8)) sns.heatmap(df_results.pivot(index='target', columns='feature', values='score').fillna(1), annot=True, center=0, ax=ax, vmin=-0.1, vmax=1, cmap="viridis"); # we can also output a Data...
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
We can drill in to some of the discovered relationships
print(example_dataset.DESCR) # NOX (pollution) predicts AGE of properties - lower pollution means more houses built after 1940 than before df.plot(kind="scatter", x="NOX", y="AGE", alpha=0.1); # NOX (pollution) predicts DIStance, lower pollution means larger distance to places of work df.plot(kind="scatter", x="NOX", y...
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
Try correlationsCorrelations can give us a direction and information about linear and rank-based relationships which we won't get from RF. Pearson (linear)
df_results = discover.discover(df[cols], classifier_overrides, method='pearson') df_results.pivot(index='target', columns='feature', values='score').fillna(1) \ .style.background_gradient(cmap="viridis", axis=1) \ .set_precision(2)
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
Spearman (rank-based)
df_results = discover.discover(df[cols], classifier_overrides, method='spearman') df_results.pivot(index='target', columns='feature', values='score').fillna(1) \ .style.background_gradient(cmap="viridis", axis=1) \ .set_precision(2) ax = df.plot(kind="scatter", x="CRIM", y="LSTAT", alpha=0.1); ax = df.plot(kind="scatt...
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
Mutual InformationMutual information represents the amount of information that each column predicts about the others.
df_results = discover.discover(df[cols], classifier_overrides, method='mutual_information') df_results.pivot(index='target', columns='feature', values='score').fillna(1) \ .style.background_gradient(cmap="viridis", axis=1) \ .set_precision(2) ax = df.plot(kind="scatter", x="TAX", y="INDUS", alpha=0.1) ax = df.plot(kin...
_____no_output_____
MIT
example_boston_discover_feature_relationships.ipynb
PeteBleackley/discover_feature_relationships
Just Neural Network
submission = pd.DataFrame() submission['LAP_TIME'] = y_predicted_nn.ravel() submission submission.to_csv(f'../Submissions/Dare_In_Reality NN Only.csv', index=False) y_predicted_nn df
_____no_output_____
MIT
Notebooks/Production.ipynb
MikeAnderson89/Dare_In_Reality_Hackathon
Amazon Fine Food Reviews AnalysisData Source: https://www.kaggle.com/snap/amazon-fine-food-reviews EDA: https://nycdatascience.com/blog/student-works/amazon-fine-foods-visualization/The Amazon Fine Food Reviews dataset consists of reviews of fine foods from Amazon.Number of reviews: 568,454Number of users: 256,059Numb...
%matplotlib inline import warnings warnings.filterwarnings("ignore") import sqlite3 import pandas as pd import numpy as np import nltk import string import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVecto...
_____no_output_____
MIT
#11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb
wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset
[2] Exploratory Data Analysis [2.1] Data Cleaning: DeduplicationIt is observed (as shown in the table below) that the reviews data had many duplicate entries. Hence it was necessary to remove duplicates in order to get unbiased results for the analysis of the data. Following is an example:
display= pd.read_sql_query(""" SELECT * FROM Reviews WHERE Score != 3 AND UserId="AR5J8UI46CURR" ORDER BY ProductID """, con) display.head()
_____no_output_____
MIT
#11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb
wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset
As it can be seen above that same user has multiple reviews with same values for HelpfulnessNumerator, HelpfulnessDenominator, Score, Time, Summary and Text and on doing analysis it was found that ProductId=B000HDOPZG was Loacker Quadratini Vanilla Wafer Cookies, 8.82-Ounce Packages (Pack of 8) ProductId=B000HDL1RQ wa...
#Sorting data according to ProductId in ascending order sorted_data=filtered_data.sort_values('ProductId', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last') #Deduplication of entries final=sorted_data.drop_duplicates(subset={"UserId","ProfileName","Time","Text"}, keep='first', inplace=False) ...
_____no_output_____
MIT
#11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb
wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset
Observation:- It was also seen that in two rows given below the value of HelpfulnessNumerator is greater than HelpfulnessDenominator which is not practically possible hence these two rows too are removed from calcualtions
display= pd.read_sql_query(""" SELECT * FROM Reviews WHERE Score != 3 AND Id=44737 OR Id=64422 ORDER BY ProductID """, con) display.head() final=final[final.HelpfulnessNumerator<=final.HelpfulnessDenominator] #Before starting the next phase of preprocessing lets see the number of entries left print(final.shape) #How ...
(160176, 10)
MIT
#11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb
wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset