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 |
|---|---|---|---|---|---|
Having created the model we can now train it, the same way we have done for the RNN: | # Then we train and evaluate
out = ss_utils.train_neural_network(train_df, val_df, "smiles",
"measured log solubility in mols per litre", transform_seq_model, cnn_model)
# And then we print out as a table some of the results.
display(HTML(tabulate.tabulate(out['out_table'], tablefm... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
What pooling operation works best? How does performance in terms of loss, number of parameters and timings compare to the RNN? Does adding additional convolutional layers change this? 🕰 **(optional) Task C -- Augmented Sequences:** Earlier in this notebook we discussed how each molecule corresponds to many SMILES str... | class Graphs:
ATOM_FEATURIZER = SymbolFeaturizer(['Ag', 'Al', 'Ar', 'As', 'Au', 'B', 'Ba', 'Be', 'Bi', 'Br', 'C',
'Ca', 'Cd', 'Ce', 'Cl', 'Co', 'Cr', 'Cs', 'Cu', 'Dy', 'Eu', 'F',
'Fe', 'Ga', 'Ge', 'H', 'He', 'Hf', 'Hg', 'I', 'In', 'Ir', 'K', 'La',
'Li', 'M... | graph_of_both.node_features:
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,... | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Having created the `Graphs` datastructure we can now create our graph neural network (GNN) which gets fed in the `Graphs` class as input. At a high level, the GNN consists of a series of message passing steps, which update the node features. After computing richer node features in this manner, a graph-level representat... | class GNN(nn.Module):
def __init__(self, node_feature_dimension, num_propagation_steps:int =4):
super().__init__()
self.num_propagation_steps = num_propagation_steps
# called T above.
# Our sub modules:
self.message_projection = nn.Linear(node_feature_dimens... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Before we can run our training loop with our new model we need to tell the PyTorch `Dataloader` (used in `ss_utils`) how to collate the graphs together when forming minibatches (the main machinery of how this happens you have already written in task 7 above). | def collate_for_graphs(batch):
"""
This is a custom collate function for use minibatches of graphs along with their regression value.
It ensures that we concatenate graphs correctly.
Look at ss_utils to see how this gets used.
"""
# Split up the graphs and the y values
list_of_graphs, l... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
And now we can train! | # Then we train and evaluate
out = ss_utils.train_neural_network(train_df, val_df, "smiles", "measured log solubility in mols per litre",
transform=Graphs.from_smiles_string, neural_network=gnn,
collate_func=collate_for_graphs)
# And then we print ... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Install packages (run only once in the runtime) | !pip install deepxde | _____no_output_____ | Apache-2.0 | examples/Lorenz_inverse_Colab.ipynb | smao-astro/deepxde |
Imports and functions | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
import re
import matplotlib.pyplot as plt
import numpy as np
import requests
import deepxde as dde
from deepxde.backend import tf
# get training data
def gen_traindata():
response = requests.g... | Using TensorFlow 2 backend.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/compat/v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not su... | Apache-2.0 | examples/Lorenz_inverse_Colab.ipynb | smao-astro/deepxde |
Define data and BCs | # define time domain
geom = dde.geometry.TimeDomain(0, 3)
# Initial conditions
ic1 = dde.IC(geom, lambda X: -8, boundary, component=0)
ic2 = dde.IC(geom, lambda X: 7, boundary, component=1)
ic3 = dde.IC(geom, lambda X: 27, boundary, component=2)
# Get the training data
observe_t, ob_y = gen_traindata()
ptset = dde.b... | _____no_output_____ | Apache-2.0 | examples/Lorenz_inverse_Colab.ipynb | smao-astro/deepxde |
Train network | # define FNN architecture and compile
net = dde.maps.FNN([1] + [40] * 3 + [3], "tanh", "Glorot uniform")
model = dde.Model(data, net)
model.compile("adam", lr=0.001)
# callbacks for storing results
fnamevar = "variables.dat"
variable = dde.callbacks.VariableValue(
[C1, C2, C3],
period=1,
filename=fnamevar... | Compiling model...
Building feed-forward neural network...
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/deepxde/maps/fnn.py:82: dense (from tensorflow.python.keras.legacy_tf_layers.core) is deprecated and will be removed in a future version.
Instructions for updating:
Use keras.layers.Dense instead.
W... | Apache-2.0 | examples/Lorenz_inverse_Colab.ipynb | smao-astro/deepxde |
Plot identified parameters | # reopen saved data using callbacks in fnamevar
lines = open(fnamevar, "r").readlines()
# read output data in fnamevar (this line is a long story...)
Chat = np.array([np.fromstring(min(re.findall(re.escape('[')+"(.*?)"+re.escape(']'),line), key=len), sep=',') for line in lines])
l,c = Chat.shape
plt.plot(range(l),C... | Predicting...
'predict' took 0.018274 s
| Apache-2.0 | examples/Lorenz_inverse_Colab.ipynb | smao-astro/deepxde |
Query | def query(video_id, MIN_FACE_HEIGHT, MIN_BRIGHTNESS, stride):
# We're going to look for frames that would be good "hero shot" frames --
# potentially good frames to show in a Netflix preview, for instance.
# We're going to look for frames where there's exactly one face of a
# certain height, and the... | _____no_output_____ | Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Braveheart | widget, result = show_query(28, 0.2, 75, 10)
selected_segments_braveheart = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_braveheart)
convert_segments(selected_segments_braveheart) | [(48232, 48300), (72574, 72649), (108792, 108835), (111688, 111995), (115709, 115730), (116403, 116498), (122525, 122543), (132329, 132383), (153664, 153720), (232645, 232673)]
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Revenge of the Sith | start = time.time()
widget, result = show_query(186, 0.2, 50, 5)
selected_segments_rots = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_rots)
convert_segments(selected_segments_rots)
end = time.time()
print... | Seconds to label: 126.90570259094238
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Steve Jobs | start = time.time()
widget, result = show_query(520, 0.2, 50, 5)
selected_segments_jobs = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_jobs)
convert_segments(selected_segments_jobs)
end = time.time()
print... | Seconds to label: 78.31287026405334
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Guardians of the Galaxy | start = time.time()
widget, result = show_query(74, 0.2, 50, 5)
selected_segments_gotg = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_gotg)
convert_segments(selected_segments_gotg)
end = time.time()
print(... | Seconds to label: 51.962666034698486
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Daddy's Home | start = time.time()
widget, result = show_query(334, 0.2, 50, 5)
selected_segments_daddy = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_daddy)
convert_segments(selected_segments_daddy)
end = time.time()
pr... | Seconds to label: 54.389283418655396
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Batman v Superman | start = time.time()
widget, result = show_query(299, 0.2, 50, 5)
selected_segments_bvs = [
(result['result'][i]['elements'][0]['min_frame'], result['result'][i]['elements'][0]['min_frame'])
for i in widget.selected
]
print(selected_segments_bvs)
convert_segments(selected_segments_bvs)
end = time.time()
print("S... | Seconds to label: 93.14249897003174
| Apache-2.0 | app/notebooks/trailer_mining_hero_shots.ipynb | DanFu09/esper |
Binary Classification Model | # Binary Classification Model
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings):
"""Creates a classification model."""
model = bert.run_classifier.modeling.BertModel(config=bert_config,
is_train... | _____no_output_____ | MIT | Hostility-Detection-in-Hindi-Constraint-2021-main/Model-Inference/Fine_Grained (Defamation).ipynb | venkateshelangovan/Hostile-Post-Prediction-in-Hindi |
NOTE**Please ensure that you have ran the *Mitchel and YouTuBean train test split* notebooks first so that all of the datasets are avaliable** | from collections import defaultdict
from pathlib import Path
import json
from typing import Callable, List, Union, Tuple, Dict, Any
import math
import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.metrics import f1_score, accuracy_score
# Models
from bel... | _____no_output_____ | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Above is just loading the data, sentiment lexicons and places to save the results of the experiments Target Dependent methods applied across multiple datasetsIn this notebook we are going to look at the two best TDParse methods:1. Target Dependent2. Target Dependent+The first does not use a sentiment lexicon and the se... | coarse_range = []
start = 0.00001
stop = 10
while True:
coarse_range.append(start)
start *= 10
if start > stop:
break
coarse_range
models = [TargetDep, TargetDepPlus]
n_cpus = 7
dataset_model_c = {}
best_c_file = results_folder.joinpath('Mass Evaluation Best C.json')
if best_c_file.is_file():
w... | Dataset: SemEval 14 Laptop Model and C Value {"<class 'bella.models.target.TargetDep'>": '0.01', "<class 'bella.models.target.TargetDepPlus'>": '0.0035'}
Dataset: SemEval 14 Restaurant Model and C Value {"<class 'bella.models.target.TargetDep'>": '0.035', "<class 'bella.models.target.TargetDepPlus'>": '0.01'}
Dataset: ... | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Finding the best word embeddingsWe are now going to perform 5 fold cross validation to find the best word embedding for each method on each dataset. The possible word embeddings are the following:1. [Glove 42 Billion Common Crawl](https://nlp.stanford.edu/projects/glove/) - 300 dimension these were trained on web data... | dataset_model_embedding = {}
best_embedding_file = results_folder.joinpath('Mass Evaluation Best Embedding.json')
if best_embedding_file.is_file():
with best_embedding_file.open('r') as best_embedding_json:
dataset_model_embedding = json.load(best_embedding_json)
for dataset_name, train, test in dataset_tr... | Dataset: SemEval 14 Laptop Model and Embedding {"<class 'bella.models.target.TargetDep'>": '[glove 300d 42b common crawl]', "<class 'bella.models.target.TargetDepPlus'>": '[glove 300d 42b common crawl]'}
Dataset: SemEval 14 Restaurant Model and Embedding {"<class 'bella.models.target.TargetDep'>": '[sswe]', "<class 'be... | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Predictions on the test dataNow we have the best C value and embeddings for each dataset and for each model we shall use these to make the predictions on the test data of all the datasets. Once we have made these predictions we shall save the raw predictions and the machine learning models so that we can analysis and ... | model_dataset_predictions = defaultdict(lambda: dict())
# Get the predictions data if it exists
for model in models:
model_results_folder = results_folder.joinpath(model.name())
dataset_predictions_fp = model_results_folder.joinpath('dataset predictions.json')
if dataset_predictions_fp.is_file():
w... | _____no_output_____ | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Mass evaluation results | dataset_test = {name: test for name, train, test in dataset_train_test}
f1_results = evaluation.evaluate_models(f1_score, dataset_test,
model_dataset_predictions,
dataframe=True, average='macro')
acc_results = evaluation.evaluate_models(a... | _____no_output_____ | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Accuracy | (acc_results * 100).round(2) | _____no_output_____ | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Macro F1 | (f1_results * 100).round(2) | _____no_output_____ | MIT | notebooks/Mass Evaluation - Target Dependent.ipynb | LaudateCorpus1/Bella-5 |
Creating a Bar Chart Using Matplotlib | import matplotlib.pyplot as plt
% matplotlib inline | _____no_output_____ | Apache-2.0 | 2_Intro_to_data_analysis/Data_Analysis_Case_study_1/Quizes/matplotlib_example.ipynb | sudoberlin/Data_Analyst_ND |
There are two required arguments in pyplot's `bar` function: the x-coordinates of the bars, and the heights of the bars. | plt.bar([1, 2, 3], [224, 620, 425]); | _____no_output_____ | Apache-2.0 | 2_Intro_to_data_analysis/Data_Analysis_Case_study_1/Quizes/matplotlib_example.ipynb | sudoberlin/Data_Analyst_ND |
You can specify the x tick labels using pyplot's `xticks` function, or by specifying another parameter in the `bar` function. The two cells below accomplish the same thing. | # plot bars
plt.bar([1, 2, 3], [224, 620, 425])
# specify x coordinates of tick labels and their labels
plt.xticks([1, 2, 3], ['a', 'b', 'c']);
# plot bars with x tick labels
plt.bar([1, 2, 3], [224, 620, 425], tick_label=['a', 'b', 'c']); | _____no_output_____ | Apache-2.0 | 2_Intro_to_data_analysis/Data_Analysis_Case_study_1/Quizes/matplotlib_example.ipynb | sudoberlin/Data_Analyst_ND |
Set the title and label axes like this. | plt.bar([1, 2, 3], [224, 620, 425], tick_label=['a', 'b', 'c'])
plt.title('Some Title')
plt.xlabel('Some X Label')
plt.ylabel('Some Y Label'); | _____no_output_____ | Apache-2.0 | 2_Intro_to_data_analysis/Data_Analysis_Case_study_1/Quizes/matplotlib_example.ipynb | sudoberlin/Data_Analyst_ND |
Template - Author: Israel Oliveira [\[e-mail\]](mailto:'Israel%20Oliveira%20') | !pip3 install -U random-forest-mc
%load_ext watermark
import pandas as pd
import numpy as np
from random_forest_mc.model import RandomForestMC
from random_forest_mc.utils import load_file_json, dump_file_json
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, roc_auc_score
from c... | _____no_output_____ | MIT | utils/Experiments.ipynb | ysraell/random-forest |
Feature analysis | # Test step
probs = cls.testForestProbs(df_test)
# Save results
target_test = df_test.Class.to_list()
Results[seed] = {
'probs': probs,
'target_test': target_test
}
# Generates the metrics
data = []
for seed,exp in Results.items():
target_test = exp['target_test']
rf_c... | _____no_output_____ | MIT | utils/Experiments.ipynb | ysraell/random-forest |
TensorFlow Regression Example Creating Data | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 1 Million Points
x_data = np.linspace(0.0,10.0,1000000)
noise = np.random.randn(len(x_data))
# y = mx + b + noise_levels
b = 10
y_true = (2.5 * x_data ) + 15 + noise
sample_indx = np.random.randint(len(x_data),size=(250))
plt.plot(x_data[sample_i... | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
TensorFlow Batch SizeWe will take the data in batches (1,000,000 points is a lot to pass in at once) | import tensorflow as tf
# Random 10 points to grab
batch_size = 10 | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Variables** | w_tf = tf.Variable(np.random.uniform())
b_tf = tf.Variable(np.random.uniform(1,10)) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Placeholders** | x_train = tf.placeholder(tf.float32,shape=(batch_size))
y_train = tf.placeholder(tf.float32,shape=(batch_size)) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Graph** | y_hat = w_tf * x_train + b_tf | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Loss Function** | error = tf.reduce_sum((y_train - y_hat)**2) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Optimizer** | optimizer = tf.train.GradientDescentOptimizer(0.001)
train = optimizer.minimize(error) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Initialize Variables** | init = tf.global_variables_initializer() | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
Session | with tf.Session() as sess:
sess.run(init)
batchs = 1000
for i in range(batchs):
batch_index = np.random.randint(len(x_data),size=(batch_size))
feed = {x_train:x_data[batch_index], y_train:y_true[batch_index]}
sess.run(train,feed_dict = feed)
final_w, final_b = sess.run([w_tf,b_tf... | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
Results | plt.plot(x_data[sample_indx],y_true[sample_indx],'*')
plt.plot(x_data, final_w*x_data+final_b,'r') | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
Train Test SplitWe haven't actually performed a train test split yet! So let's do that on our data now and perform a more realistic version of a Regression Task | from sklearn.model_selection import train_test_split
x_train, x_eval, y_train, y_eval = train_test_split(x_data,y_true,test_size=0.3)
print(x_train.shape)
print(y_train.shape)
print(x_eval.shape)
print(y_eval.shape)
sample_indx = np.random.randint(len(x_eval),size=(250))
plt.plot(x_eval[sample_indx],y_eval[sample_indx... | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
tf.keras API | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Program Keras Model** | model = Sequential()
model.add(Dense(1,input_shape = (1,))) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Setup Optimizer** | sgd = SGD(0.001) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
**Compile Model** | model.compile(loss='mse', optimizer=sgd, metrics=['mse'])
H = model.fit(x_train, y_train, epochs = 1,batch_size = 32)
w_final, b_final = model.get_weights()
print(w_final[0])
print(b_final)
plt.plot(x_data[sample_indx],y_true[sample_indx],'*')
plt.plot(x_data, w_final[0]*x_data+b_final,'r')
y_pred = model.predict(x_eva... | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
TF Eager mode | import tensorflow as tf
# Set Eager API
tf.enable_eager_execution()
tfe = tf.contrib.eager
w_tf = tfe.Variable(np.random.uniform())
b_tf = tfe.Variable(np.random.uniform(1,10)) | _____no_output_____ | MIT | 1_Linear_Regression/.ipynb_checkpoints/03-Regression_TF_eager_api-checkpoint.ipynb | zht007/tensorflow-practice |
Stem Plots============Stem plots are commonly used to visualise discrete distributions of data,and are useful to highlight discrete observations where the precision of values alongone axis is high (e.g. an independent spatial measure like depth) and the other is lessso (such that the sampling frequency along this axis ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pyrolite.plot import pyroplot
from pyrolite.plot.stem import stem
np.random.seed(82) | _____no_output_____ | BSD-3-Clause | docs/source/examples/plotting/stem.ipynb | JustinGOSSES/pyrolite |
First let's create some example data: | x = np.linspace(0, 10, 10) + np.random.randn(10) / 2.0
y = np.random.rand(10)
df = pd.DataFrame(np.vstack([x, y]).T, columns=["Depth", "Fe3O4"]) | _____no_output_____ | BSD-3-Clause | docs/source/examples/plotting/stem.ipynb | JustinGOSSES/pyrolite |
A minimal stem plot can be constructed as follows: | ax = stem(df.Depth, df.Fe3O4, figsize=(5, 3))
# or, alternatively directly from the dataframe:
ax = df.pyroplot.stem(figsize=(5, 3)) | _____no_output_____ | BSD-3-Clause | docs/source/examples/plotting/stem.ipynb | JustinGOSSES/pyrolite |
Stem plots can also be used in a vertical orientation, such as for visualisingdiscrete observations down a drill hole: | ax = df.pyroplot.stem(orientation="vertical", figsize=(3, 5))
# the yaxes can then be inverted using:
ax.invert_yaxis()
# and if you'd like the xaxis to be labeled at the top:
ax.xaxis.set_ticks_position("top")
ax.xaxis.set_label_position("top") | _____no_output_____ | BSD-3-Clause | docs/source/examples/plotting/stem.ipynb | JustinGOSSES/pyrolite |
Minicurso: (Introdução à) Análise de Dados com PandasRoteiro: | ##Bibliotecas úteis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Abrir o conjunto de dados | ks_proj2018 = pd.read_csv('ks-projects-201801-5000.csv', index_col=0) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Métodos de Visualização dos Dados -- Visualizar os 5 primeiros exemplos: df.head() | ks_proj2018.head()
### Sua vez!
### Mostre os 10 primeiros exemplos
ks_proj2018.head(10) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Visualizar as colunas com dados numéricos | ks_proj2018.dtypes
ks_proj2018.select_dtypes(include=[np.number]).head()
### Sua vez!
### Identifique as colunas com dados numéricos, atribua-as a uma variável e em seguida imprima na tela
numeric_columns = ks_proj2018.select_dtypes(include=[np.number]).columns
numeric_columns | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Visualizar as colunas com dados categóricos | ks_proj2018.select_dtypes(include=[np.object]).head()
### Sua vez!
### Identifique as colunas com dados categóricos, atribua-as a uma variável e em seguida imprima na tela
string_columns = ks_proj2018.select_dtypes(include=[np.object]).columns
string_columns | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Média | ks_proj2018[['goal', 'pledged']].mean()
### Sua vez!
### Mostre a média para todas as colunas de dados numéricos
ks_proj2018.mean() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Desvio padrão | ks_proj2018['goal'].std()
### Sua vez!
### Mostre o desvio padrão para todas as colunas de dados numéricos
ks_proj2018.std() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Máximo e mínimo | ks_proj2018['goal'].max(), ks_proj2018['goal'].min()
### Sua vez!
### Mostre o valor máximo para todas as colunas de dados numéricos
ks_proj2018.select_dtypes(include=[np.number]).max()
### Sua vez!
### Mostre o valor mínimo para todas as colunas de dados numéricos
ks_proj2018.select_dtypes(include=[np.number]).min() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Ou... ver tudo junto! | ks_proj2018['goal'].describe()
### Sua vez!
### Descreva o conjunto de dados
ks_proj2018.select_dtypes(include=[np.number]).describe() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Saber a quantidade de projetos por categoria | pd.value_counts(ks_proj2018['category'])
### Sua vez!
### Mostre a quantidade de projetos por estado (coluna 'state')
pd.value_counts(ks_proj2018['state'])
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Calcular a simetria dos dados em relação à média | ks_proj2018['goal'].skew()
### Sua vez!
### Calcule a simetria de todos os dados numéricos em relação à média
ks_proj2018.skew()
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Calcular a correlação entre os dados | ks_proj2018.corr() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
O que podemos inferir em relação à correlação entre os dados? Ordenação -- Ordenar o conjunto de dados por data de lançamento do projeto | ks_proj2018.sort_values(by='launched', ascending=True)
### Ordene o dataset pelo 'name'
ks_proj2018.sort_values(by='name', ascending=False) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Ordenar pelo número do índice | ks_proj2018.sort_index() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Vamos dar uma olhada no conjunto de dados para ver se a mudança persistiu: | ks_proj2018.head() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Ihh, parece que não! | ### Sua vez!
### Ordene o conjunto de dados pelo número do índice de forma definitiva
### Use o parâmetro 'inplace=True'
ks_proj2018.sort_index(inplace=True)
ks_proj2018.head() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
--Resetar a indexação do conjunto de dados, iniciando a contagem de 0 | ks_proj2018.reset_index(drop=True) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Vamos dar uma olhada no conjunto de dados para ver se a mudança persistiu: | ks_proj2018.head() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Ihh, parece que não! | ### Sua vez!
### Resete a indexação do conjunto de dados de forma definitiva
### Use o parâmetro 'inplace==True'
ks_proj2018.reset_index(drop=True, inplace=True)
ks_proj2018.head() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Seleção, atribuição e operações -- Índices | ks_proj2018.index
### Sua vez!
### Mude o nome do índice de 'ID' para 'id'
### Use o atributo name do índice --> df.index.name
ks_proj2018.index.name = 'id'
ks_proj2018.head() | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Nomes das colunas | ks_proj2018.columns | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Formato do conjunto de dados | ks_proj2018.shape
len(ks_proj2018) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Selecionar células utilizando método da biblioteca numpy: df['coluna'] | ks_proj2018['name'].head()
### Sua vez!
### Selecione a coluna 'pledged'
ks_proj2018['pledged'].head()
ks_proj2018['name'][0]
### Sua vez!
### Selecione o 5o item da coluna 'pledged'
ks_proj2018['pledged'][5]
ks_proj2018[4:10]
### Sua vez!
### Selecione os itens 25 a 37
ks_proj2018[25:37] | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Operação de subtração: | ks_proj2018['gap'] = ks_proj2018['goal'] - ks_proj2018['usd pledged']
ks_proj2018['gap']
### Sua vez!
### Mostre a diferença entre o arrecadado real em USD ('usd_pldeged_real') e o objetivo real
### de arrecadação em USD ('usd_goal_real')
ks_proj2018['usd_goal_real'] - ks_proj2018['usd_pledged_real'] | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Atribuição | ks_proj2018['gap'][0] = 10 | /home/allex/.anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
"""Entry point for launching... | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Vish... o que esse warning significa? Utilizando métodos da biblioteca pandas | ks_proj2018.loc[:,'name'].head()
### Sua vez!
### Selecione a coluna 'pledged'
ks_proj2018.loc[:,'pledged'].head()
ks_proj2018.loc[:,['name', 'category']].head()
### Sua vez!
### Selecione as colunas com dados numéricos. Lembre-se da lista numeric_columns
ks_proj2018.loc[:, numeric_columns]
ks_proj2018.loc[14:29,'mai... | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Apply | def maximo(linha):
return linha.max()
ks_proj2018[numeric_columns].apply(maximo)
ks_proj2018[numeric_columns].apply(lambda coluna: coluna.max())
### Sua vez!
### Mostre a média das colunas numéricas utilizando apply()
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Padronizando a coluna 'name' | ### Sua vez!
### Ordene os projetos pelo nome em ordem alfabética. Lembre-se da função sort_values().
### A seguir, imprima os 5 primeiros itens do conjunto de dados.
ks_proj2018.loc[:,string_columns] = ks_proj2018[string_columns].apply(lambda coluna: coluna.str.replace('\"', ''))
ks_proj2018[string_columns].head()
... | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Dados Temporais (Time Series) -- Vamos verificar o tipo das colunas que representam datas | ks_proj2018['launched'].dtype
### Sua vez!
### Verifique se o tipo da coluna 'deadline'
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Passar as colunas de datas para o tipo correto | ks_proj2018['launched_parsed'] = pd.to_datetime(ks_proj2018['launched'])
ks_proj2018['launched_parsed'].head()
### Sua vez!
### Passe a coluna 'deadline' para o tipo datetime, atribua a uma nova coluna 'deadline_parsed
### e imprima os primeiros itens
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Vamos verificar o tipo da nova coluna | ks_proj2018['launched_parsed'].dtype | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Certo, agora 'launched_parsed' é do tipo datetime! | ### Sua vez!
### Verifique se a coluna 'deadline_parsed' está com o tipo data
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Pegar parte da data | launched_parsed_days = ks_proj2018['launched_parsed'].dt.day
launched_parsed_days.head()
### Sua vez!
### Pegue o dia da coluna 'deadline_parsed' e atribua a uma variável
### Imprima a variável
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Plotar datas para verificar se o parsing ocorreu corretamente | launched_parsed_days.hist(bins=31)
### Sua vez!
### Plote o histograma de frequência dos 31 dias do mês da coluna 'deadline_parsed'
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Dados categóricos -- Mudando dados nominais para categóricos | categorical_columns = ['main_category', 'currency', 'state', 'country']
ks_proj2018[categorical_columns] = ks_proj2018[categorical_columns].apply(lambda coluna: coluna.astype("category"))
ks_proj2018['main_category'].cat.categories
### Sua vez!
### Mostre as categorias da coluna 'state'
### Sua vez!
### Mostre as cat... | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
-- Re-ordenando a importância dos estados dos projetos | ks_proj2018['state'].cat.set_categories(['canceled', 'failed', 'suspended','live', 'successful']) | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Vamos dar uma olhada no conjunto de dados para ver se a mudança persistiu: | ### Sua vez!
### Mostre os 5 primeiros itens do conjunto de dados | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Ihh, parece que não! | ### Sua vez!
### Modifique a ordem da importância dos estados de maneira definitiva
### Use use inplace=True
| _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Agrupamento | ks_proj2018.groupby('state').size()
### Sua vez!
### Agrupe o conjunto de dados por moeda mostre o tamanho.
ks_proj2018.groupby('state').median()
### Sua vez!
### Agrupe o conjunto de dados por moeda mostre a mediana.
ks_proj2018.groupby('state').count().T
### Sua vez!
### Agrupe o conjunto de dados por moeda mostr... | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Gráficos | ks_proj2018['goal'].plot()
### Sua vez!
### Plote apenas os exemplos com 'goal' menor que 1000
ks_proj2018.loc[ks_proj2018['usd pledged']<100000, 'usd pledged'].plot.hist(bins=10)
### Sua vez!
### Plote apenas os exemplos com 'usd pledged' menor que 40000
ks_proj2018[ks_proj2018['goal'] < 100000].boxplot('goal')
#... | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Salvar dados | ks_proj2018.to_csv('ks-projects-201801-v-processada.csv') | _____no_output_____ | MIT | modulo1/pandas.ipynb | hiramaral/IA |
Unstructured Profilers **Data profiling** - *is the process of examining a dataset and collecting statistical or informational summaries about said dataset.*The Profiler class inside the DataProfiler is designed to generate *data profiles* via the Profiler class, which ingests either a Data class or a Pandas DataFrame... | import os
import sys
import json
sys.path.insert(0, '..')
import dataprofiler as dp
data_path = "../dataprofiler/tests/data"
data = dp.Data(os.path.join(data_path, "txt/discussion_reddit.txt"))
profile = dp.Profiler(data)
report = profile.report(report_options={"output_format": "pretty"})
print(json.dumps(report, in... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
Profiler Type It should be noted, in addition to reading the input data from text files, DataProfiler allows the input data as a pandas dataframe, a pandas series, a list, and Data objects (when an unstructured format is selected) if the Profiler is explicitly chosen as unstructured. | # run data profiler and get the report
import pandas as pd
data = dp.Data(os.path.join(data_path, "csv/SchoolDataSmall.csv"), options={"data_format": "records"})
profile = dp.Profiler(data, profiler_type='unstructured')
report = profile.report(report_options={"output_format":"pretty"})
print(json.dumps(report, indent... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
Profiler options The DataProfiler has the ability to turn on and off components as needed. This is accomplished via the `ProfilerOptions` class.For example, if a user doesn't require vocab count information they may desire to turn off the word count functionality.Below, let's remove the vocab count and set the stop wo... | data = dp.Data(os.path.join(data_path, "txt/discussion_reddit.txt"))
profile_options = dp.ProfilerOptions()
# Setting multiple options via set
profile_options.set({ "*.vocab.is_enabled": False, "*.is_case_sensitive": True })
# Set options via directly setting them
profile_options.unstructured_options.text.stop_words... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
Updating Profiles Beyond just profiling, one of the unique aspects of the DataProfiler is the ability to update the profiles. To update appropriately, the schema (columns / keys) must match appropriately. | # Load and profile a CSV file
data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt"))
profile = dp.Profiler(data)
# Update the profile with new data:
new_data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt"))
profile.update_profile(new_data)
# Take a peek at the data
print(data.data)
print(new_data.dat... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
Merging Profiles Merging profiles are an alternative method for updating profiles. Particularly, multiple profiles can be generated seperately, then added together with a simple `+` command: `profile3 = profile1 + profile2` | # Load a CSV file with a schema
data1 = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt"))
profile1 = dp.Profiler(data1)
# Load another CSV file with the same schema
data2 = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt"))
profile2 = dp.Profiler(data2)
# Merge the profiles
profile3 = profile1 + profile2
... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
As you can see, the `update_profile` function and the `+` operator function similarly. The reason the `+` operator is important is that it's possible to *save and load profiles*, which we cover next. Saving and Loading a Profile Not only can the Profiler create and update profiles, it's also possible to save, load the... | # Load data
data = dp.Data(os.path.join(data_path, "txt/sentence-3x.txt"))
# Generate a profile
profile = dp.Profiler(data)
# Save a profile to disk for later (saves as pickle file)
profile.save(filepath="my_profile.pkl")
# Load a profile from disk
loaded_profile = dp.Profiler.load("my_profile.pkl")
# Report the co... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
With the ability to save and load profiles, profiles can be generated via multiple machines then merged. Further, profiles can be stored and later used in applications such as change point detection, synthetic data generation, and more. | # Load a multiple files via the Data class
filenames = ["txt/sentence-3x.txt",
"txt/sentence.txt"]
data_objects = []
for filename in filenames:
data_objects.append(dp.Data(os.path.join(data_path, filename)))
print(data_objects)
# Generate and save profiles
for i in range(len(data_objects)):
profil... | _____no_output_____ | Apache-2.0 | examples/unstructured_profilers.ipynb | scottiegarcia/DataProfiler |
Compare Country Trajectories - Total Cases> Comparing how countries trajectories of total cases are similar with Italy, South Korea and Japan- comments: true- author: Pratap Vardhan- categories: [growth, compare, interactive]- image: images/covid-compare-country-trajectories.png- permalink: /compare-country-trajectori... | #hide
import pandas as pd
import altair as alt
from IPython.display import HTML
#hide
url = ('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/'
'csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
df = pd.read_csv(url)
# rename countries
df['Country/Region'] =... | _____no_output_____ | MIT | covid19/covid19-compare-country-trajectories.ipynb | aladin002dz/notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.