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 |
|---|---|---|---|---|---|
4.3 Label Distribution | print(train_df["label"].value_counts())
fig = plt.figure(figsize=(10, 6))
label_stats_plot = train_df["label"].value_counts().plot.bar()
plt.tight_layout(pad=1)
plt.savefig("img/label_stats_plot.png", dpi=100) | half-true 2114
false 1995
mostly-true 1962
true 1676
barely-true 1654
pants-fire 839
Name: label, dtype: int64
| MIT | notebooks/eda-notebook.ipynb | archity/fake-news |
4.4 Speaker Distribution | print(train_df.speaker.value_counts())
fig = plt.figure(figsize=(10, 6))
speaker_stats_plot = train_df["speaker"].value_counts()[:10].plot.bar()
plt.tight_layout(pad=1)
plt.title("Speakers")
plt.savefig("img/speaker_stats_plot.png", dpi=100)
print(train_df.speaker_title.value_counts())
fig = plt.figure(figsize=(10, 6... | President 492
U.S. Senator 479
Governor 391
President-Elect 273
U.S. senator 263
...
Pu... | MIT | notebooks/eda-notebook.ipynb | archity/fake-news |
4.5 Democrats vs Republicans* Let's see how the 2 main parties compete with each other in terms oftruthfulness in the labels | fig = plt.figure(figsize=(8,4))
plt.suptitle("Party-wise Label")
ax1 = fig.add_subplot(121)
party_wise = train_df[train_df["party_affiliation"]=="democrat"]["label"].value_counts().to_frame()
ax1.pie(party_wise["label"], labels=party_wise.index, autopct='%1.1f%%',
startangle=90)
ax1.set_title("Democrat")
plt.... | _____no_output_____ | MIT | notebooks/eda-notebook.ipynb | archity/fake-news |
* We can combine some labels to get a more simplified plot | def get_binary_label(label):
if label in ["pants-fire", "barely-true", "false"]:
return False
elif label in ["true", "half-true", "mostly-true"]:
return True
train_df["binary_label"] = train_df.label.apply(get_binary_label)
fig = plt.figure(figsize=(8,4))
plt.suptitle("Party-wise Label")
ax1 =... | _____no_output_____ | MIT | notebooks/eda-notebook.ipynb | archity/fake-news |
5. Sentiment Analysis | from textblob import TextBlob
pol = lambda x: TextBlob(x).sentiment.polarity
sub = lambda x: TextBlob(x).sentiment.subjectivity
train_df['polarity_true'] = train_df[train_df["binary_label"]==True]['statement'].apply(pol)
train_df['subjectivity_true'] = train_df[train_df["binary_label"]==True]['statement'].apply(sub)
... | _____no_output_____ | MIT | notebooks/eda-notebook.ipynb | archity/fake-news |
Collaborative filtering> Tools to quickly get the data and train models suitable for collaborative filtering This module contains all the high-level functions you need in a collaborative filtering application to assemble your data, get a model and train it with a `Learner`. We will go other those in order but you can ... | #export
class TabularCollab(TabularPandas):
"Instance of `TabularPandas` suitable for collaborative filtering (with no continuous variable)"
with_cont=False | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
This is just to use the internal of the tabular application, don't worry about it. | #export
class CollabDataLoaders(DataLoaders):
"Base `DataLoaders` for collaborative filtering."
@delegates(DataLoaders.from_dblock)
@classmethod
def from_df(cls, ratings, valid_pct=0.2, user_name=None, item_name=None, rating_name=None, seed=None, path='.', **kwargs):
"Create a `DataLoaders` suit... | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
This class should not be used directly, one of the factory methods should be preferred instead. All those factory methods accept as arguments:- `valid_pct`: the random percentage of the dataset to set aside for validation (with an optional `seed`)- `user_name`: the name of the column containing the user (defaults to th... | show_doc(CollabDataLoaders.from_df) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Let's see how this works on an example: | path = untar_data(URLs.ML_SAMPLE)
ratings = pd.read_csv(path/'ratings.csv')
ratings.head()
dls = CollabDataLoaders.from_df(ratings, bs=64)
dls.show_batch()
show_doc(CollabDataLoaders.from_csv)
dls = CollabDataLoaders.from_csv(path/'ratings.csv', bs=64) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Models fastai provides two kinds of models for collaborative filtering: a dot-product model and a neural net. | #export
class EmbeddingDotBias(Module):
"Base dot model for collaborative filtering."
def __init__(self, n_factors, n_users, n_items, y_range=None):
self.y_range = y_range
(self.u_weight, self.i_weight, self.u_bias, self.i_bias) = [Embedding(*o) for o in [
(n_users, n_factors), (n_it... | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
The model is built with `n_factors` (the length of the internal vectors), `n_users` and `n_items`. For a given user and item, it grabs the corresponding weights and bias and returns``` pythontorch.dot(user_w, item_w) + user_b + item_b```Optionally, if `y_range` is passed, it applies a `SigmoidRange` to that result. | x,y = dls.one_batch()
model = EmbeddingDotBias(50, len(dls.classes['userId']), len(dls.classes['movieId']), y_range=(0,5)
).to(x.device)
out = model(x)
assert (0 <= out).all() and (out <= 5).all()
show_doc(EmbeddingDotBias.from_classes) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
`y_range` is passed to the main init. `user` and `item` are the names of the keys for users and items in `classes` (default to the first and second key respectively). `classes` is expected to be a dictionary key to list of categories like the result of `dls.classes` in a `CollabDataLoaders`: | dls.classes | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Let's see how it can be used in practice: | model = EmbeddingDotBias.from_classes(50, dls.classes, y_range=(0,5)
).to(x.device)
out = model(x)
assert (0 <= out).all() and (out <= 5).all() | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Two convenience methods are added to easily access the weights and bias when a model is created with `EmbeddingDotBias.from_classes`: | show_doc(EmbeddingDotBias.weight) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
The elements of `arr` are expected to be class names (which is why the model needs to be created with `EmbeddingDotBias.from_classes`) | mov = dls.classes['movieId'][42]
w = model.weight([mov])
test_eq(w, model.i_weight(tensor([42])))
show_doc(EmbeddingDotBias.bias) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
The elements of `arr` are expected to be class names (which is why the model needs to be created with `EmbeddingDotBias.from_classes`) | mov = dls.classes['movieId'][42]
b = model.bias([mov])
test_eq(b, model.i_bias(tensor([42])))
#export
class EmbeddingNN(TabularModel):
"Subclass `TabularModel` to create a NN suitable for collaborative filtering."
@delegates(TabularModel.__init__)
def __init__(self, emb_szs, layers, **kwargs):
sup... | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
`emb_szs` should be a list of two tuples, one for the users, one for the items, each tuple containing the number of users/items and the corresponding embedding size (the function `get_emb_sz` can give a good default). All the other arguments are passed to `TabularModel`. | emb_szs = get_emb_sz(dls.train_ds, {})
model = EmbeddingNN(emb_szs, [50], y_range=(0,5)
).to(x.device)
out = model(x)
assert (0 <= out).all() and (out <= 5).all() | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Create a `Learner` The following function lets us quickly create a `Learner` for collaborative filtering from the data. | # export
@log_args(to_return=True, but_as=Learner.__init__)
@delegates(Learner.__init__)
def collab_learner(dls, n_factors=50, use_nn=False, emb_szs=None, layers=None, config=None, y_range=None, loss_func=None, **kwargs):
"Create a Learner for collaborative filtering on `dls`."
emb_szs = get_emb_sz(dls, ifnone(... | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
If `use_nn=False`, the model used is an `EmbeddingDotBias` with `n_factors` and `y_range`. Otherwise, it's a `EmbeddingNN` for which you can pass `emb_szs` (will be inferred from the `dls` with `get_emb_sz` if you don't provide any), `layers` (defaults to `[n_factors]`) `y_range`, and a `config` that you can create wit... | learn = collab_learner(dls, y_range=(0,5))
learn.fit_one_cycle(1) | _____no_output_____ | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Export - | #hide
from nbdev.export import *
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted 09_vision.augment.ipynb.
Co... | Apache-2.0 | nbs/45_collab.ipynb | ldanilov/fastai |
Model | def get_3d_head(p=0.0):
pool, feat = (nn.AdaptiveAvgPool3d(1), 64)
m = nn.Sequential(Batchify(),
ConvLayer(512,512,stride=2,ndim=3), # 8
ConvLayer(512,1024,stride=2,ndim=3), # 4
ConvLayer(1024,1024,stride=2,ndim=3), # 2
nn.AdaptiveAvgPool3d((1, 1, 1)), Batchify(), Flat3d(), nn.Dr... | _____no_output_____ | Apache-2.0 | 04_trainfull3d/04_trainfull3d_labels_01_partial3d.ipynb | bearpelican/rsna_retro |
Training | learn.lr_find()
do_fit(learn, 8, 1e-3)
learn.save(f'runs/{name}-1')
learn.load(f'runs/{name}-1')
learn.dls = get_3d_dls_aug(Meta.df_comb, sz=256, bs=12, grps=Meta.grps_stg1)
do_fit(learn, 4, 1e-4)
learn.save(f'runs/{name}-2')
learn.load(f'runs/{name}-2')
learn.dls = get_3d_dls_aug(Meta.df_comb, sz=384, bs=4, path=path_... | _____no_output_____ | Apache-2.0 | 04_trainfull3d/04_trainfull3d_labels_01_partial3d.ipynb | bearpelican/rsna_retro |
Import Modules | import cv2
import numpy as np
from google.colab.patches import cv2_imshow | _____no_output_____ | MIT | ImageResize/Image_Scaling/Image_scaling.ipynb | noviicee/Image-Processing-OpenCV |
Load Image | #image is loaded using cv2.imread() method,here flag is 0 ,specifies to load image in GRAYSCALE mode.
'''
Syntax:
cv2.imread(path,flag)
Parameters:
path: string representing the path of the image to be read.
flag: specifies the way in which image should be read.
'''
img=cv2.imread("input.png",0)
cv2_imshow(img) | _____no_output_____ | MIT | ImageResize/Image_Scaling/Image_scaling.ipynb | noviicee/Image-Processing-OpenCV |
Apply scaling Operation | # To perform scaling operation,cv2.resize() method is used.
'''
Syntax:
cv2.resize(image,(width,height)=None,fx=1,fy=1,interpolation)
Parameters:
image: input image.
(width,height): determining the size of output image ; optional parameter.
fx: scaling factor for x-axis,default=1.
fy: scaling factor for y-axi... | _____no_output_____ | MIT | ImageResize/Image_Scaling/Image_scaling.ipynb | noviicee/Image-Processing-OpenCV |
Display the scaled image | cv2_imshow(scaled_up_x)
cv2_imshow(scaled_down_x)
cv2_imshow(scaled_up_y)
cv2_imshow(scaled_down_y) | _____no_output_____ | MIT | ImageResize/Image_Scaling/Image_scaling.ipynb | noviicee/Image-Processing-OpenCV |
***Introduction to Radar Using Python and MATLAB*** Andy Harrison - Copyright (C) 2019 Artech House Pulse Train Ambiguity Function*** Referring to Section 8.6.1, the amibguity function for a coherent pulse train is found by employing the generic waveform technique outlined in Section 8.6.3.*** Begin by getting the lib... | import lib_path | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Set the pulsewidth (s), the pulse repetition interval (s) and the number of pulses | pulsewidth = 0.4
pri = 1.0
number_of_pulses = 6 | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Generate the time delay (s) using the `linspace` routine from `scipy` | from numpy import linspace
# Set the time delay
time_delay = linspace(-number_of_pulses * pri, number_of_pulses * pri, 5000) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Calculate the ambiguity function for the pulse train | from Libs.ambiguity.ambiguity_function import pulse_train
from numpy import finfo
ambiguity = pulse_train(time_delay, finfo(float).eps, pulsewidth, pri, number_of_pulses) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Plot the zero-Doppler cut using the `matplotlib` routines | from matplotlib import pyplot as plt
# Set the figure size
plt.rcParams["figure.figsize"] = (15, 10)
# Plot the ambiguity function
plt.plot(time_delay, ambiguity, '')
# Set the x and y axis labels
plt.xlabel("Time (s)", size=12)
plt.ylabel("Relative Amplitude", size=12)
# Turn on the grid
plt.grid(lines... | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Set the Doppler mismatch frequencies using the `linspace` routine | doppler_frequency = linspace(-2.0 / pulsewidth, 2.0 / pulsewidth, 1000) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Calculate the ambiguity function for the pulse train | ambiguity = pulse_train(finfo(float).eps, doppler_frequency, pulsewidth, pri, number_of_pulses) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Display the zero-range cut for the pulse train | plt.plot(doppler_frequency, ambiguity, '')
# Set the x and y axis labels
plt.xlabel("Doppler (Hz)", size=12)
plt.ylabel("Relative Amplitude", size=12)
# Turn on the grid
plt.grid(linestyle=':', linewidth=0.5)
# Set the plot title and labels
plt.title('Pulse Train Ambiguity Function', size=14)
# Set the t... | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Set the time delay and Doppler mismatch frequency and create the two-dimensional grid using the `meshgrid` routine from `scipy` | from numpy import meshgrid
# Set the time delay
time_delay = linspace(-number_of_pulses * pri, number_of_pulses * pri, 1000)
# Set the Doppler mismatch
doppler_frequency = linspace(-2.0 / pulsewidth, 2.0 / pulsewidth, 1000)
# Create the grid
t, f = meshgrid(time_delay, doppler_frequency) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Calculate the ambiguity function for the pulse train | ambiguity = pulse_train(t, f, pulsewidth, pri, number_of_pulses) | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
Display the two-dimensional contour plot for the pulse train ambiguity function | # Plot the ambiguity function
from numpy import finfo
plt.contour(t, f, ambiguity + finfo('float').eps, 20, cmap='jet', vmin=-0.2, vmax=1.0)
# Set the x and y axis labels
plt.xlabel("Time (s)", size=12)
plt.ylabel("Doppler (Hz)", size=12)
# Turn on the grid
plt.grid(linestyle=':', linewidth=0.5)
# Set the p... | _____no_output_____ | Apache-2.0 | jupyter/Chapter08/pulse_train_ambiguity.ipynb | mberkanbicer/software |
============================================4D Neuroimaging/BTi phantom dataset tutorial============================================Here we read 4DBTi epochs data obtained with a spherical phantomusing four different dipole locations. For each condition wecompute evoked data and compute dipole fits.Data are provided by... | # Authors: Alex Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from mayavi import mlab
from mne.datasets import phantom_4dbti
import mne | _____no_output_____ | BSD-3-Clause | stable/_downloads/a68c968ba9eafa2b1315cbf9e139eee3/plot_phantom_4DBTi.ipynb | drammock/mne-tools.github.io |
Read data and compute a dipole fit at the peak of the evoked response | data_path = phantom_4dbti.data_path()
raw_fname = op.join(data_path, '%d/e,rfhp1.0Hz')
dipoles = list()
sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
t0 = 0.07 # peak of the response
pos = np.empty((4, 3))
for ii in range(4):
raw = mne.io.read_raw_bti(raw_fname % (ii + 1,),
... | _____no_output_____ | BSD-3-Clause | stable/_downloads/a68c968ba9eafa2b1315cbf9e139eee3/plot_phantom_4DBTi.ipynb | drammock/mne-tools.github.io |
Compute localisation errors | actual_pos = 0.01 * np.array([[0.16, 1.61, 5.13],
[0.17, 1.35, 4.15],
[0.16, 1.05, 3.19],
[0.13, 0.80, 2.26]])
actual_pos = np.dot(actual_pos, [[0, 1, 0], [-1, 0, 0], [0, 0, 1]])
errors = 1e3 * np.linalg.norm(actual_pos - pos, ax... | _____no_output_____ | BSD-3-Clause | stable/_downloads/a68c968ba9eafa2b1315cbf9e139eee3/plot_phantom_4DBTi.ipynb | drammock/mne-tools.github.io |
Plot the dipoles in 3D | def plot_pos(pos, color=(0., 0., 0.)):
mlab.points3d(pos[:, 0], pos[:, 1], pos[:, 2], scale_factor=0.005,
color=color)
mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces=[])
# Plot the position of the actual dipole
plot_pos(actual_pos, color=(1., 0., 0.))
# Plot the position of the estimat... | _____no_output_____ | BSD-3-Clause | stable/_downloads/a68c968ba9eafa2b1315cbf9e139eee3/plot_phantom_4DBTi.ipynb | drammock/mne-tools.github.io |
F1, Precision Recall, and Confusion Matrix | from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import recall_score
from sklearn.metrics import classification_report
y_prediction = model.predict_classes(X_test)
y_prediction.reshape(-1,1)
print("Recall score:"+ str(recall_score(y_test, y_prediction)))
print(classification_report(y_tes... | Confusion matrix, without normalization
[[4687 0]
[1313 0]]
Normalized confusion matrix
[[1. 0.]
[1. 0.]]
| MIT | Model/3-NeuralNetwork4.ipynb | skawns0724/KOSA-Big-Data_Vision |
Nonlinear recharge models*R.A. Collenteur, University of Graz*This notebook explains the use of the `RechargeModel` stress model to simulate the combined effect of precipitation and potential evaporation on the groundwater levels. For the computation of the groundwater recharge, three recharge models are currently ava... | import pandas as pd
import pastas as ps
import matplotlib.pyplot as plt
ps.show_versions(numba=True)
ps.set_log_level("INFO") | Python version: 3.8.2 (default, Mar 25 2020, 11:22:43)
[Clang 4.0.1 (tags/RELEASE_401/final)]
Numpy version: 1.20.2
Scipy version: 1.6.2
Pandas version: 1.1.5
Pastas version: 0.18.0b
Matplotlib version: 3.3.4
numba version: 0.51.2
| MIT | examples/notebooks/07_non_linear_recharge.ipynb | pastas/pastas |
Read Input dataInput data handling is similar to other stressmodels. The only thing that is necessary to check is that the precipitation and evaporation are provided in mm/day. This is necessary because the parameters for the nonlinear recharge models are defined in mm for the length unit and days for the time unit. I... | head = pd.read_csv("../data/B32C0639001.csv", parse_dates=['date'],
index_col='date', squeeze=True)
# Make this millimeters per day
evap = ps.read_knmi("../data/etmgeg_260.txt", variables="EV24").series * 1e3
rain = ps.read_knmi("../data/etmgeg_260.txt", variables="RH").series * 1e3
fig, axes = ... | INFO: Inferred frequency for time series EV24 260: freq=D
INFO: Inferred frequency for time series RH 260: freq=D
| MIT | examples/notebooks/07_non_linear_recharge.ipynb | pastas/pastas |
Make a basic modelThe normal workflow may be used to create and calibrate the model.1. Create a Pastas `Model` instance2. Choose a recharge model. All recharge models can be accessed through the recharge subpackage (`ps.rch`).3. Create a `RechargeModel` object and add it to the model4. Solve and visualize the model | ml = ps.Model(head)
# Select a recharge model
rch = ps.rch.FlexModel()
#rch = ps.rch.Berendrecht()
#rch = ps.rch.Linear()
rm = ps.RechargeModel(rain, evap, recharge=rch, rfunc=ps.Gamma, name="rch")
ml.add_stressmodel(rm)
ml.solve(noise=True, tmin="1990", report="basic")
ml.plots.results(figsize=(10,6)); | INFO: Cannot determine frequency of series head: freq=None. The time series is irregular.
INFO: Inferred frequency for time series RH 260: freq=D
INFO: Inferred frequency for time series EV24 260: freq=D
| MIT | examples/notebooks/07_non_linear_recharge.ipynb | pastas/pastas |
Analyze the estimated recharge fluxAfter the parameter estimation we can take a look at the recharge flux computed by the model. The flux is easy to obtain using the `get_stress` method of the model object, which automatically provides the optimal parameter values that were just estimated. After this, we can for examp... | recharge = ml.get_stress("rch").resample("A").sum()
ax = recharge.plot.bar(figsize=(10,3))
ax.set_xticklabels(recharge.index.year)
plt.ylabel("Recharge [mm/year]"); | _____no_output_____ | MIT | examples/notebooks/07_non_linear_recharge.ipynb | pastas/pastas |
Place Stock Trades into Senator Dataframe 1. Understand the Senator Trading Report (STR) Dataframe | import pandas as pd
#https://docs.google.com/spreadsheets/d/1lH_LpTgRlfzKvpRnWYgoxlkWvJj0v1r3zN3CeWMAgqI/edit?usp=sharing
try:
sen_df = pd.read_csv("Senator Stock Trades/Senate Stock Watcher 04_16_2020 All Transactions.csv")
except:
sen_df = pd.read_csv("https://github.com/pkm29/big_data_final_project/raw/maste... | _____no_output_____ | MIT | Stocks/Place Stock Trades into Senator Dataframe Ankur Edit.ipynb | paulmtree/Suspicious-Senator-Trading |
There are 4 types of trades.Exchanges: Exchange 1 stock for anotherSale (Full): Selling all of their stockPurchase: Buying a stockSale (Partial): Selling some of that particular stock | n_exchanges = len(sen_df.loc[sen_df['type'] == "Exchange"])
n_trades = len(sen_df)
print("There are " +str(n_exchanges) +" exchange trades out of a total of " +str(n_trades)+ " trades.")
sen_df = sen_df.loc[sen_df['type'] != "Exchange"]
| There are 84 exchange trades out of a total of 8600 trades.
| MIT | Stocks/Place Stock Trades into Senator Dataframe Ankur Edit.ipynb | paulmtree/Suspicious-Senator-Trading |
At this point in time, I will exclude exchange trades because they are so few and wish to build the basic structure of the project. As you can see, this would require splitting up the exchange into two rows with each company and so on. I may include this step later if time permits. There should now be 8516 trades rema... | n_trades = len(sen_df)
print("There are " +str(n_trades)+ " trades in the dataframe")
n_blank_ticker = len(sen_df.loc[sen_df['ticker'] == "--"])
print("There are " +str(n_blank_ticker) +" trades w/o a ticker out of a total of " +str(n_trades)+ " trades")
sen_df = sen_df.loc[sen_df['ticker'] != "--"] | There are 1872 trades w/o a ticker out of a total of 8516 trades
| MIT | Stocks/Place Stock Trades into Senator Dataframe Ankur Edit.ipynb | paulmtree/Suspicious-Senator-Trading |
For the same reasons we excluded exchange trades, we will also exclude trades without a ticker (which all public stocks have - the ticker is their identifier on the stock exchange). Eliminating trades without a ticker takes out trades of other types of securities (corporate bonds, municipal securities, non-public stock... | n_trades = len(sen_df)
print("There are " +str(n_trades)+ " trades in the dataframe") | There are 6644 trades in the dataframe
| MIT | Stocks/Place Stock Trades into Senator Dataframe Ankur Edit.ipynb | paulmtree/Suspicious-Senator-Trading |
2. Add Data to STR Dataframe Import Data In this step we will be using company information such as market cap and industry from online lists provided by the NYSE, NASDAQ, and ASXL exchange. Links can be found here:https://stackoverflow.com/questions/25338608/download-all-stock-symbol-list-of-a-market | ticker_list = list()
try:
NYSE_df = pd.read_csv("NYSEcompanylist.csv")
except:
NYSE_df = pd.read_csv("https://github.com/pkm29/big_data_final_project/raw/master/Stocks/NYSEcompanylist.csv")
try:
NASDAQ_df = pd.read_csv("NASDAQcompanylist.csv")
except:
NASDAQ_df = pd.read_csv("https://github.com/pkm... | [['Biotechnology: Laboratory Analytical Instruments4', 'Biotechnology: Laboratory Analytical Instruments4', 'Biotechnology: Laboratory Analytical Instruments4', 'Biotechnology: Laboratory Analytical Instruments4', 'Biotechnology: Laboratory Analytical Instruments3', 'Biotechnology: Laboratory Analytical Instruments4', ... | MIT | Stocks/Place Stock Trades into Senator Dataframe Ankur Edit.ipynb | paulmtree/Suspicious-Senator-Trading |
Collaborative filtering on Google Analytics dataThis notebook demonstrates how to implement a WALS matrix refactorization approach to do collaborative filtering. | import os
PROJECT = "qwiklabs-gcp-00-34ffb0f0dc65" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["... | 1.13.1
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
Create raw datasetFor collaborative filtering, we don't need to know anything about either the users or the content. Essentially, all we need to know is userId, itemId, and rating that the particular user gave the particular item.In this case, we are working with newspaper articles. The company doesn't ask their users... | from google.cloud import bigquery
bq = bigquery.Client(project = PROJECT)
sql = """
#standardSQL
WITH CTE_visitor_page_content AS (
SELECT
fullVisitorID,
(SELECT MAX(IF(index=10, value, NULL)) FROM UNNEST(hits.customDimensions)) AS latestContentId,
(LEAD(hits.time, 1) OVER (PARTITION BY f... | 7337153711992174438,100074831,0.2321051400452234
5190801220865459604,100170790,1.0
2293633612703952721,100510126,0.2481776360816793
5874973374932455844,100510126,0.16690549004998828
1173698801255170595,100676857,0.05464232805149575
883397426232997550,10083328,0.9487035095774818
1808867070685560283,100906145,1.0
7615995... | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
Create dataset for WALSThe raw dataset (above) won't work for WALS: The userId and itemId have to be 0,1,2 ... so we need to create a mapping from visitorId (in the raw data) to userId and contentId (in the raw data) to itemId. We will need to save the above mapping to a file because at prediction time, we'll need to ... | import pandas as pd
import numpy as np
def create_mapping(values, filename):
with open(filename, 'w') as ofp:
value_to_id = {value:idx for idx, value in enumerate(values.unique())}
for value, idx in value_to_id.items():
ofp.write("{},{}\n".format(value, idx))
return value_to_id
df =... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
Creating rows and columns datasets | import pandas as pd
import numpy as np
mapped_df = pd.read_csv(filepath_or_buffer = "data/collab_mapped.csv", header = None, names = ["userId", "itemId", "rating"])
mapped_df.head()
NITEMS = np.max(mapped_df["itemId"]) + 1
NUSERS = np.max(mapped_df["userId"]) + 1
mapped_df["rating"] = np.round(mapped_df["rating"].value... | total 31908
-rw-r--r-- 1 jupyter jupyter 13152765 Jul 31 20:41 collab_raw.csv
-rw-r--r-- 1 jupyter jupyter 2134511 Jul 31 20:41 users.csv
-rw-r--r-- 1 jupyter jupyter 82947 Jul 31 20:41 items.csv
-rw-r--r-- 1 jupyter jupyter 7812739 Jul 31 20:41 collab_mapped.csv
-rw-r--r-- 1 jupyter jupyter 2252828 Jul 31 20:41 ... | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
To summarize, we created the following data files from collab_raw.csv: ```collab_mapped.csv``` is essentially the same data as in ```collab_raw.csv``` except that ```visitorId``` and ```contentId``` which are business-specific have been mapped to ```userId``` and ```itemId``` which are enumerated in 0,1,2,.... The map... | import os
import tensorflow as tf
from tensorflow.python.lib.io import file_io
from tensorflow.contrib.factorization import WALSMatrixFactorization
def read_dataset(mode, args):
def decode_example(protos, vocab_size):
features = {
"key": tf.FixedLenFeature(shape = [1], dtype = tf.int64),
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
This code is helpful in developing the input function. You don't need it in production. | def try_out():
with tf.Session() as sess:
fn = read_dataset(
mode = tf.estimator.ModeKeys.EVAL,
args = {"input_path": "data", "batch_size": 4, "nitems": NITEMS, "nusers": NUSERS})
feats, _ = fn()
print(feats["input_rows"].eval())
print(feats["input_r... | 284,5609,36
284,2754,42
284,3168,534
2621,5528,2694
4409,5295,343
5161,3267,3369
5479,1335,55
5479,1335,55
4414,284,5572
284,241,2359
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
Run as a Python moduleLet's run it as Python module for just a few steps. | os.environ["NITEMS"] = str(NITEMS)
os.environ["NUSERS"] = str(NUSERS)
%%bash
rm -rf wals.tar.gz wals_trained
gcloud ml-engine local train \
--module-name=walsmodel.task \
--package-path=${PWD}/walsmodel \
-- \
--output_dir=${PWD}/wals_trained \
--input_path=${PWD}/data \
--num_epochs=0.01 --nite... | Will train for 2 steps, evaluating once every 162 steps
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
Run on Cloud | %%bash
gsutil -m cp data/* gs://${BUCKET}/wals/data
%%bash
OUTDIR=gs://${BUCKET}/wals/model_trained
JOBNAME=wals_$(date -u +%y%m%d_%H%M%S)
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ml-engine jobs submit training $JOBNAME \
--region=$REGION \
--module-name=walsmodel.task \
--package-path=... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
This took 10 minutes for me. Get row and column factorsOnce you have a trained WALS model, you can get row and column factors (user and item embeddings) from the checkpoint file. We'll look at how to use these in the section on building a recommendation system using deep neural networks. | def get_factors(args):
with tf.Session() as sess:
estimator = tf.contrib.factorization.WALSMatrixFactorization(
num_rows = args["nusers"],
num_cols = args["nitems"],
embedding_dimension = args["n_embeds"],
model_dir = args["output_dir"])
row_... | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_environment': 'local', '_is_chief': True, '_keep_checkpoint_every_n_hours': 10000, '_num_worker_replicas': 0, '_session_config': None, '_task_type': None, '_eval_distribute': None, '_tf_config': gpu_options {
per_process_gpu_memory_fraction: 1.0
}... | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
You can visualize the embedding vectors using dimensional reduction techniques such as PCA. | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
pca = PCA(n_components = 3)
pca.fit(user_embeddings)
user_embeddings_pca = pca.transform(user_embeddings)
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(111, projection = "3d")
xs, ys, zs = user_embed... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/wals.ipynb | gozer/training-data-analyst |
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Computing the 4-Velocity Time-Component $u^0$, the Magnetic Field Measured by a Comoving Observer $b^{\mu}$, and the Poynting Vector $S^i$ Authors: Zach Etienne & Patrick ... | # Step 1: Initialize needed Python/NRPy+ modules
import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends
import NRPy_param_funcs as par # NRPy+: Parameter interface
import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g.,... | _____no_output_____ | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 1.b: Compute $u^0$ from the Valencia 3-velocity \[Back to [top](toc)\]$$\label{u0}$$According to Eqs. 9-11 of [the IllinoisGRMHD paper](https://arxiv.org/pdf/1501.07276.pdf), the Valencia 3-velocity $v^i_{(n)}$ is related to the 4-velocity $u^\mu$ via\begin{align}\alpha v^i_{(n)} &= \frac{u^i}{u^0} + \beta^i \\\i... | ValenciavU = ixp.register_gridfunctions_for_single_rank1("AUX","ValenciavU",DIM=3)
# Step 1: Compute R = 1 - 1/max(Gamma)
R = sp.sympify(0)
for i in range(DIM):
for j in range(DIM):
R += gammaDD[i][j]*ValenciavU[i]*ValenciavU[j]
GAMMA_SPEED_LIMIT = par.Cparameters("REAL",thismodule,"GAMMA_SPEED_LIMIT",10.... |
/* Function for computing u^0 from Valencia 3-velocity. */
/* Inputs: ValenciavU[], alpha, gammaDD[][], GAMMA_SPEED_LIMIT (C parameter) */
/* Output: u0=u^0 and velocity-limited ValenciavU[] */
const double tmpR0 = 2*ValenciavU0;
const double R = ((ValenciavU0)*(ValenciavU0))*gammaDD00 + ((ValenciavU1)*(ValenciavU1))... | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 1.c: Compute $u_j$ from $u^0$, the Valencia 3-velocity, and $g_{\mu\nu}$ \[Back to [top](toc)\]$$\label{uj}$$The basic equation is\begin{align}u_j &= g_{\mu j} u^{\mu} \\&= g_{0j} u^0 + g_{ij} u^i \\&= \beta_j u^0 + \gamma_{ij} u^i \\&= \beta_j u^0 + \gamma_{ij} u^0 \left(\alpha v^i_{(n)} - \beta^i\right) \\&= u^... | u0 = par.Cparameters("REAL",thismodule,"u0",1e300) # Will be overwritten in C code. Set to crazy value to ensure this.
uD = ixp.zerorank1()
for i in range(DIM):
for j in range(DIM):
uD[j] += alpha*u0*gammaDD[i][j]*ValenciavU[i] | _____no_output_____ | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 1.d: Compute $b^\mu$ \[Back to [top](toc)\]$$\label{beta}$$We compute $b^\mu$ from the above expressions:\begin{align}\sqrt{4\pi} b^0 = B^0_{\rm (u)} &= \frac{u_j B^j}{\alpha} \\\sqrt{4\pi} b^i = B^i_{\rm (u)} &= \frac{B^i + (u_j B^j) u^i}{\alpha u^0}\\\end{align}$B^i$ is exactly equal to the $B^i$ evaluated in I... | M_PI = par.Cparameters("#define",thismodule,"M_PI","")
BU = ixp.register_gridfunctions_for_single_rank1("AUX","BU",DIM=3)
# uBcontraction = u_i B^i
uBcontraction = sp.sympify(0)
for i in range(DIM):
uBcontraction += uD[i]*BU[i]
# uU = 3-vector representing u^i = u^0 \left(\alpha v^i_{(n)} - \beta^i\right)
uU = ix... | _____no_output_____ | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 2: Defining the Poynting Flux Vector $S^{i}$ \[Back to [top](toc)\]$$\label{poynting_flux}$$The Poynting flux is defined in Eq. 11 of [Kelly *et al.*](https://arxiv.org/pdf/1710.02132.pdf) (note that we choose the minus sign convention so that the Poynting luminosity across a spherical shell is $L_{\rm EM} = \int... | # Step 2.a.i: compute g^\mu_\delta:
g4UD = ixp.zerorank2(DIM=4)
for mu in range(4):
for delta in range(4):
for nu in range(4):
g4UD[mu][delta] += g4UU[mu][nu]*g4DD[nu][delta]
# Step 2.a.ii: compute b_{\mu}
smallb4D = ixp.zerorank1(DIM=4)
for mu in range(4):
for nu in range(4):
small... | _____no_output_____ | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 3: Code Validation against `u0_smallb_Poynting__Cartesian` NRPy+ module \[Back to [top](toc)\]$$\label{code_validation}$$Here, as a code validation check, we verify agreement in the SymPy expressions for u0, smallbU, smallb2etk, and PoynSU between1. this tutorial and 2. the NRPy+ [u0_smallb_Poynting__Cartesian mo... | import sys
import u0_smallb_Poynting__Cartesian.u0_smallb_Poynting__Cartesian as u0etc
u0etc.compute_u0_smallb_Poynting__Cartesian(gammaDD,betaU,alpha,ValenciavU,BU)
if u0etc.computeu0_Cfunction != computeu0_Cfunction:
print("FAILURE: u0 C code has changed!")
sys.exit(1)
else:
print("PASSED: u0 C code matc... | PASSED: u0 C code matches!
u0etc.smallb4U[0] - smallb4U[0] = 0
u0etc.smallb4U[1] - smallb4U[1] = 0
u0etc.smallb4U[2] - smallb4U[2] = 0
u0etc.smallb4U[3] - smallb4U[3] = 0
u0etc.smallb2etk - smallb2etk = 0
u0etc.PoynSU[0] - PoynSU[0] = 0
u0etc.PoynSU[1] - PoynSU[1] = 0
u0etc.PoynSU[2] - PoynSU[2] = 0
| BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
Step 4: Appendix: Proving Eqs. 53 and 56 in [Duez *et al* (2005)](https://arxiv.org/pdf/astro-ph/0503420.pdf)$$\label{appendix}$$$u^\mu u_\mu = -1$ implies\begin{align}g^{\mu\nu} u_\mu u_\nu &= g^{00} \left(u_0\right)^2 + 2 g^{0i} u_0 u_i + g^{ij} u_i u_j = -1 \\\implies &g^{00} \left(u_0\right)^2 + 2 g^{0i} u_0 u_i +... | !jupyter nbconvert --to latex --template latex_nrpy_style.tplx --log-level='WARN' Tutorial-u0_smallb_Poynting-Cartesian.ipynb
!pdflatex -interaction=batchmode Tutorial-u0_smallb_Poynting-Cartesian.tex
!pdflatex -interaction=batchmode Tutorial-u0_smallb_Poynting-Cartesian.tex
!pdflatex -interaction=batchmode Tutorial-u0... | [pandoc warning] Duplicate link reference `[comment]' "source" (line 22, column 1)
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded f... | BSD-2-Clause | Tutorial-u0_smallb_Poynting-Cartesian.ipynb | KAClough/nrpytutorial |
T81-558: Applications of Deep Neural Networks**Module 4: Training for Tabular Data*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class w... | try:
%tensorflow_version 2.x
COLAB = True
print("Note: using Google CoLab")
except:
print("Note: not using Google CoLab")
COLAB = False | Note: not using Google CoLab
| Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
Part 4.1: Encoding a Feature Vector for Keras Deep LearningNeural networks can accept many types of data. We will begin with tabular data, where there are well defined rows and columns. This is the sort of data you would typically see in Microsoft Excel. An example of tabular data is shown below.Neural networks req... | import pandas as pd
pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 5)
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
na_values=['NA','?'])
pd.set_option('display.max_columns', 9)
pd.set_option('display.max_rows', 5)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
The following observations can be made from the above data:* The target column is the column that you seek to predict. There are several candidates here. However, we will initially use product. This field specifies what product someone bought.* There is an ID column. This column should not be fed into the neural ne... | pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 5)
dummies = pd.get_dummies(df['job'],prefix="job")
print(dummies.shape)
pd.set_option('display.max_columns', 9)
pd.set_option('display.max_rows', 10)
display(dummies) | (2000, 33)
| Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
Because there are 33 different job codes, there are 33 dummy variables. We also specified a prefix, because the job codes (such as "ax") are not that meaningful by themselves. Something such as "job_ax" also tells us the origin of this field.Next, we must merge these dummies back into the main data frame. We also dr... | pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 5)
df = pd.concat([df,dummies],axis=1)
df.drop('job', axis=1, inplace=True)
pd.set_option('display.max_columns', 9)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
We also introduce dummy variables for the area column. | pd.set_option('display.max_columns', 7)
pd.set_option('display.max_rows', 5)
df = pd.concat([df,pd.get_dummies(df['area'],prefix="area")],axis=1)
df.drop('area', axis=1, inplace=True)
pd.set_option('display.max_columns', 9)
pd.set_option('display.max_rows', 10)
display(df) | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
The last remaining transformation is to fill in missing income values. | med = df['income'].median()
df['income'] = df['income'].fillna(med) | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
There are more advanced ways of filling in missing values, but they require more analysis. The idea would be to see if another field might give a hint as to what the income were. For example, it might be beneficial to calculate a median income for each of the areas or job categories. This is something to keep in min... | print(list(df.columns)) | ['id', 'income', 'aspect', 'subscriptions', 'dist_healthy', 'save_rate', 'dist_unhealthy', 'age', 'pop_dense', 'retail_dense', 'crime', 'product', 'job_11', 'job_al', 'job_am', 'job_ax', 'job_bf', 'job_by', 'job_cv', 'job_de', 'job_dz', 'job_e2', 'job_f8', 'job_gj', 'job_gv', 'job_kd', 'job_ke', 'job_kl', 'job_kp', 'jo... | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
This includes both the target and predictors. We need a list with the target removed. We also remove **id** because it is not useful for prediction. | x_columns = df.columns.drop('product').drop('id')
print(list(x_columns)) | ['income', 'aspect', 'subscriptions', 'dist_healthy', 'save_rate', 'dist_unhealthy', 'age', 'pop_dense', 'retail_dense', 'crime', 'job_11', 'job_al', 'job_am', 'job_ax', 'job_bf', 'job_by', 'job_cv', 'job_de', 'job_dz', 'job_e2', 'job_f8', 'job_gj', 'job_gv', 'job_kd', 'job_ke', 'job_kl', 'job_kp', 'job_ks', 'job_kw', ... | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
Generate X and Y for a Classification Neural Network We can now generate *x* and *y*. Note, this is how we generate y for a classification problem. Regression would not use dummies and would simply encode the numeric value of the target. | # Convert to numpy - Classification
x_columns = df.columns.drop('product').drop('id')
x = df[x_columns].values
dummies = pd.get_dummies(df['product']) # Classification
products = dummies.columns
y = dummies.values | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
We can display the *x* and *y* matrices. | print(x)
print(y) | [[5.08760000e+04 1.31000000e+01 1.00000000e+00 ... 0.00000000e+00
1.00000000e+00 0.00000000e+00]
[6.03690000e+04 1.86250000e+01 2.00000000e+00 ... 0.00000000e+00
1.00000000e+00 0.00000000e+00]
[5.51260000e+04 3.47666667e+01 1.00000000e+00 ... 0.00000000e+00
1.00000000e+00 0.00000000e+00]
...
[2.85950000e+04 3... | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
The x and y values are now ready for a neural network. Make sure that you construct the neural network for a classification problem. Specifically,* Classification neural networks have an output neuron count equal to the number of classes.* Classification neural networks should use **categorical_crossentropy** and a *... | y = df['income'].values | _____no_output_____ | Apache-2.0 | t81_558_class_04_1_feature_encode.ipynb | IlkerCa/t81_558_deep_learning |
**This notebook is an exercise in the [Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/categorical-variables).**--- By encoding **categorical variables**, you'll obtain your best results ... | # Set up code checking
import os
if not os.path.exists("../input/train.csv"):
os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv")
os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv")
from learntools.core import binder
binder.bind(globals())
from learntools.m... | Setup Complete
| Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
In this exercise, you will work with data from the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course). Run the next code cell without changes to load the training and validation sets in `X_train`, `X_valid`,... | import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
X = pd.read_csv('../input/train.csv', index_col='Id')
X_test = pd.read_csv('../input/test.csv', index_col='Id')
# Remove rows with missing target, separate target from predictors
X.dropna(axis=0, subset=['SalePrice'], inplace=Tr... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Use the next code cell to print the first five rows of the data. | X_train.head() | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Notice that the dataset contains both numerical and categorical variables. You'll need to encode the categorical data before training a model.To compare different models, you'll use the same `score_dataset()` function from the tutorial. This function reports the [mean absolute error](https://en.wikipedia.org/wiki/Mea... | from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
# function for comparing different approaches
def score_dataset(X_train, X_valid, y_train, y_valid):
model = RandomForestRegressor(n_estimators=100, random_state=0)
model.fit(X_train, y_train)
preds = model.p... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Step 1: Drop columns with categorical dataYou'll get started with the most straightforward approach. Use the code cell below to preprocess the data in `X_train` and `X_valid` to remove columns with categorical data. Set the preprocessed DataFrames to `drop_X_train` and `drop_X_valid`, respectively. | # Fill in the lines below: drop columns in training and validation data
drop_X_train = X_train.select_dtypes(exclude=['object'])
drop_X_valid = X_valid.select_dtypes(exclude=['object'])
# Check your answers
step_1.check()
# Lines below will give you a hint or solution code
#step_1.hint()
#step_1.solution() | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Run the next code cell to get the MAE for this approach. | print("MAE from Approach 1 (Drop categorical variables):")
print(score_dataset(drop_X_train, drop_X_valid, y_train, y_valid)) | MAE from Approach 1 (Drop categorical variables):
17837.82570776256
| Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Before jumping into label encoding, we'll investigate the dataset. Specifically, we'll look at the `'Condition2'` column. The code cell below prints the unique entries in both the training and validation sets. | print("Unique values in 'Condition2' column in training data:", X_train['Condition2'].unique())
print("\nUnique values in 'Condition2' column in validation data:", X_valid['Condition2'].unique()) | Unique values in 'Condition2' column in training data: ['Norm' 'PosA' 'Feedr' 'PosN' 'Artery' 'RRAe']
Unique values in 'Condition2' column in validation data: ['Norm' 'RRAn' 'RRNn' 'Artery' 'Feedr' 'PosN']
| Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Step 2: Label encoding Part AIf you now write code to: - fit a label encoder to the training data, and then - use it to transform both the training and validation data, you'll get an error. Can you see why this is the case? (_You'll need to use the above output to answer this question._) | # Check your answer (Run this code cell to receive credit!)
step_2.a.check()
#step_2.a.hint() | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
This is a common problem that you'll encounter with real-world data, and there are many approaches to fixing this issue. For instance, you can write a custom label encoder to deal with new categories. The simplest approach, however, is to drop the problematic categorical columns. Run the code cell below to save the ... | # All categorical columns
object_cols = [col for col in X_train.columns if X_train[col].dtype == "object"]
# Columns that can be safely label encoded
good_label_cols = [col for col in object_cols if
set(X_train[col]) == set(X_valid[col])]
# Problematic columns that will be dropped from the... | Categorical columns that will be label encoded: ['MSZoning', 'Street', 'LotShape', 'LandContour', 'LotConfig', 'BldgType', 'HouseStyle', 'ExterQual', 'CentralAir', 'KitchenQual', 'PavedDrive', 'SaleCondition']
Categorical columns that will be dropped from the dataset: ['Neighborhood', 'LandSlope', 'Condition1', 'Heati... | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Part BUse the next code cell to label encode the data in `X_train` and `X_valid`. Set the preprocessed DataFrames to `label_X_train` and `label_X_valid`, respectively. - We have provided code below to drop the categorical columns in `bad_label_cols` from the dataset. - You should label encode the categorical columns... | from sklearn.preprocessing import LabelEncoder
# Drop categorical columns that will not be encoded
label_X_train = X_train.drop(bad_label_cols, axis=1)
label_X_valid = X_valid.drop(bad_label_cols, axis=1)
# Apply label encoder
label_encoder = LabelEncoder()
for col in good_label_cols:
label_X_train[col] = label_... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Run the next code cell to get the MAE for this approach. | print("MAE from Approach 2 (Label Encoding):")
print(score_dataset(label_X_train, label_X_valid, y_train, y_valid)) | MAE from Approach 2 (Label Encoding):
17575.291883561644
| Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
So far, you've tried two different approaches to dealing with categorical variables. And, you've seen that encoding categorical data yields better results than removing columns from the dataset.Soon, you'll try one-hot encoding. Before then, there's one additional topic we need to cover. Begin by running the next co... | # Get number of unique entries in each column with categorical data
object_nunique = list(map(lambda col: X_train[col].nunique(), object_cols))
d = dict(zip(object_cols, object_nunique))
# Print number of unique entries by column, in ascending order
sorted(d.items(), key=lambda x: x[1]) | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Step 3: Investigating cardinality Part AThe output above shows, for each column with categorical data, the number of unique values in the column. For instance, the `'Street'` column in the training data has two unique values: `'Grvl'` and `'Pave'`, corresponding to a gravel road and a paved road, respectively.We refe... | # Fill in the line below: How many categorical variables in the training data
# have cardinality greater than 10?
high_cardinality_numcols = 3
# Fill in the line below: How many columns are needed to one-hot encode the
# 'Neighborhood' variable in the training data?
num_cols_neighborhood = 25
# Check your answers
st... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Part BFor large datasets with many rows, one-hot encoding can greatly expand the size of the dataset. For this reason, we typically will only one-hot encode columns with relatively low cardinality. Then, high cardinality columns can either be dropped from the dataset, or we can use label encoding.As an example, cons... | # Fill in the line below: How many entries are added to the dataset by
# replacing the column with a one-hot encoding?
OH_entries_added = 1e4*100 - 1e4
# Fill in the line below: How many entries are added to the dataset by
# replacing the column with a label encoding?
label_entries_added = 0
# Check your answers
ste... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Next, you'll experiment with one-hot encoding. But, instead of encoding all of the categorical variables in the dataset, you'll only create a one-hot encoding for columns with cardinality less than 10.Run the code cell below without changes to set `low_cardinality_cols` to a Python list containing the columns that wil... | # Columns that will be one-hot encoded
low_cardinality_cols = [col for col in object_cols if X_train[col].nunique() < 10]
# Columns that will be dropped from the dataset
high_cardinality_cols = list(set(object_cols)-set(low_cardinality_cols))
print('Categorical columns that will be one-hot encoded:', low_cardinality_... | Categorical columns that will be one-hot encoded: ['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 'LandSlope', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'ExterQual', 'ExterCond', 'Foundation', 'Heating', 'HeatingQC', 'CentralAir', 'KitchenQual', 'Function... | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Step 4: One-hot encodingUse the next code cell to one-hot encode the data in `X_train` and `X_valid`. Set the preprocessed DataFrames to `OH_X_train` and `OH_X_valid`, respectively. - The full list of categorical columns in the dataset can be found in the Python list `object_cols`.- You should only one-hot encode th... | from sklearn.preprocessing import OneHotEncoder
# Use as many lines of code as you need!
OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)
OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[low_cardinality_cols]))
OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[low_cardinality_cols... | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Run the next code cell to get the MAE for this approach. | print("MAE from Approach 3 (One-Hot Encoding):")
print(score_dataset(OH_X_train, OH_X_valid, y_train, y_valid)) | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Generate test predictions and submit your resultsAfter you complete Step 4, if you'd like to use what you've learned to submit your results to the leaderboard, you'll need to preprocess the test data before generating predictions.**This step is completely optional, and you do not need to submit results to the leaderbo... | # (Optional) Your code here | _____no_output_____ | Apache-2.0 | pre_exercises/Intermediate_ML/exercise-categorical-variables.ipynb | krishnaaxo/Spotify_Skip_Action_Prediction |
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"); | #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
View on TensorFlow.org Run in Google Colab View source on GitHub Using TPUsTensor Processing Units (TPUs) are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the TensorFlow Research Cloud and Go... | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
import numpy as np
(x_train, y_train), (x_test... | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
Initialize TPUStrategyWe first initialize the TPUStrategy object before creating the model, so that Keras knows that we are creating a model for TPUs. To do this, we are first creating a TPUClusterResolver using the IP address of the TPU, and then creating a TPUStrategy object from the Cluster Resolver. | import os
resolver = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver) | _____no_output_____ | Apache-2.0 | site/en/r2/guide/_tpu.ipynb | christophmeyer/docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.