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 correct bias to set can be derived from:$$ p_0 = pos/(pos + neg) = 1/(1+e^{-b_0}) $$$$ b_0 = -log_e(1/p_0 - 1) $$$$ b_0 = log_e(pos/neg)$$ | initial_bias = np.log([pos/neg])
initial_bias | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Set that as the initial bias, and the model will give much more reasonable initial guesses. It should be near: `pos/total = 0.0018` | model = make_model(output_bias=initial_bias)
model.predict(train_features[:10]) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
With this initialization the initial loss should be approximately:$$-p_0log(p_0)-(1-p_0)log(1-p_0) = 0.01317$$ | results = model.evaluate(train_features, train_labels, batch_size=BATCH_SIZE, verbose=0)
print("Loss: {:0.4f}".format(results[0])) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
This initial loss is about 50 times less than if would have been with naive initialization.This way the model doesn't need to spend the first few epochs just learning that positive examples are unlikely. This also makes it easier to read plots of the loss during training. Checkpoint the initial weightsTo make the vari... | initial_weights = os.path.join(tempfile.mkdtemp(), 'initial_weights')
model.save_weights(initial_weights) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Confirm that the bias fix helpsBefore moving on, confirm quick that the careful bias initialization actually helped.Train the model for 20 epochs, with and without this careful initialization, and compare the losses: | model = make_model()
model.load_weights(initial_weights)
model.layers[-1].bias.assign([0.0])
zero_bias_history = model.fit(
train_features,
train_labels,
batch_size=BATCH_SIZE,
epochs=20,
validation_data=(val_features, val_labels),
verbose=0)
model = make_model()
model.load_weights(initial_weig... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
The above figure makes it clear: In terms of validation loss, on this problem, this careful initialization gives a clear advantage. Train the model | model = make_model()
model.load_weights(initial_weights)
baseline_history = model.fit(
train_features,
train_labels,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
callbacks=[early_stopping],
validation_data=(val_features, val_labels)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Check training historyIn this section, you will produce plots of your model's accuracy and loss on the training and validation set. These are useful to check for overfitting, which you can learn more about in the [Overfit and underfit](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit) tutorial.Additiona... | def plot_metrics(history):
metrics = ['loss', 'prc', 'precision', 'recall']
for n, metric in enumerate(metrics):
name = metric.replace("_"," ").capitalize()
plt.subplot(2,2,n+1)
plt.plot(history.epoch, history.history[metric], color=colors[0], label='Train')
plt.plot(history.epoch, history.history['... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Note: That the validation curve generally performs better than the training curve. This is mainly caused by the fact that the dropout layer is not active when evaluating the model. Evaluate metricsYou can use a [confusion matrix](https://developers.google.com/machine-learning/glossary/confusion_matrix) to summarize th... | train_predictions_baseline = model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_baseline = model.predict(test_features, batch_size=BATCH_SIZE)
def plot_cm(labels, predictions, p=0.5):
cm = confusion_matrix(labels, predictions > p)
plt.figure(figsize=(5,5))
sns.heatmap(cm, annot=True, fmt="d")
... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Evaluate your model on the test dataset and display the results for the metrics you created above: | baseline_results = model.evaluate(test_features, test_labels,
batch_size=BATCH_SIZE, verbose=0)
for name, value in zip(model.metrics_names, baseline_results):
print(name, ': ', value)
print()
plot_cm(test_labels, test_predictions_baseline) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
If the model had predicted everything perfectly, this would be a [diagonal matrix](https://en.wikipedia.org/wiki/Diagonal_matrix) where values off the main diagonal, indicating incorrect predictions, would be zero. In this case the matrix shows that you have relatively few false positives, meaning that there were relat... | def plot_roc(name, labels, predictions, **kwargs):
fp, tp, _ = sklearn.metrics.roc_curve(labels, predictions)
plt.plot(100*fp, 100*tp, label=name, linewidth=2, **kwargs)
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([-0.5,20])
plt.ylim([80,100.5])
plt.grid(True)
ax = plt.g... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Plot the AUPRC
Now plot the [AUPRC](https://developers.google.com/machine-learning/glossary?hl=enPR_AUC). Area under the interpolated precision-recall curve, obtained by plotting (recall, precision) points for different values of the classification threshold. Depending on how it's calculated, PR AUC may be equivalent ... | def plot_prc(name, labels, predictions, **kwargs):
precision, recall, _ = sklearn.metrics.precision_recall_curve(labels, predictions)
plt.plot(precision, recall, label=name, linewidth=2, **kwargs)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.grid(True)
ax = plt.gca()
ax.set_aspe... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
It looks like the precision is relatively high, but the recall and the area under the ROC curve (AUC) aren't as high as you might like. Classifiers often face challenges when trying to maximize both precision and recall, which is especially true when working with imbalanced datasets. It is important to consider the cos... | # Scaling by total/2 helps keep the loss to a similar magnitude.
# The sum of the weights of all examples stays the same.
weight_for_0 = (1 / neg) * (total / 2.0)
weight_for_1 = (1 / pos) * (total / 2.0)
class_weight = {0: weight_for_0, 1: weight_for_1}
print('Weight for class 0: {:.2f}'.format(weight_for_0))
print('... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Train a model with class weightsNow try re-training and evaluating the model with class weights to see how that affects the predictions.Note: Using `class_weights` changes the range of the loss. This may affect the stability of the training depending on the optimizer. Optimizers whose step size is dependent on the mag... | weighted_model = make_model()
weighted_model.load_weights(initial_weights)
weighted_history = weighted_model.fit(
train_features,
train_labels,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
callbacks=[early_stopping],
validation_data=(val_features, val_labels),
# The class weights go here
class... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Check training history | plot_metrics(weighted_history) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Evaluate metrics | train_predictions_weighted = weighted_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_weighted = weighted_model.predict(test_features, batch_size=BATCH_SIZE)
weighted_results = weighted_model.evaluate(test_features, test_labels,
batch_size=BATCH_SIZE, ver... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Here you can see that with class weights the accuracy and precision are lower because there are more false positives, but conversely the recall and AUC are higher because the model also found more true positives. Despite having lower accuracy, this model has higher recall (and identifies more fraudulent transactions). ... | plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_pred... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Plot the AUPRC | plot_prc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_prc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_prc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_prc("Test Weighted", test_labels, test_... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Oversampling Oversample the minority classA related approach would be to resample the dataset by oversampling the minority class. | pos_features = train_features[bool_train_labels]
neg_features = train_features[~bool_train_labels]
pos_labels = train_labels[bool_train_labels]
neg_labels = train_labels[~bool_train_labels] | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Using NumPyYou can balance the dataset manually by choosing the right number of random indices from the positive examples: | ids = np.arange(len(pos_features))
choices = np.random.choice(ids, len(neg_features))
res_pos_features = pos_features[choices]
res_pos_labels = pos_labels[choices]
res_pos_features.shape
resampled_features = np.concatenate([res_pos_features, neg_features], axis=0)
resampled_labels = np.concatenate([res_pos_labels, ne... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Using `tf.data` If you're using `tf.data` the easiest way to produce balanced examples is to start with a `positive` and a `negative` dataset, and merge them. See [the tf.data guide](../../guide/data.ipynb) for more examples. | BUFFER_SIZE = 100000
def make_ds(features, labels):
ds = tf.data.Dataset.from_tensor_slices((features, labels))#.cache()
ds = ds.shuffle(BUFFER_SIZE).repeat()
return ds
pos_ds = make_ds(pos_features, pos_labels)
neg_ds = make_ds(neg_features, neg_labels) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Each dataset provides `(feature, label)` pairs: | for features, label in pos_ds.take(1):
print("Features:\n", features.numpy())
print()
print("Label: ", label.numpy()) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Merge the two together using `experimental.sample_from_datasets`: | resampled_ds = tf.data.experimental.sample_from_datasets([pos_ds, neg_ds], weights=[0.5, 0.5])
resampled_ds = resampled_ds.batch(BATCH_SIZE).prefetch(2)
for features, label in resampled_ds.take(1):
print(label.numpy().mean()) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
To use this dataset, you'll need the number of steps per epoch.The definition of "epoch" in this case is less clear. Say it's the number of batches required to see each negative example once: | resampled_steps_per_epoch = np.ceil(2.0*neg/BATCH_SIZE)
resampled_steps_per_epoch | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Train on the oversampled dataNow try training the model with the resampled data set instead of using class weights to see how these methods compare.Note: Because the data was balanced by replicating the positive examples, the total dataset size is larger, and each epoch runs for more training steps. | resampled_model = make_model()
resampled_model.load_weights(initial_weights)
# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1]
output_layer.bias.assign([0])
val_ds = tf.data.Dataset.from_tensor_slices((val_features, val_labels)).cache()
val_ds = val_ds.batch(BATCH_SI... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
If the training process were considering the whole dataset on each gradient update, this oversampling would be basically identical to the class weighting.But when training the model batch-wise, as you did here, the oversampled data provides a smoother gradient signal: Instead of each positive example being shown in one... | plot_metrics(resampled_history) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Re-train Because training is easier on the balanced data, the above training procedure may overfit quickly. So break up the epochs to give the `tf.keras.callbacks.EarlyStopping` finer control over when to stop training. | resampled_model = make_model()
resampled_model.load_weights(initial_weights)
# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1]
output_layer.bias.assign([0])
resampled_history = resampled_model.fit(
resampled_ds,
# These are not real epochs
steps_per_epoch... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Re-check training history | plot_metrics(resampled_history) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Evaluate metrics | train_predictions_resampled = resampled_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_resampled = resampled_model.predict(test_features, batch_size=BATCH_SIZE)
resampled_results = resampled_model.evaluate(test_features, test_labels,
batch_size=BATCH_S... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Plot the ROC | plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_pred... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
Plot the AUPRC
| plot_prc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_prc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_prc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_prc("Test Weighted", test_labels, test_... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/imbalanced_data.ipynb | arshPratap/docs |
CachingInteracting with files on a cloud provider can mean a lot of waiting on files downloading and uploading. `cloudpathlib` provides seamless on-demand caching of cloud content that can be persistent across processes and sessions to make sure you only download or upload when you need to. Are we synced?Before `clou... | from cloudpathlib import CloudPath
from itertools import islice
ladi = CloudPath("s3://ladi/Images/FEMA_CAP/2020/70349")
# list first 5 images for this incident
for p in islice(ladi.iterdir(), 5):
print(p) | s3://ladi/Images/FEMA_CAP/2020/70349/DSC_0001_5a63d42e-27c6-448a-84f1-bfc632125b8e.jpg
s3://ladi/Images/FEMA_CAP/2020/70349/DSC_0002_a89f1b79-786f-4dac-9dcc-609fb1a977b1.jpg
s3://ladi/Images/FEMA_CAP/2020/70349/DSC_0003_02c30af6-911e-4e01-8c24-7644da2b8672.jpg
s3://ladi/Images/FEMA_CAP/2020/70349/DSC_0004_d37c02b9-01a8... | MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Just because we saw these images are available, it doesn't mean we have downloaded any of this data yet. | # Nothing in the cache yet
!tree {ladi.fspath} | /var/folders/8g/v8lwvfhj6_l6ct_zd_rs84mw0000gn/T/tmpqfelhthi/ladi/Images/FEMA_CAP/2020/70349 [error opening dir]
0 directories, 0 files
| MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Now let's look at just the first image from this dataset. | flood_image = ladi / "DSC_0001_5a63d42e-27c6-448a-84f1-bfc632125b8e.jpg"
flood_image.exists()
# Still nothing in the cache
!tree {ladi.fspath} | /var/folders/8g/v8lwvfhj6_l6ct_zd_rs84mw0000gn/T/tmpqfelhthi/ladi/Images/FEMA_CAP/2020/70349 [error opening dir]
0 directories, 0 files
| MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Even though we refer to a specific file and make sure it exists in the cloud, we can still do all of that work without actually downloading the file.In order to read the file, we do have to download the data. Let's actually display the image: | %%time
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
with flood_image.open("rb") as f:
i = Image.open(f)
plt.imshow(i)
# Downloaded image file in the cache
!tree {ladi.fspath} | [01;34m/var/folders/8g/v8lwvfhj6_l6ct_zd_rs84mw0000gn/T/tmpqfelhthi/ladi/Images/FEMA_CAP/2020/70349[00m
└── [01;35mDSC_0001_5a63d42e-27c6-448a-84f1-bfc632125b8e.jpg[00m
0 directories, 1 file
| MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Just be using `open`, we've downloaded the file in the background to the cache. Now that it is local, we won't redownload that file unless it changes on the server. We can confirm that by checking if the file is faster to read a second time. | %%time
with flood_image.open("rb") as f:
i = Image.open(f)
plt.imshow(i) | CPU times: user 351 ms, sys: 36.7 ms, total: 388 ms
Wall time: 1.08 s
| MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Notice that the second display is much faster since we use the cached version! Keeping the cache aroundBy default, the cache uses [`tempfile`](https://docs.python.org/3/library/tempfile.html) this means at some point either Python or your operating system will remove whatever files you have cached. This is helpful in ... | from cloudpathlib import S3Client
# explicitly instantiate a client that always uses the local cache
client = S3Client(local_cache_dir="data")
ladi = client.CloudPath("s3://ladi/Images/FEMA_CAP/2020/70349")
# Again, nothing in the cache yet, but we see it is all in the "data" folder
!tree {ladi.fspath} | data/ladi/Images/FEMA_CAP/2020/70349 [error opening dir]
0 directories, 0 files
| MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Now let's look at just the first image from this dataset. Note that paths created by using the `ladi` root (e.g., by using the `/` operator below or calls like `iterdir` and `glob`) will inherit the same `Client` instance, and therefore the same `local_cache_dir` without our having to do extra work. | flood_image = ladi / "DSC_0002_a89f1b79-786f-4dac-9dcc-609fb1a977b1.jpg"
with flood_image.open("rb") as f:
i = Image.open(f)
plt.imshow(i)
# Now
!tree {ladi.fspath}
# let's explicitly cleanup this directory, since it is not handled for us
!rm -rf data | _____no_output_____ | MIT | docs/docs/caching.ipynb | ElucidataInc/cloudpathlib |
Simple demonstration of calculating segmentation metrics | import os
import sys
sys.path.append('..')
import umetrics
import numpy as np
from skimage.io import imread
# load a ground truth - prediction image pair
n = 1
p = '/Users/arl/Dropbox/Data/TestingData/UNet2D_testing_Scribble/set12'
true = imread(os.path.join(p, 'labels_compressed', f'l_{n}.tif'))
pred = imread(os.path... | _____no_output_____ | MIT | notebooks/unet_segmentation_metrics.ipynb | KristinaUlicna/unet_segmentation_metrics |
visualize the metrics | # uncomment for interactive
# %matplotlib qt
result.plot()
print(result.results) | ============================
Segmentation Metrics (n=1)
============================
n_true_labels: 110
n_pred_labels: 103
n_true_positives: 97
n_false_positives: 6
n_false_negatives: 8
IoU: 0.838
Jaccard: 0.874
pixel_identity: 0.991
localization_error: 2.635
| MIT | notebooks/unet_segmentation_metrics.ipynb | KristinaUlicna/unet_segmentation_metrics |
plot some stats | import matplotlib.pyplot as plt
bins = np.linspace(0,3000,21)
plt.figure()
plt.hist(result._reference.areas, bins, alpha=0.5, label='true')
plt.hist(result._predicted.areas, bins, alpha=0.5, label='pred', edgecolor='k')
plt.legend()
plt.title('Histogram of detected object areas')
plt.xlabel('Pixels')
plt.show() | _____no_output_____ | MIT | notebooks/unet_segmentation_metrics.ipynb | KristinaUlicna/unet_segmentation_metrics |
do some batch processing | files = []
for n in range(10):
true = os.path.join(p, 'labels_compressed', f'l_{n}.tif')
pred = os.path.join(p, 'segmented_2019-11-27', f's_{n}.tif')
files.append((true, pred))
batch_result = umetrics.batch(files)
print(batch_result) | =============================
Segmentation Metrics (n=10)
=============================
n_true_labels: 2350
n_pred_labels: 2291
n_true_positives: 2175
n_false_positives: 86
n_false_negatives: 96
IoU: 0.858
Jaccard: 0.923
pixel_identity: 0.983
localization_error: 2.172
| MIT | notebooks/unet_segmentation_metrics.ipynb | KristinaUlicna/unet_segmentation_metrics |
*NOTE(arl)*: the metrics here are calculated as follows in batch mode:+ `n_true_labels` is the sum of all true labels, etc+ `IoU` is the mean IoU of all found objects+ `Jaccard` is the Jaccard index over all found objects+ `localization_error` is the mean error for all found objects+ `pixel_identity` is the per image p... | plt.figure()
plt.hist(batch_result.per_object_IoU)
plt.title('Histogram of per object IoU metric')
plt.xlabel('IoU')
plt.show()
plt.figure()
plt.hist(batch_result.per_object_localization_error, bins=np.linspace(0,10,50))
plt.title('Histogram of per object localization error')
plt.xlabel('Error in Pixels')
plt.show() | _____no_output_____ | MIT | notebooks/unet_segmentation_metrics.ipynb | KristinaUlicna/unet_segmentation_metrics |
Basic Usage Guide for Obstacle Tower Gym Interface | from obstacle_tower_env import ObstacleTowerEnv, ObstacleTowerEvaluation
%matplotlib inline
from matplotlib import pyplot as plt
from IPython.display import display, clear_output
import numpy as np
# import matplotlib.pyplot as plt
# import matplotlib.animation as animation | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Launching the environmentEnsure that the Obstacle Tower binary has been downloaded (https://github.com/Unity-Technologies/obstacle-tower-envdownload-the-environment), and placed in the correct sub-folder. Here we use the `examples/ObstacleTower` sub-folder. | # Realtime mode determines whether the environment window will render the scene,
# as well as whether the environment will run at realtime speed. Set this to `True`
# to visual the agent behavior as you would in player mode.
env = ObstacleTowerEnv('./ObstacleTower/obstacletower', retro=False, realtime_mode=True) | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Environment informationWe can also set the random seed used to generate the environment, as well as choose a starting floor. | # The environment provided has a MultiDiscrete action space, where the 4 dimensions are:
# 0. Movement (No-Op/Forward/Back)
# 1. Camera Rotation (No-Op/Counter-Clockwise/Clockwise)
# 2. Jump (No-Op/Jump)
# 3. Movement (No-Op/Right/Left)
print(env.action_space)
# The observation space provided includes a 168x168 imag... | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Interacting with the environment | import numpy as np
seed = 5 # seed = np.random.randint(100)
env.seed(seed) # Seeds can be chosen from range of 0-100.
env.floor(0) # Floors can be chosen from range of 0-100.
obs = env.reset()
plt.imshow(obs[0])
def run_episode(env):
done = False
seed = 5
env.seed(seed)
env.floor(0)
obs = ... | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Setting environment parametersWe can also set the random seed used to generate the environment, as well as choose a starting floor. | # Seeds can be chosen from range of 0-100.
env.seed(5)
# Floors can be chosen from range of 0-100.
env.floor(15)
# Additional reset parameters can be set using a config dictionary
# Here we set the agent perspective to first-person mode.
config = {'agent-perspective': 1}
# These parameters won't take place until the ne... | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Evaluation | from obstacle_tower_env import ObstacleTowerEnv, ObstacleTowerEvaluation
%matplotlib inline
from matplotlib import pyplot as plt
def run_episode(env):
done = False
episode_return = 0.0
while not done:
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
... | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Launching the environment (retro mode)We also provide a `retro mode` which uses observation and action spaces similar to those found in the Arcade Learning Environment (ALE). | env = ObstacleTowerEnv('./ObstacleTower/obstacletower', retro=True)
# In retro mode, the observation is an 84x84 image with the time remaining and key count visually embedded.
env.observation_space | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Interacting with the environment (retro mode) | obs = env.reset()
print(obs.shape)
obs, reward, done, info = env.step(env.action_space.sample())
plt.imshow(obs) | _____no_output_____ | Apache-2.0 | examples/run.ipynb | Pianochicken/Final-Project-Obstacle-Tower |
Taking Log | def logTransform(df):
ts_log = np.log(df)
plt.plot(ts_log)
return ts_log
ts1_log = logTransform(ts1)
test_stationarity(ts1_log.Value) | C:\Users\priya\Anaconda3\lib\site-packages\ipykernel\__main__.py:5: FutureWarning: pd.rolling_mean is deprecated for Series and will be removed in a future version, replace with
Series.rolling(center=False,window=12).mean()
C:\Users\priya\Anaconda3\lib\site-packages\ipykernel\__main__.py:6: FutureWarning: pd.rolling_... | Apache-2.0 | Development Indicators Project/python notebooks/BR_GDP-growth.ipynb | autodidact-m/Projects |
Log first difference | def logFirstDifference(ts1_log):
ts1_log_diff = ts1_log - ts1_log.shift()
ts1_log_diff.dropna(inplace=True)
return ts1_log_diff
ts1_log_diff = logFirstDifference(ts1_log)
test_stationarity(ts1_log_diff.Value) | C:\Users\priya\Anaconda3\lib\site-packages\ipykernel\__main__.py:5: FutureWarning: pd.rolling_mean is deprecated for Series and will be removed in a future version, replace with
Series.rolling(center=False,window=12).mean()
C:\Users\priya\Anaconda3\lib\site-packages\ipykernel\__main__.py:6: FutureWarning: pd.rolling_... | Apache-2.0 | Development Indicators Project/python notebooks/BR_GDP-growth.ipynb | autodidact-m/Projects |
First difference | def firstDifference(df):
#ts_first_diff = df - df.shift()
#ts_first_diff.dropna(inplace=True)
ts_first_diff = df.diff()
ts_first_diff.dropna(inplace=True)
return ts_first_diff
ts1_first_diff = firstDifference(ts1)
test_stationarity(ts1_first_diff.Value)
def expWeightedavg(ts1_log):
expwighted_... | _____no_output_____ | Apache-2.0 | Development Indicators Project/python notebooks/BR_GDP-growth.ipynb | autodidact-m/Projects |
- As seen from the graph above both ACF and PACF are geometric hence this is an ARMA model | autocorrelation_plot(ts1_log)
plt.show()
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts1_log)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts1_log)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_l... | _____no_output_____ | Apache-2.0 | Development Indicators Project/python notebooks/BR_GDP-growth.ipynb | autodidact-m/Projects |
Question C | SVMs hand-onYilun Kuang (Mark)N15511943FML HW 2 Question 1 ```shell Login to the computing clusterssh yk2516@greene.hpc.nyu.educd /scratch/yk2516/svm Download libsvm github repogit clone https://github.com/cjlin1/libsvm.gitcd libsvmmake Install the libsvm pypi packages on the systemsingularity exec --nv ... | import os
import numpy as np
import pandas as pd
def preprocess(train_length = 3133):
pd_tmp = pd.read_csv('abalone.data',header=None)
sex_map = {'M':("1 0 0"),'F':("0 1 0"),'I':("0 0 1")}
pd_tmp[0]=pd_tmp[0].apply(lambda x: sex_map[x])
pd_sex = pd_tmp[0].str.split(expand=True)
pd_tmp = pd_tmp.drop(... | _____no_output_____ | BSD-3-Clause | yk2516_hw2_q3.ipynb | YilunKuang/FML_HW2 |
Question 3 | import scipy
from libsvm.svmutil import *
y, x = svm_read_problem('abalone_scale', return_scipy = True)
# Train & Test split
train_length = 3133
y_train, x_train = y[0:train_length], x[0:train_length, :]
y_test, x_test = y[train_length:], x[train_length:, :]
# Transform the train dataset into binary classification pr... | _____no_output_____ | BSD-3-Clause | yk2516_hw2_q3.ipynb | YilunKuang/FML_HW2 |
Question 4 | argmin_ind = np.unravel_index(np.argmin(np.array(lst_cross_validated_error)), np.array(lst_cross_validated_error).shape)
k_lst = [i for i in range(-k_val_sup,k_val_sup)]
best_d = ploy_degree_lst[argmin_ind[0]]
best_k = k_lst[argmin_ind[1]]
best_C = 3**(k_lst[argmin_ind[1]])
print(f"The minimum cross validation error is... | _____no_output_____ | BSD-3-Clause | yk2516_hw2_q3.ipynb | YilunKuang/FML_HW2 |
Question 5 | lst_train_err = []
lst_test_err = []
for num_exs in range(1,train_length,500):
best_m = svm_train(new_label[:num_exs], x_train[:num_exs],"-c %s -t %s -d %s -q" % (best_C, kernel_type, best_d))
p_label, p_acc_train, p_val = svm_predict(new_label[:num_exs], x_train[:num_exs], best_m)
p_label, p_acc_test... | _____no_output_____ | BSD-3-Clause | yk2516_hw2_q3.ipynb | YilunKuang/FML_HW2 |
Question 6 c)For the hinge loss minimization problem of SVM, we consider the sklearn library implementation.By sklearn documentation, the `SGDClassifier` trained with the hinge loss using Stochastic Gradient Descent is equivalent to a linear SVM. | from sklearn.metrics import accuracy_score
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier(loss="hinge")
# Test Error
clf.fit(x_train, new_label)
pred_svm_test = clf.predict(x_test)
svm_hinge_acc_Test = accuracy_score(y_test,pred_svm_test)
# Five-Folds cross validation error
lst_svm_hinge_cross_valid... | _____no_output_____ | BSD-3-Clause | yk2516_hw2_q3.ipynb | YilunKuang/FML_HW2 |
Faruk ve Talha isimli öğrencilerden **birini** seçeceğiz.* Faruk’u seçme olasılığımız **P(F) = 0.6**,* Talha’yı seçme olasılığımız **P(T) = 0.4** olsun. * Bu durumu **bernoulli** diyagramı ile gösterebiliriz.* **Bernoulli ayrık rassal değişkenler**den oluşan bir diyagramdır.* Bu yüzden **Olasılık kütle fonks... | ## 205112015 Hasan Burak AYDIN Olasılık Kütle Fonksiyonu (PMF) Çalışması
from scipy.stats import bernoulli #bernoulli kütle yoğunluk fonksiyonunun plot diyagramı için kütüphanelerin dahil edilmesi
import matplotlib.pyplot as plt
X = [0,1] #X rassal değişkenimizin aldığı değerlerin diziye atanması
pF = 0.6 #Faruk'u... | _____no_output_____ | MIT | probabilitymassfunction.ipynb | hasanburakaydin/Plugins |
Recommendations with IBMIn this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform. You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code p... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import project_tests as t
import pickle
%matplotlib inline
df = pd.read_csv('data/user-item-interactions.csv')
df_content = pd.read_csv('data/articles_community.csv')
del df['Unnamed: 0']
del df_content['Unnamed: 0']
# Show df to get an idea of t... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
Part I : Exploratory Data AnalysisUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of ti... | count_interactions = df.groupby('email').count()['article_id']
plt.hist(count_interactions, bins=30);
plt.title('Number of times each user interacts with an article');
plt.xlabel('Number of Interactions');
plt.ylabel('Number of Articles');
# Fill in the median and maximum number of user_article interactios below
media... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`2.` Explore and remove duplicate articles from the **df_content** dataframe. | # Find and explore duplicate articles
df_content[df_content.duplicated()]
# Remove any rows that have the same article_id - only keep the first
df_content.drop_duplicates(subset=['article_id'],keep='first',inplace=True) | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`3.` Use the cells below to find:**a.** The number of unique articles that have an interaction with a user. **b.** The number of unique articles in the dataset (whether they have any interactions or not).**c.** The number of unique users in the dataset. (excluding null values) **d.** The number of user-article interac... | unique_articles = len(pd.unique(df['article_id']))# The number of unique articles that have at least one interaction
total_articles = len(pd.unique(df_content['article_id']))# The number of unique articles on the IBM platform
unique_users = len(pd.unique(df['email'].dropna()))# The number of unique users
user_article_i... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belong... | most_viewed_article_id = str(df.article_id.value_counts().axes[0][0])# The most viewed article in the dataset as a string with one value following the decimal
max_views = df.article_id.value_counts().max()# The most viewed article in the dataset was viewed how many times?
## No need to change the code here - this will... | It looks like you have everything right here! Nice job!
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
Part II: Rank-Based RecommendationsUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.`1.` ... | def get_top_articles(n, df=df):
'''
INPUT:
n - (int) the number of top articles to return
df - (pandas dataframe) df as defined at the top of the notebook
OUTPUT:
top_articles - (list) A list of the top 'n' article titles
'''
top_articles = df['title'].value_counts().axes[0][... | Your top_5 looks like the solution list! Nice job.
Your top_10 looks like the solution list! Nice job.
Your top_20 looks like the solution list! Nice job.
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
Part III: User-User Based Collaborative Filtering`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. * Each **user** should only appear in each **row** once.* Each **article** should only show up in one **column**. * **If a user has interacted... | # create the user-article matrix with 1's and 0's
def create_user_item_matrix(df):
'''
INPUT:
df - pandas dataframe with article_id, title, user_id columns
OUTPUT:
user_item - user item matrix
Description:
Return a matrix with user ids as rows and article ids on the columns with ... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here ... | def find_similar_users(user_id, user_item=user_item):
'''
INPUT:
user_id - (int) a user_id
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
OUTPUT:
similar_users - (list) an ordered list where the closes... | The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 131, 3870, 46, 4201, 49]
The 5 most similar users to user 3933 are: [1, 23, 3782, 203, 4459]
The 3 most similar users to user 46 are: [4201, 23, 3782]
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. | def get_article_names(article_ids, df=df):
'''
INPUT:
article_ids - (list) a list of article ids
df - (pandas dataframe) df as defined at the top of the notebook
OUTPUT:
article_names - (list) a list of article names associated with the list of article ids
(this is iden... | If this is all you see, you passed all of our tests! Nice job!
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. * Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.* ... | def get_article_order(user_id,counts):
'''
INPUT:
user_id - (int)
counts - (pandas Series) value_counts
OUTPUT:
top_articles - (list) A list of article id sorted by interactions
'''
ids,titles = get_user_articles(user_id)
dic = {}
for this_id in ids:
dic[this_id... | The top 10 recommendations for user 20 are the following article ids:
['173.0', '1432.0', '1431.0', '593.0', '1162.0', '18.0', '911.0', '111.0', '1436.0', '880.0']
The top 10 recommendations for user 20 are the following article names:
['10 must attend data science, ml and ai conferences in 2018', 'visualize data with... | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below. | ### Tests with a dictionary of results
user1_most_sim = find_similar_users(1)[0]# Find the user that is most similar to user 1
user131_10th_sim = find_similar_users(131)[9]# Find the 10th most similar user to user 131
## Dictionary Test Here
sol_5_dict = {
'The user that is most similar to user 1.': user1_most_si... | This all looks good! Nice job!
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users. A new user has no reading records,so it isn't able to find what the user ... | new_user = '0.0'
# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.
# Provide a list of the top 10 article ids you would give to
new_user_recs = df['article_id'].value_counts().axes[0][:10].tolist()# Your recommendations here
assert set(new_user_recs) == se... | That's right! Nice job!
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
Part IV: Matrix FactorizationIn this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will jus... | # Load the matrix here
user_item_matrix = pd.read_pickle('user_item_matrix.p')
# quick look at the matrix
user_item_matrix.head() | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson. | # Perform SVD on the User-Item Matrix Here
u, s, vt = np.linalg.svd(user_item_matrix)# use the built in to get the three matrices | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
in the lessson ,there are missing values in matrix,but in this project , if users and articles don't have interacted with each other,the values is 0,so matrix has no missing values and the code won't cause any error. **Provide your response here.** `3.` Now for the tricky part, how do we choose the number of latent fe... | num_latent_feats = np.arange(10,700+10,20)
sum_errs = []
for k in num_latent_feats:
# restructure with k latent features
s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]
# take dot product
user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))
# compute error for each p... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in ... | df_train = df.head(40000)
df_test = df.tail(5993)
def create_test_and_train_user_item(df_train, df_test):
'''
INPUT:
df_train - training dataframe
df_test - test dataframe
OUTPUT:
user_item_train - a user-item matrix of the training dataframe
(unique users for each r... | Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.
| MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`5.` Now use the **user_item_train** dataset from above to find **U**, **S**, and **V** transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on... | # fit SVD on the user_item_train matrix
u_train, s_train, vt_train = np.linalg.svd(user_item_train)# fit svd similar to above then use the cells below
user_item_test.head(2)
def get_error(s,u,v,user_item,k=100):
'''
INPUT:
s,u,v: result of svd training
user_item:user_item matrices
k: - (int) numb... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? - training error an... | from subprocess import call
call(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb']) | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | MihaiLai/Recommendation-System |
Creating and Training the Model | from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,y_train) | _____no_output_____ | MIT | 01-Linear Regression with Python.ipynb | AhmetTuranBalkan/ML-Algorithms |
Model Evaluation | coeff_df = pd.DataFrame(lm.coef_,X.columns,columns=['Coefficient'])
coeff_df
predictions = lm.predict(X_test)
plt.scatter(y_test,predictions)
plt.show()
from sklearn import metrics
print('MAE:', metrics.mean_absolute_error(y_test, predictions))
print('MSE:', metrics.mean_squared_error(y_test, predictions))
print('RMSE:... | MAE: 82288.2225191
MSE: 10460958907.2
RMSE: 102278.829223
| MIT | 01-Linear Regression with Python.ipynb | AhmetTuranBalkan/ML-Algorithms |
Chapter 5 - Outlier Analysis Segment 8 - Extreme value analysis using univariate methods | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
%matplotlib inline
rcParams['figure.figsize'] = 5,4
import pathlib
import os
address = pathlib.Path(os.getcwd()).parent
address = pathlib.Path(os.path.join(address, 'Data/iris.data.csv'))
df = pd.read_csv(filepath_or_buff... | _____no_output_____ | MIT | Pt_1/05_08_Extreme_value_analysis_using_univariate_methods/05_08_end.ipynb | vladcuevas/Python-Data-Science-Labs |
Identifying outliers from Tukey boxplots | df.boxplot(return_type='dict')
plt.plot()
Sepal_Width = X[:,1]
iris_outliers = (Sepal_Width > 4)
df[iris_outliers]
Sepal_Width = X[:,1]
iris_outliers = (Sepal_Width < 2.05)
df[iris_outliers] | _____no_output_____ | MIT | Pt_1/05_08_Extreme_value_analysis_using_univariate_methods/05_08_end.ipynb | vladcuevas/Python-Data-Science-Labs |
Applying Tukey outlier labeling | pd.options.display.float_format = '{:.1f}'.format
X_df = pd.DataFrame(X)
print(X_df.describe()) | 0 1 2 3
count 150.0 150.0 150.0 150.0
mean 5.8 3.1 3.8 1.2
std 0.8 0.4 1.8 0.8
min 4.3 2.0 1.0 0.1
25% 5.1 2.8 1.6 0.3
50% 5.8 3.0 4.3 1.3
75% 6.4 3.3 5.1 1.8
max 7.9 4.4 6.9 2.5
| MIT | Pt_1/05_08_Extreme_value_analysis_using_univariate_methods/05_08_end.ipynb | vladcuevas/Python-Data-Science-Labs |
1. Google Play Store apps and reviewsMobile apps are everywhere. They are easy to create and can be lucrative. Because of these two factors, more and more apps are being developed. In this notebook, we will do a comprehensive analysis of the Android app market by comparing over ten thousand apps in Google Play across ... | # Read in dataset
import pandas as pd
import pandas as pd
apps_with_duplicates = pd.read_csv('datasets/apps.csv')
# Drop duplicates
apps = apps_with_duplicates.drop_duplicates()
# Print the total number of apps
print('Total number of apps in the dataset = ', apps.shape[0])
# Have a look at a random sample of 5 entri... | Total number of apps in the dataset = 9659
| Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
2. Data cleaningThe four features that we will be working with most frequently henceforth are Installs, Size, Rating and Price. The info() function (from the previous task) told us that Installs and Price columns are of type object and not int64 or float64 as we would expect. This is because the column contains some ... | # List of characters to remove
chars_to_remove = ['+',",","$"]
# List of column names to clean
cols_to_clean = ["Installs","Price"]
# Loop for each column
for col in cols_to_clean:
# Replace each character with an empty string
for char in chars_to_remove:
apps[col] = apps[col].astype(str).str.replace(c... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
3. Exploring app categoriesWith more than 1 billion active users in 190 countries around the world, Google Play continues to be an important distribution platform to build a global audience. For businesses to get their apps in front of users, it's important to make them more quickly and easily discoverable on Google P... | import plotly
plotly.offline.init_notebook_mode(connected=True)
import plotly.graph_objs as go
# Print the total number of unique categories
num_categories = len(apps["Category"].unique())
print('Number of categories = ', num_categories)
# Count the number of apps in each 'Category' and sort them in descending order
... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
4. Distribution of app ratingsAfter having witnessed the market share for each category of apps, let's see how all these apps perform on an average. App ratings (on a scale of 1 to 5) impact the discoverability, conversion of apps as well as the company's overall brand image. Ratings are a key performance indicator of... | # Average rating of apps
avg_app_rating = apps['Rating'].mean()
print('Average app rating = ', avg_app_rating)
# Distribution of apps according to their ratings
data = [go.Histogram(
x = apps['Rating']
)]
# Vertical dashed line to indicate the average app rating
layout = {'shapes': [{
'type' :'l... | Average app rating = 4.173243045387994
| Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
5. Size and price of an appLet's now examine app size and app price. For size, if the mobile app is too large, it may be difficult and/or expensive for users to download. Lengthy download times could turn users off before they even experience your mobile app. Plus, each user's device has a finite amount of disk space.... | %matplotlib inline
import seaborn as sns
sns.set_style("darkgrid")
import warnings
warnings.filterwarnings("ignore")
# Filter rows where both Rating and Size values are not null
apps_with_size_and_rating_present = apps[(~apps["Rating"].isnull()) & (~apps["Size"].isnull())]
# Subset for categories with at least 250 ap... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
6. Relation between app category and app priceSo now comes the hard part. How are companies and developers supposed to make ends meet? What monetization strategies can companies use to maximize profit? The costs of apps are largely based on features, complexity, and platform.There are many factors to consider when sel... | import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.set_size_inches(15, 8)
# Select a few popular app categories
popular_app_cats = apps[apps.Category.isin(['GAME', 'FAMILY', 'PHOTOGRAPHY',
'MEDICAL', 'TOOLS', 'FINANCE',
'... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
7. Filter out "junk" appsIt looks like a bunch of the really expensive apps are "junk" apps. That is, apps that don't really have a purpose. Some app developer may create an app called I Am Rich Premium or most expensive app (H) just for a joke or to test their app development skills. Some developers even do this with... | # Select apps priced below $100
apps_under_100 =popular_app_cats[popular_app_cats["Price"]<100]
fig, ax = plt.subplots()
fig.set_size_inches(15, 8)
# Examine price vs category with the authentic apps
ax = sns.stripplot(x=apps_under_100["Price"], y=apps_under_100["Category"], data=apps_under_100,
ji... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
8. Popularity of paid apps vs free appsFor apps in the Play Store today, there are five types of pricing strategies: free, freemium, paid, paymium, and subscription. Let's focus on free and paid apps only. Some characteristics of free apps are:Free to download.Main source of income often comes from advertisements.Ofte... | trace0 = go.Box(
# Data for paid apps
y=apps[apps['Type'] == 'Paid']['Installs'],
name = 'Paid'
)
trace1 = go.Box(
# Data for free apps
y=apps[apps['Type'] == 'Free']['Installs'],
name = 'Free'
)
layout = go.Layout(
title = "Number of downloads of paid apps vs. free apps",
yaxis = dict... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
9. Sentiment analysis of user reviewsMining user review data to determine how people feel about your product, brand, or service can be done using a technique called sentiment analysis. User reviews for apps can be analyzed to identify if the mood is positive, negative or neutral about that app. For example, positive w... | # Load user_reviews.csv
reviews_df = pd.read_csv('datasets/user_reviews.csv')
# Join and merge the two dataframe
merged_df = pd.merge(apps, reviews_df, on = 'App', how = "inner")
# Drop NA values from Sentiment and Translated_Review columns
merged_df = merged_df.dropna(subset=['Sentiment', 'Translated_Review'])
sns.... | _____no_output_____ | Unlicense | App market.ipynb | Simonm952/simonm952.github.io |
Fetal Health Classification
Source: Google
Fetal mortality refers to stillbirths or fetal death. It encompasses any death of a fetus after 20 weeks of gestation.
Cardiotocograms (CTGs) are a simple and cost accessible option to assess fetal health, allowing healthcare professionals to take action in o... | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('../Datasets/fetal_health.csv') | _____no_output_____ | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
| Variable symbol | Variable description|
| ----------------|---------------------|
|LB | Fetal heart rate baseline (beats per minute)|
|AC | Number of accelerations per second|
|FM | Number of fetal movements per second|
|UC | Number of uterine contractions per second|
|DL | Number of light decelerations per second|
|... | df.head()
df.info()
df.describe()
df.isna().sum() | _____no_output_____ | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
Thankfully, there are no NaN values in the dataset. | sns.countplot(x='fetal_health', data=df)
print(df['fetal_health'].value_counts()) | 1.0 1655
2.0 295
3.0 176
Name: fetal_health, dtype: int64
| MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
We can see that there is the problem of class imbalance in this dataset. This means we cannot use **accuracy** as a metric to evaluate the performance of our model. The most appropiate metric for model evaluation can be:
1. F1 Score
2. Recall
3. Precision Before diving deep into understanding the data and features, let... | corr = df.corr()
plt.figure(figsize=(24, 20))
sns.heatmap(corr, annot=True)
plt.title("Correlation Matrix")
plt.show() | _____no_output_____ | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
From the above correlation matrix, we can observe that the following features show some correlation with target variable fetal health:
1. accelerations (negative corr)
2. uterine contractions (negative corr)
3. prolonged_decelerations (positive corr)
4. abnormal short term variability (positive corr)
5. percentage of ... | from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import StandardScale... | There are total 1594 rows in training dataset
There are total 532 rows in test dataset
| MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
If you remember, in the initial investigation of the data, we found out that we have imbalanced classes.
To handle the problem of imbalanced classes, we can use oversampling techniques. In oversampling, we populate the minority classes with some synthetic data.
Let us try some oversampling techniques and judge thei... | from imblearn.over_sampling import SMOTE
smt = SMOTE()
X_train_sm, y_train_sm = smt.fit_resample(X_train, y_train) | /usr/local/lib/python3.7/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).
"(https://pypi.org/project/six/).", Fu... | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
2. ADASYN | from imblearn.over_sampling import ADASYN
ada = ADASYN(random_state=130)
X_train_ada, y_train_ada = ada.fit_resample(X_train, y_train) | /usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.
warnings.warn(msg, category=FutureWarning)
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:8... | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
3. SMOTE + Tomek Links | from imblearn.combine import SMOTETomek
smtom = SMOTETomek(random_state=139)
X_train_smtom, y_train_smtom = smtom.fit_resample(X_train, y_train) | /usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.
warnings.warn(msg, category=FutureWarning)
/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:8... | MIT | Notebooks/FetalHealthClassification_Imbalanced.ipynb | codeshruti/HealthCheck |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.