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
The exponential function $\mathrm{exp}(x) := e^x$ is computed as follows:
math.exp(1)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The natural logarithm $\ln(x)$, which is defined as the inverse of the function $\exp(x)$, is called `log` (instead of `ln`):
math.log(math.e * math.e)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The square root $\sqrt{x}$ of a number $x$ is computed using the function `sqrt`:
math.sqrt(2)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The flooring function $\texttt{floor}(x)$ truncates a floating point number $x$ down to the biggest integer number less or equal to $x$:$$ \texttt{floor}(x) = \max(\{ n \in \mathbb{Z} \mid n \leq x \} $$
math.floor(1.999)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The ceiling function $\texttt{ceil}(x)$ rounds a floating point number $x$ up to the next integer number bigger or equal to $x$:$$ \texttt{ceil}(x) = \min(\{ n \in \mathbb{Z} \mid x \leq n \} $$
math.ceil(1.001) round(1.5), round(1.39), round(1.51) abs(-1)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The Help System Typing a single question mark '?' starts the help system of *Jupyter*.
?
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
If the name of a module is followed by a question mark, a description of the module is printed.
math?
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
This also works for functions defined in a module.
math.sin?
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The question mark operator only works inside a Jupyter notebook. If you are using an interpreted in the command line for executing *Python* commands, use the function `help` instead.
help(math) help(math.sin) help(dir)
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
We can use the function dir() to print the names of the variables that have been defined.
dir() 2 * 3 _
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
The magic command %quickref prints an overview of the so called magic commands that are available in Jupyter notebooks.
%quickref
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
We can use the command ls to list the files in the current directory.
ls -al
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Prefixing a shell command with a `!` executes this command in a shell. Below, I have used the Windows command `dir`. On Linux, the corresponding command is called `ls`.
!ls !dir
_____no_output_____
MIT
Python/Introduction.ipynb
BuserLukas/Logic
Extracting training data from the ODC * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser* **Compatibility:** Notebook currently compatible with the `DEA Sandbox` environment* **Products used:** [ls8_nbart_geomedian_annual](https://explor...
%matplotlib inline import os import sys import datacube import numpy as np import xarray as xr import subprocess as sp import geopandas as gpd from odc.io.cgroups import get_cpu_quota from datacube.utils.geometry import assign_crs sys.path.append('../../Scripts') from dea_plotting import map_shapefile from dea_bandin...
/env/lib/python3.6/site-packages/geopandas/_compat.py:88: UserWarning: The Shapely GEOS version (3.7.2-CAPI-1.11.0 ) is incompatible with the GEOS version PyGEOS was compiled with (3.9.0-CAPI-1.16.2). Conversions between both will be slow. shapely_geos_version, geos_capi_version_string /env/lib/python3.6/site-package...
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Analysis parameters* `path`: The path to the input vector file from which we will extract training data. A default geojson is provided.* `field`: This is the name of column in your shapefile attribute table that contains the class labels. **The class labels must be integers**
path = 'data/crop_training_WA.geojson' field = 'class'
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Find the number of CPUs
ncpus = round(get_cpu_quota()) print('ncpus = ' + str(ncpus))
ncpus = 7
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Preview input dataWe can load and preview our input data shapefile using `geopandas`. The shapefile should contain a column with class labels (e.g. 'class'). These labels will be used to train our model. > Remember, the class labels **must** be represented by `integers`.
# Load input data shapefile input_data = gpd.read_file(path) # Plot first five rows input_data.head() # Plot training data in an interactive map map_shapefile(input_data, attribute=field)
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Extracting training dataThe function `collect_training_data` takes our geojson containing class labels and extracts training data (features) from the datacube over the locations specified by the input geometries. The function will also pre-process our training data by stacking the arrays into a useful format and remov...
# Set up our inputs to collect_training_data time = ('2014') zonal_stats = None return_coords = True # Set up the inputs for the ODC query measurements = ['blue', 'green', 'red', 'nir', 'swir1', 'swir2'] resolution = (-30, 30) output_crs = 'epsg:3577' # Generate a new datacube query object query = { 'time': time, ...
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Defining feature layersTo create the desired feature layers, we pass instructions to `collect training data` through the `feature_func` parameter. * `feature_func`: A function for generating feature layers that is applied to the data within the bounds of the input geometry. The 'feature_func' must accept a 'dc_query' ...
def feature_layers(query): #connect to the datacube dc = datacube.Datacube(app='custom_feature_layers') #load ls8 geomedian ds = dc.load(product='ls8_nbart_geomedian_annual', **query) # Calculate some band indices da = calculate_indices(ds, i...
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Now, we can pass this function to `collect_training_data`. This will take a few minutes to run all 430 samples on the default sandbox as it only has two cpus.
%%time column_names, model_input = collect_training_data( gdf=input_data, dc_query=query, ncpus=ncpus, return_coords=return_coords, field=field, zonal_stats=zonal_stats, feature_func=feature_layers) print(column_names) print('') print(np.array_str(model_input, precision=2, suppress_small=Tru...
['class', 'blue', 'green', 'red', 'nir', 'swir1', 'swir2', 'NDVI', 'LAI', 'MNDWI', 'sdev', 'edev', 'bcdev', 'PV_PC_10', 'PV_PC_50', 'PV_PC_90', 'x_coord', 'y_coord'] [[ 1. 809. 1249. ... 70. -1447515. -3510225.] [ 1. 1005. 1464. ... 68. -1393035. -3614685.] [ 1. 95...
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Separate coordinate dataBy setting `return_coords=True` in the `collect_training_data` function, our training data now has two extra columns called `x_coord` and `y_coord`. We need to separate these from our training dataset as they will not be used to train the machine learning model. Instead, these variables will b...
# Select the variables we want to use to train our model coord_variables = ['x_coord', 'y_coord'] # Extract relevant indices from the processed shapefile model_col_indices = [column_names.index(var_name) for var_name in coord_variables] # Export to coordinates to file np.savetxt("results/training_data_coordinates.txt...
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Export training dataOnce we've collected all the training data we require, we can write the data to disk. This will allow us to import the data in the next step(s) of the workflow.
# Set the name and location of the output file output_file = "results/test_training_data.txt" # Grab all columns except the x-y coords model_col_indices = [column_names.index(var_name) for var_name in column_names[0:-2]] # Export files to disk np.savetxt(output_file, model_input[:, model_col_indices], header=" ".join(...
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
Recommended next stepsTo continue working through the notebooks in this `Scalable Machine Learning on the ODC` workflow, go to the next notebook `2_Inspect_training_data.ipynb`.1. **Extracting training data from the ODC (this notebook)**2. [Inspecting training data](2_Inspect_training_data.ipynb)3. [Evaluate, optimize...
print(datacube.__version__)
1.8.4.dev52+g07bc51a5
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
TagsBrowse all available tags on the DEA User Guide's [Tags Index](https://docs.dea.ga.gov.au/genindex.html)
**Tags** :index:`Landsat 8 geomedian`, :index:`Landsat 8 TMAD`, :index:`machine learning`, :index:`collect_training_data`, :index:`Fractional Cover`
_____no_output_____
Apache-2.0
Real_world_examples/Scalable_machine_learning/1_Extract_training_data.ipynb
anchor228/dea-notebooks
说明: 给定两个数组arr1和arr2,arr2的元素是不同的,arr2中的所有元素也在arr1中。 对arr1的元素进行排序,以使arr1中项目的相对顺序与arr2中的相同。 不在arr2中出现的元素应按升序放置在arr1的末尾。Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19]Constraints: 1、arr1.length, arr2.length <= 1000 2、0 <= arr1[i], arr2[i] <= 1000...
class Solution: def relativeSortArray(self, arr1, arr2): res = sorted(arr1) idx_r = 0 idx_2 = 0 print(res) while idx_r < len(res) and idx_2 < len(arr2): if res[idx_r] == arr2[idx_2]: if idx_r < len(res) - 1 and res[idx_r + 1] != res[idx_r]: ...
{2: 3, 3: 2, 1: 1, 4: 1, 6: 1, 7: 1, 9: 1, 19: 1}
Apache-2.0
Sort/0926/1122. Relative Sort Array.ipynb
YuHe0108/Leetcode
import tensorflow as tf import tensorflow.feature_column as fc import os import sys import matplotlib.pyplot as plt from IPython.display import clear_output tf.enable_eager_execution() !pip install -q requests !git clone --depth 1 https://github.com/tensorflow/models # add the root directory of the repo to your pytho...
_____no_output_____
MIT
tf_estimator_linearmodel.ipynb
Junhojuno/DeepLearning-Beginning
Pre-processing the text for Object2VecProcessing the text to fit Object2Vec algorithm.
import boto3 import pandas as pd import re from sklearn import preprocessing import numpy as np import json import os from sklearn.feature_extraction.text import CountVectorizer import random random.seed(42) from random import sample from sklearn.utils import shuffle from nltk import word_tokenize
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Functions
def get_filtered_objects(bucket_name, prefix): """filter objects based on bucket and prefix""" s3 = boto3.client("s3") files = s3.list_objects_v2(Bucket = bucket_name, Prefix =prefix) return files def download_object(bucket_name, key, local_path): """Download S3 object to local""" s3 = boto3.res...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Download the data locally
bucket_name = "YOUR_BUCKET_HERE" prefix = "connect/" #save the files locally. create_dir("./data") files = get_filtered_objects(bucket_name, prefix)['Contents'] files = get_csv(files) local_files=[] print(files) for file in files: full_prefix = "/".join(file.split("/")[:-1]) inner_folder = full_prefix.replace(p...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Concatenate the .csv files
import pandas.errors content = [] for filename in local_files: try: df = pd.read_csv(filename, sep=";") print(df.columns) content.append(df) except pandas.errors.ParserError: print("File", filename, "cannot be parsed. Check its format") data = pd.concat(content) customer_text = d...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Create random labelsChange this to use your own labelsAlso: we are here replicating the texts to increase statistics
customer_text = pd.concat([customer_text]*300, ignore_index=True) customer_text['labels']=np.random.randint(low=0, high=5, size=len(customer_text)) customer_text.labels.hist()
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Get vocabulary from the corpus using sklearn for the heavy liftingThe vocabulary will be built only taking into account words that belong to news related to crimes.
counts = CountVectorizer(min_df=5, max_df=0.95, token_pattern=r'(?u)\b[A-Za-z]{2,}\b').fit(customer_text['Content'].values.tolist()) vocab = counts.get_feature_names() vocab_to_token_dict = dict(zip(vocab, range(len(vocab)))) token_to_vocab_dict = dict(zip(range(len(vocab)), vocab)) len(vocab) create_dir("./vocab") voc...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Encode data bodyTransform the texts in the data to encodings from the vocabulary created.
import nltk nltk.download('punkt') customer_text['encoded_content'] = customer_text['Content'].apply(lambda x: sentence_to_tokens(x, vocab_to_token_dict)) customer_text['labels'] customer_text['labels']=customer_text['labels'].apply(lambda x: [x]) customer_text[['labels','encoded_content']] # remove entriews with no te...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Build sentence pairs Object2Vec
#negative pairs for the algorithm: need to decide which lables we want to sample *against*. negative_labels_to_sample = range(5) sentence_pairs = build_sentence_pairs(customer_text)
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
Build negative sentence pairs for training Object2VecNegative sampling for the Object2Vec algorithm - add negative and positive pairs (document,label)
sentence_pairs = build_negative_pairs(customer_text,negative_labels_to_sample,sentence_pairs) print("Sample of input for Object2vec algorith: {}".format(sentence_pairs[1])) !pip install jsonlines
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
train/test/val split, save to file
# shuffle and split test/train/val random.seed(42) random.shuffle(sentence_pairs) n_train = int(0.7 * len(sentence_pairs)) # split train and test sentence_pairs_train = sentence_pairs[:n_train] sentence_pairs_test = sentence_pairs[n_train:] # further split test set into validation set (val_vectors) and test set (te...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
8. Upload to S3
import os s3_client = boto3.client('s3') out_prefix = "connect/O2VInput" for n in ['train', 'test', 'val',]: s3_client.upload_file("./data/"+n+'.jsonl', bucket_name, \ os.path.join(out_prefix, n, n+'.jsonl'),\ ExtraArgs = {'ServerSideEncryption':'AES256'}) #uplo...
_____no_output_____
MIT-0
notebooks/connect_01_text_processing.ipynb
aws-samples/contact-lens-for-amazon-connect-data-gathering-mechanism
1. American Sign Language (ASL)American Sign Language (ASL) is the primary language used by many deaf individuals in North America, and it is also used by hard-of-hearing and hearing individuals. The language is as rich as spoken languages and employs signs made with the hand, along with facial gestures and bodily po...
# Import packages and set numpy random seed import numpy as np np.random.seed(5) import tensorflow as tf tf.set_random_seed(2) from datasets import sign_language import matplotlib.pyplot as plt %matplotlib inline # Load pre-shuffled training and test datasets (x_train, y_train), (x_test, y_test) = sign_language.load_...
_____no_output_____
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
2. Visualize the training dataNow we'll begin by creating a list of string-valued labels containing the letters that appear in the dataset. Then, we visualize the first several images in the training data, along with their corresponding labels.
# Store labels of dataset labels = ['A','B','C'] # Print the first several training images, along with the labels fig = plt.figure(figsize=(20,5)) for i in range(36): ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[]) ax.imshow(np.squeeze(x_train[i])) ax.set_title("{}".format(labels[y_train[i]])) plt...
_____no_output_____
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
3. Examine the datasetLet's examine how many images of each letter can be found in the dataset.Remember that dataset has already been split into training and test sets for you, where x_train and x_test contain the images, and y_train and y_test contain their corresponding labels.Each entry in y_train and y_test is one...
# Number of A's in the training dataset num_A_train = sum(y_train==0) # Number of B's in the training dataset num_B_train = sum(y_train==1) # Number of C's in the training dataset num_C_train = sum(y_train==2) # Number of A's in the test dataset num_A_test = sum(y_test==0) # Number of B's in the test dataset num_B_tes...
Training set: A: 540, B: 528, C: 532 Test set: A: 118, B: 144, C: 138
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
4. One-hot encode the dataCurrently, our labels for each of the letters are encoded as categorical integers, where 'A', 'B' and 'C' are encoded as 0, 1, and 2, respectively. However, recall that Keras models do not accept labels in this format, and we must first one-hot encode the labels before supplying them to a Ke...
from keras.utils import np_utils # One-hot encode the training labels y_train_OH = np_utils.to_categorical(y_train, 3) # One-hot encode the test labels y_test_OH = np_utils.to_categorical(y_test, 3)
_____no_output_____
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
5. Define the modelNow it's time to define a convolutional neural network to classify the data.This network accepts an image of an American Sign Language letter as input. The output layer returns the network's predicted probabilities that the image belongs in each category.
from keras.layers import Conv2D, MaxPooling2D from keras.layers import Flatten, Dense from keras.models import Sequential model = Sequential() # First convolutional layer accepts image input model.add(Conv2D(filters=5, kernel_size=5, padding='same', activation='relu', input_shape=(50, 50, 3)))...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_10 (Conv2D) (None, 50, 50, 5) 380 ________________________________________________________...
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
6. Compile the modelAfter we have defined a neural network in Keras, the next step is to compile it!
# Compile the model model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
7. Train the modelOnce we have compiled the model, we're ready to fit it to the training data.
# Train the model hist = model.fit(x_train, y_train_OH, validation_split=0.2, epochs=2, batch_size=32)
Train on 1280 samples, validate on 320 samples Epoch 1/2 1280/1280 [==============================] - 4s 3ms/step - loss: 0.9623 - acc: 0.6102 - val_loss: 0.7729 - val_acc: 0.8688 Epoch 2/2 1280/1280 [==============================] - 3s 3ms/step - loss: 0.6252 - acc: 0.8656 - val_loss: 0.4826 - val_acc: 0.9406
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
8. Test the modelTo evaluate the model, we'll use the test dataset. This will tell us how the network performs when classifying images it has never seen before!If the classification accuracy on the test dataset is similar to the training dataset, this is a good sign that the model did not overfit to the training data...
# Obtain accuracy on test set score = model.evaluate(x=x_test, y=y_test_OH, verbose=0) print('Test accuracy:', score[1])
Test accuracy: 0.9475
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
9. Visualize mistakesHooray! Our network gets very high accuracy on the test set! The final step is to take a look at the images that were incorrectly classified by the model. Do any of the mislabeled images look relatively difficult to classify, even to the human eye? Sometimes, it's possible to review the images...
# Get predicted probabilities for test dataset y_probs = ... # Get predicted labels for test dataset y_preds = ... # Indices corresponding to test images which were mislabeled bad_test_idxs = ... # Print mislabeled examples fig = plt.figure(figsize=(25,4)) for i, idx in enumerate(bad_test_idxs): ax = fig.add_sub...
_____no_output_____
MIT
ASL Recognition with Deep Learning/notebook.ipynb
Shogun89/DataCamp-Python
def fibonaci(n): print("Llamada",n) if n== 1 or n ==0: return n else: return (fibonaci(n-1) + fibonaci (n-2)) print(fibonaci(6))
Llamada 6 Llamada 5 Llamada 4 Llamada 3 Llamada 2 Llamada 1 Llamada 0 Llamada 1 Llamada 2 Llamada 1 Llamada 0 Llamada 3 Llamada 2 Llamada 1 Llamada 0 Llamada 1 Llamada 4 Llamada 3 Llamada 2 Llamada 1 Llamada 0 Llamada 1 Llamada 2 Llamada 1 Llamada 0 8
MIT
7Diciembre.ipynb
samuelgh15/daa_2021_1
Printing basic types
print("Hello World!") print("Welcome to Foundations of Data Science!") print(2020) print(1.314) print(True) print(False) print(True or False) print(True and False)
_____no_output_____
Apache-2.0
1-Python-Basics.ipynb
aktgitrepo/python-for-datascience
Variables and inputs
var = "value" print(var) print(type(var)) print(id(var)) var_2 = "_2" print(var_2) print(id(var_2)) print("variable " + var) num = 2020 print(type(num)) print(type(num)) is_good = True print(type(is_good)) my_name = input("What is your name ") print(my_name, type(my_name)) hours_per_week = 24 * 7 print("hours_per_week"...
_____no_output_____
Apache-2.0
1-Python-Basics.ipynb
aktgitrepo/python-for-datascience
String Processing
topic = "Foundations of Data Science" print(topic) print(topic[0]) print(topic[1]) print(topic[10]) print(topic[-1]) print(topic[-2]) print(topic[0:10]) print(topic[12:16]) print(topic.lower()) print(topic) topic = topic.lower() print(topic.upper()) print(topic.islower()) topic = topic.upper() print(topic.islower()) pr...
_____no_output_____
Apache-2.0
1-Python-Basics.ipynb
aktgitrepo/python-for-datascience
If, For, While Blocks
hours_per_week = 5 if hours_per_week > 10: print(my_name + " you are doing well") if hours_per_week > 10: print(my_name + " you are doing well") print("Outside If") if hours_per_week > 10: print(my_name + " you are doing well") else: print(my_name + " you need to study more") for i in range(5): prin...
_____no_output_____
Apache-2.0
1-Python-Basics.ipynb
aktgitrepo/python-for-datascience
Functions
def fibonacci(pos): a = 1 b = 1 for i in range(pos): temp = a + b a = b b = temp return temp print(fibonacci(3)) print(fibonacci(8), fibonacci(7)) for i in range(2, 20): ratio = fibonacci(i) / fibonacci(i - 1) print(i, ratio) def fibonacci_relative(pos, a, b): for i i...
_____no_output_____
Apache-2.0
1-Python-Basics.ipynb
aktgitrepo/python-for-datascience
KMeans
X_cluster = pd.DataFrame(data['LotArea']) X_cluster['OverallCond'] = data['OverallCond'] X_cluster['OverallQual'] = data['OverallQual'] #X_svm['FullBath'] = data['FullBath'] X_cluster['TotRmsAbvGrd'] = data['TotRmsAbvGrd'] #X_cluster['SalePrice'] = data['SalePrice'] #X_svm['GarageArea'] = data['GarageArea'] k_range = ...
_____no_output_____
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
We decided to cluster using several features that we previously saw had significant relationships with SalePrice. The clustering revealed several unique properties. In the first graph, which shows the distribution of SalePrice within each cluster, indicates that the variables we chose do indeed have a strong relationsh...
<font color=blue size = 40>**Ensemble (Stacking) Model**</font> init_prior = [] data['BldgType'] = LabelEncoder().fit_transform(data['BldgType']) init_prior.append('OverallQual') init_prior.append('BldgType') init_prior.append('TotalBsmtSF') init_prior.append('1stFlrSF') init_prior.append('GrLivArea') init_prior.append...
_____no_output_____
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
Sets of somewhat correlated variables:['GarageCars', 'OverallQual', 'GarageArea']['TotalBsmtSF', '1stFlrSF']['GrLivArea', '2ndFlrSF', 'FullBath', 'TotRmsAbvGrd']['GarageYrBlt', 'YearRemodAdd', 'YearBuilt'] **Feature Selection**
new_prior = list(init_prior) names = ['Garage','LowerSF','Living','Year'] new_prior.extend(names) for dependents in [['GarageCars', 'OverallQual', 'GarageArea'],['TotalBsmtSF','1stFlrSF'], ['GrLivArea', '2ndFlrSF', 'FullBath', 'TotRmsAbvGrd'],['GarageYrBlt', 'YearRemodAdd', 'YearBuilt']]: pca = PC...
_____no_output_____
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
**Preprocessing**
plt.rcParams['figure.figsize'] = (16,4) for feature_name in new_prior_2: plt.title(feature_name) plt.subplot(1, 3, 1) plt.hist(data[feature_name],density=True) plt.xlabel(feature_name) plt.ylabel('Frequency') stdev = np.std(data[feature_name]) mean = np.mean(data[feature_name]) col_...
_____no_output_____
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
Clustering Algorithm for part of Stack
def cluster_from_stack_of_KMeans(data, K=8, num_weak_learners = 5,num_neighbors=1, distance_penalty= lambda x: x): assert K < len(data) assert num_neighbors <= len(data) C = np.empty((num_weak_learners,data.shape[0])) SSE = np.empty((num_weak_learners,)) for it...
_____no_output_____
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
Finding Stable Parameters for clustering
k_ticks = [3,7,20] w_ticks = [5,20] n_ticks = [1,2,3] def sample_clustering_params(): cluster_sizes = {} for k in k_ticks: for w in w_ticks: for n in n_ticks: c_sizes = [] for i in range(5): train, valid, _, _ = train_test_split( ...
190325167167.65564
MIT
Intro to Python Class Projects/Intro to Python ML Project D.ipynb
Ddottsai/Code-Storage
Задание 1.2 - Линейный классификатор (Linear classifier)В этом задании мы реализуем другую модель машинного обучения - линейный классификатор. Линейный классификатор подбирает для каждого класса веса, на которые нужно умножить значение каждого признака и потом сложить вместе.Тот класс, у которого эта сумма больше, и я...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 from dataset import load_svhn, random_split_train_val from gradient_check import check_gradient from metrics import multiclass_accuracy import linear_classifer
_____no_output_____
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Как всегда, первым делом загружаем данныеМы будем использовать все тот же SVHN.
def prepare_for_linear_classifier(train_X, test_X): train_flat = train_X.reshape(train_X.shape[0], -1).astype(np.float) / 255.0 test_flat = test_X.reshape(test_X.shape[0], -1).astype(np.float) / 255.0 # Subtract mean mean_image = np.mean(train_flat, axis = 0) train_flat -= mean_image test_f...
_____no_output_____
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Играемся с градиентами!В этом курсе мы будем писать много функций, которые вычисляют градиенты аналитическим методом.Все функции, в которых мы будем вычислять градиенты будут написаны по одной и той же схеме. Они будут получать на вход точку, где нужно вычислить значение и градиент функции, а на выходе будут выдавать...
# TODO: Implement check_gradient function in gradient_check.py # All the functions below should pass the gradient check def square(x): return float(x*x), 2*x check_gradient(square, np.array([3.0])) def array_sum(x): assert x.shape == (2,), x.shape return np.sum(x), np.ones_like(x) check_gradient(array_s...
Gradient check passed! Gradient check passed! Gradient check passed!
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Начинаем писать свои функции, считающие аналитический градиентТеперь реализуем функцию softmax, которая получает на вход оценки для каждого класса и преобразует их в вероятности от 0 до 1:![image](https://wikimedia.org/api/rest_v1/media/math/render/svg/e348290cf48ddbb6e9a6ef4e39363568b67c09d3)**Важно:** Практический а...
# TODO Implement softmax and cross-entropy for single sample probs = linear_classifer.softmax(np.array([-10, 0, 10])) # Make sure it works for big numbers too! probs = linear_classifer.softmax(np.array([1000, 0, 0])) assert np.isclose(probs[0], 1.0)
_____no_output_____
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Кроме этого, мы реализуем cross-entropy loss, которую мы будем использовать как функцию ошибки (error function).В общем виде cross-entropy определена следующим образом:![image](https://wikimedia.org/api/rest_v1/media/math/render/svg/0cb6da032ab424eefdca0884cd4113fe578f4293)где x - все классы, p(x) - истинная вероятност...
probs = linear_classifer.softmax(np.array([-5, 0, 5])) display(probs) linear_classifer.cross_entropy_loss(probs, 1)
_____no_output_____
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
После того как мы реализовали сами функции, мы можем реализовать градиент.Оказывается, что вычисление градиента становится гораздо проще, если объединить эти функции в одну, которая сначала вычисляет вероятности через softmax, а потом использует их для вычисления функции ошибки через cross-entropy loss.Эта функция `sof...
# TODO Implement combined function or softmax and cross entropy and produces gradient loss, grad = linear_classifer.softmax_with_cross_entropy(np.array([1, 0, 0]), 1) check_gradient(lambda x: linear_classifer.softmax_with_cross_entropy(x, 1), np.array([1, 0, 0], np.float))
Gradient check passed!
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
В качестве метода тренировки мы будем использовать стохастический градиентный спуск (stochastic gradient descent или SGD), который работает с батчами сэмплов. Поэтому все наши фукнции будут получать не один пример, а батч, то есть входом будет не вектор из `num_classes` оценок, а матрица размерности `batch_size, num_cl...
# TODO Extend combined function so it can receive a 2d array with batch of samples np.random.seed(42) # Test batch_size = 1 num_classes = 4 batch_size = 1 predictions = np.random.randint(-1, 3, size=(num_classes, batch_size)).astype(np.float) target_index = np.random.randint(0, num_classes, size=(batch_size, 1)).astype...
Gradient check passed! Gradient check passed!
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
И теперь регуляризацияМы будем использовать L2 regularization для весов как часть общей функции ошибки.Напомним, L2 regularization определяется какl2_reg_loss = regularization_strength * sumij W[i, j]2Реализуйте функцию для его вычисления и вычисления соотвествующих градиентов.
# TODO Implement linear_softmax function that uses softmax with cross-entropy for linear classifier batch_size = 2 num_classes = 2 num_features = 3 np.random.seed(42) W = np.random.randint(-1, 3, size=(num_features, num_classes)).astype(np.float) X = np.random.randint(-1, 3, size=(batch_size, num_features)).astype(np.f...
Gradient check passed!
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Тренировка! Градиенты в порядке, реализуем процесс тренировки!
# TODO: Implement LinearSoftmaxClassifier.fit function classifier = linear_classifer.LinearSoftmaxClassifier() loss_history = classifier.fit(train_X, train_y, epochs=10, learning_rate=1e-3, batch_size=300, reg=1e1) # let's look at the loss history! plt.plot(loss_history) # Let's check how it performs on validation set ...
Accuracy: 0.09399999999999997 Epoch 0, loss: 2.609400 Epoch 1, loss: 2.609363 Epoch 2, loss: 2.609327 Epoch 3, loss: 2.609292 Epoch 4, loss: 2.609257 Epoch 5, loss: 2.609224 Epoch 6, loss: 2.609191 Epoch 7, loss: 2.609159 Epoch 8, loss: 2.609128 Epoch 9, loss: 2.609097 Epoch 10, loss: 2.609068 Epoch 11, loss: 2.609039...
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Как и раньше, используем кросс-валидацию для подбора гиперпараметтов.В этот раз, чтобы тренировка занимала разумное время, мы будем использовать только одно разделение на тренировочные (training) и проверочные (validation) данные.Теперь нам нужно подобрать не один, а два гиперпараметра! Не ограничивайте себя изначальн...
num_epochs = 200 batch_size = 300 learning_rates = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5] reg_strengths = [1e-3, 1e-2, 1e-4, 1e-5, 1e-6, 1e-7] best_val_accuracy = 0 for learning_rate in learning_rates: for reg_strength in reg_strengths: classifier.fit(train_X, train_y, batch_size, learning_rate, reg_strength, num_...
Epoch 0, loss: 2.299253 Epoch 1, loss: 2.296205 Epoch 2, loss: 2.293332 Epoch 3, loss: 2.290550 Epoch 4, loss: 2.287845 Epoch 5, loss: 2.285214 Epoch 6, loss: 2.282651 Epoch 7, loss: 2.280155 Epoch 8, loss: 2.277721 Epoch 9, loss: 2.275346 Epoch 10, loss: 2.273029 Epoch 11, loss: 2.270765 Epoch 12, loss: 2.268554 Epoch...
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
Какой же точности мы добились на тестовых данных?
test_pred = best_classifier.predict(test_X) test_accuracy = multiclass_accuracy(test_pred, test_y) print('Linear softmax classifier test set accuracy: %f' % (test_accuracy, ))
_____no_output_____
MIT
assignments/assignment1/Linear classifier.ipynb
DANTEpolaris/dlcourse_ai
This notebook links to **ModelFlow** models and examples.Please have patience until the notebook had been loaded and executed. ModelFlow AbstractModelFlow is a Python toolkit which can handle a wide range of models from small to huge. This covers: on-boarding a model, analyze the logical structure, solve the model...
from modelclass import model model.modelflow_auto()
_____no_output_____
X11
Examples/Overview.ipynb
IbHansen/Modelflow2
Gallery Below you will find links Jupyter notebooks using ModelFlow to run different models. The purpose of the notebooks are primarily to illustrate how ModelFlow can be used to manage a fairly large range of models and to show some of the capabilities.
model.display_toc()
_____no_output_____
X11
Examples/Overview.ipynb
IbHansen/Modelflow2
**MITRE ATT&CK API FILTERS**: Python Client------------------ Import ATTACK API Client
from attackcti import attack_client
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Import Extra Libraries
from pandas import * from pandas.io.json import json_normalize
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Initialize ATT&CK Client Variable
lift = attack_client()
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Technique by Name (TAXII)You can use a custom method in the attack_client class to get a technique across all the matrices by its name. It is case sensitive.
technique_name = lift.get_technique_by_name('Rundll32') technique_name
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Data Sources from All Techniques (TAXII)* You can also get all the data sources available in ATT&CK* Currently the only techniques with data sources are the ones in Enterprise ATT&CK.
data_sources = lift.get_data_sources() len(data_sources) data_sources
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Any STIX Object by ID (TAXII)* You can get any STIX object by its id across all the matrices. It is case sensitive.* You can use the following STIX Object Types: * attack-pattern > techniques * course-of-action > mitigations * intrusion-set > groups * malware * tool
object_by_id = lift.get_object_by_attack_id('attack-pattern', 'T1307') object_by_id
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Any Group by Alias (TAXII)You can get any Group by its Alias property across all the matrices. It is case sensitive.
group_name = lift.get_group_by_alias('Cozy Bear') group_name
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Relationships by Any Object (TAXII)* You can get available relationships defined in ATT&CK of type **uses** and **mitigates** for specific objects across all the matrices.
groups = lift.get_groups() one_group = groups[0] relationships = lift.get_relationships_by_object(one_group) relationships[0]
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get All Techniques with Mitigations (TAXII)The difference with this function and **get_all_techniques()** is that **get_techniques_mitigated_by_all_mitigations** returns techniques that have mitigations mapped to them.
techniques_mitigated = lift.get_techniques_mitigated_by_all_mitigations() techniques_mitigated[0]
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Techniques Used by Software (TAXII)This the function returns information about a specific software STIX object.
all_software = lift.get_software() one_software = all_software[0] software_techniques = lift.get_techniques_used_by_software(one_software) software_techniques[0]
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Techniques Used by Group (TAXII)If you do not provide the name of a specific **Group** (Case Sensitive), the function returns information about all the groups available across all the matrices.
groups = lift.get_groups() one_group = groups[0] group_techniques = lift.get_techniques_used_by_group(one_group) group_techniques[0]
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
Get Software Used by Group (TAXII)You can retrieve every software (malware or tool) mapped to a specific Group STIX object
groups = lift.get_groups() one_group = groups[0] group_software = lift.get_software_used_by_group(one_group) group_software[0]
_____no_output_____
BSD-3-Clause
notebooks/Usage_Filters.ipynb
binaryflesh/ATTACK-Python-Client
_*Running simulations with noise and measurement error mitigation in Aqua*_This notebook demonstrates using the [Qiskit Aer](https://qiskit.org/aer) `qasm_simulator` to run a simulation with noise, based on a noise model, in Aqua. This can be useful to investigate behavior under different noise conditions. Aer not onl...
import numpy as np import pylab from qiskit import Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_for...
_____no_output_____
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
Noisy simulation will be demonstrated here with VQE, finding the minimum (ground state) energy of an Hamiltonian, but the technique applies to any quantum algorithm from Aqua.So for VQE we need a qubit operator as input. Here we will take a set of paulis that were originally computed by qiskit-chemistry, for an H2 mole...
pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"}, {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"}, {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"}, {"coeff": {"imag": 0.0, "real": -0.011...
Number of qubits: 2
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
As the above problem is still easily tractable classically we can use ExactEigensolver to compute a reference value so we can compare later the results. _(A copy of the operator is used below as what is passed to ExactEigensolver will be converted to matrix form and we want the operator we use later, on the Aer qasm si...
ee = ExactEigensolver(qubit_op.copy()) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref))
Reference value: -1.8572750302023797
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
Performance *without* noiseFirst we will run on the simulator without adding noise to see the result. I have created the backend and QuantumInstance, which holds the backend as well as various other run time configuration, which are defaulted here, so it easy to compare when we get to the next section where noise is a...
backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) aqua_globals.random_seed = 167 optim...
VQE on Aer qasm simulator (no noise): -1.8598749159580135 Delta from reference: -0.0025998857556337462
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
We captured the energy values above during the convergence so we can see what went on in the graph below.
pylab.rcParams['figure.figsize'] = (12, 4) pylab.plot(counts, values) pylab.xlabel('Eval count') pylab.ylabel('Energy') pylab.title('Convergence with no noise');
_____no_output_____
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
Performance *with* noiseNow we will add noise. Here we will create a noise model for Aer from an actual device. You can create custom noise models with Aer but that goes beyond the scope of this notebook. Links to further information on Aer noise model, for those that may be interested in doing this, were given in ins...
from qiskit.providers.aer import noise provider = IBMQ.load_account() device = provider.get_backend('ibmqx4') coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates print(noise_model) backend = Aer.get_backend(...
_____no_output_____
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
Declarative approach and noise modelNote: if you are running an experiment using the declarative approach, with a dictionary/json, there are keywords in the `backend` section that let you define the noise model based on a device, as well as setup the coupling map too. The basis gate setup, that is shown above, will au...
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, ...
_____no_output_____
Apache-2.0
aqua/simulations_with_noise_and_measurement_error_mitigation.ipynb
lukasszz/qiskit-tutorials-community
Omni
ptr_before = [graspy.utils.pass_to_ranks(g) for g in graphs] lccs = get_multigraph_lcc(graphs) tensor = np.stack(lccs) tensor.shape ptr = [graspy.utils.pass_to_ranks(g) for g in lccs] omni = OmnibusEmbed() Zhat = omni.fit_transform(lccs[:100]) Zhat = Zhat.reshape(100, 670, -1) cmds = ClassicalMDS() Xhat = cmds.fit_tra...
/home/j1c/graphstats/venv/lib/python3.5/site-packages/ipykernel_launcher.py:2: Warning: test
Apache-2.0
Experiments/20181204/Untitled.ipynb
j1c/multigraph_clustering
*This notebook contains an excerpt instructional material from [gully](https://twitter.com/gully_) and the [K2 Guest Observer Office](https://keplerscience.arc.nasa.gov/); the content is available [on GitHub](https://github.com/gully/goldenrod).* Spot-check Everest Validation Summaries for KEGS This notebook does mor...
import matplotlib.pyplot as plt import numpy as np from astropy.io import fits import astropy import os import pandas as pd import seaborn as sns from astropy.utils.console import ProgressBar import everest %matplotlib inline %config InlineBackend.figure_format = 'retina' everest_path = '../../everest/everest/missions/...
_____no_output_____
MIT
notebooks/01.06-Everest_KEGS_DVS.ipynb
gully/goldenrod
Decent examples to try to replicate: 12
i+=1 star = everest.Everest(ke_list[i]) star.dvs() for i in range(len(ke_list)): star = everest.Everest(ke_list[i]) star.dvs()
INFO [everest.user.DownloadFile()]: Found cached file. INFO [everest.user.load_fits()]: Loading FITS file for 211305171. INFO [everest.user.DownloadFile()]: Found cached file. INFO [everest.user.DownloadFile()]: Found cached file. INFO [everest.user.load_fits()]: Loading FITS file for 211311876. INFO [everest.use...
MIT
notebooks/01.06-Everest_KEGS_DVS.ipynb
gully/goldenrod
Ex2 - Getting and Knowing your DataCheck out [Chipotle Exercises Video Tutorial](https://www.youtube.com/watch?v=lpuYZ5EUyS8&list=PLgJhDSE2ZLxaY_DigHeiIDC1cD09rXgJv&index=2) to watch a data scientist go through the exercises This time we are going to pull data directly from the internet.Special thanks to: https://gith...
import pandas as pd import numpy as np
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv). Step 3. Assign it to a variable called chipo.
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv' chipo = pd.read_csv(url, sep = '\t')
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 4. See the first 10 entries
chipo.head(10)
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 5. What is the number of observations in the dataset?
# Solution 1 chipo.shape[0] # entries <= 4622 observations # Solution 2 chipo.info() # entries <= 4622 observations
<class 'pandas.core.frame.DataFrame'> RangeIndex: 4622 entries, 0 to 4621 Data columns (total 5 columns): order_id 4622 non-null int64 quantity 4622 non-null int64 item_name 4622 non-null object choice_description 3376 non-null object item_price 4622 non-null object d...
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 6. What is the number of columns in the dataset?
chipo.shape[1]
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 7. Print the name of all the columns.
chipo.columns
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise
Step 8. How is the dataset indexed?
chipo.index
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/Chipotle/Exercise_with_Solutions.ipynb
ismael-araujo/pandas-exercise