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
|
---|---|---|---|---|---|
**Summary**- The user visit count is very high for Chrome but Firefox users have genereted more revenue Device Category | count_mean('device.deviceCategory',"#FF851B","#FF4136") | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- Desktop site has generated more user count as well as more revenue- One thing to note is tablet users have generated almost same revenue as mobile users Operating system | count_mean('device.operatingSystem',"#80DEEA","#0097A7") | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- Less chrome OS users but high revenue is generated.-For windows phone users also generated good revenue. Continent Based | count_mean('geoNetwork.continent',"#F48FB1","#C2185B") | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- African Users have generated more than a billion mean revenue.- Users from american have used the website a lot but didnt purchased products. Country Based | data = train_df[['geoNetwork.country','totals.transactionRevenue']][(train_df['totals.transactionRevenue'] >1)]
temp = data.groupby('geoNetwork.country',as_index=False)['totals.transactionRevenue'].mean()
temp['code'] = 'sample'
for i,country in enumerate(temp['geoNetwork.country']):
mapping = {country.name: country.alpha_3 for country in pycountry.countries}
temp.set_value(i,'code',mapping.get(country))
chart = [ dict(
type = 'choropleth',
locations = temp['code'],
z = temp['totals.transactionRevenue'],
text = temp['geoNetwork.country'],
autocolorscale = True,
reversescale = True,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
autotick = True,
title = 'Mean Revenue'),
) ]
layout = dict(
title = 'Mean revenue based on country',
geo = dict(
showframe = True,
showcoastlines = True,
showocean = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict( data=chart, layout=layout )
py.iplot( fig, validate=False) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- We can see the revenue generated based on the countries- only 4 countries in africa have generated huge mean revenue. Metro Based | count_mean('geoNetwork.metro',"#CE93D8", "#7B1FA2") | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- Most of the users metro location is not present in the dataset.- may be we have to assume some hypothesis here Network Domain | count_mean('geoNetwork.networkDomain','#90CAF9','#1976D2') | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- Most users who generate revenue uses digitalwest.net- Again same we have huge users count from unknown source/ (not set) Region | count_mean('geoNetwork.region','#DCE775','#AFB42B') | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary**- Tokyo has generated more than 1 Billion mean revenue Sub Continent Based | count_mean('geoNetwork.subContinent','#FFE082','#FFA000') | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- No surprise Africa stands top in mean revenue Page view V/S bounces | train_df['totals.pageviews'] = train_df['totals.pageviews'].fillna(0).astype('int32')
train_df['totals.bounces'] = train_df['totals.bounces'].fillna(0).astype('int32')
pageview = train_df.groupby('date')['totals.pageviews'].apply(lambda x:x[x >= 1].count()).reset_index()
bounce = train_df.groupby('date')['totals.bounces'].apply(lambda x:x[x >= 1].count()).reset_index()
pageviews = go.Scatter(x = pageview['date'],y= pageview['totals.pageviews'], name = 'Pageview',marker=dict(color = "#B0BEC5"))
bounces = go.Scatter(x = bounce['date'],y= bounce['totals.bounces'],name = 'Bounce',marker=dict(color = "#37474F"))
py.iplot([pageviews,bounces]) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
**Summary**- We can see the based on pageview we have increase/decrease of bounce rate new cusotmer or old customer | train_df['totals.newVisits'] = train_df['totals.newVisits'].fillna(0).astype('int32')
train_df['totals.hits'] = train_df['totals.hits'].fillna(0).astype('int32')
newvisit = train_df.groupby('date')['totals.newVisits'].apply(lambda x:x[x == 1].count()).reset_index()
oldVisit = train_df.groupby('date')['totals.newVisits'].apply(lambda x:x[x == 0].count()).reset_index()
hit = train_df.groupby('date')['totals.hits'].apply(lambda x:x[x >= 1].count()).reset_index()
hits = go.Scatter(x = hit['date'],y = hit['totals.hits'], name = 'total hits', marker=dict(color = '#FFEE58'))
new_vist = go.Scatter(x = newvisit['date'],y= newvisit['totals.newVisits'],name = 'New Vists', marker=dict(color = '#F57F17'))
oldvisit = go.Scatter(x = oldVisit['date'],y = oldVisit['totals.newVisits'], name = 'Old Visit', marker=dict(color = '#FFD600'))
py.iplot([hits, new_vist, oldvisit]) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- Out of all the hits we have more new visit than old visit- That means the returning customer is very less than the new customers.- Or there can be other meaning. Minmum & maximum revenue on daily basis | temp = train_df[(train_df['totals.transactionRevenue'] >0)]
data = temp[['totals.transactionRevenue','date']].groupby('date')['totals.transactionRevenue'].agg(['min','max']).reset_index()
mean = go.Scatter(x = data['date'], y = data['min'],name = "Min",marker = dict(color = '#00E676'))
count = go.Scatter(x = data['date'],y = data['max'], name = "Max",marker = dict(color = '#00838F'))
py.iplot([mean,count]) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- I have removed all the non-zero transaction.- This graph is to understand the minimum and maximum revenue the company generates.- 5th april the company generated the maximum revenue.- there are few days where the maximum and minimum revenue are same(Eg - 15 Jan 2017) Revenue based on month | train_df['month'] = train_df['date'].dt.month
train_df['day'] = train_df['date'].dt.day
train_df['weekday'] = train_df['date'].dt.weekday
temp = train_df.groupby('month')['totals.transactionRevenue'].agg(['count','mean']).reset_index()
count_chart = go.Bar(x = temp['month'], y = temp['count'],name = 'Count',marker = dict(color = "#E6EE9C"))
mean_chart = go.Bar(x = temp['month'],y = temp['mean'], name = 'Mean',marker = dict(color = "#AFB42B"))
fig = tools.make_subplots(rows = 1, cols = 2, subplot_titles = ('Total Count', 'Mean Count'))
fig.append_trace(count_chart,1,1)
fig.append_trace(mean_chart, 1,2)
py.iplot(fig) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- It is seen that November month has higest number of visitors but the transaction generated in that month is very low.- April month has generated higest mean revenue while its visitors are not high. Revenue based on day | temp = train_df.groupby('day')['totals.transactionRevenue'].agg(['count','mean']).reset_index()
count_chart = go.Bar(x = temp['day'], y = temp['count'],name = 'Count', marker = dict(color = '#1DE9B6'))
mean_chart = go.Bar(x = temp['day'],y = temp['mean'], name = 'Mean', marker = dict(color = '#00796B'))
fig = tools.make_subplots(rows = 1, cols = 2, subplot_titles = ('Total Count', 'Mean Count'))
fig.append_trace(count_chart,1,1)
fig.append_trace(mean_chart, 1,2)
py.iplot(fig) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- It is seen that on 31th day the view count is very less I dont blame any because only Jan, Mar, May, Jul, Aug, Oct, Dec has 31 days.- But the intresting fact is that the 2nd highest mean revenue is on day 31st.- I think it can either be because of Jan or Dec as they are the start or end of the year. Revenue based on weekday | temp = train_df.groupby('weekday')['totals.transactionRevenue'].agg(['count','mean']).reset_index()
count_chart = go.Bar(x = temp['weekday'], y = temp['count'],name = 'Count', marker = dict(color = '#9575CD'))
mean_chart = go.Bar(x = temp['weekday'],y = temp['mean'], name = 'Mean', marker = dict(color = '#B388FF'))
fig = tools.make_subplots(rows = 1, cols = 2, subplot_titles = ('Total Count', 'Mean Count'))
fig.append_trace(count_chart,1,1)
fig.append_trace(mean_chart, 1,2)
py.iplot(fig) | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- Most of the revenue is generated on monday.- very less revenue is generated on weekend. Most Ad Content | train_df['trafficSource.adContent'] = train_df['trafficSource.adContent'].fillna('')
wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.adContent']))
plt.figure( figsize=(15,20))
plt.imshow(wordcloud2)
plt.axis("off")
plt.show() | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
** Summary **- Image speak for it self Keywords used by users | train_df['trafficSource.keyword'] = train_df['trafficSource.keyword'].fillna('')
wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.keyword']))
plt.figure( figsize=(20,20) )
plt.imshow(wordcloud2)
plt.axis("off")
plt.show() | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
Source from where users came | train_df['trafficSource.source'] = train_df['trafficSource.source'].fillna('')
wordcloud2 = WordCloud(width=800, height=400).generate(' '.join(train_df['trafficSource.source']))
plt.figure( figsize=(15,20) )
plt.imshow(wordcloud2)
plt.axis("off")
plt.show() | _____no_output_____ | MIT | 9 google customer revenue prediction/exploratory-google-store-analysis.ipynb | MLVPRASAD/KaggleProjects |
Facial Keypoint Detection This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with. Let's take a look at some examples of images and corresponding facial keypoints.Facial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face.--- Load and Visualize DataThe first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints. Training and Testing DataThis facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data.* 3462 of these images are training images, for you to use as you create a model to predict keypoints.* 2308 are test images, which will be used to test the accuracy of your model.The information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y).--- | # import the required libraries
import glob
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
key_pts_frame = pd.read_csv('data/training_frames_keypoints.csv')
n = 0
image_name = key_pts_frame.iloc[n, 0]
key_pts = key_pts_frame.iloc[n, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
print('Image name: ', image_name)
print('Landmarks shape: ', key_pts.shape)
print('First 4 key pts: {}'.format(key_pts[:4]))
# print out some stats about the data
print('Number of images: ', key_pts_frame.shape[0]) | Number of images: 3462
| MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Look at some imagesBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape. | def show_keypoints(image, key_pts):
"""Show image with keypoints"""
plt.imshow(image)
plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m')
# Display a few different types of images by changing the index n
# select an image by index in our data frame
n = 5
image_name = key_pts_frame.iloc[n, 0]
key_pts = key_pts_frame.iloc[n, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
plt.figure(figsize=(5, 5))
show_keypoints(mpimg.imread(os.path.join('data/training/', image_name)), key_pts)
plt.show() | /home/roy/anaconda3/envs/cvnd/lib/python3.6/site-packages/ipykernel_launcher.py:6: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
| MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Dataset class and TransformationsTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html). Dataset class``torch.utils.data.Dataset`` is an abstract class representing adataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network.Your custom dataset should inherit ``Dataset`` and override the followingmethods:- ``__len__`` so that ``len(dataset)`` returns the size of the dataset.- ``__getitem__`` to support the indexing such that ``dataset[i]`` can be used to get the i-th sample of image/keypoint data.Let's create a dataset class for our face keypoints dataset. We willread the CSV file in ``__init__`` but leave the reading of images to``__getitem__``. This is memory efficient because all the images are notstored in the memory at once but read as required.A sample of our dataset will be a dictionary``{'image': image, 'keypoints': key_pts}``. Our dataset will take anoptional argument ``transform`` so that any required processing can beapplied on the sample. We will see the usefulness of ``transform`` in thenext section. | from torch.utils.data import Dataset, DataLoader
class FacialKeypointsDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.key_pts_frame = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.key_pts_frame)
def __getitem__(self, idx):
image_name = os.path.join(self.root_dir,
self.key_pts_frame.iloc[idx, 0])
image = mpimg.imread(image_name)
# if image has an alpha color channel, get rid of it
if(image.shape[2] == 4):
image = image[:,:,0:3]
key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix()
key_pts = key_pts.astype('float').reshape(-1, 2)
sample = {'image': image, 'keypoints': key_pts}
if self.transform:
sample = self.transform(sample)
return sample | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Now that we've defined this class, let's instantiate the dataset and display some images. | # Construct the dataset
face_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',
root_dir='data/training/')
# print some stats about the dataset
print('Length of dataset: ', len(face_dataset))
# Display a few of the images from the dataset
num_to_display = 3
for i in range(num_to_display):
# define the size of images
fig = plt.figure(figsize=(20,10))
# randomly select a sample
rand_i = np.random.randint(0, len(face_dataset))
sample = face_dataset[rand_i]
# print the shape of the image and keypoints
print(i, sample['image'].shape, sample['keypoints'].shape)
ax = plt.subplot(1, num_to_display, i + 1)
ax.set_title('Sample #{}'.format(i))
# Using the same display function, defined earlier
show_keypoints(sample['image'], sample['keypoints'])
| 0 (157, 136, 3) (68, 2)
1 (295, 261, 3) (68, 2)
2 (147, 165, 3) (68, 2)
| MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
TransformsNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.Therefore, we will need to write some pre-processing code.Let's create four transforms:- ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1]- ``Rescale``: to rescale an image to a desired size.- ``RandomCrop``: to crop an image randomly.- ``ToTensor``: to convert numpy images to torch images.We will write them as callable classes instead of simple functions sothat parameters of the transform need not be passed everytime it'scalled. For this, we just need to implement ``__call__`` method and (if we require parameters to be passed in), the ``__init__`` method. We can then use a transform like this: tx = Transform(params) transformed_sample = tx(sample)Observe below how these transforms are generally applied to both the image and its keypoints. | import torch
from torchvision import transforms, utils
# tranforms
class Normalize(object):
"""Convert a color image to grayscale and normalize the color range to [0,1]."""
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
image_copy = np.copy(image)
key_pts_copy = np.copy(key_pts)
# convert image to grayscale
image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# scale color range from [0, 255] to [0, 1]
image_copy= image_copy/255.0
# scale keypoints to be centered around 0 with a range of [-1, 1]
# mean = 100, sqrt = 50, so, pts should be (pts - 100)/50
key_pts_copy = (key_pts_copy - 100)/50.0
return {'image': image_copy, 'keypoints': key_pts_copy}
class Rescale(object):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
"""
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
self.output_size = output_size
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
h, w = image.shape[:2]
if isinstance(self.output_size, int):
if h > w:
new_h, new_w = self.output_size * h / w, self.output_size
else:
new_h, new_w = self.output_size, self.output_size * w / h
else:
new_h, new_w = self.output_size
new_h, new_w = int(new_h), int(new_w)
img = cv2.resize(image, (new_w, new_h))
# scale the pts, too
key_pts = key_pts * [new_w / w, new_h / h]
return {'image': img, 'keypoints': key_pts}
class RandomCrop(object):
"""Crop randomly the image in a sample.
Args:
output_size (tuple or int): Desired output size. If int, square crop
is made.
"""
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
h, w = image.shape[:2]
new_h, new_w = self.output_size
top = np.random.randint(0, h - new_h)
left = np.random.randint(0, w - new_w)
image = image[top: top + new_h,
left: left + new_w]
key_pts = key_pts - [left, top]
return {'image': image, 'keypoints': key_pts}
class ToTensor(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample):
image, key_pts = sample['image'], sample['keypoints']
# if image has no grayscale color channel, add one
if(len(image.shape) == 2):
# add that third color dim
image = image.reshape(image.shape[0], image.shape[1], 1)
# swap color axis because
# numpy image: H x W x C
# torch image: C X H X W
image = image.transpose((2, 0, 1))
return {'image': torch.from_numpy(image),
'keypoints': torch.from_numpy(key_pts)} | _____no_output_____ | MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Test out the transformsLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size. | # test out some of these transforms
rescale = Rescale(100)
crop = RandomCrop(50)
composed = transforms.Compose([Rescale(250),
RandomCrop(224)])
# apply the transforms to a sample image
test_num = 500
sample = face_dataset[test_num]
fig = plt.figure()
for i, tx in enumerate([rescale, crop, composed]):
transformed_sample = tx(sample)
ax = plt.subplot(1, 3, i + 1)
plt.tight_layout()
ax.set_title(type(tx).__name__)
show_keypoints(transformed_sample['image'], transformed_sample['keypoints'])
plt.show() | /home/roy/anaconda3/envs/cvnd/lib/python3.6/site-packages/ipykernel_launcher.py:31: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
| MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Create the transformed datasetApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size). | # define the data tranform
# order matters! i.e. rescaling should come before a smaller crop
data_transform = transforms.Compose([Rescale(250),
RandomCrop(224),
Normalize(),
ToTensor()])
# create the transformed dataset
transformed_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',
root_dir='data/training/',
transform=data_transform)
# print some stats about the transformed data
print('Number of images: ', len(transformed_dataset))
# make sure the sample tensors are the expected size
for i in range(5):
sample = transformed_dataset[i]
print(i, sample['image'].size(), sample['keypoints'].size())
| Number of images: 3462
0 torch.Size([1, 224, 224]) torch.Size([68, 2])
1 torch.Size([1, 224, 224]) torch.Size([68, 2])
2 torch.Size([1, 224, 224]) torch.Size([68, 2])
3 torch.Size([1, 224, 224]) torch.Size([68, 2])
4 torch.Size([1, 224, 224]) torch.Size([68, 2])
| MIT | 1. Load and Visualize Data.ipynb | royveshovda/P1_Facial_Keypoints |
Processor temperatureWe have a temperature sensor in the processor of our company's server. We want to analyze the data provided to determinate whether we should change the cooling system for a better one. It is expensive and as a data analyst we cannot make decisions without a basis.We provide the temperatures measured throughout the 24 hours of a day in a list-type data structure composed of 24 integers:```temperatures_C = [33,66,65,0,59,60,62,64,70,76,80,69,80,83,68,79,61,53,50,49,53,48,45,39]``` Goals1. Treatment of lists2. Use of loop or list comprenhention3. Calculation of the mean, minimum and maximum.4. Filtering of lists.5. Interpolate an outlier.6. Logical operators.7. Print Temperature graphTo facilitate understanding, the temperature graph is shown below. You do not have to do anything in this section. The test starts in **Problem**. | # import
import matplotlib.pyplot as plt
%matplotlib inline
# axis x, axis y
y = [33,66,65,0,59,60,62,64,70,76,80,81,80,83,90,79,61,53,50,49,53,48,45,39]
x = list(range(len(y)))
# plot
plt.plot(x, y)
plt.axhline(y=70, linewidth=1, color='r')
plt.xlabel('hours')
plt.ylabel('Temperature ºC')
plt.title('Temperatures of our server throughout the day') | _____no_output_____ | Unlicense | temperature/temperature.ipynb | Gayushka/data-prework-labs |
ProblemIf the sensor detects more than 4 hours with temperatures greater than or equal to 70ºC or any temperature above 80ºC or the average exceeds 65ºC throughout the day, we must give the order to change the cooling system to avoid damaging the processor.We will guide you step by step so you can make the decision by calculating some intermediate steps:1. Minimum temperature2. Maximum temperature3. Temperatures equal to or greater than 70ºC4. Average temperatures throughout the day.5. If there was a sensor failure at 03:00 and we did not capture the data, how would you estimate the value that we lack? Correct that value in the list of temperatures.6. Bonus: Our maintenance staff is from the United States and does not understand the international metric system. Pass temperatures to Degrees Fahrenheit.Formula: F = 1.8 * C + 32web: https://en.wikipedia.org/wiki/Conversion_of_units_of_temperature | # assign a variable to the list of temperatures
# 1. Calculate the minimum of the list and print the value using print()
print('minimum value: ',min(y))
# 2. Calculate the maximum of the list and print the value using print()
print('maximum value: ', max(y))
# 3. Items in the list that are greater than 70ºC and print the result
print('\nTemps greater than 70C:')
for temp in y:
if temp > 70:
print(temp)
# 4. Calculate the mean temperature throughout the day and print the result
import statistics as s
print('\nMean temperature: ', s.mean(y))
# 5.1 Solve the fault in the sensor by estimating a value
print('\nEstimate #1: ', s.mean(y)) #mean of entire dataset
print('Estimate #2: ', s.mean(y[1:3] + y[4:6])) #mean of local/subdataset
# 5.2 Update of the estimated value at 03:00 on the list
e_two = s.mean(y[1:3] + y[4:6])
y[3] = e_two
print('\nUpdated list: ', y[:6])
# Bonus: convert the list of ºC to ºFarenheit
yF = []
for c_temp in y:
yF.append(round(1.8*c_temp + 32, 1))
print('\nFarenheight temps: ',yF)
| minimum value: 33
maximum value: 90
Temps greater than 70C:
76
80
81
80
83
90
79
Mean temperature: 62.854166666666664
Estimate #1: 62.854166666666664
Estimate #2: 62.5
Updated list: [33, 66, 65, 62.5, 59, 60]
Farenheight temps: [91.4, 150.8, 149.0, 144.5, 138.2, 140.0, 143.6, 147.2, 158.0, 168.8, 176.0, 177.8, 176.0, 181.4, 194.0, 174.2, 141.8, 127.4, 122.0, 120.2, 127.4, 118.4, 113.0, 102.2]
| Unlicense | temperature/temperature.ipynb | Gayushka/data-prework-labs |
Take the decisionRemember that if the sensor detects more than 4 hours with temperatures greater than or equal to 70ºC or any temperature higher than 80ºC or the average was higher than 65ºC throughout the day, we must give the order to change the cooling system to avoid the danger of damaging the equipment:* more than 4 hours with temperatures greater than or equal to 70ºC* some temperature higher than 80ºC* average was higher than 65ºC throughout the dayIf any of these three is met, the cooling system must be changed. | # Print True or False depending on whether you would change the cooling system or not
hours_over = 0
for temp in y:
if temp >= 70:
hours_over += 1
if hours_over > 4:
print('Change Cooling System: ', True)
break
for temp in y:
if temp > 80:
print('Change Cooling System: ', True)
break
if s.mean(y) > 65:
print('Change Cooling System: ', True)
| Change Cooling System: True
Change Cooling System: True
| Unlicense | temperature/temperature.ipynb | Gayushka/data-prework-labs |
Future improvements1. We want the hours (not the temperatures) whose temperature exceeds 70ºC2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set. Is this condition met?3. Average of each of the lists (ºC and ºF). How they relate?4. Standard deviation of each of the lists. How they relate? | # 1. We want the hours (not the temperatures) whose temperature exceeds 70ºC
hours = []
for i in range(len(y)):
if y[i] > 70:
hours.append(i)
hours
# 2. Condition that those hours are more than 4 consecutive and consecutive, not simply the sum of the whole set.
#Is this condition met?
previous = 0
consecutives = 0
for hour in hours:
if hour == (previous + 1):
consecutives += 1
previous = hour
if consecutives > 4:
print('Consecutive condition is met: ', True)
break
# 3. Average of each of the lists (ºC and ºF). How they relate?
print(s.mean(y))
print(s.mean(yF))
(62.85 * 1.8) + 32 #both means are == to each other
#mean C and mean F is not exactly == in my example because i used round() function on list of F
# 4. Standard deviation of each of the lists. How they relate?
print(s.pstdev(y))
print(s.pstdev(yF))
| 14.632639861130853
26.338751750035534
| Unlicense | temperature/temperature.ipynb | Gayushka/data-prework-labs |
Analysis regarding the emissions impact**(these are the informations on the model after running this notebook right after "westeros_LEDS_baseline.ipynb". if you're running it after "westeros_LEDS_diffusion_baseline.ipynb", please jump two cells further)**Here we add the emission bounds and I added a carbon footprint for the bulb and the LED.We can see that if we take the carbon footprint calculated with the number on this website: [https://www.carbonfootprint.com/energyconsumption.html](https://www.carbonfootprint.com/energyconsumption.html) :bulb: 0.63 tCO2/KWa / led: 0.61 tCO2/kWa the model chooses only normal bulbs: ___________________________________________________________________________________________________________________ It is only when the carbon footprint goes down to 0.055 tCO2/kWa that the model starts using them. The fact that we are using LEDs in our everyday life in the real world is that we have to use less watts per lamp to have the same light if we use LEDs. This reality is not shown in this model since we are working with CO2 per kWa and not per "light" which would make more sense. This explains why the carbon footprint has to be lower down. Here is what we get with 0.055 tCO2/kWa: Adding emissions for LEDs **and** for bulbs leads to a really high use of wind power plant at the end to stay below the emissions bound (see graphs at the end). ____________________________________________________________________________________________________________________________________________________________________________________________________________________________________ **(Here are the informations after linking this notebook to "westeros_LEDS_diffusion_baseline.ipynb")**After setting a diffusion rate for LEDs, we can see that LEDs are not beeing used, even with a small carbon footprint. This is because in this model, it has to be diffused rapidly in order to be efficient enough to replace the normal light bulb. Here is the result with only 0.0001 tCO2/kWa for LEDs: | import pandas as pd
import ixmp
import message_ix
from message_ix.utils import make_df
%matplotlib inline
mp = ixmp.Platform()
model = 'Westeros with LEDs'
base = message_ix.Scenario(mp, model=model, scenario='baseline')
scen = base.clone(model, 'emission_bound','introducing an upper bound on emissions',
keep_solution=False)
scen.check_out()
year_df = scen.vintage_and_active_years()
vintage_years, act_years = year_df['year_vtg'], year_df['year_act']
model_horizon = scen.set('year')
country = 'Westeros' | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Introducing Emissions | # first we introduce the emission of CO2 and the emission category GHG
scen.add_set('emission', 'CO2')
scen.add_cat('emission', 'GHG', 'CO2')
# we now add CO2 emissions to the coal powerplant
base_emission_factor = {
'node_loc': country,
'year_vtg': vintage_years,
'year_act': act_years,
'mode': 'standard',
'unit': 'tCO2/kWa',
}
# adding new units to the model library (needed only once)
mp.add_unit('tCO2/kWa')
mp.add_unit('MtCO2')
emission_factor = make_df(base_emission_factor, technology= 'coal_ppl', emission= 'CO2', value = 7.4)
scen.add_par('emission_factor', emission_factor) | INFO:root:unit `tCO2/kWa` is already defined in the platform instance
INFO:root:unit `MtCO2` is already defined in the platform instance
| MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Now we add emission factor for bulbs and LEDs as well [https://www.carbonfootprint.com/energyconsumption.html](https://www.carbonfootprint.com/energyconsumption.html) | emission_factor = make_df(base_emission_factor, technology= 'bulb', emission= 'CO2', value = 0.63)
scen.add_par('emission_factor', emission_factor)
emission_factor = make_df(base_emission_factor, technology= 'led', emission= 'CO2', value = 0.055)
scen.add_par('emission_factor', emission_factor) | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Define a Bound on EmissionsThe `type_year: cumulative` assigns an upper bound on the *weighted average of emissions* over the entire time horizon. | scen.add_par('bound_emission', [country, 'GHG', 'all', 'cumulative'],
value=500., unit='MtCO2') | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Time to Solve the Model | scen.commit(comment='introducing emissions and setting an upper bound')
scen.set_as_default()
scen.solve() | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
To compare: without emissions bounds: 238'193 With emissions bounds but without any CO2 impact for the light: 336'222 | scen.var('OBJ')['lvl'] | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Plotting Results | from tools import Plots
p = Plots(scen, country, firstyear=700) | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
ActivityHow much energy is generated in each time period from the different potential sources? | p.plot_activity(baseyear=True, subset=['coal_ppl', 'wind_ppl']) | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Here we can se the part of LEDs per year | p.plot_activity(baseyear=True, subset=['bulb', 'led']) | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
CapacityHow much capacity of each plant is installed in each period? | p.plot_capacity(baseyear=True, subset=['coal_ppl', 'wind_ppl']) | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Electricity PriceAnd how much does the electricity cost? These prices are in fact **shadow prices** taken from the **dual variables** of the model solution. They reflect the marginal cost of electricity generation (i.e., the additional cost of the system for supplying one more unit of electricity), which is in fact the marginal cost of the most expensive generator. Note the price drop when the most expensive technology is no longer in the system. | p.plot_prices(subset=['light'], baseyear=True) | INFO:numexpr.utils:NumExpr defaulting to 8 threads.
| MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
Close the connection to the database | mp.close_db() | _____no_output_____ | MIT | tutorial/westeros/westeros_emissions_bounds_LEDs.ipynb | luciecastella/Tuto_Westeros |
We will use keras and tensorflow to implement VAE ⏭ | import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras import backend as K | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
**REPARAMETERIZATION TRICK:** This sampling uses mean and logarithmic variance and sample z by using random value from normal distribution. ⚓ Reparameterization sample was first introduced [Kingma and Welling, 2013](https://arxiv.org/pdf/1312.6114.pdf) The process also defined by [Gunderson](https://gregorygundersen.com/blog/2018/04/29/reparameterization/). ♋ | class Sampling(layers.Layer):
"""Uses (z_mean, z_log_var) to sample z, the vector encoding a digit."""
def call(self, inputs):
z_mean, z_log_var = inputs
batch = tf.shape(z_mean)[0]
dim = tf.shape(z_mean)[1]
epsilon = tf.keras.backend.random_normal(shape=(batch, dim))
return z_mean + tf.exp(0.5 * z_log_var) * epsilon | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
VAE Encoder ▶ ▶ ▶ ☕ Encoder create z_mean and z_variance, then sample z from this z_mean and z_variance using epsilon. | latent_dim = 2 # because of z_mean and z_log_variance
encoder_inputs = keras.Input(shape=(28, 28, 1))
x = layers.Conv2D(32, 3, activation="relu", strides=2, padding="same")(encoder_inputs)
x = layers.Conv2D(64, 3, activation="relu", strides=2, padding="same")(x)
conv_shape = K.int_shape(x) #Shape of conv to be provided to decoder
print(conv_shape)
x = layers.Flatten()(x)
x = layers.Dense(32, activation="relu")(x)
z_mean = layers.Dense(latent_dim, name="z_mean")(x)
z_log_var = layers.Dense(latent_dim, name="z_log_var")(x)
z = Sampling()([z_mean, z_log_var])
encoder = keras.Model(encoder_inputs, [z_mean, z_log_var, z], name="encoder")
encoder.summary() | (None, 7, 7, 64)
Model: "encoder"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_6 (InputLayer) [(None, 28, 28, 1)] 0 []
conv2d_6 (Conv2D) (None, 14, 14, 32) 320 ['input_6[0][0]']
conv2d_7 (Conv2D) (None, 7, 7, 64) 18496 ['conv2d_6[0][0]']
flatten_2 (Flatten) (None, 3136) 0 ['conv2d_7[0][0]']
dense_4 (Dense) (None, 32) 100384 ['flatten_2[0][0]']
z_mean (Dense) (None, 2) 66 ['dense_4[0][0]']
z_log_var (Dense) (None, 2) 66 ['dense_4[0][0]']
sampling_2 (Sampling) (None, 2) 0 ['z_mean[0][0]',
'z_log_var[0][0]']
==================================================================================================
Total params: 119,332
Trainable params: 119,332
Non-trainable params: 0
__________________________________________________________________________________________________
| Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
VAE Decoder ◀ ◀ ◀☁ The tied architecture (reverse architecture from encoder to decoder) is preferred in AE. There is an [explanation](https://https://stats.stackexchange.com/questions/419684/why-is-the-autoencoder-decoder-usually-the-reverse-architecture-as-the-encoder) about it.--- | latent_inputs = keras.Input(shape=(latent_dim,))
x = layers.Dense(conv_shape[1] * conv_shape[2] * conv_shape[3], activation="relu")(latent_inputs) # 7x7x64 shape
x = layers.Reshape((conv_shape[1],conv_shape[2], conv_shape[3]))(x)
x = layers.Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x)
x = layers.Conv2DTranspose(32, 3, activation="relu", strides=2, padding="same")(x)
decoder_outputs = layers.Conv2DTranspose(1, 3, activation="sigmoid", padding="same")(x)
decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder")
decoder.summary() | Model: "decoder"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_7 (InputLayer) [(None, 2)] 0
dense_5 (Dense) (None, 3136) 9408
reshape_2 (Reshape) (None, 7, 7, 64) 0
conv2d_transpose_6 (Conv2DT (None, 14, 14, 64) 36928
ranspose)
conv2d_transpose_7 (Conv2DT (None, 28, 28, 32) 18464
ranspose)
conv2d_transpose_8 (Conv2DT (None, 28, 28, 1) 289
ranspose)
=================================================================
Total params: 65,089
Trainable params: 65,089
Non-trainable params: 0
_________________________________________________________________
| Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
VAE MODEL ✅ | class VAE(keras.Model):
def __init__(self, encoder, decoder, **kwargs):
super(VAE, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.total_loss_tracker = keras.metrics.Mean(name="total_loss")
self.reconstruction_loss_tracker = keras.metrics.Mean(
name="reconstruction_loss"
)
self.kl_loss_tracker = keras.metrics.Mean(name="kl_loss")
@property
def metrics(self):
return [
self.total_loss_tracker,
self.reconstruction_loss_tracker,
self.kl_loss_tracker,
]
def train_step(self, data):
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2)
)
)
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
total_loss = reconstruction_loss + kl_loss
grads = tape.gradient(total_loss, self.trainable_weights)
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
self.total_loss_tracker.update_state(total_loss)
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
return {
"loss": self.total_loss_tracker.result(),
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result(),
}
from google.colab import drive
drive.mount('/content/gdrive') | Mounted at /content/gdrive
| Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
⛹ If you want to run it on your desktop, you can download [data](https://https://www.kaggle.com/nikbearbrown/tmnist-alphabet-94-characters) and read from same directory with this ipynb file | import pandas as pd
df = pd.read_csv('gdrive/My Drive/DeepLearning/94_character_TMNIST.csv')
#df = pd.read_csv('94_character_TMNIST.csv')
print(df.shape)
X = df.drop(columns={'names','labels'})
X_images = X.values.reshape(-1,28,28)
X_images = np.expand_dims(X_images, -1).astype("float32") / 255 | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
⚡ I tried different batch size(32,64,128,256) to train VAE model, 128 gives better result than others. | vae = VAE(encoder, decoder)
vae.compile(optimizer=keras.optimizers.Adam())
vae.fit(X_images, epochs=10, batch_size=128) | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
⛳ This plot latent space plot image between **[scale_x_left , scale_x_right]** and **[scale_y_bottom, scale_y_top]** | import matplotlib.pyplot as plt
def plot_latent_space(vae, n=8, figsize=12):
# display a n*n 2D manifold of digits
digit_size = 28
scale_x_left = 1 # If we change the range, t generate different image.
scale_x_right = 4
scale_y_bottom = 0
scale_y_top = 1
figure = np.zeros((digit_size * n, digit_size * n))
# If we want to see different x and y range we can change values in grid_x and gird_y. I trid x= [-3,-2] and y = [-3,-1] values and m labeled imaged are generated.
grid_x = np.linspace(scale_x_left, scale_x_right, n) # -3, -2
grid_y = np.linspace(scale_y_bottom, scale_y_top, n)[::-1] # -3, -1
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
z_sample = np.array([[xi, yi]])
x_decoded = vae.decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[
i * digit_size : (i + 1) * digit_size,
j * digit_size : (j + 1) * digit_size,
] = digit
plt.figure(figsize=(figsize, figsize))
start_range = digit_size // 2
end_range = n * digit_size + start_range
pixel_range = np.arange(start_range, end_range, digit_size)
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
plt.xticks(pixel_range, sample_range_x)
plt.yticks(pixel_range, sample_range_y)
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.imshow(figure, cmap="Greys_r")
plt.show()
plot_latent_space(vae) | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
♑ When we plot all the Training data with labels, we can see ***z_mean*** values of the data. ❎ If we sample with this ***z_mean*** value, we can acquire similar image from this latent space. ⭕ Because two points are close to each other in latent space means they are looking similar(variant of this label). | def plot_label_clusters(vae, data, labels):
# display a 2D plot of the digit classes in the latent space
z_mean, _, _ = vae.encoder.predict(data)
plt.figure(figsize=(12, 12))
plt.scatter(z_mean[:, 0], z_mean[:, 1], c=labels)
plt.colorbar()
plt.xlabel("z[0]")
plt.ylabel("z[1]")
plt.show()
y = df[['labels']]
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y_label = le.fit_transform(y)
plot_label_clusters(vae, X_images, y_label) | /usr/local/lib/python3.7/dist-packages/sklearn/preprocessing/_label.py:115: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)
| Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
⛪ Visualize one image |
#Single decoded image with random input latent vector (of size 1x2)
#Latent space range is about -5 to 5 so pick random values within this range
sample_vector = np.array([[3,0.5]])
decoded_example = decoder.predict(sample_vector)
decoded_example_reshaped = decoded_example.reshape(28, 28)
plt.imshow(decoded_example_reshaped) | _____no_output_____ | Apache-2.0 | VariationalAutoEncoder.ipynb | z-tufekci/DeepLearning |
Markdown ¿Qué es?Lenguaje de marcado que nos permite aplicar formato a nuestros textos mediante unos caracteres especiales. Muy útil cuando tenemos que documentar algo, escribir un artículo, o entregar un reporte. Este lenguaje está pensado para web, pero es muy común utilizarlo en cualquier tipo de texto, independientemente de su destino.Lo bueno que tiene es que se edita en **texto plano y está integrado en muchísimas herramientas**, como Jupyter Notebook o RStudio. Markdown vs HTMLTenemos un viejo conocido en cuanto a programación web: HTML. Son lenguajes muy diferentes. Con HTML podemos construir un complejo **árbol de tags**, mientras que markdown se desarrolla en texto plano. Por supuesto, las finalidades también son distintas. HTML se aplica a todo tipo de webs, ya sean sencillas o complejas, mientras que markdown se suele usar para blogs o artículos. Su sencillez a la hora de desarrollar le penaliza en su versatilidad. Pero como el objetivo de este curso no es hacer páginas web, markdown cumple más que de sobra para acompañar y mejorar la comprensión de nuestro código. Además, ya verás a lo largo de este notebook que ambos lenguajes son perfectamente compatibles. ¿Cómo funciona?Contiene una serie de **caracteres especiales** que le dan forma a los textos. Por ejemplo, si queremos un texto en *cursiva*, simplemente lo rodearemos con asteriscos. Lo veremos en detalle en este Notebook. ¿De qué nos va a servir?En Jupyter lo normal será crear celdas con código, pero también tenemos la posibilidad de insertar celdas de markdown, donde podremos poner **imágenes, títulos, enumerar texto, listar, citar y mucho más!** 1. Primera celdaHaz doble clik en esta celda y verás cómo cambia el texto. Significa que estás en el **modo edición** de Markdown.Como puedes observar, markdown se edita como si fuese texto plano, y en el caso concreto de los párrafos, no necesita de ningún caracter para que markdown sepa que es un párrafo. Sin embargo, fíjate que para la cabecera "1.Primer celda", hay dos hashtags delante que indican que es un encabezado. Veremos en el apartado 2 cómo crear cabeceras.Haz ctrl + enter para ejecuta la celda (o botón de play de arriba). Así abandonamos el modo edición y nuestro texto obtiene el formato que deseábamos.**¡Tu turno!** Crea una celda nueva en el menu de arriba y selecciona la opción Markdown  | # Esto es código de Python.
# Va a ser muy habitual en el curso, acompañar el código de Python mediante celdas de markdown. | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/03_Markdown/RESU_Markdown en Jupyter.ipynb | JuanDG5/bootcamp_thebridge_PTSep20 |
Expansion velocity of the universeIn 1929, Edwin Hubble published a [paper](http://www.pnas.org/content/pnas/15/3/168.full.pdf) in which he compared the radial velocity of objects with their distance. The former can be done pretty precisely with spectroscopy, the latter is much more uncertain. His original data are [here](table1.txt).He saw that the velocity increases with distance and speculated that this could be the sign of a cosmological expansion. Let's find out what he did.Load the data into an array with `numpy.genfromtxt`, make use of its arguments `names` and `dtype` to read in the column names from the header and choosing the data type on its own as needed. You should get 6 columns * `CAT`, `NUMBER`: These two combined give you the name of the galaxy. * `R`: distance in Mpc * `V`: radial velocity in km/s * `RA`, `DEC`: equatorial coordinates of the galaxy Make a scatter plot of V vs R. Don't forget labels and units... | import numpy as np
data = np.genfromtxt('table1.txt', names=True, dtype=None)
print("Samples:", len(data))
print("Data Types:", data.dtype)
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
plt.scatter(data['R'], data['V'])
plt.xlabel('R [Mpc]')
plt.ylabel('V [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Use `np.linalg.lstsq` to fit a linear regression function and determine the slope $H_0$ of the line $V=H_0 R$. For that, reshape $R$ as a $N\times1$ matrix (the design matrix) and solve for 1 unknown parameter. Add the best-fit line to the plot. | N = len(data)
X = data['R'].reshape((N,1))
params, _, _, _ = np.linalg.lstsq(X, data['V'])
print(params)
H0 = params[0]
R = np.linspace(0,2.5,100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(data['R'], data['V'])
ax.plot(R, H0*R, 'k--')
ax.set_xlim(xmin=0, xmax=2.5)
ax.set_xlabel('Distance [Mpc]')
ax.set_ylabel('Velocity [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Why is there scatter with respect to the best-fit curve? Is it fair to only fit for the slope and not also for the intercept? How would $H_0$ change if you include an intercept in the fit? | X = np.ones((N, 2))
X[:,1] = data['R']
params, _, _, _ = np.linalg.lstsq(X, data['V'])
print(params)
inter, H0 = params
R = np.linspace(0,2.5,100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(data['R'], data['V'])
ax.plot(R, H0*R + inter, 'k--')
ax.set_xlim(xmin=0, xmax=2.5)
ax.set_xlabel('Distance [Mpc]')
ax.set_ylabel('Velocity [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Correcting for motion of the sun$V$ as given in the table is a combination of any assumed cosmic expansion and the motion of the sun with respect to that cosmic frame. So, we need to generalize the model to $V=H_0 R + V_s$, where the solar velocity is given by $V_s = X \cos(RA)\cos(DEC) + Y\sin(RA)\cos(DEC)+Z\sin(DEC)$. We'll use `astropy` to read in the RA/DEC coordinate strings and properly convert them to degrees (and then radians): | import astropy.coordinates as coord
import astropy.units as u
pos = coord.SkyCoord(ra=data['RA'].astype('U8'), dec=data['DEC'].astype('U9'), unit=(u.hourangle,u.deg),frame='fk5')
ra_ = pos.ra.to(u.deg).value * np.pi/180
dec_ = pos.dec.to(u.deg).value * np.pi/180 | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Construct a new $N\times4$ design matrix for the four unknown parameters $H_0$, $X$, $Y$, $Z$ to account for the solar motion. The resulting $H_0$ is Hubble's own version of the "Hubble constant". What do you get? | Ah = np.empty((N,4))
Ah[:,0] = data['R']
Ah[:,1] = np.cos(ra_)*np.cos(dec_)
Ah[:,2] = np.sin(ra_)*np.cos(dec_)
Ah[:,3] = np.sin(dec_)
params_h, _, _, _ = np.linalg.lstsq(Ah, data['V'])
print(params_h)
H0 = params_h[0] | [ 465.17797833 -67.84096674 236.14706994 -199.58892695]
| MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Make a scatter plot of $V-V_S$ vs $R$. How is it different from the previous one without the correction for solar velicity. Add the best-fit linear regression line. | VS = params_h[1]*Ah[:,1] + params_h[2]*Ah[:,2] + params_h[3]*Ah[:,3]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(data['R'], data['V'] - VS)
ax.plot(R, H0*R, 'k-')
ax.set_xlim(xmin=0, xmax=2.5)
ax.set_xlabel('Distance [Mpc]')
ax.set_ylabel('Velocity [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Using `astropy.units`, can you estimate the age of the universe from $H_0$? Does it make sense? | H0q = H0 * u.km / u.s / u.Mpc
(1./H0q).to(u.Gyr) | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Deconstructing lstsqSo far we have not incorporated any measurement uncertainties. Can you guess or estimate them from the scatter with respect to the best-fit line? You may want to look at the residuals returned by `np.linalg.lstsq`... | scatter = data['V'] - VS - H0*data['R']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(scatter, 10)
ax.set_xlabel('$\Delta$V [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Let see how adopting a suitable value $\sigma$ for those uncertainties would affect the estimate of $H_0$?The problem you solved so far is $Ax=b$, and errors don't occur. With errors the respective equation is changed to $A^\top \Sigma^{-1} Ax=A^\top \Sigma^{-1}b$, where in this case the covariance matrix $\Sigma=\sigma^2\mathbf{1}$. This problem can still be solved by `np.linalg.lstsq`.Construct the modified design matrix and data vector and get a new estimate of $H_0$. Has it changed? Use `np.dot`, `np.transpose`, and `np.linalg.inv` (or their shorthands). | error = scatter.std()
Sigma = error**2*np.eye(N)
Ae = np.dot(Ah.T, np.dot(np.linalg.inv(Sigma), Ah))
be = np.dot(Ah.T, np.dot(np.linalg.inv(Sigma), data['V']))
params_e, _, _, _ = np.linalg.lstsq(Ae, be)
print(params_e) | [ 465.17797833 -67.84096674 236.14706994 -199.58892695]
| MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Compute the parameter covariance matrix $S=(A^\top \Sigma^{-1} A)^{-1}$ and read off the variance of $H_0$. Update your plot to illustrate that uncertainty. | S = np.linalg.inv(Ae)
dH0 = np.sqrt(S[0,0])
print(dH0)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(data['R'], data['V'] - VS)
ax.plot(R, H0*R, 'k-')
ax.plot(R, (H0-dH0)*R, 'k--')
ax.plot(R, (H0+dH0)*R, 'k--')
ax.set_xlim(xmin=0, xmax=2.5)
ax.set_xlabel('Distance [Mpc]')
ax.set_ylabel('Velocity [km/s]') | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
How large is the relative error? Would that help with the problematic age estimate above? | H0q = (H0-dH0) * u.km / u.s / u.Mpc
(1./H0q).to(u.Gyr) | _____no_output_____ | MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Compare the noise-free result from above (Hubble's result) with $SA^\top \Sigma^{-1}b$. Did adopting errors change the result? | params_h, _, _, _ = np.linalg.lstsq(Ah, data['V'])
print(params_h)
print (np.dot(S, be)) | [ 465.17797833 -67.84096674 236.14706994 -199.58892695]
[ 465.17797833 -67.84096674 236.14706994 -199.58892695]
| MIT | day3/solutions/Hubble-Solutions.ipynb | ishanikulkarni/usrp-sciprog |
Graphical AnalysisPyevolve comes with a Graphical Plotting Tool, based on the [Matplotlib plotting library](http://matplotlib.org/).To use this graphical plotting tool, you need to use the [DBAdapters.DBSQLite](http://pyevolve.sourceforge.net/0_6rc1/module_dbadapters.html) adapter and create a database file, where the population of each generation is stored.We are going to extend the first example with the database and graphical output. | from pyevolve import G1DList, GSimpleGA
from pyevolve import DBAdapters
def eval_func(chromosome):
score = 0.0
for value in chromosome:
if value==0:
score += 1.0
return score
genome = G1DList.G1DList(20)
genome.evaluator.set(eval_func)
genome.setParams(rangemin=0, rangemax=10) | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
The database adapter is defined in the following cell. The database is stored in a file, and the elements need a specific identifier. We will use always the same identifier, but you could change it if you want to save different evolutions in the same database. The parameter resetDB is set for deleting any existing data in the database. | sqlite_adapter = DBAdapters.DBSQLite(dbname='first_example.db', identify="ex1", resetDB=True) | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
When you run your GA, all the statistics will be dumped to this database. When you use the graph tool, it will read the statistics from this database file.Let's evolve the example. Now, instead of evolving step by step, we will set a number of generations for completing the evolution with a single call to ga.evolve. | ga = GSimpleGA.GSimpleGA(genome)
ga.setDBAdapter(sqlite_adapter)
ga.setGenerations(20)
ga.evolve(freq_stats=5)
print("Generation: %d" % ga.currentGeneration)
best = ga.bestIndividual()
print('\tBest individual: %s' % str(best.genomeList))
print('\tBest score: %.0f' % best.score) | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
PlottingHere are described the main graph types. Usually you can choose to plot the **raw** or **fitness** score, which are defined as:* The raw score represents the score returned by the [Evaluation function](http://pyevolve.sourceforge.net/0_6rc1/intro.htmlterm-evaluation-function), this score is not scaled.* The fitness score is the scaled raw score, for example, if you use the Linear Scaling ([Scaling.LinearScaling()](http://pyevolve.sourceforge.net/0_6rc1/module_scaling.html?highlight=scalingScaling.LinearScaling)), the fitness score will be the raw score scaled with the Linear Scaling method. The fitness score represents how good is the individual relative to our population. | %matplotlib inline
from pyevolve_plot import plot_errorbars_raw, plot_errorbars_fitness, \
plot_maxmin_raw, plot_maxmin_fitness, \
plot_diff_raw, plot_pop_heatmap_raw | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Error bars graph (raw scores)In this graph, you will find the generations on the x-axis and the raw scores on the y-axis. The green vertical bars represents the maximum and the minimum raw scores of the current population at generation indicated in the x-axis. The blue line between them is the average raw score of the population. | plot_errorbars_raw('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Error bars graph (fitness scores)The differente between this graph option and the previous one is that we are using the fitness scores instead of the raw scores. | plot_errorbars_fitness('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Max/min/avg/std. dev. graph (raw scores)In this graph we have the green line showing the maximum raw score at the generation in the x-axis, the red line shows the minimum raw score, and the blue line shows the average raw scores. The green shaded region represents the difference between our max. and min. raw scores. The black line shows the standard deviation of the average raw scores. We also have some annotations like the maximum raw score, maximum std. dev. and the min std. dev. | plot_maxmin_raw('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Max/min/avg/std. dev. graph (fitness scores)This graphs shows the maximum fitness score from the population at the x-axis generation using the green line. The red line shows the minimum fitness score and the blue line shows the average fitness score from the population. The green shaded region between the green and red line shows the difference between the best and worst individual of population. | plot_maxmin_fitness('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Min/max difference graph, raw and fitness scoresIn this graph, we have two subplots, the first is the difference between the best individual raw score and the worst individual raw score. The second graph shows the difference between the best individual fitness score and the worst individual fitness score. Both subplots show the generation on the x-axis and the score difference in the y-axis. | plot_diff_raw('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Heat map of population raw score distributionThe heat map graph is a plot with the population individual plotted as the x-axis and the generation plotted in the y-axis. On the right side we have a legend with the color/score relation. As you can see, on the initial populations, the last individals scores are the worst (represented in this colormap with the dark blue). To create this graph, we use the Gaussian interpolation method. | plot_pop_heatmap_raw('first_example.db','ex1') | _____no_output_____ | MIT | Graphical Analysis.ipynb | ecervera/GA |
Analysing structured data with data frames (c) 2019 [Steve Phelps](mailto:[email protected]) Data frames- The `pandas` module provides a powerful data-structure called a data frame.- It is similar, but not identical to: - a table in a relational database, - an Excel spreadsheet, - a dataframe in R. Types of dataData frames can be used to represent:- [Panel data](https://en.wikipedia.org/wiki/Panel_data)- [Time series](https://en.wikipedia.org/wiki/Time_series) data- [Relational data](https://en.wikipedia.org/wiki/Relational_model) Loading data- Data frames can be read and written to/from: - financial web sites - database queries - database tables - CSV files - json files - Beware that data frames are memory resident; - If you read a large amount of data your PC might crash - With big data, typically you would read a subset or summary of the data via e.g. a select statement. Importing pandas- The pandas module is usually imported with the alias `pd`. | import pandas as pd | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Series- A Series contains a one-dimensional array of data, *and* an associated sequence of labels called the *index*.- The index can contain numeric, string, or date/time values.- When the index is a time value, the series is a [time series](https://en.wikipedia.org/wiki/Time_series).- The index must be the same length as the data.- If no index is supplied it is automatically generated as `range(len(data))`. Creating a series from an array | import numpy as np
data = np.random.randn(5)
data
my_series = pd.Series(data, index=['a', 'b', 'c', 'd', 'e'])
my_series | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Plotting a series- We can plot a series by invoking the `plot()` method on an instance of a `Series` object.- The x-axis will autimatically be labelled with the series index. | import matplotlib.pyplot as plt
my_series.plot()
plt.show() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Creating a series with automatic index- In the following example the index is creating automatically: | pd.Series(data) | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Creating a Series from a `dict` | d = {'a' : 0., 'b' : 1., 'c' : 2.}
my_series = pd.Series(d)
my_series | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Indexing a series with `[]`- Series can be accessed using the same syntax as arrays and dicts.- We use the labels in the index to access each element. | my_series['b'] | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
- We can also use the label like an attribute: | my_series.b | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Slicing a series- We can specify a range of labels to obtain a slice: | my_series[['b', 'c']] | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Arithmetic and vectorised functions- `numpy` vectorization works for series objects too. | d = {'a' : 0., 'b' : 1., 'c' : 2.}
squared_values = pd.Series(d) ** 2
squared_values
x = pd.Series({'a' : 0., 'b' : 1., 'c' : 2.})
y = pd.Series({'a' : 3., 'b' : 4., 'c' : 5.})
x + y | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Time series | dates = pd.date_range('1/1/2000', periods=5)
dates
time_series = pd.Series(data, index=dates)
time_series | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Plotting a time-series | ax = time_series.plot() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Missing values- Pandas uses `nan` to represent missing data.- So `nan` is used to represent missing, invalid or unknown data values.- It is important to note that this only convention only applies within pandas. - Other frameworks have very different semantics for these values. DataFrame- A data frame has multiple columns, each of which can hold a *different* type of value.- Like a series, it has an index which provides a label for each and every row. - Data frames can be constructed from: - dict of arrays, - dict of lists, - dict of dict - dict of Series - 2-dimensional array - a single Series - another DataFrame Creating a dict of series | series_dict = {
'x' :
pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'y' :
pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd']),
'z' :
pd.Series([0.1, 0.2, 0.3, 0.4], index=['a', 'b', 'c', 'd'])
}
series_dict | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Converting the dict to a data frame | df = pd.DataFrame(series_dict)
df | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Plotting data frames- When plotting a data frame, each column is plotted as its own series on the same graph.- The column names are used to label each series.- The row names (index) is used to label the x-axis. | ax = df.plot() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Indexing - The outer dimension is the column index.- When we retrieve a single column, the result is a Series | df['x']
df['x']['b']
df.x.b | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Projections- Data frames can be sliced just like series.- When we slice columns we call this a *projection*, because it is analogous to specifying a subset of attributes in a relational query, e.g. `SELECT x FROM table`.- If we project a single column the result is a series: | slice = df['x'][['b', 'c']]
slice
type(slice) | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Projecting multiple columns- When we include multiple columns in the projection the result is a DataFrame. | slice = df[['x', 'y']]
slice
type(slice) | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Vectorization- Vectorized functions and operators work just as with series objects: | df['x'] + df['y']
df ** 2 | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Logical indexing- We can use logical indexing to retrieve a subset of the data. | df['x'] >= 2
df[df['x'] >= 2] | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Descriptive statistics - To quickly obtain descriptive statistics on numerical values use the `describe` method. | df.describe() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Accessing a single statistic- The result is itself a DataFrame, so we can index a particular statistic like so: | df.describe()['x']['mean'] | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Accessing the row and column labels- The row labels (index) and column labels can be accessed: | df.index
df.columns | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Head and tail- Data frames have `head()` and `tail()` methods which behave analgously to the Unix commands of the same name. Financial data- Pandas was originally developed to analyse financial data.- We can download tabulated data in a portable format called [Comma Separated Values (CSV)](https://www.loc.gov/preservation/digital/formats/fdd/fdd000323.shtml). | import pandas as pd
googl = pd.read_csv('data/GOOGL.csv') | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Examining the first few rows- When working with large data sets it is useful to view just the first/last few rows in the dataset.- We can use the `head()` method to retrieve the first rows: | googl.head() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Examining the last few rows | googl.tail() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Converting to datetime values- So far, the `Date` attribute is of type string. | googl.Date[0]
type(googl.Date[0]) | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
- In order to work with time-series data, we need to construct an index containing time values.- Time values are of type `datetime` or `Timestamp`.- We can use the function `to_datetime()` to convert strings to time values. | pd.to_datetime(googl['Date']).head() | _____no_output_____ | CC-BY-4.0 | src/main/ipynb/pandas.ipynb | pperezgr/python-bigdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.