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
Melanoma Diagnoses
import os import keras import pandas as pd import numpy as np from PIL import Image import matplotlib.pyplot as plt %matplotlib inline from keras import applications from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing import image from keras import optimizers from keras.models import Sequ...
Using TensorFlow backend.
MIT
solution.ipynb
ezhilvendhan/dermatogist-ai-solution
Import Images
def load_image( infilename ) : img = Image.open( infilename ) img.load() data = np.asarray( img, dtype="float32" ) return data data_dir = 'data' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' fig = plt.figure(figsize=(20,5)) train_files = os.listdir(train_...
_____no_output_____
MIT
solution.ipynb
ezhilvendhan/dermatogist-ai-solution
Image Data transformation
img_width, img_height = 256, 256 batch_size = 16 epochs = 10 train_datagen = ImageDataGenerator( rescale = 1./255, horizontal_flip = True, # fill_mode = "nearest", zoom_range = 0.2, # width_shift_range = 0.3, # height_shift_range=0.3, shear_range=0.2, # rotation_range=30 ) test_datagen...
_____no_output_____
MIT
solution.ipynb
ezhilvendhan/dermatogist-ai-solution
Fine-tune Model
# create the base pre-trained model vgg_model = applications.VGG19(weights = "imagenet", include_top=False, input_shape = (img_width, img_height, 3)) for layer in vgg_model.layers[:5]: layer.trainable = False #Adding custom Layers x = vgg_model.output x = Gl...
Epoch 1/3 125/125 [==============================] - 325s - loss: 0.8962 - val_loss: 1.2098 Epoch 2/3 125/125 [==============================] - 309s - loss: 0.8286 - val_loss: 1.2344 Epoch 3/3 125/125 [==============================] - 302s - loss: 0.8126 - val_loss: 1.1027
MIT
solution.ipynb
ezhilvendhan/dermatogist-ai-solution
Train Model
# Save the model according to the conditions checkpoint = ModelCheckpoint("cancer_vgg19_wt.h5", monitor='val_acc', verbose=2, save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='va...
_____no_output_____
MIT
solution.ipynb
ezhilvendhan/dermatogist-ai-solution
Table of Contents
import geopandas import plotly
_____no_output_____
MIT
i2i/fspmaps/Phase-6-newData.ipynb
Vizzuality/notebooks
Section 4 Try another nameYou are still working on your Twitter sentiment analysis. You analyze now some things that caught your attention. You noticed that there are email addresses inserted in some tweets. Now, you are curious to find out which is the most common name.You want to extract the first part of the email...
sentiment_analysis = ['Just got ur newsletter, those fares really are unbelievable. Write to statravelAU@gmail.com or statravelpo@hotmail.com. They have amazing prices', 'I should have paid more attention when we covered photoshop in my webpage design class in undergrad. Contact me Hollywoodheat34@msn.net.', 'hey mis...
Lists of users found in this tweet: ['statravelAU', 'statravelpo'] Lists of users found in this tweet: ['Hollywoodheat34'] Lists of users found in this tweet: ['msdrama098']
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Flying homeYour boss assigned you to a small project. They are performing an analysis of the travels people made to attend business meetings. You are given a dataset with only the email subjects for each of the people traveling.You learn that the text followed a pattern. Here is an example:Here you have your boarding ...
# Import re import re # Write regex to capture information of the flight regex = r"([A-Z]{2})(\d{4})\s([A-Z]{3})-([A-Z]{3})\s(\d{2}[A-Z]{3})" flight = 'Subject: You are now ready to fly. Here you have your boarding pass IB3723 AMS-MAD 06OCT' # Find all matches of the flight information flight_matches = re.findall(regex...
Airline: IB Flight number: 3723 Departure: AMS Destination: MAD Date: 06OCT
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Love it!You are still working on the Twitter sentiment analysis project. First, you want to identify positive tweets about movies and concerts.You plan to find all the sentences that contain the words love, like, or enjoy and capture that word. You will limit the tweets by focusing on those that contain the words movi...
sentiment_analysis = ['I totally love the concert The Book of Souls World Tour. It kinda amazing!', 'I enjoy the movie Wreck-It Ralph. I watched with my boyfriend.', "I still like the movie Wish Upon a Star. Too bad Disney doesn't show it anymore."] # Write a regex that matches sentences with the optional words regex...
Positive comments found [('love', 'concert', 'The Book of Souls World Tour')] Positive comments found [('enjoy', 'movie', 'Wreck-It Ralph')] Positive comments found [('like', 'movie', 'Wish Upon a Star')]
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Ugh! Not for me!After finding positive tweets, you want to do it for negative tweets. Your plan now is to find sentences that contain the words hate, dislike or disapprove. You will again save the movie or concert name. You will get the tweet containing the words movie or concert but this time, you don't plan to save ...
sentiment_analysis = ['That was horrible! I really dislike the movie The cabin and the ant. So boring.', "I disapprove the movie Honest with you. It's full of cliches.", 'I dislike very much the concert After twelve Tour. The sound was horrible.'] # Write a regex that matches sentences with the optional words regex_n...
Negative comments found [('dislike', 'The cabin and the ant')] Negative comments found [('disapprove', 'Honest with you')] Negative comments found [('dislike', 'After twelve Tour')]
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Parsing PDF filesYou now need to work on another small project you have been delaying. Your company gave you some PDF files of signed contracts. The goal of the project is to create a database with the information you parse from them. Three of these columns should correspond to the day, month, and year when the contra...
contract = 'Provider will invoice Client for Services performed within 30 days of performance. Client will pay Provider as set forth in each Statement of Work within 30 days of receipt and acceptance of such invoice. It is understood that payments to Provider for services rendered shall be made in full as agreed, with...
Our first contract is dated back to 2001. Particularly, the day 25 of the month 03.
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Close the tag, please!In the meantime, you are working on one of your other projects. The company is going to develop a new product. It will help developers automatically check the code they are writing. You need to write a short script for checking that every HTML tag that is open has its proper closure.You have an e...
html_tags = ['<body>Welcome to our course! It would be an awesome experience</body>', '<article>To be a data scientist, you need to have knowledge in statistics and mathematics</article>', '<nav>About me Links Contact me!'] for string in html_tags: # Complete the regex and find if it matches a closed HTML tags ...
Your tag body is closed Your tag article is closed Close your nav tag!
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Reeepeated charactersBack to your sentiment analysis! Your next task is to replace elongated words that appear in the tweets. We define an elongated word as a word that contains a repeating character twice or more times. e.g. "Awesoooome".Replacing those words is very important since a classifier will treat them as a ...
sentiment_analysis = ['@marykatherine_q i know! I heard it this morning and wondered the same thing. Moscooooooow is so behind the times', 'Staying at a friends house...neighborrrrrrrs are so loud-having a party', 'Just woke up an already have read some e-mail'] # Complete the regex to match an elongated word regex_e...
Elongated word found: Moscooooooow Elongated word found: neighborrrrrrrs No elongated word found
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Surrounding wordsNow, you want to perform some visualizations with your sentiment_analysis dataset. You are interested in the words surrounding python. You want to count how many times a specific words appears right before and after it.Positive lookahead (?=) makes sure that first part of the expression is followed by...
sentiment_analysis = 'You need excellent python skills to be a data scientist. Must be! Excellent python' # Positive lookahead look_ahead = re.findall(r"\w+(?=\spython)", sentiment_analysis) # Print out print(look_ahead) # Positive lookbehind look_behind = re.findall(r"(?<=[Pp]ython\s)\w+", sentiment_analysis) # Prin...
['skills']
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Filtering phone numbersNow, you need to write a script for a cell-phone searcher. It should scan a list of phone numbers and return those that meet certain characteristics.The phone numbers in the list have the structure:- Optional area code: 3 numbers- Prefix: 4 numbers- Line number: 6 numbers- Optional extension: 2 ...
cellphones = ['4564-646464-01', '345-5785-544245', '6476-579052-01'] for phone in cellphones: # Get all phone numbers not preceded by area code number = re.findall(r"(?<!\d{3}-)\d{4}-\d{6}-\d{2}", phone) print(number) for phone in cellphones: # Get all phone numbers not followed by optional extension number = re.f...
[] ['345-5785-544245'] []
MIT
regular-expressions-in-python/4. Advanced Regular Expression Concepts/notebook_section_4.ipynb
nhutnamhcmus/datacamp-playground
Batch Normalization – Lesson1. [What is it?](theory)2. [What are it's benefits?](benefits)3. [How do we add it to a network?](implementation_1)4. [Let's see it work!](demos)5. [What are you hiding?](implementation_2) What is Batch Normalization?Batch normalization was introduced in Sergey Ioffe's and Christian Szegedy...
# Import necessary packages import tensorflow as tf import tqdm import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import MNIST data so we have something for our experiments from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes. Extracting MNIST_data/train-images-idx3-ubyte.gz Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes. Extracting MNIST_data/train-labels-idx1-ubyte.gz Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes. Extracting MNIST_data/t10k-...
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Neural network classes for testingThe following class, `NeuralNet`, allows us to create identical neural networks with and without batch normalization. The code is heavily documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the noteboo...
class NeuralNet: def __init__(self, initial_weights, activation_fn, use_batch_norm): """ Initializes this object, creating a TensorFlow graph using the given parameters. :param initial_weights: list of NumPy arrays or Tensors Initial values for the weights for every laye...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
There are quite a few comments in the code, so those should answer most of your questions. However, let's take a look at the most important lines.We add batch normalization to layers inside the `fully_connected` function. Here are some important points about that code:1. Layers with batch normalization do not include a...
def plot_training_accuracies(*args, **kwargs): """ Displays a plot of the accuracies calculated during training to demonstrate how many iterations it took for the model(s) to converge. :param args: One or more NeuralNet objects You can supply any number of NeuralNet objects as unnamed argum...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Comparisons between identical networks, with and without batch normalizationThe next series of cells train networks with various settings to show the differences with and without batch normalization. They are meant to clearly demonstrate the effects of batch normalization. We include a deeper discussion of batch norma...
train_and_test(False, 0.01, tf.nn.relu)
100%|██████████| 50000/50000 [00:42<00:00, 1183.34it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
As expected, both networks train well and eventually reach similar test accuracies. However, notice that the model with batch normalization converges slightly faster than the other network, reaching accuracies over 90% almost immediately and nearing its max acuracy in 10 or 15 thousand iterations. The other network tak...
train_and_test(False, 0.01, tf.nn.relu, 2000, 50)
100%|██████████| 2000/2000 [00:01<00:00, 1069.17it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
As you can see, using batch normalization produces a model with over 95% accuracy in only 2000 batches, and it was above 90% at somewhere around 500 batches. Without batch normalization, the model takes 1750 iterations just to hit 80% – the network with batch normalization hits that mark after around 200 iterations! (N...
train_and_test(False, 0.01, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:43<00:00, 1153.97it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
With the number of layers we're using and this small learning rate, using a sigmoid activation function takes a long time to start learning. It eventually starts making progress, but it took over 45 thousand batches just to get over 80% accuracy. Using batch normalization gets to 90% in around one thousand batches. **...
train_and_test(False, 1, tf.nn.relu)
100%|██████████| 50000/50000 [00:35<00:00, 1397.55it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Now we're using ReLUs again, but with a larger learning rate. The plot shows how training started out pretty normally, with the network with batch normalization starting out faster than the other. But the higher learning rate bounces the accuracy around a bit more, and at some point the accuracy in the network without ...
train_and_test(False, 1, tf.nn.relu)
100%|██████████| 50000/50000 [00:36<00:00, 1379.92it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
In both of the previous examples, the network with batch normalization manages to gets over 98% accuracy, and get near that result almost immediately. The higher learning rate allows the network to train extremely fast. **The following creates two networks using a sigmoid activation function, a learning rate of 1, and ...
train_and_test(False, 1, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:36<00:00, 1382.38it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
In this example, we switched to a sigmoid activation function. It appears to hande the higher learning rate well, with both networks achieving high accuracy.The cell below shows a similar pair of networks trained for only 2000 iterations.
train_and_test(False, 1, tf.nn.sigmoid, 2000, 50)
100%|██████████| 2000/2000 [00:01<00:00, 1167.28it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
As you can see, even though these parameters work well for both networks, the one with batch normalization gets over 90% in 400 or so batches, whereas the other takes over 1700. When training larger networks, these sorts of differences become more pronounced. **The following creates two networks using a ReLU activation...
train_and_test(False, 2, tf.nn.relu)
100%|██████████| 50000/50000 [00:35<00:00, 1412.09it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
With this very large learning rate, the network with batch normalization trains fine and almost immediately manages 98% accuracy. However, the network without normalization doesn't learn at all. **The following creates two networks using a sigmoid activation function, a learning rate of 2, and reasonable starting weigh...
train_and_test(False, 2, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:35<00:00, 1395.37it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Once again, using a sigmoid activation function with the larger learning rate works well both with and without batch normalization.However, look at the plot below where we train models with the same parameters but only 2000 iterations. As usual, batch normalization lets it train faster.
train_and_test(False, 2, tf.nn.sigmoid, 2000, 50)
100%|██████████| 2000/2000 [00:01<00:00, 1170.27it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose random values with a standard deviation of 5. If you were really training a neural network, you would **not** want to do this. But these examples demonstr...
train_and_test(True, 0.01, tf.nn.relu)
100%|██████████| 50000/50000 [00:43<00:00, 1147.21it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
As the plot shows, without batch normalization the network never learns anything at all. But with batch normalization, it actually learns pretty well and gets to almost 80% accuracy. The starting weights obviously hurt the network, but you can see how well batch normalization does in overcoming them. **The following c...
train_and_test(True, 0.01, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:45<00:00, 1108.50it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Using a sigmoid activation function works better than the ReLU in the previous example, but without batch normalization it would take a tremendously long time to train the network, if it ever trained at all. **The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting w...
train_and_test(True, 1, tf.nn.relu)
100%|██████████| 50000/50000 [00:38<00:00, 1313.14it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
The higher learning rate used here allows the network with batch normalization to surpass 90% in about 30 thousand batches. The network without it never gets anywhere. **The following creates two networks using a sigmoid activation function, a learning rate of 1, and bad starting weights.**
train_and_test(True, 1, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:35<00:00, 1409.45it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
Using sigmoid works better than ReLUs for this higher learning rate. However, you can see that without batch normalization, the network takes a long time tro train, bounces around a lot, and spends a long time stuck at 90%. The network with batch normalization trains much more quickly, seems to be more stable, and achi...
train_and_test(True, 2, tf.nn.relu)
100%|██████████| 50000/50000 [00:35<00:00, 1392.83it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
We've already seen that ReLUs do not do as well as sigmoids with higher learning rates, and here we are using an extremely high rate. As expected, without batch normalization the network doesn't learn at all. But with batch normalization, it eventually achieves 90% accuracy. Notice, though, how its accuracy bounces aro...
train_and_test(True, 2, tf.nn.sigmoid)
100%|██████████| 50000/50000 [00:35<00:00, 1401.19it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
In this case, the network with batch normalization trained faster and reached a higher accuracy. Meanwhile, the high learning rate makes the network without normalization bounce around erratically and have trouble getting past 90%. Full Disclosure: Batch Normalization Doesn't Fix EverythingBatch normalization isn't ma...
train_and_test(True, 1, tf.nn.relu)
100%|██████████| 50000/50000 [00:36<00:00, 1386.17it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
When we used these same parameters [earlier](successful_example_lr_1), we saw the network with batch normalization reach 92% validation accuracy. This time we used different starting weights, initialized using the same standard deviation as before, and the network doesn't learn at all. (Remember, an accuracy around 10%...
train_and_test(True, 2, tf.nn.relu)
100%|██████████| 50000/50000 [00:35<00:00, 1398.39it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
When we trained with these parameters and batch normalization [earlier](successful_example_lr_2), we reached 90% validation accuracy. However, this time the network _almost_ starts to make some progress in the beginning, but it quickly breaks down and stops learning. **Note:** Both of the above examples use *extremely*...
def fully_connected(self, layer_in, initial_weights, activation_fn=None): """ Creates a standard, fully connected layer. Its number of inputs and outputs will be defined by the shape of `initial_weights`, and its starting weight values will be taken directly from that same parameter. If `self.use_batch_...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
This version of `fully_connected` is much longer than the original, but once again has extensive comments to help you understand it. Here are some important points:1. It explicitly creates variables to store gamma, beta, and the population mean and variance. These were all handled for us in the previous version of the ...
def batch_norm_test(test_training_accuracy): """ :param test_training_accuracy: bool If True, perform inference with batch normalization using batch mean and variance; if False, perform inference with batch normalization using estimated population mean and variance. """ weights = [np.ra...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
In the following cell, we pass `True` for `test_training_accuracy`, which performs the same batch normalization that we normally perform **during training**.
batch_norm_test(True)
100%|██████████| 2000/2000 [00:03<00:00, 514.57it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
As you can see, the network guessed the same value every time! But why? Because during training, a network with batch normalization adjusts the values at each layer based on the mean and variance **of that batch**. The "batches" we are using for these predictions have a single input each time, so their values _are_ the...
batch_norm_test(False)
100%|██████████| 2000/2000 [00:03<00:00, 511.58it/s]
MIT
batch-norm/Batch_Normalization_Lesson.ipynb
JJINDAHOUSE/deep-learning
0. Environment Setting
import pandas as pd import numpy as np import time import tensorflow as tf import tensorflow.keras as keras from keras.models import load_model from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences start_time = time.time() # 학습완료된 모델, 전처리 완료된 데이터 다운로...
_____no_output_____
MIT
Demo of LSTM_Sentiment_Classification_KOR.ipynb
yool-seoul/sentiment_analysis_lstm
1. Data loading
MAX_LEN = 50 VOCAB_SIZE = 13648 # Tokenizer 인코딩을 위한 학습용 엑셀 파일읽어들이기 약 30초 걸림. df1 = pd.read_excel('./demo_sentiment.xlsx', sheet_name='Train') def tokenize(s): return ['/'.join(t) for t in m.pos(s)] train_docs = [tokenize(row[1]['sentence']) for row in df1.iterrows()] tokenizer = Tokenizer(num_words = VOCAB_SIZE) tok...
Elapsed time for ready : 00:01:11
MIT
Demo of LSTM_Sentiment_Classification_KOR.ipynb
yool-seoul/sentiment_analysis_lstm
2. Ready to test
# 이용자가 알아보기 쉽게 결과를 분석해서 출력해 주는 함수들. def sentiment_predict(sentence, log=False): sentences = tokenize(sentence) encoded = tokenizer.texts_to_sequences([sentences]) padded = pad_sequences(encoded, maxlen=MAX_LEN) score = loaded_model.predict(padded) if log: print('Predict score: ', score) return score de...
_____no_output_____
MIT
Demo of LSTM_Sentiment_Classification_KOR.ipynb
yool-seoul/sentiment_analysis_lstm
Sequence Classification with LSTM on MNIST Table of contents- Introduction- Architectures- Long Short-Term Memory Model (LSTM)- Building a LSTM with TensorFlow IntroductionRecurrent Neural Networks are Deep Learning models with simple structures and a feedback mechanism builted-in, or in different words, the output ...
%matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets(".", one_hot=True)
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes. Extracting ./train-images-idx3-ubyte.gz Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes. Extracting ./train-labels-idx1-ubyte.gz Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes. Extracting ./t10k-images-idx3-ubyte.gz Succes...
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
The function **`input_data.read_data_sets(...)`** loads the entire dataset and returns an object **`tensorflow.contrib.learn.python.learn.datasets.mnist.DataSets`**The argument **(`one_hot=True`)** creates the label arrays as 10-dimensional binary vectors (only zeros and ones), in which the index cell for the number on...
train_imgs = mnist.train.images train_labels = mnist.train.labels test_imgs = mnist.test.images test_labels = mnist.test.labels n_train = train_imgs.shape[0] n_test = test_imgs.shape[0] dim = train_imgs.shape[1] n_classes = train_labels.shape[1] print("Train Images:", train_imgs.shape) print("Train Labels:", train_la...
Train Images: (55000, 784) Train Labels: (55000, 10) Test Images: (10000, 784) Test Labels: (10000, 10)
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Let's get one sample, just to understand the structure of MNIST dataset The next code snippet prints the **label vector** (one_hot format), **the class** and actual sample formatted as **image**:
samplesIdx = [100, 101, 102] # Change these numbers here to see other samples. from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax1 = fig.add_subplot(121) ax1.imshow(test_imgs[samplesIdx[0]].reshape([28, 28]), cmap='gray') xx, yy = np.meshgrid(np.linspace(0, 28, 28), np.linspace(0, 28, 28)) X = xx Y = yy ...
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
--- Let's understand the parameters, inputs and outputsWe will treat the MNIST image $\in \mathcal{R}^{28 \times 28}$ as $28$ sequences of a vector $\mathbf{x} \in \mathcal{R}^{28}$. Our simple RNN consists of: 1. One input layer which converts a $28*28$ dimensional input to an $128$ dimensional hidden layer, 2. One ...
n_input = 28 # MNIST data input (img shape: 28*28). n_steps = 28 # Timesteps. n_hidden = 128 # Hidden layer number of features. n_classes = 10 # MNIST total classes (0-9 digits). learning_rate = 0.001 training_iters = 100000 batch_size = 100 display_step = 10
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Construct a Recurrent Neural Network The input should be a Tensor of shape: [batch_size, time_steps, input_dimension], but in our case it would be (?, 28, 28)
x = tf.placeholder(dtype="float", shape=[None, n_steps, n_input], name="x") # Current data input shape: (batch_size, n_steps, n_input) [100x28x28] y = tf.placeholder(dtype="float", shape=[None, n_classes], name="y")
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Lets create the weights and biases for the read out layer.
weights = { 'out': tf.Variable(tf.random_normal([n_hidden, n_classes])) } biases = { 'out': tf.Variable(tf.random_normal([n_classes])) }
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Lets define a lstm cell with tensorflow.
lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
__dynamic_rnn__ creates a recurrent neural network specified from __lstm_cell__:
outputs, states = tf.nn.dynamic_rnn(lstm_cell, inputs=x, dtype=tf.float32)
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
The output of the RNN would be a [100x28x128] matrix. We use the linear activation to map it to a [?x10] matrix.
output = tf.reshape(tf.split(outputs, 28, axis=1, num=None, name='split')[-1], [-1,128]) pred = tf.matmul(output, weights['out']) + biases['out'] pred
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Now, we define the cost function and optimizer:
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Here we define the accuracy and evaluation methods to be used in the learning process:
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
Just recall that we will treat the MNIST image $\in \mathcal{R}^{28 \times 28}$ as $28$ sequences of a vector $\mathbf{x} \in \mathcal{R}^{28}$.
init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) step = 1 # Keep training until reach max iterations. while step * batch_size < training_iters: # We will read a batch of 100 images [100 x 784] as batch_x # batch_y is a matrix of [100x10] batch_x...
_____no_output_____
MIT
Recurrent Neural Networks/LSTM-MNIST.ipynb
KostadinPlachkov/DeepLearning
通过Sub-Pixel实现图像超分辨率**作者:** [Ralph LU](https://github.com/ralph0813)**日期:** 2022.4 **摘要:** 本示例通过Sub-Pixel实现图像超分辨率。 一、简要介绍在计算机视觉中,图像超分辨率(Image Super Resolution)是指由一幅低分辨率图像或图像序列恢复出高分辨率图像。图像超分辨率技术分为超分辨率复原和超分辨率重建。本示例简要介绍如何通过飞桨开源框架,实现图像超分辨率。包括数据集的定义、模型的搭建与训练。参考论文:《Real-Time Single Image and Video Super-Resolution Using an ...
import os import io import math import random import numpy as np import matplotlib.pyplot as plt from PIL import Image from IPython.display import display import paddle from paddle.io import Dataset from paddle.vision.transforms import transforms print(paddle.__version__)
2.3.0-rc0
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
三、数据集 3.1 数据集下载本案例使用BSR_bsds500数据集,下载链接:http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz
!wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz !tar -zxvf BSR_bsds500.tgz
_____no_output_____
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
3.2 数据集概览```BSR├── BSDS500│   └── data│   ├── groundTruth│   │   ├── test│   │   ├── train│   │   └── val│   └── images│   ├── test│   ├── train│   └── val├── bench│   ├── benchmarks│   ├── data│   │   ├── ...│   │   └── ...│   └── source└── documentation```可以看到需要的图片文件在BSR/B...
class BSD_data(Dataset): """ 继承paddle.io.Dataset类 """ def __init__(self, mode='train',image_path="BSR/BSDS500/data/images/"): """ 实现构造函数,定义数据读取方式,划分训练和测试数据集 """ super(BSD_data, self).__init__() self.mode = mode.lower() if self.mode == 'train': ...
_____no_output_____
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
3.4 PetDataSet数据集抽样展示实现好BSD_data数据集后,我们来测试一下数据集是否符合预期,因为BSD_data是一个可以被迭代的Class,我们通过for循环从里面读取数据进行展示。
# 测试定义的数据集 train_dataset = BSD_data(mode='train') val_dataset = BSD_data(mode='val') print('=============train dataset=============') x, y = train_dataset[0] x = x[0] y = y[0] x = x * 255 y = y * 255 img_ = Image.fromarray(np.uint8(x), mode="L") img = Image.fromarray(np.uint8(y), mode="L") display(img_) display(img_.s...
=============train dataset=============
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
四、模型组网Sub_Pixel_CNN是一个全卷积网络,网络结构比较简单,这里采用Layer类继承方式组网。
class Sub_Pixel_CNN(paddle.nn.Layer): def __init__(self, upscale_factor=3, channels=1): super(Sub_Pixel_CNN, self).__init__() self.conv1 = paddle.nn.Conv2D(channels,64,5,stride=1, padding=2) self.conv2 = paddle.nn.Conv2D(64,64,3,stride=1, padding=1) self.conv3 = paddle.nn.C...
_____no_output_____
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
4.1 模型封装
# 模型封装 model = paddle.Model(Sub_Pixel_CNN())
W0422 19:56:08.608785 191 gpu_context.cc:244] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 10.1, Runtime API Version: 10.1 W0422 19:56:08.614269 191 gpu_context.cc:272] device: 0, cuDNN Version: 7.6.
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
4.2 模型可视化调用飞桨提供的summary接口对组建好的模型进行可视化,方便进行模型结构和参数信息的查看和确认。
model.summary((1,1, 100, 100))
--------------------------------------------------------------------------- Layer (type) Input Shape Output Shape Param # =========================================================================== Conv2D-1 [[1, 1, 100, 100]] [1, 64, 100, 100] 1,664 Conv2D-2 [[1,...
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
五、模型训练 5.1 启动模型训练使用模型代码进行Model实例生成,使用prepare接口定义优化器、损失函数和评价指标等信息,用于后续训练使用。在所有初步配置完成后,调用fit接口开启训练执行过程,调用fit时只需要将前面定义好的训练数据集、测试数据集、训练轮次(Epoch)和批次大小(batch_size)配置好即可。
model.prepare(paddle.optimizer.Adam(learning_rate=0.001,parameters=model.parameters()), paddle.nn.MSELoss() ) # 启动模型训练,指定训练数据集,设置训练轮次,设置每次数据集计算的批次大小,设置日志格式 model.fit(train_dataset, epochs=20, batch_size=16, verbose=1)
The loss value printed in the log is the current step, and the metric is the average value of previous steps. Epoch 1/20
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
六、模型预测 6.1 预测我们可以直接使用model.predict接口来对数据集进行预测操作,只需要将预测数据集传递到接口内即可。
predict_results = model.predict(val_dataset)
Predict begin... step 100/100 [==============================] - 8ms/step Predict samples: 100
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
6.2 定义预测结果可视化函数
import math import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset def psnr(img1, img2): """ PSMR计算函数 """ mse = np.mean( (img1/255. - img2/255.) ** 2 ) if mse < 1.0e-10: return 100 ...
_____no_output_____
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
6.3 执行预测从我们的预测数据集中抽1个张图片来看看预测的效果,展示一下原图、小图和预测结果。
main(model,'BSR/BSDS500/data/images/test/100007.jpg')
Predict begin... step 1/1 [==============================] - 4ms/step Predict samples: 1
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
7.模型保存将模型保存到 checkpoint/model_final ,并保留训练参数
model.save('checkpoint/model_final',training=True)
_____no_output_____
Apache-2.0
docs/practices/cv/super_resolution_sub_pixel.ipynb
nemonameless/docs
Science Case 4: NGC3504 The galaxy NGC3504 has been observed in two unrelated ALMA projects, both in band 6 at at 230 GHz, cause for an interesting comparison.1. **2016.1.00650.S** - one 7m and two 12m observations of just NGC3504, to study flow in a bar2. **2017.1.00964.S** - a collection of 7 galaxies with the pur...
%matplotlib inline import matplotlib.pyplot as plt source = "NGC3504"
_____no_output_____
MIT
notebooks/Case4.ipynb
teuben/study7
astroquery.almaFirst we should query the science archive, we can do https://almascience.nrao.edu/aq/ as well, but we want also show this via the notebook.
from astroquery.alma import Alma import pandas as pd # display the whole table in the notebook pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth',25) # more to come here. here we just want to show how much you can...
[b'2017.1.00964.S' b'2016.1.00650.S'] [b'uid://A001/X1288/Xba6' b'uid://A001/X1288/Xba8' b'uid://A001/X87a/X70a' b'uid://A001/X87a/X708' b'uid://A001/X87a/X706']
MIT
notebooks/Case4.ipynb
teuben/study7
Thus we have indeed two projects,and five observations across those two.Lets print how many beams we have across the image
ci=['obs_id','s_fov','s_resolution'] n['nres'] = 3600*n['s_fov']/n['s_resolution'] print(n[ci])
obs_id s_fov s_resolution deg deg --------------------- -------------------- -------------------- uid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106 uid://A001/X1288/Xba6 0.006863718695429476 0.034121085407438106 ...
MIT
notebooks/Case4.ipynb
teuben/study7
Notice there appears to be a units issue with s_resolution: they appear to be in arcsec. There is also a 'spatial_resolution', but it has the same issue. astroquery.admit
from astroquery.admit import ADMIT import pandas as pd pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth',25) a = ADMIT() a.check()
Found /home/teuben/ALMA/study7/query/admit.db Checking db.... 0 71 71 71 Database version: 27-feb-2022. core.py version: 26-feb-2022 header : 1 entries alma : 124 entries win : 123 entries lines : 33 entries sources : 769 entries
MIT
notebooks/Case4.ipynb
teuben/study7
ContinuumFirst we want to see if any continuum is detected, so we select all windows with one channel.
p = a.query(source_name_alma=source,nchan=1,flux='>0') print(p.shape) a.key_description.show_in_notebook(display_length=20)
_____no_output_____
MIT
notebooks/Case4.ipynb
teuben/study7
We collect a few observables: observing time, as well as peak and flux and the resolutionNote we need to clean up the units
ci=['obs_id','spw','nsources','t_min', 'flux', 'peak_s','fop','bmaj_arcsec','smaj_arcsec'] p['fop'] = p['flux']/p['peak_s'] p['bmaj_arcsec'] = p['bmaj'] * 3600 p['smaj_arcsec'] = p['smaj'] * 3600 print(p[ci])
obs_id spw nsources t_min flux \ 0 uid://A001/X1288/Xba6 spw21 1 58050.543677 0.000860 1 uid://A001/X1288/Xba8 spw19 1 58119.297186 0.001110 2 uid://A001/X1288/Xba8 spw21 1 58119.297186 0.001240 3 ...
MIT
notebooks/Case4.ipynb
teuben/study7
It's a little surprising that flux/peak is 1.5 for the lowest and highest resolution array data, but there clearly is something very odd about the middle resolution (X708) data.
plt.scatter(p['t_min'],p['flux']); plt.title(source + " continuum lightcurve") plt.xlabel('MJD') plt.ylabel('Flux (Jy)');
_____no_output_____
MIT
notebooks/Case4.ipynb
teuben/study7
well, the fluxes are somewhat all over the place..... averaging 10-15 mJy.The other dataset of NGC3504 at mjd > 58000 seems to have lost a lot of flux.Here is a figure of the continuum source, as seen in the three different ALMA confirmation. Figures have been taking from ADMIT, including where sources were detected. A...
p = a.query(source_name_alma=source,nchan='>1',mom0flux='>0') p = a.query(nchan='>1',mom0flux='>0') print(p.shape) print(p.columns) ci=['obs_id','spw','restfreq','formula','mom0flux','mom1peak','mom2peak'] ci=['spw','restfreq','formula','mom0flux','mom1peak','vlsr','mom2peak','nlines'] print(p[ci])
spw restfreq formula mom0flux mom1peak vlsr mom2peak \ 0 spw21 243.48293 H2COH+ 1863.8500 1457.430 1447.989431 31.01830 1 spw23 244.59816 HCOOH 4235.2400 1427.340 1447.989431 31.75560 2 spw23 244.59816 HCOOH 313.3270 1420.510 1447.989431 38.15480 3 ...
MIT
notebooks/Case4.ipynb
teuben/study7
[SOLUTION] Attention BasicsIn this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attention in a real-world model, a lot of the focus goes into piping the data and juggling the various vectors rather than the...
dec_hidden_state = [5,1,20]
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Let's visualize this vector:
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Let's visualize our decoder hidden state plt.figure(figsize=(1.5, 4.5)) sns.heatmap(np.transpose(np.matrix(dec_hidden_state)), annot=True, cmap=sns.light_palette("purple", as_cmap=True), linewidths=1)
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Our first scoring function will score a single annotation (encoder hidden state), which looks like this:
annotation = [3,12,45] #e.g. Encoder hidden state # Let's visualize the single annotation plt.figure(figsize=(1.5, 4.5)) sns.heatmap(np.transpose(np.matrix(annotation)), annot=True, cmap=sns.light_palette("orange", as_cmap=True), linewidths=1)
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
IMPLEMENT: Scoring a Single AnnotationLet's calculate the dot product of a single annotation. NumPy's [dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) is a good candidate for this operation
def single_dot_attention_score(dec_hidden_state, enc_hidden_state): # TODO: return the dot product of the two vectors return np.dot(dec_hidden_state, enc_hidden_state) single_dot_attention_score(dec_hidden_state, annotation)
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Annotations MatrixLet's now look at scoring all the annotations at once. To do that, here's our annotation matrix:
annotations = np.transpose([[3,12,45], [59,2,5], [1,43,5], [4,3,45.3]])
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
And it can be visualized like this (each column is a hidden state of an encoder time step):
# Let's visualize our annotation (each column is an annotation) ax = sns.heatmap(annotations, annot=True, cmap=sns.light_palette("orange", as_cmap=True), linewidths=1)
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
IMPLEMENT: Scoring All Annotations at OnceLet's calculate the scores of all the annotations in one step using matrix multiplication. Let's continue to us the dot scoring methodTo do that, we'll have to transpose `dec_hidden_state` and [matrix multiply](https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul....
def dot_attention_score(dec_hidden_state, annotations): # TODO: return the product of dec_hidden_state transpose and enc_hidden_states return np.matmul(np.transpose(dec_hidden_state), annotations) attention_weights_raw = dot_attention_score(dec_hidden_state, annotations) attention_weights_raw
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Looking at these scores, can you guess which of the four vectors will get the most attention from the decoder at this time step? SoftmaxNow that we have our scores, let's apply softmax:
def softmax(x): x = np.array(x, dtype=np.float128) e_x = np.exp(x) return e_x / e_x.sum(axis=0) attention_weights = softmax(attention_weights_raw) attention_weights
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Even when knowing which annotation will get the most focus, it's interesting to see how drastic softmax makes the end score become. The first and last annotation had the respective scores of 927 and 929. But after softmax, the attention they'll get is 0.119 and 0.880 respectively. Applying the scores back on the annota...
def apply_attention_scores(attention_weights, annotations): # TODO: Multiple the annotations by their weights return attention_weights * annotations applied_attention = apply_attention_scores(attention_weights, annotations) applied_attention
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Let's visualize how the context vector looks now that we've applied the attention scores back on it:
# Let's visualize our annotations after applying attention to them ax = sns.heatmap(applied_attention, annot=True, cmap=sns.light_palette("orange", as_cmap=True), linewidths=1)
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Contrast this with the raw annotations visualized earlier in the notebook, and we can see that the second and third annotations (columns) have been nearly wiped out. The first annotation maintains some of its value, and the fourth annotation is the most pronounced. Calculating the Attention Context VectorAll that remai...
def calculate_attention_vector(applied_attention): return np.sum(applied_attention, axis=1) attention_vector = calculate_attention_vector(applied_attention) attention_vector # Let's visualize the attention context vector plt.figure(figsize=(1.5, 4.5)) sns.heatmap(np.transpose(np.matrix(attention_vector)), annot=Tr...
_____no_output_____
MIT
attention/Attention_Basics_Solution.ipynb
Muhanad23/udacity-deep-learning-nanodegree
Open Machine Learning CourseAuthor: Mariya Mansurova, Analyst & developer in Yandex.Metrics team. Translated by Ivan Zakharov, ML enthusiast.All content is distributed under the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. Assignment 9 (demo) Time series analysis ...
import pandas as pd import os from plotly import __version__ from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot from plotly import graph_objs as go import requests import pandas as pd print(__version__) # need 1.9.0 or greater init_notebook_mode(connected = True) def plotly_df(df, title =...
2.7.0
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
Data preparationFirst, read the data in as a `dataframe`. Today we will predict the number of views of the [Machine Learning](https://en.wikipedia.org/wiki/Machine_learning) wiki page. I downloaded the data using the [Wikipediatrend](https://www.r-bloggers.com/using-wikipediatrend/) library for `R`.
df = pd.read_csv('../../data/wiki_machine_learning.csv', sep = ' ') df = df[df['count'] != 0] df.head() df.shape df.date = pd.to_datetime(df.date) plotly_df(df.set_index('date')[['count']])
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
Predicting with Facebook ProphetWe will build a prediction using the simple library `Facebook Prophet`. In order to evaluate the quality of the model, we drop the last 30 days from the training sample.
from fbprophet import Prophet predictions = 30 df = df[['date', 'count']] df.columns = ['ds', 'y'] train_df = df[:-predictions].copy() # Your code here
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
** Question 1: ** What is the prediction of the number of views of the wiki page on January 20? Round to the nearest integer.- 4947- 3833- 5229- 2744 Estimate the quality of the prediction with the last 30 points.
# Your code here
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
** Question 2 **: What is MAPE equal to?- 38.38- 42.42- 5.39- 65.91 ** Question 3 **: What is MAE equal to?- 355- 4007- 713- 903 Predicting with ARIMA
%matplotlib inline import matplotlib.pyplot as plt from scipy import stats import statsmodels.api as sm
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
** Question 4: ** Let's verify the stationarity of the series using the Dickey-Fuller test. Is the series stationary? What is the p-value?- Series is stationary, p_value = 0.107- Series is not stationary, p_value = 0.107- Series is stationary, p_value = 0.001- Series is not stationary, p_value = 0.001
# Your code here
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
** Question 5 **: Next, we turn to the construction of the SARIMAX model (`sm.tsa.statespace.SARIMAX`). What is the best set of parameters (among listed) for the SARIMAX model according to the `AIC` criterion?- D = 1, d = 0, Q = 0, q = 2, P = 3, p = 1- D = 2, d = 1, Q = 1, q = 2, P = 3, p = 1- D = 1, d = 1, Q = 1, q = ...
# Your code here
_____no_output_____
MIT
assignments/demo/assignment09_time_series.ipynb
geomars/oldschool
Bruner Eduardo Augusto Albrecht Case - Data EngineeringApós a compra de um produto através do Olist, o vendedor recebe uma notificação para começar a processar o pedido e o cliente recebe uma estimativa de data de entrega. Possivelmente, nem todas as decisões da empresa foram acertadas no quesito de carteira de produ...
#Carregando as bibliotecas import pandas as pd import matplotlib.pyplot as plt print("Setup Complete") #carreagando os datasets para os dataframes #Informação geográfica sobre os vendedores sellers = pd.read_csv('sellers_dataset.csv',index_col = 'seller_id', parse_dates=True) #Informação geográfica sobre os clientes...
<class 'pandas.core.frame.DataFrame'> Index: 112650 entries, 00010242fe8c5a6d1ba2dd792cb16214 to fffe41c64501cc87c801fd61db3f6244 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 order_item_id 112650 non-null int64 1 ...
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
Análise para Vendas: >**Vendas por Estado**
orders_by_state = pd.merge(left = customers, right = orders, on='customer_id', right_index=False) orders_by_state result = orders_by_state.groupby(['customer_state'])['customer_id'].count() print(result) result.plot()
customer_state AC 81 AL 413 AM 148 AP 68 BA 3380 CE 1336 DF 2140 ES 2033 GO 2020 MA 747 MG 11635 MS 715 MT 907 PA 975 PB 536 PE 1652 PI 495 PR 5045 RJ 12852 RN 485 RO 253 RR 46 RS 5466 SC 3637 SE 350 SP ...
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
>**vendas por dia/semana/mês no marketplace:**> * Seria interesente quando montasse o dataframe ter conhecimento sobre cada um dos dados, pois assim poderiamos aplicar o dtype para adeguar os dados à sua melhor forma
orders["Day"] = orders["order_approved_at"].apply(lambda x: pd.Timestamp(x).day_name()) #orders["Day"] = pd.to_datetime(orders["order_purchase_timestamp"]).dt.isocalendar().day #dias da semana em números,1->7 orders["Week"] = pd.to_datetime(orders["order_approved_at"]).dt.isocalendar().week orders["Month"] = orders["...
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
>**Quais são as quantidades de produtos que cada vendedor vende?**
products_by_sellers = items.groupby(['seller_id', 'product_id']).size().reset_index() products_by_sellers.sort_values(0, ascending=False) products_by_sellers = products_by_sellers.rename(columns={'seller_id':'Seller_id','product_id':'Product_id',0:'Qntd'}) products_by_sellers
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
>**Taxa de conversão (%) = (Número de pedidos de uma dado vendendor / número de visitantes no site) x 100**> * Levando em conta os números de pedidos já enviados( ou que o pagamentga já foi aceito)/ pelo núemro de customer_unique_id
items #dar merge para uma nova tabela number_of_clients= len(customers.index) orders_by_sellers = items.groupby(['seller_id', 'order_id'])['order_id'].count().reset_index() orders_by_sellers.sort_values(0, ascending=False) orders_by_sellers = orders_by_sellers.rename(columns={'seller_id':'Seller_id','order_id':'Order_i...
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
>**Qual método de compra se sobresai?**
most_payments_methods =payments.groupby(['payment_type'])['payment_type'].count() most_payments_methods.plot.bar()
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio
Análise para Produtos: > **Quais produtos são mais comprados (Top 10 produtos mais comprados)**
top_items = items.groupby(['product_id']).size().reset_index() top_items = top_items.set_index('product_id') top_items = top_items.rename(columns={0:'Qntd'}) top_items = top_items.sort_values('Qntd', ascending=False) top_items.head(10) #top_items.head(10).plot.barh()
_____no_output_____
MIT
DataScience/Olist/EnfaseLabs.ipynb
brunereduardo/DataPortfolio