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
Theano
!pip install numpy matplotlib !pip install --upgrade https://github.com/Theano/Theano/archive/master.zip !pip install --upgrade https://github.com/Lasagne/Lasagne/archive/master.zip
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Разминка
import theano import theano.tensor as T %pylab inline
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
будущий параметр функции -- символьная переменная
N = T.scalar('a dimension', dtype='float32')
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
рецепт получения квадрата -- орперации над символьными переменным
result = T.power(N, 2)
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
theano.grad(cost, wrt)
grad_result = theano.grad(result, N)
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
компиляция функции "получения квадрата"
sq_function = theano.function(inputs=[N], outputs=result) gr_function = theano.function(inputs=[N], outputs=grad_result)
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
применение функции
# Заводим np.array x xv = np.arange(-10, 10) # Применяем функцию к каждому x val = map(float, [sq_function(x) for x in xv]) # Посичтаем градиент в кажой точке grad = map(float, [gr_function(x) for x in xv])
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Что мы увидим если нарисуем функцию и градиент?
pylab.plot(xv, val, label='x*x') pylab.plot(xv, grad, label='d x*x / dx') pylab.legend()
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Lasagne* lasagne - это библиотека для написания нейронок произвольной формы на theano* В качестве демо-задачи выберем то же распознавание чисел, но на большем масштабе задачи, картинки 28x28, 10 цифр
from mnist import load_dataset X_train, y_train, X_val, y_val, X_test, y_test = load_dataset() print 'X размера', X_train.shape, 'y размера', y_train.shape fig, axes = plt.subplots(nrows=1, ncols=7, figsize=(20, 20)) for i, ax in enumerate(axes): ax.imshow(X_train[i, 0], cmap='gray')
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Давайте посмотрим на DenseLayer в lasagne- http://lasagne.readthedocs.io/en/latest/modules/layers/dense.html- https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/dense.pyL16-L124 - Весь содаржательный код тут https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/dense.pyL121
import lasagne from lasagne import init from theano import tensor as T from lasagne.nonlinearities import softmax X, y = T.tensor4('X'), T.vector('y', 'int32')
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Так задаётся архитектура нейронки
#входной слой (вспомогательный) net = lasagne.layers.InputLayer(shape=(None, 1, 28, 28), input_var=X) net = lasagne.layers.Conv2DLayer(net, 15, 28, pad='valid', W=init.Constant()) # сверточный слой net = lasagne.layers.Conv2DLayer(net, 10, 2, pad='full', W=init.Constant()) # сверточный слой net = lasagne.layers.Den...
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Процесс обучения
import time from mnist import iterate_minibatches num_epochs = 5 #количество проходов по данным batch_size = 50 #размер мини-батча for epoch in range(num_epochs): train_err, train_acc, train_batches, start_time = 0, 0, 0, time.time() for inputs, targets in iterate_minibatches(X_train, y_train, batch_size): ...
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
Ансамблирование с DropOut
#предсказание нейронки (theano-преобразование) y_predicted = T.mean([lasagne.layers.get_output(net, deterministic=False) for i in range(10)], axis=0) accuracy = lasagne.objectives.categorical_accuracy(y_predicted, y).mean() accuracy_fun = theano.function([X, y], accuracy) # точность без обновления весов, для теста test...
_____no_output_____
Apache-2.0
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
查看当前GPU信息
from tensorflow.python.client import device_lib device_lib.list_local_devices() !pip install bert-tensorflow import pandas as pd import tensorflow as tf import tensorflow_hub as hub import pickle import bert from bert import run_classifier from bert import optimization from bert import tokenization def pretty_print(re...
_____no_output_____
MIT
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
----- 只需更改下方代码 ------ 导入数据集
!wget https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/training.txt !wget https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/validation.txt train = pd.read_table("training.txt",sep='\t',error_bad_lines=False) #mytrain= mytrain[order] test = pd.read_table("validation.txt",sep='\t',...
_____no_output_____
MIT
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
在此更改你的参数,如标签,bert模型地址,epochs
myparam = { "DATA_COLUMN": "massage", "LABEL_COLUMN": "label", "LEARNING_RATE": 2e-5, "NUM_TRAIN_EPOCHS":1, "bert_model_hub":"https://tfhub.dev/google/bert_chinese_L-12_H-768_A-12/1" }
_____no_output_____
MIT
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
训练模型,通常情况下,一个epochs用k80训练大概在10min左右
result, estimator = run_on_dfs(train, test, **myparam)
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
MIT
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
bert模型还是比较强的,一个epochs就能达到准确率为99%
pretty_print(result)
_____no_output_____
MIT
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
Anna KaRNNaIn this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [implem...
import time from collections import namedtuple import numpy as np import tensorflow as tf
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
First we'll load the text file and convert it into integers for our network to use.
with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for c in text], dtype=np.int32) text[:100] chars[:100]
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text.Here I'll make both input and target arrays. The targets are the same as the inputs, except shifted one cha...
def split_data(chars, batch_size, num_steps, split_frac=0.9): """ Split character data into training and validation sets, inputs and targets for each set. Arguments --------- chars: character array batch_size: Size of examples in each of batch num_steps: Number of sequence steps to kee...
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size `batch_size X num_steps`. For example, if we want our network to train on a sequence of 100 characters, `num_steps = 100`. For the next batch, we'll shift this window the ...
def get_batch(arrs, num_steps): batch_size, slice_size = arrs[0].shape n_batches = int(slice_size/num_steps) for b in range(n_batches): yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs] def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2, lea...
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
HyperparametersHere I'm defining the hyperparameters for the network. The two you probably haven't seen before are `lstm_size` and `num_layers`. These set the number of hidden units in the LSTM layers and the number of LSTM layers, respectively. Of course, making these bigger will improve the network's performance but...
batch_size = 100 num_steps = 100 lstm_size = 512 num_layers = 2 learning_rate = 0.001
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
Write out the graph for TensorBoard
model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=lstm_size, num_layers=num_layers) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) ...
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
TrainingTime for training which is is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by `save_every_n`) I calculate the validation loss and save a check...
!mkdir -p checkpoints/anna epochs = 1 save_every_n = 200 train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps) model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=ls...
_____no_output_____
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
SamplingNow that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the ne...
def pick_top_n(preds, vocab_size, top_n=5): p = np.squeeze(preds) p[np.argsort(p)[:-top_n]] = 0 p = p / np.sum(p) c = np.random.choice(vocab_size, 1, p=p)[0] return c def sample(checkpoint, n_samples, lstm_size, vocab_size, prime="The "): prime = "Far" samples = [c for c in prime] model ...
Farrat, his felt has at it. "When the pose ther hor exceed to his sheant was," weat a sime of his sounsed. The coment and the facily that which had began terede a marilicaly whice whether the pose of his hand, at she was alligated herself the same on she had to taiking to his forthing and streath how to hand began in ...
MIT
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
Numpy Basic operations
import numpy as np numbers = [1, 2, 3, 4, 5] print(np.mean(numbers)) print(np.median(numbers)) print(np.std(numbers)) #This is the standard deviation
3.0 3.0 1.41421356237
Unlicense
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
Numpy Arraies are optimize to run faster
array = np.array(numbers, float) print (array) array[1] array[:2] array[1]=10.0 print array
[ 1. 10. 3. 4. 5.]
Unlicense
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
Numpy Array can be two dimensional
array = np.array([[1,2,3], [4,5,6]], float) print (array) print "" print array[1][1] print "" print array[1, :] print "" print array[:, 2] print "" print array[:, 1] ray = np.array([[1,2,3], [4,5,6]], float) print ray print (ray[1][2]) print (ray[1][1]) print (ray[:, 2])
[[ 1. 2. 3.] [ 4. 5. 6.]] 6.0 5.0 [ 3. 6.]
Unlicense
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
Array arithmetics
ray1 = np.array([1, 2, 3], float) ray2 = np.array([5, 2, 6], float) print (ray1+ray2) print (ray1*ray2) print (np.mean(ray1)) print(np.dot(ray1, ray2)) array_1 = np.array([1, 2, 3], float) array_2 = np.array([5, 2, 6], float) array_1 + array_2
_____no_output_____
Unlicense
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
Array multipliation
array_1 * array_2
_____no_output_____
Unlicense
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
Make logistic Regression model with MNIST
mnist = input_data.read_data_sets('data/',one_hot = True) trainimg = mnist.train.images trainLabel = mnist.train.labels testimg = mnist.test.images testLabel = mnist.test.labels print("MNIST Loaded") x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float', [None, 10]) w = tf.Variable(tf.random_normal([784,1...
Epoch: 000/010 cost: 75.560586708 train_acc: 0.910 test_acc: 0.865 Epoch: 002/010 cost: 32.222071790 train_acc: 0.910 test_acc: 0.895 Epoch: 004/010 cost: 27.124585262 train_acc: 0.930 test_acc: 0.903 Epoch: 006/010 cost: 24.715282281 train_acc: 0.940 test_acc: 0.911 Epoch: 008/010 cost: 23.033731372 train_acc: 0.910 t...
MIT
week3 logistic Regression.ipynb
SongChiyoon/study-Tensorflow
Change sys.path to use my tensortrade instead of the one in env
import sys sys.path.append("/Users/jasonfiacco/Documents/Yale/Senior/thesis/deeptrader") print(sys.path)
['/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '', '/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/py...
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Read PredictIt Data Instead
import ssl import pandas as pd ssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError def fetch_data(symbol): path = "/Users/jasonfiacco/Documents/Yale/Senior/thesis/predictit_datasets/" filename = "{}.xlsx".format(symbol) df = pd.read_excel(path + fil...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Plot the closing prices for all the markets
%matplotlib inline closing_prices = all_data.loc[:, [("close" in name) for name in all_data.columns]] closing_prices.plot()
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Slice just a specific time period from the dataframe
all_data.index = pd.to_datetime(all_data.index) subset_data = all_data[(all_data.index >= '09-01-2017') & (all_data.index <= '09-04-2019')] subset_data.head()
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Define ExchangesAn exchange needs a name, an execution service, and streams of price data in order to function properly.The setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that l...
from tensortrade.exchanges import Exchange from tensortrade.exchanges.services.execution.simulated import execute_order from tensortrade.data import Stream #Exchange(name of exchange, service) #It looks like each Stream takes a name, and then a list of the closing prices. predictit_exch = Exchange("predictit", servic...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Now that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges. Doing it without adding other features. Just use price
#You still have to add "Streams" for all the standard columns open, high, low, close, volume in this case from tensortrade.data import DataFeed, Module with Module("predictit") as predictit_ns: predictit_nodes = [Stream(name, list(subset_data[name])) for name in subset_data.columns] #Then create the Feed from...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
PortfolioMake the portfolio using the any combinations of exchanges and intruments that the exchange supports
#I am going to have to add "instruments" for all 25 of the PredictIt markets I'm working with. from tensortrade.instruments import USD, WARREN, CRUZ, MANCHIN, SANDERS, NELSON, DONNELLY,\ PELOSI, MANAFORT, BROWN, RYAN, STABENOW from tensortrade.wallets import Wallet, Portfolio portfolio ...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Environment
from tensortrade.environments import TradingEnvironment env = TradingEnvironment( feed=feed, portfolio=portfolio, action_scheme='simple', reward_scheme='simple', window_size=15, enable_logger=False, renderers = 'screenlog' ) env.feed.next()
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
^An environment doesn't just show the OHLCV for each instrument. It also shows free, locked, total, as well as "USD_BTC" Using 123's Ray example
import os parent_dir = "/Users/jasonfiacco/Documents/Yale/Senior/thesis/deeptrader" os.environ["PYTHONPATH"] = parent_dir + ":" + os.environ.get("PYTHONPATH", "") !PYTHONWARNINGS=ignore::yaml.YAMLLoadWarning #Import tensortrade import tensortrade # Define Exchanges from tensortrade.exchanges import Exchange from tenso...
2020-03-05 22:30:39,190 INFO resource_spec.py:212 -- Starting Ray with 5.71 GiB memory available for workers and up to 2.86 GiB for objects. You can adjust these settings with ray.init(memory=<bytes>, object_store_memory=<bytes>). 2020-03-05 22:30:39,555 INFO services.py:1078 -- View the Ray dashboard at local...
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Train using the old fashioned RLLib way
for i in range(10): # Perform one iteration of training the policy with PPO print("Training iteration {}...".format(i)) result = trainer.train() print("result: {}".format(result)) if i % 100 == 0: checkpoint = trainer.save() print("checkpoint saved at", checkpoint) result['hist...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
OR train using the tune way (better so far)
analysis = tune.run( "DQN", name = "DQN10-paralellism", checkpoint_at_end=True, stop={ "timesteps_total": 4000, }, config={ "env": "ray_trading_env", "lr": grid_search([1e-4]), # try different lrs "num_workers": 2, # paral...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Restoring an already existing agent that I tuned
import os logdir = analysis.get_best_logdir("episode_reward_mean", mode="max") trainer.restore(os.path.join(logdir, "checkpoint_993/checkpoint-993")) trainer.restore("/Users/jasonfiacco/ray_results/DQN4/DQN_ray_trading_env_fedb24f0_0_lr=1e-06_2020-03-03_15-46-02kzbdv53d/checkpoint_5/checkpoint-5")
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Testing
#Set up a testing environment with test data. test_env = TradingEnvironment( feed=feed, portfolio=portfolio, action_scheme='simple', reward_scheme='simple', window_size=15, enable_logger=False, renderers = 'screenlog' ) for episode_num in range(1): state = test_env.reset() done = Fal...
[2020-03-04 9:54:39 PM] Step: 1 [2020-03-04 9:54:41 PM] Step: 101 [2020-03-04 9:54:44 PM] Step: 201 [2020-03-04 9:54:47 PM] Step: 301 [2020-03-04 9:54:50 PM] Step: 401 [2020-03-04 9:54:52 PM] Step: 501 [2020-03-04 9:54:55 PM] Step: 601 [2020-03-04 9:54:58 PM] Step: 701 Cumulative reward: 4.969025307093819
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Plot
%matplotlib inline portfolio.performance.plot() portfolio.performance.net_worth.plot() #Plot the total balance in each type of item p = portfolio.performance p2 = p.iloc[:, :] weights = p2.loc[:, [("/worth" in name) for name in p2.columns]] weights.iloc[:, 1:8].plot()
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Try Plotly Render too
from tensortrade.environments.render import PlotlyTradingChart from tensortrade.environments.render import FileLogger chart_renderer = PlotlyTradingChart( height = 800 ) file_logger = FileLogger( filename='example.log', # omit or None for automatic file name path='training_logs' # create a new directory...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
Extra Stuff
apath = "/Users/jasonfiacco/Documents/Yale/Senior/thesis/jasonfiacco-selectedmarkets-mytickers.xlsx" df = pd.read_excel(apath, skiprows=2) jason_tickers = df.iloc[:, 5].tolist() descriptions = df.iloc[:, 1].tolist() for ticker, description in zip(jason_tickers, descriptions): l = "{} = Instrument(\'{}\', 2, \'{}\'...
_____no_output_____
Apache-2.0
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
1. Convert pdf to image
## NOTE: install tesseract (https://github.com/UB-Mannheim/tesseract/wiki) and Poppler first # !pip install pytesseract # !pip install Pillow # !pip install pdf2image # import statements from PIL import Image from pdf2image import convert_from_path import sys import os import numpy as np folder_path = 'C:\\Users\Vaness...
_____no_output_____
MIT
dict_ocr.ipynb
vanessapigwin/scrapingpractice
2. Check file integrity, size
folder_path = 'C:\\Users\\Vanessa\\Jupyter Notebooks\\STUFF' file_list = [f for f in os.listdir(folder_path) if f.endswith('.png')] print('Total files to check:', len(file_list)) # getting maximum dimension of each image max_width = 0 max_height = 0 for file in file_list: try: with Image.open(os.path.join...
_____no_output_____
MIT
dict_ocr.ipynb
vanessapigwin/scrapingpractice
3. Convert image to OCR
import cv2 as cv import pytesseract pytesseract.pytesseract.tesseract_cmd=r'C:\Program Files\Tesseract-OCR\tesseract.exe' custom_config = r' --psm 6' # method to ocr def remove_header_bg(img): # convert image to hsv img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) h, s, v = cv.split(img_hsv) # thresh...
HH-001_1 converted HH-002_1 converted HH-003_1 converted HH-004_1 converted HH-005_1 converted HH-006_1 converted HH-006_2 converted HH-007_1 converted HH-008_1 converted HH-010_1 converted HH-010_2 converted HH-011_1 converted HH-011_2 converted HH-012_1 converted HH-013_1 converted HH-013_2 converted ...
MIT
dict_ocr.ipynb
vanessapigwin/scrapingpractice
[Table of Contents](./table_of_contents.ipynb) Smoothing
#format the book %matplotlib inline from __future__ import division, print_function from book_format import load_style load_style()
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
Introduction The performance of the Kalman filter is not optimal when you consider future data. For example, suppose we are tracking an aircraft, and the latest measurement deviates far from the current track, like so (I'll only consider 1 dimension for simplicity):
import matplotlib.pyplot as plt data = [10.1, 10.2, 9.8, 10.1, 10.2, 10.3, 10.1, 9.9, 10.2, 10.0, 9.9, 11.4] plt.plot(data) plt.xlabel('time') plt.ylabel('position');
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
After a period of near steady state, we have a very large change. Assume the change is past the limit of the aircraft's flight envelope. Nonetheless the Kalman filter incorporates that new measurement into the filter based on the current Kalman gain. It cannot reject the noise because the measurement could reflect the ...
data2 = [11.3, 12.1, 13.3, 13.9, 14.5, 15.2] plt.plot(data + data2);
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
Given these future measurements we can infer that yes, the aircraft initiated a turn. On the other hand, suppose these are the following measurements.
data3 = [9.8, 10.2, 9.9, 10.1, 10.0, 10.3, 9.9, 10.1] plt.plot(data + data3);
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
In this case we are led to conclude that the aircraft did not turn and that the outlying measurement was merely very noisy. An Overview of How Smoothers WorkThe Kalman filter is a *recursive* filter with the Markov property - it's estimate at step `k` is based only on the estimate from step `k-1` and the measurement...
import numpy as np from numpy import random from numpy.random import randn import matplotlib.pyplot as plt from filterpy.kalman import KalmanFilter import kf_book.book_plots as bp def plot_rts(noise, Q=0.001, show_velocity=False): random.seed(123) fk = KalmanFilter(dim_x=2, dim_z=1) fk.x = np.array([0., 1...
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
I've injected a lot of noise into the signal to allow you to visually distinguish the RTS output from the ideal output. In the graph above we can see that the Kalman filter, drawn as the green dotted line, is reasonably smooth compared to the input, but it still wanders from from the ideal line when several measurement...
plot_rts(noise=1.)
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
However, we must understand that this smoothing is predicated on the system model. We have told the filter that what we are tracking follows a constant velocity model with very low process error. When the filter *looks ahead* it sees that the future behavior closely matches a constant velocity so it is able to reject m...
plot_rts(noise=7., Q=.1)
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
This underscores the fact that these filters are not *smoothing* the data in colloquial sense of the term. The filter is making an optimal estimate based on previous measurements, future measurements, and what you tell it about the behavior of the system and the noise in the system and measurements.Let's wrap this up b...
plot_rts(7.,show_velocity=True)
gu
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
The improvement in the velocity, which is an hidden variable, is even more dramatic. Fixed-Lag SmoothingThe RTS smoother presented above should always be your choice of algorithm if you can run in batch mode because it incorporates all available data into each estimate. Not all problems allow you to do that, but you ...
from kf_book.book_plots import figsize from kf_book.smoothing_internal import * with figsize(y=2): show_fixed_lag_numberline()
_____no_output_____
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
At step $k$ we can estimate $x_k$ using the normal Kalman filter equations. However, we can make a better estimate for $x_{k-1}$ by using the measurement received for $x_k$. Likewise, we can make a better estimate for $x_{k-2}$ by using the measurements recevied for $x_{k-1}$ and $x_{k}$. We can extend this computation...
from filterpy.kalman import FixedLagSmoother, KalmanFilter import numpy.random as random fls = FixedLagSmoother(dim_x=2, dim_z=1, N=8) fls.x = np.array([0., .5]) fls.F = np.array([[1.,1.], [0.,1.]]) fls.H = np.array([[1.,0.]]) fls.P *= 200 fls.R *= 5. fls.Q *= 0.001 kf = KalmanFilter(dim_x=2, dim_...
standard deviation fixed-lag: 2.616 standard deviation kalman: 3.562
CC-BY-4.0
13-Smoothing.ipynb
yangzongsheng/kalman
準備
# バージョン指定時にコメントアウト #!pip install torch==1.7.0 #!pip install torchvision==0.8.1 import torch import torchvision # バージョンの確認 print(torch.__version__) print(torchvision.__version__) # Google ドライブにマウント from google.colab import drive drive.mount('/content/gdrive') %cd '/content/gdrive/MyDrive/Colab Notebooks/gan_sample/ch...
_____no_output_____
MIT
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
データセットの作成
np.random.seed(1234) torch.manual_seed(1234) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # データの取得 root = os.path.join('data', 'mnist') transform = transforms.Compose([transforms.ToTensor(), lambda x: x.view(-1)]) mnist_train = \ torchvision.datasets.MNIST(r...
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to data/mnist/MNIST/raw/train-images-idx3-ubyte.gz
MIT
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
ネットワークの定義
class Autoencoder(nn.Module): def __init__(self, device='cpu'): super().__init__() self.device = device self.l1 = nn.Linear(784, 200) self.l2 = nn.Linear(200, 784) def forward(self, x): # エンコーダ h = self.l1(x) # 活性化関数 h = torch.relu(h) # デ...
_____no_output_____
MIT
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
学習の実行
# モデルの設定 model = Autoencoder(device=device).to(device) # 損失関数の設定 criterion = nn.BCELoss() # 最適化関数の設定 optimizer = optimizers.Adam(model.parameters()) epochs = 10 # エポックのループ for epoch in range(epochs): train_loss = 0. # バッチサイズのループ for (x, _) in train_dataloader: x = x.to(device) # 訓練モードへの切替 ...
Epoch: 1, Loss: 0.153 Epoch: 2, Loss: 0.085 Epoch: 3, Loss: 0.075 Epoch: 4, Loss: 0.071 Epoch: 5, Loss: 0.069 Epoch: 6, Loss: 0.068 Epoch: 7, Loss: 0.067 Epoch: 8, Loss: 0.067 Epoch: 9, Loss: 0.066 Epoch: 10, Loss: 0.066
MIT
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
画像の復元
# dataloaderからのデータ取り出し x, _ = next(iter(test_dataloader)) x = x.to(device) # 評価モードへの切替 model.eval() # 復元画像 x_rec = model(x) # 入力画像、復元画像の表示 for i, image in enumerate([x, x_rec]): image = image.view(28, 28).detach().cpu().numpy() plt.subplot(1, 2, i+1) plt.imshow(image, cmap='binary_r') pl...
_____no_output_____
MIT
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
Optimization and gradient descent method
from IPython.display import IFrame IFrame(src="https://cdnapisec.kaltura.com/p/2356971/sp/235697100/embedIframeJs/uiconf_id/41416911/partner_id/2356971?iframeembed=true&playerId=kaltura_player&entry_id=1_wota11ay&flashvars[streamerType]=auto&amp;flashvars[localizationCode]=en&amp;flashvars[leadWithHTML5]=true&amp;flas...
_____no_output_____
MIT
docs/_sources/Module1/m1_06.ipynb
liuzhengqi1996/math452_Spring2022
One-step error probability Write a computer program implementing asynchronous deterministic updates for a Hopfield network. Use Hebb's rule with $w_{ii}=0$. Generate and store p=[12,24,48,70,100,120] random patterns with N=120 bits. Each bit is either +1 or -1 with probability $\tfrac{1}{2}$.For each value of ppp est...
import numpy as np import time def calculate_instance( n, p, zero_diagonal): #Create p random patterns patterns = [] for i in range(p): patterns.append(np.random.choice([-1,1],n)) #Create weights matrix according to hebbs rule weights = patterns[0][:,None]*patterns[0] for el in patt...
_____no_output_____
MIT
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
List your numerically computed $P_{\text {error}}^{t=1}$ for the parameters given above.
p = [12, 24, 48, 70, 100, 120] N = 120 I = 100000 for p_i in p: solve = [0,0] for i in range(I): ret = calculate_instance(N, p_i, True) if ret: solve[0]+=1 else: solve[1]+=1 p_error = float(solve[1]/I) print(f"Number of patterns: {p_i}, P_error(t=1): {p_e...
Number of patterns: 12, P_error(t=1): 0.00057 Number of patterns: 24, P_error(t=1): 0.01143 Number of patterns: 48, P_error(t=1): 0.05569 Number of patterns: 70, P_error(t=1): 0.09447 Number of patterns: 100, P_error(t=1): 0.13699 Number of patterns: 120, P_error(t=1): 0.15952
MIT
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
Repeat the task, but now apply Hebb's rule without setting the diagonal weights to zero. For each value of p listed above, estimate the one-step error probability $P_{\text {error}}^{t=1}$ based on $10^5$ independent trials.
p = [12, 24, 48, 70, 100, 120] N = 120 I = 100000 for p_i in p: solve = [0,0] for i in range(I): ret = calculate_instance(N, p_i, False) if ret: solve[0]+=1 else: solve[1]+=1 p_error = float(solve[1]/I) print(f"Number of patterns: {p_i}, P_error(t=1): {p_...
Number of patterns: 12, P_error(t=1): 0.00021 Number of patterns: 24, P_error(t=1): 0.0029 Number of patterns: 48, P_error(t=1): 0.0127 Number of patterns: 70, P_error(t=1): 0.01841 Number of patterns: 100, P_error(t=1): 0.02115 Number of patterns: 120, P_error(t=1): 0.02116
MIT
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
Acquiring Data from open repositoriesA crucial step in the work of a computational biologist is not only to analyse data, but acquiring datasets to analyse as well as toy datasets to test out computational methods and algorithms. The internet is full of such open datasets. Sometimes you have to sign up and make a user...
# import basic libraries import numpy as np import pandas as pd from matplotlib import pyplot as plt
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
We start with scikit-learn's datasets for testing out ML algorithms. Visit [here](https://scikit-learn.org/stable/modules/classes.html?highlight=datasetsmodule-sklearn.datasets) for an overview of the datasets.
from sklearn.datasets import fetch_olivetti_faces, fetch_20newsgroups, load_breast_cancer, load_diabetes, load_digits, load_iris
C:\Users\Peder\Anaconda3\envs\cbm101\lib\importlib\_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject return f(*args, **kwds)
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Load the MNIST dataset (images of hand written digits)
X,y = load_digits(return_X_y=True) y.shape X.shape #1797 images, 64 pixels per image
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
exercise 1. Make a function `plot` taking an argument (k) to visualize the k'th sample. It is currently flattened, you will need to reshape it. Use `plt.imshow` for plotting.
# %load solutions/ex2_1.py def plot(k): plt.imshow(X[k].reshape(8,8), cmap='gray') plt.title(f"Number = {y[k]}") plt.show() plot(15); plot(450) faces = fetch_olivetti_faces()
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Exercise 2. Inspect the dataset. How many classes are there? How many samples per class? Also, plot some examples. What do the classes represent?
# %load solutions/ex2_2.py # example solution. # You are not expected to make a nice plotting function, # you can simply call plt.imshow a number of times and observe print(faces.DESCR) # this shows there are 40 classes, 10 samples per class print(faces.target) #the targets i.e. classes print(np.unique(faces.target)...
.. _olivetti_faces_dataset: The Olivetti faces dataset -------------------------- `This dataset contains a set of face images`_ taken between April 1992 and April 1994 at AT&T Laboratories Cambridge. The :func:`sklearn.datasets.fetch_olivetti_faces` function is the data fetching / caching function that downloads the...
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Once you have made yourself familiar with the dataset you can do some data exploration with unsupervised methods, like below. The next few lines of code are simply for illustration, don't worry about the code (we will cover unsupervised methods in submodule F).
from sklearn.decomposition import randomized_svd X = faces.data n_dim = 3 u, s, v = randomized_svd(X, n_dim)
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Now we have factorized the images into their constituent parts. The code below displays the various components isolated one by one.
def show_ims(ims): fig = plt.figure(figsize=(16,10)) idxs = [0,1,2, 11,12,13, 40,41,42, 101,101,103] for i,k in enumerate(idxs): ax=fig.add_subplot(3,4,i+1) ax.imshow(ims[k]) ax.set_title(f"target={y[k]}") for i in range(n_dim): my_s = np.zeros(s.shape[0]) my_s[i] = s[i] ...
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Are you able to see what the components represent? It at least looks like the second component signifies the lightning (the light direction), the third highlights eyebrows and facial chin shape.
from sklearn.manifold import TSNE tsne = TSNE(init='pca', random_state=0) trans = tsne.fit_transform(X) m = 8*10 # choose 4 people plt.figure(figsize=(16,10)) xs, ys = trans[:m,0], trans[:m,1] plt.scatter(xs, ys, c=y[:m], cmap='rainbow') for i,v in enumerate(zip(xs,ys, y[:m])): xx,yy,s = v #plt.text(xx,yy,s)...
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Many people seem to have multiple subclusters. What is the difference between those clusters? (e.g. 68,62,65 versus the other 60's)
ims = faces.images idxs = [68,62,65,66,60,64,63] #idxs = [9,4,1, 5,3] for k in idxs: plt.imshow(ims[k], cmap='gray') plt.show() def show(im): return plt.imshow(im, cmap='gray') import pandas as pd df= pd.read_csv('data/archive/covid_impact_on_airport_traffic.csv') df.shape df.describe() df.head() df.Countr...
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Here we will look at [OpenML](https://www.openml.org/) - a repository of open datasets free to explore data and test methods. Fetching an OpenML datasetWe need to pass in an ID to access, as follows:
from sklearn.datasets import fetch_openml
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
OpenML contains all sorts of datatypes. By browsing the website we found a electroencephalography (EEG) dataset to explore:
data_id = 1471 #this was found by browsing OpenML dataset = fetch_openml(data_id=data_id, as_frame=True) dir(dataset) dataset.url type(dataset) print(dataset.DESCR) original_names = ['AF3', 'F7', 'F3', 'FC5', 'T7', 'P', 'O1', 'O2', 'P8', 'T8', 'FC6', 'F4', 'F8', 'AF4'] dataset.feature_names df = dataset.fr...
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
From the plot we can quickly identify a bunch of huge outliers, making the plot look completely uselss. We assume these are artifacts, and remove them.
df2 = df.iloc[:,:-1].clip_upper(6000) df2.plot()
C:\Users\Peder\Anaconda3\envs\cbm101\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: clip_upper(threshold) is deprecated, use clip(upper=threshold) instead """Entry point for launching an IPython kernel.
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Now we see better what is going on. Lets just remove the frames corresponding to those outliers
frames = np.nonzero(np.any(df.iloc[:,:-1].values>5000, axis=1))[0] frames df.drop(index=frames, inplace=True) df.plot(figsize=(16,8)) plt.legend(labels=original_names) df.columns
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Do some modelling of the data
from sklearn.linear_model import LogisticRegression lasso = LogisticRegression(penalty='l2') X = df.values[:,:-1] y = df.Class y = y.astype(np.int) - 1 # map to 0,1 print(X.shape) print(y.shape) lasso.fit(X,y) comp = (lasso.predict(X) == y).values np.sum(comp.astype(np.int))/y.shape[0] # shitty accuracy lasso.coef_[0]....
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
Interpreting the coeficients: we naturally tend to read the magnitude of the coefficients as feature importance. That is a fair interpretation, but currently we did not scale our features to a comparable range prior to fittting the model, so we cannot draw that conclusion. Extra exercise. Go to [OpenML](https://openml...
### YOUR CODE HERE
_____no_output_____
MIT
C_Data_resources/2_Open_datasets.ipynb
oercompbiomed/CBM101
View Campaign and InteractionsIn the first notebook `Personalize_BuildCampaign.ipynb` you successfully built and deployed a recommendation model using deep learning with Amazon Personalize.This notebook will expand on that and will walk you through adding the ability to react to real time behavior of users. If their i...
# Imports import boto3 import json import numpy as np import pandas as pd import time import uuid
_____no_output_____
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Below you will paste in the campaign ARN that you used in your previous notebook. Also pick a random user ID from 50 - 300. Lastly you will also need to find your Dataset Group ARN from the previous notebook.
# Setup and Config # Recommendations from Event data personalize = boto3.client('personalize') personalize_runtime = boto3.client('personalize-runtime') HRNN_Campaign_ARN = "arn:aws:personalize:us-east-1:930444659029:campaign/DEMO-campaign" # Define User USER_ID = "676" # Dataset Group Arn: datasetGroupArn = "arn:aw...
_____no_output_____
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Creating an Event TrackerBefore your recommendation system can respond to real time events you will need an event tracker, the code below will generate one and can be used going forward with this lab. Feel free to name it something more clever.
response = personalize.create_event_tracker( name='MovieClickTracker', datasetGroupArn=datasetGroupArn ) print(response['eventTrackerArn']) print(response['trackingId']) TRACKING_ID = response['trackingId']
arn:aws:personalize:us-east-1:930444659029:event-tracker/bbe80586 b8a5944c-8095-40ff-a915-2a6af53b7f55
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Configuring Source DataAbove you'll see your tracking ID and this has been assigned to a variable so no further action is needed by you. The lines below are going to setup the data used for recommendations so you can render the list of movies later.
data = pd.read_csv('./ml-20m/ratings.csv', sep=',', dtype={'userid': "int64", 'movieid': "int64", 'rating': "float64", 'timestamp': "int64"}) pd.set_option('display.max_rows', 5) data.rename(columns = {'userId':'USER_ID','movieId':'ITEM_ID','rating':'RATING','timestamp':'TIMESTAMP'}, inplace = True) data = data[data['R...
USER: 40094 ITEM: Hotel Rwanda (2004)
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Getting RecommendationsJust like in the previous notebook it is a great idea to get a list of recommendatiosn first and then see how additional behavior by a user alters the recommendations.
# Get Recommendations as is get_recommendations_response = personalize_runtime.get_recommendations( campaignArn = HRNN_Campaign_ARN, userId = USER_ID, ) item_list = get_recommendations_response['itemList'] title_list = [items.loc[items['ITEM_ID'] == np.int(item['itemId'])].values[0][-1] for item in item_list] ...
Recommendations: [ "Signs (2002)", "Panic Room (2002)", "Vanilla Sky (2001)", "American Pie 2 (2001)", "Blade II (2002)", "Bourne Identity, The (2002)", "Star Wars: Episode II - Attack of the Clones (2002)", "Memento (2000)", "Fast and the Furious, The (2001)", "Unbreakable (2000)", "Snatch (2000)...
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Simulating User BehaviorThe lines below provide a code sample that simulates a user interacting with a particular item, you will then get recommendations that differ from those when you started.
session_dict = {} def send_movie_click(USER_ID, ITEM_ID): """ Simulates a click as an envent to send an event to Amazon Personalize's Event Tracker """ # Configure Session try: session_ID = session_dict[USER_ID] except: session_dict[USER_ID] = str(uuid.uuid1()) sessio...
_____no_output_____
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
Immediately below this line will update the tracker as if the user has clicked a particular title.
# Pick a movie, we will use ID 1653 or Gattica send_movie_click(USER_ID=USER_ID, ITEM_ID=1653)
_____no_output_____
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
After executing this block you will see the alterations in the recommendations now that you have event tracking enabled and that you have sent the events to the service.
get_recommendations_response = personalize_runtime.get_recommendations( campaignArn = HRNN_Campaign_ARN, userId = str(USER_ID), ) item_list = get_recommendations_response['itemList'] title_list = [items.loc[items['ITEM_ID'] == np.int(item['itemId'])].values[0][-1] for item in item_list] print("Recommendations...
Recommendations: [ "Signs (2002)", "Fifth Element, The (1997)", "Gattaca (1997)", "Unbreakable (2000)", "Face/Off (1997)", "Predator (1987)", "Dark City (1998)", "Star Wars: Episode II - Attack of the Clones (2002)", "Cube (1997)", "Spider-Man (2002)", "Game, The (1997)", "Minority Report (2002)...
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
ConclusionYou can see now that recommendations are altered by changing the movie that a user interacts with, this system can be modified to any application where users are interacting with a collection of items. These tools are available at any time to pull down and start exploring what is possible with the data you h...
eventTrackerArn = response['eventTrackerArn'] print("Tracker ARN is: " + str(eventTrackerArn))
_____no_output_____
MIT-0
getting_started/2.View_Campaign_And_Interactions.ipynb
lmorri/personalize-movielens-20m
* [Sudoku Scraper](https://github.com/apauliuc/sudoku-scraper)* [Scraped Website](https://www.menneske.no/sudoku/3x4/eng/)
import pandas as pd from google.colab import files # upload the uncleaned 12x12 data uploaded = files.upload() # loading and looking at the data df = pd.read_csv("uncleaned_sudokus_12x12.csv") print(df.shape) df.head() # cleaning dataset clean_df = df.copy() clean_df.head() # replace # '0' with '.' # '10' with 'A' # '1...
_____no_output_____
MIT
Notebooks/data/12x12_puzzles.ipynb
Lambda-School-Labs/omega2020-ds
Import the Libraries
import os import warnings warnings.filterwarnings('ignore') # importing packages import pandas as pd import re import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # sklearn packages from sklearn import metrics from sklearn.model_selection import train_test_split, GridSearchCV...
_____no_output_____
MIT
IndependenceDay_Hack_LightGBM.ipynb
Niranjankumar-c/IndiaML_Hiring_Hackathon_2019
Loading the data
#load the train and test data totaldf_onehot = pd.read_csv("totaldata_onehot.csv") #load the train data totaldf_onehot.head() #split the data into train and test traindf_cleaned = totaldf_onehot[totaldf_onehot["source"] == "train"].drop("source", axis = 1) testdf_cleaned = totaldf_onehot[totaldf_onehot["source"] == ...
_____no_output_____
MIT
IndependenceDay_Hack_LightGBM.ipynb
Niranjankumar-c/IndiaML_Hiring_Hackathon_2019
Collaborative filtering example `collab` models use data in a `DataFrame` of user, items, and ratings.
path = untar_data(URLs.ML_SAMPLE) path ratings = pd.read_csv(path/'ratings.csv') series2cat(ratings, 'userId', 'movieId') ratings.head() data = CollabDataBunch.from_df(ratings, seed=42) y_range = [0, 5.5]
_____no_output_____
Apache-2.0
examples/collab.ipynb
MartinGer/fastai
That's all we need to create and train a model:
learn = collab_learner(data, n_factors=50, y_range=y_range) learn.fit_one_cycle(4, 5e-3)
Total time: 00:02 epoch train_loss valid_loss 1 1.724424 1.277289 (00:00) 2 0.893744 0.678392 (00:00) 3 0.655527 0.651847 (00:00) 4 0.562305 0.649613 (00:00)
Apache-2.0
examples/collab.ipynb
MartinGer/fastai
📝 Exercise 00The goal of this exercise is to fit a similar model as in the previousnotebook to get familiar with manipulating scikit-learn objects and inparticular the `.fit/.predict/.score` API. Let's load the adult census dataset with only numerical variables
import pandas as pd adult_census = pd.read_csv("../datasets/adult-census-numeric.csv") data = adult_census.drop(columns="class") target = adult_census["class"]
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_00.ipynb
khanfarhan10/scikit-learn-mooc