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 |
|---|---|---|---|---|---|
tf.data.Dataset: parse files and prepare training and validation datasetsPlease read the [best practices for building](https://www.tensorflow.org/guide/performance/datasets) input pipelines with tf.data.Dataset | def read_label(tf_bytestring):
label = tf.io.decode_raw(tf_bytestring, tf.uint8)
label = tf.reshape(label, [])
label = tf.one_hot(label, 10)
return label
def read_image(tf_bytestring):
image = tf.io.decode_raw(tf_bytestring, tf.uint8)
image = tf.cast(image, tf.float32)/256.0
image = tf.re... | _____no_output_____ | Apache-2.0 | courses/fast-and-lean-data-science/05K_MNIST_TF20Keras_Tensorboard_solution.ipynb | Glairly/introduction_to_tensorflow |
Let's have a look at the data | N = 24
(training_digits, training_labels,
validation_digits, validation_labels) = dataset_to_numpy_util(training_dataset, validation_dataset, N)
display_digits(training_digits, training_labels, training_labels, "training digits and their labels", N)
display_digits(validation_digits[:N], validation_labels[:N], validati... | _____no_output_____ | Apache-2.0 | courses/fast-and-lean-data-science/05K_MNIST_TF20Keras_Tensorboard_solution.ipynb | Glairly/introduction_to_tensorflow |
Keras model: 3 convolutional layers, 2 dense layers | # This model trains to 99.4%— sometimes 99.5%— accuracy in 10 epochs (with a batch size of 64)
def make_model():
model = tf.keras.Sequential(
[
tf.keras.layers.Reshape(input_shape=(28*28,), target_shape=(28, 28, 1)),
tf.keras.layers.Conv2D(filters=6, kernel_size=3, padding='same', use_b... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
reshape (Reshape) (None, 28, 28, 1) 0
____________________________________... | Apache-2.0 | courses/fast-and-lean-data-science/05K_MNIST_TF20Keras_Tensorboard_solution.ipynb | Glairly/introduction_to_tensorflow |
Train and validate the model | EPOCHS = 10
steps_per_epoch = 60000//global_batch_size # 60,000 items in this dataset
print("Step (batches) per epoch: ", steps_per_epoch)
history = model.fit(training_dataset, steps_per_epoch=steps_per_epoch, epochs=EPOCHS,
validation_data=validation_dataset, validation_steps=1, callbac... | Step (batches) per epoch: 117
Epoch 00001: LearningRateScheduler reducing learning rate to 0.00808.
Epoch 1/10
2/117 [..............................] - ETA: 2:33 - accuracy: 0.3652 - loss: 2.0532WARNING:tensorflow:Method (on_train_batch_end) is slow compared to the batch update (1.480141). Check your callbacks.
| Apache-2.0 | courses/fast-and-lean-data-science/05K_MNIST_TF20Keras_Tensorboard_solution.ipynb | Glairly/introduction_to_tensorflow |
Visualize predictions | # recognize digits from local fonts
probabilities = model.predict(font_digits, steps=1)
predicted_labels = np.argmax(probabilities, axis=1)
display_digits(font_digits, predicted_labels, font_labels, "predictions from local fonts (bad predictions in red)", N)
# recognize validation digits
probabilities = model.predict(... | _____no_output_____ | Apache-2.0 | courses/fast-and-lean-data-science/05K_MNIST_TF20Keras_Tensorboard_solution.ipynb | Glairly/introduction_to_tensorflow |
class stack:
def __init__ (self):
self.__datos=[]
def is_empty(self):
return len(self.__datos)==0
def get_top(self):
return self.__datos[-1]
def pop(self):
return self.__datos.pop()
def push(self,valor):
self.__datos.append(valor)
def get_length(self):
return len(self.__datos)
... | --------------------
--------------------
None
Esta balanceado
| MIT | pilas.ipynb | pandemicbat801/daa_2021_1 | |
wcm Nikola Tagsconvert ipynb/py doc imports as tags for nikola blog .meta files.When user searches for notebook to blog with bbknikola python script also get the tags for the .meta file. Open up the .py file and convert this:blogpost.pyimport requestsimport osimport reInto:blogpost.metablogpostblogpost2015/02/31 00:00:... | import modulefinder
import runpy
import os
from walkdir import filtered_walk, dir_paths, all_paths, file_paths
mwcm = modulefinder.ModuleFinder()
mwcm.any_missing()
mwcm.run_script('/home/wcmckee/github/niketa/rgdsnatch.py')
mwcm.path
mwcm.scan_code
from splinter import Browser
browser = Browser()
browser.visit('http:... | _____no_output_____ | MIT | wcmnikolatags.ipynb | wcmckee/niketa |
Use Keras to build 3 networks, each with at least 10 hidden layers such that:* The first model has fewer than 10 nodes per layer.* The second model has between 10-50 nodes per layer.* The third model has between 50-100 nodes per layer.Then, answer these questions: * Did any of these models achieve better than 20% accu... | # For drawing the MNIST digits as well as plots to help us evaluate performance we
# will make extensive use of matplotlib
from matplotlib import pyplot as plt
# All of the Keras datasets are in keras.datasets
from tensorflow.keras.datasets import mnist
#Allows us to flatten 2d given data
from tensorflow.keras.utils ... | 10000/10000 [==============================] - 2s 164us/sample - loss: 2.3010 - accuracy: 0.1135
| Unlicense | 01-intro-to-deep-learning/Task2-checkpoint.ipynb | AaronJH3/intro-to-deep-learning |
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_valid, y_valid) = mnist.load_data()
x_train.shape
x_train[30000]
%matplotlib inline
import matplotlib.pyplot as plt
image = x_train[30000]
plt.imshow(image, cmap='gray')
x_train = x_train.reshape(60000, 784)
x_valid = x_valid.reshape(10000, 784)
# Norm... | _____no_output_____ | MIT | nvidia_keras_mnist.ipynb | haricash/cnn-resources | |
Categorically encoding values | import tensorflow.keras as keras
num_categories = 10
y_train = keras.utils.to_categorical(y_train, num_categories)
y_valid = keras.utils.to_categorical(y_valid, num_categories)
from tensorflow.keras.models import Sequential
# This instantiates the model type
model = Sequential()
# This adds layers to the model
from ten... | _____no_output_____ | MIT | nvidia_keras_mnist.ipynb | haricash/cnn-resources |
HuggingFace Pipeline | from transformers import pipeline
classifier = pipeline('sentiment-analysis')
classifier('We are very happy to show you the 🤗 Transformers library.')
results = classifier(["We are very happy to show you the 🤗 Transformers library.","We hope you don't hate it."])
for result in results:
print(f"label: {result['labe... | label: 5 stars, with score: 0.7725
label: 5 stars, with score: 0.2365
| MIT | introduction.ipynb | nattiya/Transformers |
Pre-trained Model | from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokeni... | label: 5 stars, with score: 0.7725
label: 5 stars, with score: 0.2365
| MIT | introduction.ipynb | nattiya/Transformers |
Tokenizer | inputs = tokenizer("We are very happy to show you the 🤗 Transformers library.")
print(inputs)
pt_batch = tokenizer(
["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
padding=True,
truncation=True,
return_tensors="pt"
)
for key, value in pt_batch.items():
... | input_ids: [[101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], [101, 2057, 3246, 2017, 2123, 1005, 1056, 5223, 2009, 1012, 102, 0, 0, 0]]
attention_mask: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]
| MIT | introduction.ipynb | nattiya/Transformers |
Model Output | pt_outputs = pt_model(**pt_batch)
print(pt_outputs)
import torch.nn.functional as F
pt_predictions = F.softmax(pt_outputs[0], dim=-1)
print(pt_predictions)
import torch
pt_outputs = pt_model(**pt_batch, labels = torch.tensor([1, 0]))
print(pt_outputs)
pt_outputs = pt_model(**pt_batch, output_hidden_states=True, output_... | (tensor([[[[6.9022e-02, 3.8968e-02, 2.4874e-02, ..., 6.2119e-02,
9.8898e-02, 2.0635e-01],
[6.6224e-02, 9.9285e-02, 1.4523e-02, ..., 1.1821e-01,
2.1042e-02, 2.1536e-02],
[2.4178e-01, 1.3899e-01, 2.0652e-02, ..., 2.8374e-02,
6.0764e-02, 1.6392e-01],
...,
... | MIT | introduction.ipynb | nattiya/Transformers |
Save/load Model | tokenizer.save_pretrained(".")
pt_model.save_pretrained(".")
tokenizer = AutoTokenizer.from_pretrained(".")
pt_model = AutoModel.from_pretrained(".") | _____no_output_____ | MIT | introduction.ipynb | nattiya/Transformers |
Customizing Model To change the hidden size, we can't use a pretrained model anymore and have to train from scratch by instantiating the model from a custom configuration. | from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification
config = DistilBertConfig(n_heads=8, dim=512, hidden_dim=4*512)
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertForSequenceClassification(config) | _____no_output_____ | MIT | introduction.ipynb | nattiya/Transformers |
To change only the head of the model (for instance, the number of labels), we can still use a pretrained model for the body. For instance, let's define a classifier for 10 different labels using a pretrained body. | from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification
model_name = "distilbert-base-uncased"
model = DistilBertForSequenceClassification.from_pretrained(model_name, num_labels=10)
tokenizer = DistilBertTokenizer.from_pretrained(model_name) | _____no_output_____ | MIT | introduction.ipynb | nattiya/Transformers |
Classificação de Revisões do IMDb com Keras | from keras.datasets import imdb
from keras import preprocessing
import numpy as np
import pandas as pd | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Leitura dos dados | df = pd.read_csv('movie_data.csv.gz', encoding='utf-8')
df.head()
samples = df["review"].values
dimensionality = 1000 #dimensão do vetor quer vai representar a palavra | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Constrói o índice de palavras | from keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(num_words=1000)
tokenizer.fit_on_texts(samples) #constroi o índice de palavras
word_index = tokenizer.word_index
print('Foram encontrados %s tokens.' % len(word_index)) | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Transforma strings em lista de índices inteiros | sequences = tokenizer.texts_to_sequences(samples) #transforma o texto em sequencias de índices
sequences[0][:10] #os 10 primeiros índices da frase 0 | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Pre-processa sequencias para padronizar o tamanho | maxlen = 200
sequences_padding = preprocessing.sequence.pad_sequences(sequences, maxlen=maxlen)
len(sequences[10])
len(sequences_padding[10]) | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Usando a camada Embedding e classificando os dados do IMDB SimpleRNN Construindo o modelo | from keras.models import Sequential
from keras.layers import SimpleRNN, Embedding, Dense, Input
original_dim = 10000 #numero de palavra para considerar como feature
new_dim = 32
model = Sequential()
model.add(Embedding(input_dim=dimensionality,input_length=maxlen,output_dim=new_dim))
model.add(SimpleRNN(new_dim, input_... | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Compilando o modelo | model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Dividindo os dados em treino e teste | import random
size = len(sequences_padding)
indices = np.arange(size)
random.shuffle(indices)
indices
x = sequences_padding[indices]
y = df.sentiment.values[indices]
x
y
treino = 0.8
x_treino = x[:int(treino*size),:]
y_treino = y[:int(treino*size)]
x_teste = x[int(treino*size):]
y_teste = y[int(treino*size):]
y_teste... | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Treinando o modelo | history = model.fit(x_treino, y_treino, epochs=10, batch_size=256, validation_split=0.2) | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Avaliando o modelo | evaluation = model.evaluate(x_teste,y_teste) | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Visualizando resultados | import matplotlib.pyplot as plt
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['treino', 'validação'], loc='upper left')
plt.show()
evaluation | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Modelo LSTM | from keras.layers import LSTM, Dense, Masking, Embedding
model = Sequential()
# Embedding layer
model.add(Embedding(input_dim=dimensionality,input_length=maxlen,output_dim=new_dim))
# Recurrent layer
model.add(LSTM(new_dim, return_sequences=False, dropout=0.1, recurrent_dropout=0.1))
# Fully connected layer
model.a... | _____no_output_____ | MIT | 2019/09-Redes_Neurais_e_Aprendizado_Profundo/SentimentAnalysisRNN.ipynb | InsightLab/imersao-ciencia-de-dados-2019 |
Account Information [OANDA REST-V20 API Wrapper Doc on Account](http://oanda-api-v20.readthedocs.io/en/latest/endpoints/accounts.html)[OANDA API Getting Started](http://developer.oanda.com/rest-live-v20/introduction/)[OANDA API Account](http://developer.oanda.com/rest-live-v20/account-ep/) Account Details | import pandas as pd
import oandapyV20
import oandapyV20.endpoints.accounts as accounts
import configparser
config = configparser.ConfigParser()
config.read('../config/config_v20.ini')
accountID = config['oanda']['account_id']
access_token = config['oanda']['api_key']
client = oandapyV20.API(access_token=access_token)
r... | _____no_output_____ | MIT | Oanda v20 REST-oandapyV20/03.00 Account Information.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda |
Account List | r = accounts.AccountList()
client.request(r)
print(r.response) | {'accounts': [{'tags': [], 'id': '101-003-5120068-001'}]}
| MIT | Oanda v20 REST-oandapyV20/03.00 Account Information.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda |
Account Summary | r = accounts.AccountSummary(accountID)
client.request(r)
print(r.response)
pd.Series(r.response['account']) | _____no_output_____ | MIT | Oanda v20 REST-oandapyV20/03.00 Account Information.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda |
Account Instruments | r = accounts.AccountInstruments(accountID=accountID, params = "EUR_USD")
client.request(r)
pd.DataFrame(r.response['instruments']) | _____no_output_____ | MIT | Oanda v20 REST-oandapyV20/03.00 Account Information.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda |
**This notebook is an exercise in the [Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/pipelines).**--- In this exercise, you will use **pipelines** to improve the efficiency of your mach... | # Set up code checking
import os
if not os.path.exists("../input/train.csv"):
os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv")
os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv")
from learntools.core import binder
binder.bind(globals())
from learntools.m... | Setup Complete
| MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
You will work with data from the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course). Run the next code cell without changes to load the training and validation sets in `X_train`, `X_valid`, `y_train`, and `y... | import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
X_full = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', index_col='Id')
# Remove rows with missing target, separate target from predictors
X_full.dropna(axis=0, subset=['SalePrice... | _____no_output_____ | MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
The next code cell uses code from the tutorial to preprocess the data and train a model. Run this code without changes. | from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
# Preprocessing for numerical data
numerical_tr... | MAE: 17861.780102739725
| MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
The code yields a value around 17862 for the mean absolute error (MAE). In the next step, you will amend the code to do better. Step 1: Improve the performance Part ANow, it's your turn! In the code cell below, define your own preprocessing steps and random forest model. Fill in values for the following variables:- ... | # Preprocessing for numerical data
numerical_transformer = SimpleImputer(strategy='constant') # Your code here
# Preprocessing for categorical data
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
]) # Your code ... | _____no_output_____ | MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
Part BRun the code cell below without changes.To pass this step, you need to have defined a pipeline in **Part A** that achieves lower MAE than the code above. You're encouraged to take your time here and try out many different approaches, to see how low you can get the MAE! (_If your code does not pass, please amen... | # Bundle preprocessing and modeling code in a pipeline
my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
('model', model)
])
# Preprocessing of training data, fit model
my_pipeline.fit(X_train, y_train)
# Preprocessing of validation data, get pre... | _____no_output_____ | MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
Step 2: Generate test predictionsNow, you'll use your trained model to generate predictions with the test data. | # Preprocessing of test data, fit model
preds_test = my_pipeline.predict(X_test) # Your code here
# Check your answer
step_2.check()
# Lines below will give you a hint or solution code
#step_2.hint()
#step_2.solution() | _____no_output_____ | MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
Run the next code cell without changes to save your results to a CSV file that can be submitted directly to the competition. | # Save test predictions to file
output = pd.DataFrame({'Id': X_test.index,
'SalePrice': preds_test})
output.to_csv('submission.csv', index=False) | _____no_output_____ | MIT | exercise-pipelines.ipynb | mdhasan8/Machine-Learning-in-Python |
Import the registers from TICs Pro generated \*.txt file: | import csv
_lmk04832Config = []
with open("./clk_configs/LMK04832_clk1_clk2_16MHz.txt", newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
_lmk04832Config.append(int(row[1],16))
xrfclk._clear_int()
xrfclk._write_Lmk04832Regs_regs(_lmk04832Config) | _____no_output_____ | BSD-3-Clause | ZCU111/packages/xrfclk/pkg/test/test_chips.ipynb | yunqu/ZCU111-PYNQ |
Test to run through all possible configurations for Status_LD2 on LMK04832: | xrfclk._clear_int()
from time import sleep
for TYPE in [TYPE for TYPE in range(3,7) if TYPE != 5]:
for MUX in [MUX for MUX in range(0, 19) if MUX != 6]:
Status_LD2 = (MUX << 3) + TYPE
Status_LD2_REG = hex((0x16E << 8) + Status_LD2)
_lmk04832Config[116] = int(Status_LD2_REG, 16)
xrfcl... | _____no_output_____ | BSD-3-Clause | ZCU111/packages/xrfclk/pkg/test/test_chips.ipynb | yunqu/ZCU111-PYNQ |
GloVeUsing the large abstract data encoded with the balanced title tokens. Imports and SetupCommon imports and standardized code for importing the relevant data, models, etc., in order to minimize copy-paste/typo errors. Imports and colab setup | %%capture import_capture --no-stder
# Jupyter magic methods
# For auto-reloading when external modules are changed
%load_ext autoreload
%autoreload 2
# For showing plots inline
%matplotlib inline
# pip installs needed in Colab for arxiv_vixra_models
!pip install wandb
!pip install pytorch-lightning
!pip install unidec... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
`wandb` log in: | wandb.login() | [34m[1mwandb[0m: Currently logged in as: [33mgarrett361[0m (use `wandb login --relogin` to force relogin)
| Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Google drive access | from google.colab import drive
drive.mount("/content/drive", force_remount=True)
# Enter the relevant foldername
FOLDERNAME = '/content/drive/My Drive/ML/arxiv_vixra'
assert FOLDERNAME is not None, "[!] Enter the foldername."
# For importing modules stored in FOLDERNAME or a subdirectory thereof:
import sys
sys.path.ap... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Copy data to cwd for speed. | SUBDIR = '/data/data_splits/'
title_tokens_file_name = 'balanced_title_normalized_vocab.feather'
!cp '{FOLDERNAME + SUBDIR + title_tokens_file_name}' .
title_tokens_df = pd.read_feather(title_tokens_file_name)
with open(FOLDERNAME + SUBDIR + 'heatmap_words.txt', 'r') as f:
heatmap_words = f.read().split()
with open... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Computing specs. Save the number of processors to pass as `num_workers` into the Datamodule and cuda availability for other flags. | # GPU. Save availability to IS_CUDA_AVAILABLE.
gpu_info= !nvidia-smi
gpu_info = '\n'.join(gpu_info)
if gpu_info.find('failed') >= 0:
print('Not connected to a GPU')
IS_CUDA_AVAILABLE = False
else:
print(f"GPU\n{50 * '-'}\n", gpu_info, '\n')
IS_CUDA_AVAILABLE = True
# Memory.
from psutil import virtual_memory, ... | large_abstract_glove
| Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Create the mapping from words to indices and vice-versa, recalling that 0 and 1 are reserved for padding and ``, respectively. | title_word_to_idx = avm.word_to_idx_dict_from_df(title_tokens_df)
title_idx_to_word = avm.idx_to_word_dict_from_df(title_tokens_df) | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Load in the relevant co-occurence matrix: | co_matrix = torch.load(FOLDERNAME + SUBDIR + "large_abstract_with_title_mapping_co_matrix_context_5.pt") | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Model TrainingSetting hyperparameters and performing a `wandb`-synced training loop. | cyclic_lr_scheduler_args = {'base_lr': 5e-5,
'max_lr': 5e-2,
'step_size_up': 128,
'cycle_momentum': False}
plateau_lr_scheduler_args = {'verbose': True,
'patience': 2,
'factor'... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Training: | trainer = Trainer(logger=WandbLogger(),
gpus=-1 if IS_CUDA_AVAILABLE else 0,
log_every_n_steps=1,
precision=16,
profiler='simple',
callbacks=[avm.WandbVisualEmbeddingCallback(model=model,
... | Using 16bit native Automatic Mixed Precision (AMP)
GPU available: True, used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
| Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Loading Best Models | wandb_api = wandb.Api()
notebook_runs = wandb_api.runs(ENTITY + "/" + PROJECT)
run_cats = ('best_loss', 'name', 'wandb_path', 'timestamp')
runs_sort_cat = 'best_loss'
run_state_dict_file_name = 'glove.pt'
run_init_params_file_name = 'model_init_params.pt'
notebook_runs_dict = {key: [] for key in run_cats}
for run in ... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Save the state dicts locally and rebuild the corresponding models. | # wandb stores None values in the config dict as a string literal. Need to
# fix these entries, annoyingly.
for key, val in best_model_df.config.items():
if val == 'None':
best_model_df.config[key] = None
# Write to disk
glove_file_name = f"glove_dim_{best_model_df.config['embedding_dim']}.pt"
wandb.restore... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
Visualize | heatmap = avm.embedding_cosine_heatmap(model=best_model,
words=heatmap_words,
word_to_idx=title_word_to_idx)
pca = avm.pca_3d_embedding_plotter_topk(model=best_model,
words=pca_words,
... | _____no_output_____ | Apache-2.0 | glove/large_abstract_glove.ipynb | garrett361/arxiv-vixra-ml |
12 - Doubly Robust Estimation Don't Put All your Eggs in One BasketWe've learned how to use linear regression and propensity score weighting to estimate \\(E[Y|Y=1] - E[Y|Y=0] | X\\). But which one should we use and when? When in doubt, just use both! Doubly Robust Estimation is a way of combining propensity score and... | import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
from matplotlib import style
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
style.use("fivethirtyeight")
pd.set_option("display.max_columns", 6)
data = pd.read_csv("./data/learning_mindset.csv")
da... | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
Although the study was randomised, it doesn't seem to be the case that this data is free from confounding. One possible reason for this is that the treatment variable is measured by the student's receipt of the seminar. So, although the opportunity to participate was random, participation is not. We are dealing with a ... | data.groupby("success_expect")["intervention"].mean() | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
As we know by now, we could adjust for this using a linear regression or by estimating a propensity score model with a logistic regression. Before we do that, however, we need to convert the categorical variables to dummies. | categ = ["ethnicity", "gender", "school_urbanicity"]
cont = ["school_mindset", "school_achievement", "school_ethnic_minority", "school_poverty", "school_size"]
data_with_categ = pd.concat([
data.drop(columns=categ), # dataset without the categorical features
pd.get_dummies(data[categ], columns=categ, drop_firs... | (10391, 32)
| MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
We are now ready to understand how doubly robust estimation works. Doubly Robust EstimationInstead of deriving the estimator, I'll first show it to you and only then tell why it is awesome.$\hat{ATE} = \frac{1}{N}\sum \bigg( \dfrac{T_i(Y_i - \hat{\mu_1}(X_i))}{\hat{P}(X_i)} + ... | from sklearn.linear_model import LogisticRegression, LinearRegression
def doubly_robust(df, X, T, Y):
ps = LogisticRegression(C=1e6).fit(df[X], df[T]).predict_proba(df[X])[:, 1]
mu0 = LinearRegression().fit(df.query(f"{T}==0")[X], df.query(f"{T}==0")[Y]).predict(df[X])
mu1 = LinearRegression().fit(df.query... | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
Doubly robust estimator is saying that we should expect individuals who attended the mindset seminar to be 0.388 standard deviations above their untreated fellows, in terms of achievements. Once again, we can use bootstrap to construct confidence intervals. | from joblib import Parallel, delayed # for parallel processing
np.random.seed(88)
# run 1000 bootstrap samples
bootstrap_sample = 1000
ates = Parallel(n_jobs=4)(delayed(doubly_robust)(data_with_categ.sample(frac=1, replace=True), X, T, Y)
for _ in range(bootstrap_sample))
ates = np.array(ates... | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
Now that we got a taste of the doubly robust estimator, let's examine why it is so great. First, it is called doubly robust because it only requires one of the models, \\(\hat{P}(x)\\) or \\(\hat{\mu}(x)\\), to be correctly specified. To see this, take the first part that estimates \\(E[Y_1]\\) and take a good look at ... | from sklearn.linear_model import LogisticRegression, LinearRegression
def doubly_robust_wrong_ps(df, X, T, Y):
# wrong PS model
np.random.seed(654)
ps = np.random.uniform(0.1, 0.9, df.shape[0])
mu0 = LinearRegression().fit(df.query(f"{T}==0")[X], df.query(f"{T}==0")[Y]).predict(df[X])
mu1 = LinearR... | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
If we use bootstrap, we can see that the variance is slightly higher than when the propensity score was estimated with a logistic regression. | np.random.seed(88)
parallel_fn = delayed(doubly_robust_wrong_ps)
wrong_ps = Parallel(n_jobs=4)(parallel_fn(data_with_categ.sample(frac=1, replace=True), X, T, Y)
for _ in range(bootstrap_sample))
wrong_ps = np.array(wrong_ps)
print(f"ATE 95% CI:", (np.percentile(ates, 2.5), np.percentile(a... | ATE 95% CI: (0.3536507259630512, 0.4197834129772669)
| MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
This covers the case that the propensity model is wrong but the outcome model is correct. What about the other situation? Let's again take a good look at the first part of the estimator, but let's rearrange some terms$\hat{E}[Y_1] = \frac{1}{N}\sum \bigg( \dfrac{T_i(Y_i - \hat{\mu_1}(X_i))}{\hat{P}(X_i)} + \hat{\mu_1}(... | from sklearn.linear_model import LogisticRegression, LinearRegression
def doubly_robust_wrong_model(df, X, T, Y):
np.random.seed(654)
ps = LogisticRegression(C=1e6).fit(df[X], df[T]).predict_proba(df[X])[:, 1]
# wrong mu(x) model
mu0 = np.random.normal(0, 1, df.shape[0])
mu1 = np.random.normal... | _____no_output_____ | MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
One again, we can use bootstrap and see that the variance is just slightly higher. | np.random.seed(88)
parallel_fn = delayed(doubly_robust_wrong_model)
wrong_mux = Parallel(n_jobs=4)(parallel_fn(data_with_categ.sample(frac=1, replace=True), X, T, Y)
for _ in range(bootstrap_sample))
wrong_mux = np.array(wrong_mux)
print(f"ATE 95% CI:", (np.percentile(ates, 2.5), np.perce... | ATE 95% CI: (0.3536507259630512, 0.4197834129772669)
| MIT | causal-inference-for-the-brave-and-true/12-Doubly-Robust-Estimation.ipynb | qiringji/python-causality-handbook |
The `object` Class As we discussed earlier, `object` is a built-in Python **class**, and every class in Python inherits from that class. | type(object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
As you can see the type of `object` is `type` - this means it is a class, just like `int`, `str`, `dict` are also classes (types): | type(int), type(str), type(dict) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
When we create a class that does not explicitly inherit from anything, we are implicitly inheriting from `object`: | class Person:
pass
issubclass(Person, object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
And it's not just our custom classes that inherit from `object`, every type in Python does too: | issubclass(int, object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
Even modules, which are objects and instances of `module` are subclasses of `object`: | import math
type(math) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
So the `math` module is an instance of the `module` type: | ty = type(math)
type(ty)
issubclass(ty, object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
If you're wondering where the `module` type (class) lives, you can get a reference to it the way I did here, or you can look for it in the `types` module where you can it and the other built-in types. | import types
dir(types) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
For example, if we define a function: | def my_func():
pass
type(my_func)
types.FunctionType is type(my_func) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
And `FunctionType` inherits from `object`: | issubclass(types.FunctionType, object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
and of course, instances of that type are therefore also instances of `object`: | isinstance(my_func, object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
as well as being instances of `FunctionType`: | isinstance(my_func, types.FunctionType) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
The `object` class implements a certain amount of base functionality.We can see some of them here: | dir(object) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
So as you can see `object` implements methods such as `__eq__`, `__hash__`, `__repr__` and `__str__`. Let's investigate some of those, starting with `__repr__` and `__str__`: | o1 = object()
str(o1)
repr(o1) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
You probably recognize that output! If we define our own class that does not **override** the `__repr__` or `__str__` methods, when we call those methods on instances of that class it will actually call the implementation in the `object` class: | class Person:
pass
p = Person()
str(p) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
So this actually called the `__str__` method in the `object` class (but it is an instance method, so it applies to our specific instance `p`). Similarly, the `__eq__` method in the object class is implemented, and uses the object **id** to determine equality: | o1 = object()
o2 = object()
id(o1), id(o2)
o1 is o2, o1 == o2, o1 is o1, o1 == o1 | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
So we can use the `==` operator with our custom classes even if we did not implement `__eq__` explicitly - because it inherits it from the `object` class. And so we have the same functionality - our custom objects will compare equal only if they are the same object (id): | p1 = Person()
p2 = Person()
p1 is p2, p1 == p2, p1 is p1, p1 == p1 | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
We can actually see what specific method is being called by looking at the id of the method in our object, and in the object class: | id(Person.__eq__)
id(object.__eq__) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
See? Same method! In the same way, we can write classes that do not have `__init__` or `__new__` methods - because they just inherit it from `object`: | id(Person.__init__), id(object.__init__) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
But of course, if we override those methods, then the `object` methods will not be used: | class Person:
def __init__(self):
pass
id(Person.__init__), id(object.__init__) | _____no_output_____ | Apache-2.0 | dd_1/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb | rebekka-halal/bg |
Route automation When I'm planning a trip, I usually like knowing the distance between all the places, I will be visiting in order to plan a route and just get a general idea of how much it will cost, etc.Picking out the distance between all the locations gets annoying fast, so I wrote this script.Works with almost a... | import requests,bs4,re,pandas as pd
def google_search(start,destination):
"""
This function sends a search request to google and takes extracts out the answer from the quick answer box,
code is written such that it works for distances between locations with the format google uses,
as of when the co... | _____no_output_____ | MIT | distance_spread.ipynb | FardinAhsan146/Spreadsheet-of-distances-google-maps |
Training and Evaluating an NER model with spaCy on the CoNLL datasetIn this notebook, we will take a look at using spaCy commandline to train and evaluate a NER model. We will also compare it with the pretrained NER model in spacy. Note: we will create multiple folders during this experiment:spacyNER_data Step 1: Co... | #Read the CONLL data from conll2003 folder, and store the formatted data into a folder spacyNER_data
!mkdir spacyNER_data
#the above two lines create folders if they don't exist. If they do, the output shows a message that it
#already exists and cannot be created again
!python3 -m spacy convert "Data/conll2003/en/train... | mkdir: cannot create directory ‘spacyNER_data’: File exists
[38;5;2m✔ Generated output file (1 documents)[0m
spacyNER_data/train.json
[38;5;2m✔ Generated output file (1 documents)[0m
spacyNER_data/test.json
[38;5;2m✔ Generated output file (1 documents)[0m
spacyNER_data/valid.json
| MIT | Ch5/04_NER_using_spaCy - CoNLL.ipynb | quicksilverTrx/practical-nlp |
For example, the data before and after running spacy's convert program looks as follows. | !echo "BEFORE : (Data/conll2003/en/train.txt)"
!head "Data/conll2003/en/train.txt" -n 11 | tail -n 9
!echo "\nAFTER : (Data/conll2003/en/train.json)"
!head "spacyNER_data/train.json" -n 64 | tail -n 49 | BEFORE : (Data/conll2003/en/train.txt)
EU NNP B-NP B-ORG
rejects VBZ B-VP O
German JJ B-NP B-MISC
call NN I-NP O
to TO B-VP O
boycott VB I-VP O
British JJ B-NP B-MISC
lamb NN I-NP O
. . O O
AFTER : (Data/conll2003/en/train.json)
{
"tokens":[
{
"orth":"EU",
... | MIT | Ch5/04_NER_using_spaCy - CoNLL.ipynb | quicksilverTrx/practical-nlp |
Training the NER model with Spacy (CLI)All the commandline options can be seen at: https://spacy.io/api/clitrainWe are training using the train program in spacy, for English (en), and the results are stored in a folder called "model" (created while training). Our training file is in "spacyNER_data/train.json" and the ... | !python3 -m spacy train en model spacyNER_data/train.json spacyNER_data/valid.json -G -p tagger,ner | Training pipeline: ['tagger', 'ner']
Starting with blank model 'en'
Counting training words (limit=0)
Itn Dep Loss NER Loss UAS NER P NER R NER F Tag % Token % CPU WPS GPU WPS
--- ---------- ---------- ------- ------- ------- ------- ------- ------- ------- -------
0 0.000 ... | MIT | Ch5/04_NER_using_spaCy - CoNLL.ipynb | quicksilverTrx/practical-nlp |
Notice how the performance improves with each iteration! Evaluating the model with test data set (`spacyNER_data/test.json`) On Trained model (`model/model-best`) | #create a folder to store the output and visualizations.
!mkdir result
!python3 -m spacy evaluate model/model-best spacyNER_data/test.json -dp result
# !python -m spacy evaluate model/model-final data/test.txt.json -dp result | [1m
================================== Results ==================================[0m
Time 3.53 s
Words 46666
Words/s 13234
TOK 100.00
POS 94.79
UAS 0.00
LAS 0.00
NER P 78.09
NER R 78.75
NER F 78.42
[38;5;2m✔ Generated 25 parses as HTML[0m
result
| MIT | Ch5/04_NER_using_spaCy - CoNLL.ipynb | quicksilverTrx/practical-nlp |
a Visualization of the entity tagged test data can be seen in result/entities.html folder. On spacy's Pretrained NER model (`en`) | !mkdir pretrained_result
!python3 -m spacy evaluate en spacyNER_data/test.json -dp pretrained_result | [1m
================================== Results ==================================[0m
Time 6.52 s
Words 46666
Words/s 7160
TOK 100.00
POS 86.84
UAS 0.00
LAS 0.00
NER P 7.97
NER R 10.68
NER F 9.12
[38;5;2m✔ Generated 25 parses as HTML[0m
pretrained_result
| MIT | Ch5/04_NER_using_spaCy - CoNLL.ipynb | quicksilverTrx/practical-nlp |
Day 1: Report Repair[*Advent of Code day 1 - 2020-12-01*](https://adventofcode.com/2020/day/1) and [*solution megathread*](https://www.reddit.com/r/adventofcode/comments/k4e4lm/2020_day_1_solutions/)[](https://mybinder.org/v2/gh/UncleCJ/advent-of-code/master?filepath=day-0... | # Initialize - from https://www.techcoil.com/blog/how-to-download-a-file-via-http-post-and-http-get-with-python-3-requests-library/
# I'm fairly sure there is some error here, but leaving it until I need to or can fix it
import os
import requests
if os.path.isfile('./input.txt'):
print("-- Already have input, skip... | _____no_output_____ | CC0-1.0 | 2020/01/code.ipynb | UncleCJ/advent-of-code |
Part 2The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation. They offer you a second one if you can find *three* numbers in your expense report that meet the same criteria.Using the above example again, the three entries that sum to `202... | answer = 0
# write your solution here - 'inputdata' is a list of the lines | _____no_output_____ | CC0-1.0 | 2020/01/code.ipynb | UncleCJ/advent-of-code |
create dot_file which store the tree structure | clf.score(x_train,y_train)
py_prediction = clf.predict(x_test)
py_prediction
clf.score(x_test,y_test)
from sklearn.preprocessing import StandardScaler
scalar = StandardScaler()
x_transfrom = scalar.fit_transform(X)
data.head()
grid_param = {
'criterion': ['gini', 'entropy'],
'max_depth' : range(2,100,1),
'm... | _____no_output_____ | Apache-2.0 | Decission Tree.ipynb | Yogi7789/Machine-Learning-Assignment-Pratical |
Tensores--- | # Tensor con dimensiones dadas de números aleatorios
A = torch.randn((8, 3, 5))
# Tamaño de un tensor
A.size()
# Tensor.size() funciona como una tupla
A.size() == (8, 3, 5)
# Los tensores soportan slicing
A[0, :, 0]
# torch.zeros devuelve un tensor de la forma especificado con puros ceros
C = torch.zeros((5, 5))
C.dtyp... | _____no_output_____ | MIT | pytorchIntro/Tensores.ipynb | HectorFranc/deep-learning-with-Pytorch |
Datasets--- | from google.colab import drive
drive.mount('/gdrive')
# torchvision tiene datasets relacionados con imagenes
from torchvision import datasets
# Datasets en torchvision
dir(datasets)
# Descarga el dataset CIFAR10 en la ruta especificada.
# Lo descarga porque download=True
cifar = datasets.CIFAR10('/gdrive/My Drive/dl-... | _____no_output_____ | MIT | pytorchIntro/Tensores.ipynb | HectorFranc/deep-learning-with-Pytorch |
import os, sys
in_colab = 'google.colab' in sys.modules
# Pull files from Github repo
os.chdir('/content')
!git init .
!git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge.git
!git pull origin master
# Install required python packages
!pip install -r requirements.txt
# Change int... | Reinitialized existing Git repository in /content/.git/
fatal: remote origin already exists.
From https://github.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge
* branch master -> FETCH_HEAD
Already up to date.
Requirement already satisfied: category_encoders==2.0.0 in /usr/local/lib/python3.6/dist-packages... | MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge | |
Load and Split the Data - Train and Test | import category_encoders as ce
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
import n... | (25475, 34) (6369, 34) (16973, 34)
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Baseline | print('Baseline - Mean of Price', train['price'].mean()) | Baseline - Mean of Price 3580.408792934249
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Engineer Features | # Wrangle train & test sets in the same way
def engineer_features(df):
# Avoid SettingWithCopyWarning
df = df.copy()
# Does the apartment have a description?
df['description'] = df['description'].str.strip().fillna('')
df['has_description'] = df['description'] != ''
# How long is ... | (25475, 39)
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Train, Validate, Test - 80/20 | #train, val = train_test_split(train, train_size=0.80, test_size=0.20, random_state=42)
print(train.shape, val.shape, test.shape) | (25475, 39) (6369, 39) (16973, 39)
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Cross-Validate | import category_encoders as ce
import numpy as np
from sklearn.feature_selection import f_regression, SelectKBest
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing impo... | MAE for 3 folds: [412.16837219 408.79720129 411.15995068]
Mean of Scores: 410.70850805232976
Standard Deviation of Scores: 1.4128101196260034
Absolute Scores: 0.0034399338994116784
| MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Use Pipeline to Encode Categoricals and Fit a Random Forest | pipeline = make_pipeline(
#ce.TargetEncoder(min_samples_leaf=1, smoothing=1),
ce.OneHotEncoder(use_cat_names=True),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=10, random_state=42, n_jobs=-1)
) | _____no_output_____ | MIT | Kaggle_Challenge_Sprint_Study_Guide2.ipynb | JimKing100/DS-Unit-2-Kaggle-Challenge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.