markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Showing the most popular songs in the dataset
graphlab.canvas.set_target('ipynb') song_data['song'].show() len(song_data)
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Count number of unique users in the dataset
users = song_data['user_id'].unique() len(users)
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Create a song recommender
train_data,test_data = song_data.random_split(.8,seed=0)
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Simple popularity-based recommender
popularity_model = graphlab.popularity_recommender.create(train_data, user_id='user_id', item_id='song')
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Use the popularity model to make some predictions A popularity model makes the same prediction for all users, so provides no personalization.
popularity_model.recommend(users=[users[0]]) popularity_model.recommend(users=[users[1]])
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Build a song recommender with personalization We now create a model that allows us to make personalized recommendations to each user.
personalized_model = graphlab.item_similarity_recommender.create(train_data, user_id='user_id', item_id='song')
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Applying the personalized model to make song recommendations As you can see, different users get different recommendations now.
personalized_model.recommend(users=[users[0]]) personalized_model.recommend(users=[users[1]])
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
We can also apply the model to find similar songs to any song in the dataset
personalized_model.get_similar_items(['With Or Without You - U2']) personalized_model.get_similar_items(['Chan Chan (Live) - Buena Vista Social Club'])
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
Quantitative comparison between the models We now formally compare the popularity and the personalized models using precision-recall curves.
if graphlab.version[:3] >= "1.6": model_performance = graphlab.compare(test_data, [popularity_model, personalized_model], user_sample=0.05) graphlab.show_comparison(model_performance,[popularity_model, personalized_model]) else: %matplotlib inline model_performance = graphlab.recommender.util.compare_mo...
songrecommender/.ipynb_checkpoints/Song recommender-checkpoint.ipynb
anilcs13m/MachineLearning_Mastering
gpl-2.0
If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Ignore the error message related to tensorflow-serving-api.
import sys import warnings warnings.filterwarnings('ignore') os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # If you are running this notebook in Colab, follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests....
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. AI Platform runs the code from this package. In this tutorial, AI Platform als...
BUCKET_NAME = "michaelabel-gcp-training-ml" REGION = "us-central1" os.environ['BUCKET_NAME'] = BUCKET_NAME os.environ['REGION'] = REGION
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Run the following cell to create your Cloud Storage bucket if it does not already exist.
%%bash exists=$(gsutil ls -d | grep -w gs://${BUCKET_NAME}/) if [ -n "$exists" ]; then echo -e "Bucket gs://${BUCKET_NAME} already exists." else echo "Creating a new GCS bucket." gsutil mb -l ${REGION} gs://${BUCKET_NAME} echo -e "\nHere are your current buckets:" gsutil ls fi
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Import libraries for creating model Import the libraries we'll be using in this tutorial. This tutorial has been tested with TensorFlow 1.15.2.
%tensorflow_version 1.x import tensorflow as tf import tensorflow.feature_column as fc import pandas as pd import numpy as np import json import time # Should be 1.15.2 print(tf.__version__)
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Downloading and preprocessing data In this section you'll download the data to train and evaluate your model from a public GCS bucket. The original data has been preprocessed from the public BigQuery dataset linked above.
%%bash # Copy the data to your notebook instance mkdir taxi_preproc gsutil cp -r gs://cloud-training/bootcamps/serverlessml/taxi_preproc/*_xai.csv ./taxi_preproc ls -l taxi_preproc
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Read the data with Pandas We'll use Pandas to read the training and validation data into a DataFrame. We will only use the first 7 columns of the csv files for our models.
CSV_COLUMNS = ['fare_amount', 'dayofweek', 'hourofday', 'pickuplon', 'pickuplat', 'dropofflon', 'dropofflat'] DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] DTYPES = ['float32', 'str' , 'int32', 'float32' , 'float32' , 'float32' , 'float32' ] def prepare_data(file_path): df = pd.read_csv(fil...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Build, train, and evaluate our model with Keras We'll use tf.Keras to build a our ML model that takes our features as input and predicts the fare amount. But first, we will do some feature engineering. We will be utilizing tf.feature_column and tf.keras.layers.Lambda to implement our feature engineering in the model g...
# Create functions to compute engineered features in later Lambda layers def euclidean(params): lat1, lon1, lat2, lon2 = params londiff = lon2 - lon1 latdiff = lat2 - lat1 return tf.sqrt(londiff*londiff + latdiff*latdiff) NUMERIC_COLS = ['pickuplon', 'pickuplat', 'dropofflon', 'dropofflat', 'hourofday', 'dayof...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create an input data pipeline with tf.data Per best practices, we will use tf.Data to create our input data pipeline. Our data is all in an in-memory dataframe, so we will use tf.data.Dataset.from_tensor_slices to create our pipeline.
def load_dataset(features, labels, mode): dataset = tf.data.Dataset.from_tensor_slices(({"dayofweek" : features["dayofweek"], "hourofday" : features["hourofday"], "pickuplat" : features["pickuplat"], ...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Train the model Now we train the model. We will specify a number of epochs which to train the model and tell the model how many steps to expect per epoch.
tf.keras.backend.get_session().run(tf.tables_initializer(name='init_all_tables')) steps_per_epoch = 426433 // 256 model.fit(train_dataset, steps_per_epoch=steps_per_epoch, validation_data=valid_dataset, epochs=10) # Send test instances to model for prediction predict = model.predict(valid_dataset, steps = 1) predict...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Export the model as a TF 1 SavedModel In order to deploy our model in a format compatible with AI Explanations, we'll follow the steps below to convert our Keras model to a TF Estimator, and then use the export_saved_model method to generate the SavedModel and save it in GCS.
## Convert our Keras model to an estimator keras_estimator = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir='export') print(model.input) # We need this serving input function to export our model in the next cell serving_fn = tf.estimator.export.build_raw_serving_input_receiver_fn( model.input ...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Use TensorFlow's saved_model_cli to inspect the model's SignatureDef. We'll use this information when we deploy our model to AI Explanations in the next section.
!saved_model_cli show --dir $export_path --all
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Deploy the model to AI Explanations In order to deploy the model to Explanations, we need to generate an explanations_metadata.json file and upload this to the Cloud Storage bucket with our SavedModel. Then we'll deploy the model using gcloud. Prepare explanation metadata We need to tell AI Explanations the names of th...
# Print the names of our tensors print('Model input tensors: ', model.input) print('Model output tensor: ', model.output.name) baselines_med = train_data.median().values.tolist() baselines_mode = train_data.mode().values.tolist() print(baselines_med) print(baselines_mode) explanation_metadata = { "inputs": { ...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Since this is a regression model (predicting a numerical value), the baseline prediction will be the same for every example we send to the model. If this were instead a classification model, each class would have a different baseline prediction.
# Write the json to a local file with open('explanation_metadata.json', 'w') as output_file: json.dump(explanation_metadata, output_file) !gsutil cp explanation_metadata.json $export_path
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create the model Now we will create out model on Cloud AI Platform if it does not already exist.
MODEL = 'taxifare_explain' os.environ["MODEL"] = MODEL %%bash exists=$(gcloud ai-platform models list | grep ${MODEL}) if [ -n "$exists" ]; then echo -e "Model ${MODEL} already exists." else echo "Creating a new model." gcloud ai-platform models create ${MODEL} fi
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create the model version Creating the version will take ~5-10 minutes. Note that your first deploy may take longer.
# Each time you create a version the name should be unique import datetime now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") VERSION_IG = 'v_IG_{}'.format(now) VERSION_SHAP = 'v_SHAP_{}'.format(now) # Create the version with gcloud !gcloud beta ai-platform versions create $VERSION_IG \ --model $MODEL \ --origin $...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Getting predictions and explanations on deployed model Now that your model is deployed, you can use the AI Platform Prediction API to get feature attributions. We'll pass it a single test example here and see which features were most important in the model's prediction. Here we'll use gcloud to call our deployed model....
# Format data for prediction to our model !rm taxi-data.txt !touch taxi-data.txt prediction_json = {"dayofweek": "3", "hourofday": "17", "pickuplon": "-74.0026", "pickuplat": "40.7410", "dropofflat": "40.7790", "dropofflon": "-73.8772"} with open('taxi-data.txt', 'a') as outfile: json.dump(prediction_json, outfile) ...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Making the explain request Now we make the explaination requests. We will go ahead and do this here for both integrated gradients and SHAP using the prediction JSON from above.
resp_obj = !gcloud beta ai-platform explain --model $MODEL --version $VERSION_IG --json-instances='taxi-data.txt' response_IG = json.loads(resp_obj.s) resp_obj resp_obj = !gcloud beta ai-platform explain --model $MODEL --version $VERSION_SHAP --json-instances='taxi-data.txt' response_SHAP = json.loads(resp_obj.s) resp...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Understanding the explanations response First let's just look at the difference between our predictions using our baselines and our predicted taxi fare for the example.
explanations_IG = response_IG['explanations'][0]['attributions_by_label'][0] explanations_SHAP = response_SHAP['explanations'][0]['attributions_by_label'][0] predicted = round(explanations_SHAP['example_score'], 2) baseline = round(explanations_SHAP['baseline_score'], 2 ) print('Baseline taxi fare: ' + str(baseline) +...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Next let's look at the feature attributions for this particular example. Positive attribution values mean a particular feature pushed our model prediction up by that amount, and vice versa for negative attribution values. Which features seem like they're the most important...well it seems like the location features are...
from tabulate import tabulate feature_names = valid_data.columns.tolist() attributions_IG = explanations_IG['attributions'] attributions_SHAP = explanations_SHAP['attributions'] rows = [] for feat in feature_names: rows.append([feat, prediction_json[feat], attributions_IG[feat], attributions_SHAP[feat]]) print(tabul...
blogs/explainable_ai/AI_Explanations_on_CAIP.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Where the META MODELs are as follows: DNN - A Deep Neural Network classifier [16, 32, 32, 16, 2] from the Keras toolkit. Cross-entropy loss function. NBC - A Naive Bayes Classifier SVMC - A support vector machine classifier. LOGC - A Logistic classifier. Modelling. The Meta Models run on Linux and Windows und...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from pylab import * from sklearn.preprocessing import minmax_scale def sort_map(column): array = minmax_scale(train_results[column]) return array[np.argsort(-array)] scale = 1.0 fig = plt.figure(num=None, figsize=(8 * scale, 6 * scale), dpi...
Notebooks/OSM_Results/OSM Prelim Results.ipynb
kellerberrin/OSM-QSAR
mit
ION_ACTIVITY [ACTIVE] in EC50_200
ion_active = ec50_200_active.loc[train_results["ION_ACTIVITY"] == "ACTIVE"].sort_values("EC50") mols, labels = mol_label_list(ion_active) Draw.MolsToGridImage(mols,legends=labels,molsPerRow=4)
Notebooks/OSM_Results/OSM Prelim Results.ipynb
kellerberrin/OSM-QSAR
mit
ION_ACTIVITY [ACTIVE] Exemplar molecules that were added to the training set when moving from EC50_200 to EC50_500 Commentary These molecules have the same Triazole arm as we noticed in the previous notebook when trying to classifiy the molecular ION_ACTIVITY using D840_ACTIVE (DRAGON). This structure is also well repr...
sorted = test_results.sort_values("M5_500_250", ascending=False) mols, labels = mol_label_list(sorted) Draw.MolsToGridImage(mols,legends=labels,molsPerRow=4)
Notebooks/OSM_Results/OSM Prelim Results.ipynb
kellerberrin/OSM-QSAR
mit
练习二:写函数,根据给定符号和行数,打印相应直角三角形,等腰三角形及其他形式的三角形。
def printzj(fuhao,k): for i in range(1,k+1): print(fuhao*i) def printdy(fuhao,k): for i in range(1,k+1): if i==1: print(' '*(k-1) + fuhao) elif i%2==0: print(' '*(k-i) + fuhao*(i-1)*2+fuhao) else: print(' '*(k-i)+fuhao*(i-1)*2+fuhao) ...
chapter2/homework/computer/4-19/201611680283.ipynb
zhouqifanbdh/liupengyuan.github.io
mit
练习三:将任务4中的英语名词单数变复数的函数,尽可能的考虑多种情况,重新进行实现。
def n_change(a): k=len(a) if a[k-1:k] in ['o','s','x']: print (a,'es',sep='') elif a[k-2:k] in ['ch','sh']: print(a,'es',sep='') elif a[k-1:k]=='y' and a[k-2:k-1] in ['a','e','i','o','u']: print(a,'s',sep='') elif a[k-1:k]=='y': print(a[:-1],'ies',sep='') else: ...
chapter2/homework/computer/4-19/201611680283.ipynb
zhouqifanbdh/liupengyuan.github.io
mit
Datafreymin əsasına yerləşəcək verilənlər mənbə üzrə üzrə daxili və xarici formalara bölünür: Python daxili mənbələr: Siyahı: sətr əsaslı: İlk misal cədvəl daxilində dəyərlərin ard-arda, sətr-bə-sətr, siyahı daxilində DataFreymə daxil edilməsidir. SQL ilə tanış olan oxuyuculara bu dil daxilində İNSERT əmrin yada sala ...
email_list_lst=[('Omar','Bayramov','omarbayramov@hotmail.com',1), ('Ali','Aliyev','alialiyev@example.com',0), ('Dmitry','Vladimirov','v.dmitry@koala.kl',1), ('Donald','Trump','grabthat@pussycatdolls.com',1), ('Rashid','Maniyev','rashid.maniyev@exponential....
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Növbəti email_list_lst_cln dəyşəninə isə sütun adlarından ibarət siyahı təhkim edirik.
email_list_lst_cln=['f_name','l_name','email_adrs','a_status',]
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Nəhayət, DataFrame-nin "from_records" funksiyasına email_list_lst və email_list_lst_cln dəyərlərini ötürüb email_list_lst dəyərlərindən email_list_lst_cln sütunları ilə cədvəl yaradırıq və sonra cədvəli əks etdiririk.
df=pd.DataFrame.from_records(email_list_lst, columns=email_list_lst_cln) df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Siyahı: sütun əsaslı: Əvvəlki misaldan fərqli olaraq bu dəfə məlumatı sütun-sütun qəbul edib cədvələ ötürən yanaşmadan istifadə olunacaq. Bunun üçün kortej siyahısından istifadə olunacaq ki hər bir kortej özü-özlüyündə sütun adın əks edən sətrdən və həmin sətrdə yerləşən dəyərlər siyahısından ibarətdir.
email_list_lst=[('f_name', ['Omar', 'Ali', 'Dmitry', 'Donald', 'Rashid',]), ('l_name', ['Bayramov', 'Aliyev', 'Vladimirov', 'Trump', 'Maniyev',]), ('email_adrs', ['omarbayramov@hotmail.com', 'alialiyev@example.com', 'v.dmitry@koala.kl', 'grabthat@pussycatdolls.com', 'rashid.maniyev@expon...
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Lüğət: yazı əsaslı Növbəti misal mənim ən çox tərcihə etdiyim (əlbəttə ki çox vaxt verilənlər istədiyimiz formada olmur, və bizim nəyə üstünlük verdiyimiz onları heç marağlandırmır) üsula keçirik. Bu üsula üstünlük verməyimin səbəbi çox sadədir: bundan əvvəl və bundan sonra qeyd olunmuş yollardan istifadə edərkən məlum...
email_list=[{ 'f_name' : 'Omar', 'l_name': 'Bayramov', 'email_adrs' : 'omarbayramov@hotmail.com', 'a_status' : 1 }, {'f_name' : 'Ali', 'l_name': 'Aliyev', 'email_adrs':'alialiyev@example.com', 'a_status' : 0}, {'f_name': 'Dmitry'...
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Burada gördüyünüz kimi məlumat DataFrame daxilinə keçsədə, sütunlar istədiyimiz ardıcıllıqda yox, əlifba ardıcıllığı üzrə sıralanmışdır. Bu məqamı aradan qaldırmaq üçün ya yuxarıda DataFrame yaradan zamandaki kimi əvvəlcədən column parametri vasitəsi ilə sütun adların və ardıcıllığın qeyd etməli, və ya sonradan aşaqda ...
df=df[['f_name','l_name','email_adrs','a_status',]] df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Lüğət: sütun əsaslı Bu misal yuxarıda üzərindən keçdiyimiz "Siyahı:sütun əsaslı"-ya çox oxşayır. Fərq dəyərlərin bu dəfə siyahı şəkilində lüğət açarı olaraq qeyd olunmasıdır.
email_list_dct={'f_name': ['Omar', 'Ali', 'Dmitry', 'Donald', 'Rashid',], 'l_name': ['Bayramov', 'Aliyev', 'Vladimirov', 'Trump', 'Maniyev',], 'email_adrs': ['omarbayramov@hotmail.com', 'alialiyev@example.com', 'v.dmitry@koala.kl', 'grabthat@pussycatdolls.com', 'rashid.maniyev@exponentia...
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Cədvəli yaradaq və sütunların yerlərin dəyişək:
df = pd.DataFrame.from_dict(email_list_dct) df=df[['f_name','l_name','email_adrs','a_status',]] df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Python xarici mənbələr: Standart, Python-un daxili verilən strukturlarından başqa Pandas fayl sistemi, Məlumat bazarı və digər mənbələrdən verilənləri əldə edib cədvəl qurmağa imkan yaradır. Excel fayl Cədvəli yaratmaq üçün pandas-ın read_excel funksiyasına Excel faylına işarələyən fayl sistemi yolu, fayl internetdə ye...
df = pd.read_excel('https://raw.githubusercontent.com/limpapud/datasets/master/Tutorial_datasets/excel_to_dataframe.xlsx', sheet_name='data_for_ttrl') df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
CSV Yuxarıdaki funksiyadaki kimi ilk öncə .csv fayla yol, amma sonra sətr daxilində dəyərləri bir birindən ayıran işarə delimiter parameterinə ötürülməlidir. Ötürülmədikdə standart olaraq vergülü qəbul olunur.
df = pd.read_csv('https://raw.githubusercontent.com/limpapud/datasets/master/Tutorial_datasets/csv_to_dataframe.csv', delimiter=',') df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
JSON Json faylından verilənləri qəbul etmək üçün URL və ya fayl sistemində fayla yol tələb olunur. Json faylı misalı aşağıda qeyd olunub. Diqqət ilə baxdığınız halda özünüz üçün json faylın Lüğət: yazı əsaslı datafreym yaratma metodunda istifadə etdiyimiz dəyər təyinatından heç fərqi olmadığını görmüş oldunuz.
df = pd.read_json('https://raw.githubusercontent.com/limpapud/datasets/master/Tutorial_datasets/json_to_dataframe.json') df = df[['f_name','l_name','email_adrs','a_status',]] df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
SQL Və son olaraq SQLite fayl məlumat bazasından məlumat sorğulayaq və datafreymə yerləşdirək. İlk öncə işimiz üçün tələb olunan modulları import edək.
import sqlalchemy from sqlalchemy import create_engine import sqlite3
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Sorğulama üçün engine yaradaq və məlumat bazası faylına yolu göstərək.
engine = create_engine('sqlite:///C:/Users/omarbayramov/Documents/GitHub/datasets/Tutorial_datasets/sql_to_dataframe.db')
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Qoşulma yaradıb, məlumat bazasında yerləşən emails cədvəlindən bütün sətrləri sorğulayaq.
con=engine.connect() a=con.execute('SELECT * FROM emails')
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Məlumat sorğulandıqdan sonra fetchall funksiyası vasitəsi ilə sətrləri "oxuyub" data dəyişkəninə təhkim edək və sonda MB bağlantısın bağlayaq.
data=a.fetchall() a.close() data
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Əldə olunan məlumatın strukturu tanış qəlir mi? Diqqət ilə baxsanız ilk tanış olduğumuz Siyahı: sətr əsaslı məlumat strukturun tanıyarsınız. Artıq tanış olduğumuz proseduru icra edərək cədvəl qurmaq qaldı:
df=pd.DataFrame(data, columns=['f_name','l_name','email_adrs','a_status',]) df
DataScience_Tutorials/AZ/Pandas_DF_Creation.ipynb
limpapud/data_science_tutorials_projects
mit
Next, let's add some particles. We'll work in units in which $G=1$ (see below on how to set $G$ to another value). The first particle we add is the central object. We place it at rest at the origin and use the convention of setting the mass of the central object $M_*$ to 1:
rebound.add(m=1.)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Let's look at the particle we just added:
print(rebound.particles[0])
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
The output tells us that the mass of the particle is 1 and all coordinates are zero. The next particle we're adding is a planet. We'll use Cartesian coordinates to initialize it. Any coordinate that we do not specify in the rebound.add() command is assumed to be 0. We place our planet on a circular orbit at $a=1$ and ...
rebound.add(m=1e-3, x=1., vy=1.)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Instead of initializing the particle with Cartesian coordinates, we can also use orbital elements. By default, REBOUND will use Jacobi coordinates, i.e. REBOUND assumes the orbital elements describe the particle's orbit around the centre of mass of all particles added previously. Our second planet will have a mass of $...
rebound.add(m=1e-3, a=2., e=0.1)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Now that we have added two more particles, let's have a quick look at what's "in REBOUND" by using
rebound.status()
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Next, let's tell REBOUND which integrator (WHFast, of course!) and timestep we want to use. In our system of units, an orbit at $a=1$ has the orbital period of $T_{\rm orb} =2\pi \sqrt{\frac{GM}{a}}= 2\pi$. So a reasonable timestep to start with would be $dt=10^{-3}$.
rebound.integrator = "whfast" rebound.dt = 1e-3
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
whfast referrs to the 2nd order symplectic integrator WHFast described by Rein & Tamayo (2015). By default 11th order symplectic correctors are used. We are now ready to start the integration. Let's integrate for one orbit, i.e. until $t=2\pi$. Because we use a fixed timestep, rebound would have to change it to integr...
rebound.integrate(6.28318530717959, exact_finish_time=0) # 6.28318530717959 is 2*pi
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Once again, let's look at what REBOUND's status is
rebound.status()
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
As you can see the time has advanced to $t=2\pi$ and the positions and velocities of all particles have changed. If you want to post-process the particle data, you can access it in the following way:
particles = rebound.particles for p in particles: print(p.x, p.y, p.vx, p.vy)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
The particles object is an array of pointers to the particles. This means you can call particles = rebound.particles before the integration and the contents of particles will be updated after the integration. If you add or remove particles, you'll need to call rebound.particles again. Visualization with matplotlib Inst...
import numpy as np torb = 2.*np.pi Noutputs = 100 times = np.linspace(torb, 2.*torb, Noutputs) x = np.zeros(Noutputs) y = np.zeros(Noutputs)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Next, we'll step through the simulation. Rebound will integrate up to time. Depending on the timestep, it might overshoot slightly. If you want to have the outputs at exactly the time you specify you can set the exactTime=1 flag in the integrate function. However, note that changing the timestep in a symplectic integra...
for i,time in enumerate(times): rebound.integrate(time, exact_finish_time=0) x[i] = particles[1].x y[i] = particles[1].y
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Let's plot the orbit using matplotlib.
%matplotlib inline import matplotlib.pyplot as plt fig = plt.figure(figsize=(5,5)) ax = plt.subplot(111) ax.set_xlim([-2,2]) ax.set_ylim([-2,2]) plt.plot(x, y);
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Hurray! It worked. The orbit looks like it should, it's an almost perfect circle. There are small perturbations though, induced by the outer planet. Let's integrate a bit longer to see them.
Noutputs = 1000 times = np.linspace(2.*torb, 20.*torb, Noutputs) x = np.zeros(Noutputs) y = np.zeros(Noutputs) for i,time in enumerate(times): rebound.integrate(time, exact_finish_time=0) x[i] = particles[1].x y[i] = particles[1].y fig = plt.figure(figsize=(5,5)) ax = plt.subplot(111) ax.set_xlim([-2,2...
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
Oops! This doesn't look like what we expected to see (small perturbations to an almost circluar orbit). What you see here is the barycenter slowly drifting. Some integration packages require that the simulation be carried out in a particular frame, but WHFast provides extra flexibility by working in any inertial frame....
rebound.move_to_com()
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
So let's try this again. Let's integrate for a bit longer this time.
times = np.linspace(20.*torb, 1000.*torb, Noutputs) for i,time in enumerate(times): rebound.integrate(time, exact_finish_time=0) x[i] = particles[1].x y[i] = particles[1].y fig = plt.figure(figsize=(5,5)) ax = plt.subplot(111) ax.set_xlim([-1.5,1.5]) ax.set_ylim([-1.5,1.5]) plt.scatter(x, y, marker='.'...
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
That looks much more like it. Let us finally plot the orbital elements as a function of time.
times = np.linspace(1000.*torb, 9000.*torb, Noutputs) a = np.zeros(Noutputs) e = np.zeros(Noutputs) for i,time in enumerate(times): rebound.integrate(time, exact_finish_time=0) orbits = rebound.calculate_orbits() a[i] = orbits[1].a e[i] = orbits[1].e fig = plt.figure(figsize=(15,5)) ax = plt.subpl...
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
The semimajor axis seems to almost stay constant, whereas the eccentricity undergoes an oscillation. Thus, one might conclude the planets interact only secularly, i.e. there are no large resonant terms. Advanced settings of WHFast You can set various attributes to change the default behaviour of WHFast depending on the...
rebound.integrator = "whfast-nocor"
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
You can also set the order of the symplectic corrector explicitly:
rebound.integrator = "whfast" rebound.integrator_whfast_corrector = 7
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
You can choose between 0 (no correctors), 3, 5, 7 and 11 (default). Keeping particle data synchronized By default, REBOUND will only synchronized particle data at the end of the integration, i.e. if you call rebound.integrate(100.), it will assume you don't need to access the particle data between now and $t=100$. Ther...
rebound.init_megno(1e-16)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
you implicitly force REBOUND to keep the particle coordinates synchronized. This will slow it down and might reduce its accuracy. You can also manually force REBOUND to keep the particles synchronized at the end of every timestep by integrating with the synchronize_each_timestep flag set to 1:
rebound.integrate(10., synchronize_each_timestep=1)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
In either case, you can change particle data between subsequent calls to integrate:
rebound.integrate(20.) rebound.particles[0].m = 1.1 # Sudden increase of particle's mass rebound.integrate(30.)
python_tutorials/WHFast.ipynb
quasars100/Resonance_testing_scripts
gpl-3.0
The model can be initialized using an iterable of relations, where a relation is simply a pair of nodes -
model = PoincareModel(train_data=[('node.1', 'node.2'), ('node.2', 'node.3')])
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
The model can also be initialized from a csv-like file containing one relation per line. The module provides a convenience class PoincareRelations to do so.
relations = PoincareRelations(file_path=wordnet_mammal_file, delimiter='\t') model = PoincareModel(train_data=relations)
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
Note that the above only initializes the model and does not begin training. To train the model -
model = PoincareModel(train_data=relations, size=2, burn_in=0) model.train(epochs=1, print_every=500)
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
The same model can be trained further on more epochs in case the user decides that the model hasn't converged yet.
model.train(epochs=1, print_every=500)
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
The model can be saved and loaded using two different methods -
# Saves the entire PoincareModel instance, the loaded model can be trained further model.save('/tmp/test_model') PoincareModel.load('/tmp/test_model') # Saves only the vectors from the PoincareModel instance, in the commonly used word2vec format model.kv.save_word2vec_format('/tmp/test_vectors') PoincareKeyedVectors.l...
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
3. What the embedding can be used for
# Load an example model models_directory = os.path.join(poincare_directory, 'models') test_model_path = os.path.join(models_directory, 'gensim_model_batch_size_10_burn_in_0_epochs_50_neg_20_dim_50') model = PoincareModel.load(test_model_path)
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
The learnt representations can be used to perform various kinds of useful operations. This section is split into two - some simple operations that are directly mentioned in the paper, as well as some experimental operations that are hinted at, and might require more work to refine. The models that are used in this sect...
# Distance between any two nodes model.kv.distance('plant.n.02', 'tree.n.01') model.kv.distance('plant.n.02', 'animal.n.01') # Nodes most similar to a given input node model.kv.most_similar('electricity.n.01') model.kv.most_similar('man.n.01') # Nodes closer to node 1 than node 2 is from node 1 model.kv.nodes_close...
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
3.2 Experimental operations These operations are based on the notion that the norm of a vector represents its hierarchical position. Leaf nodes typically tend to have the highest norms, and as we move up the hierarchy, the norm decreases, with the root node being close to the center (or origin).
# Closest child node model.kv.closest_child('person.n.01') # Closest parent node model.kv.closest_parent('person.n.01') # Position in hierarchy - lower values represent that the node is higher in the hierarchy print(model.kv.norm('person.n.01')) print(model.kv.norm('teacher.n.01')) # Difference in hierarchy between ...
docs/notebooks/Poincare Tutorial.ipynb
mattilyra/gensim
lgpl-2.1
Layouts AnchorLayout, BoxLayout, FloatLayout, RelativeLayout, GridLayout, PageLayout, ScatterLayout, StackLayout
%%bash cat boxlayout.kv %%bash python boxlayout.py > /dev/null 2>&1
Kivy/Kivy.ipynb
CLEpy/CLEpy-MotM
mit
Widgets
%%bash cat widgets.kv %%bash python widgets.py > /dev/null 2>&1
Kivy/Kivy.ipynb
CLEpy/CLEpy-MotM
mit
Data binding
%%bash cat databinding.kv %%bash python databinding.py > /dev/null 2>&1
Kivy/Kivy.ipynb
CLEpy/CLEpy-MotM
mit
Build a custom estimator linear regressor In this exercise, we'll be trying to predict median_house_value. It will be our label. We'll use the remaining columns as our input features. To train our model, we'll use the Estimator API and create a custom estimator for linear regression. Note that we don't actually need a ...
# Define feature columns feature_columns = { colname : tf.feature_column.numeric_column(colname) \ for colname in ['housing_median_age','median_income','num_rooms','num_bedrooms','persons_per_house'] } # Bucketize lat, lon so it's not so high-res; California is mostly N-S, so more lats than lons feature_columns['...
courses/machine_learning/deepdive/05_artandscience/labs/d_customestimator_linear.ipynb
turbomanage/training-data-analyst
apache-2.0
Questão 2
# Carregando o Dataset data = pd.read_csv("car.data", header=None) # Transformando as variáveis categóricas em valores discretos contáveis # Apesar de diminuir a interpretação dos atributos, essa medida facilita bastante a vida dos métodos de contagem for i in range(0, data.shape[1]): data.iloc[:,i] = LabelEncoder...
2017/05-naive-bayes/resp_naive_bayes_moesio.ipynb
IsacLira/data-science-cookbook
mit
Questão 3
# Utilização da minha função própria de Naive Bayes para o mesmo conjunto de dados nBayes = NaiveBayes() nBayes.fit(X_train.values, y_train.values) y_pred = nBayes.predict(X_test.values) # Impressão dos Resultados print("Naive Bayes (My Version :D)") print("Total Accuracy: {}%".format(accuracy_score(y_true=y_test, y_p...
2017/05-naive-bayes/resp_naive_bayes_moesio.ipynb
IsacLira/data-science-cookbook
mit
Set your Processor Variables
# TODO(developer): Fill these variables with your values before running the sample PROJECT_ID = "YOUR_PROJECT_ID_HERE" LOCATION = "us" # Format is 'us' or 'eu' PROCESSOR_ID = "PROCESSOR_ID" # Create processor in Cloud Console GCS_INPUT_BUCKET = 'cloud-samples-data' GCS_INPUT_PREFIX = 'documentai/async_forms/' GCS_OU...
general/async_form_parser.ipynb
GoogleCloudPlatform/documentai-notebooks
apache-2.0
The following code calls the synchronous API and parses the form fields and values.
def process_document_sample(): # Instantiates a client client_options = {"api_endpoint": "{}-documentai.googleapis.com".format(LOCATION)} client = documentai.DocumentProcessorServiceClient(client_options=client_options) storage_client = storage.Client() blobs = storage_client.list_blobs(GCS_INP...
general/async_form_parser.ipynb
GoogleCloudPlatform/documentai-notebooks
apache-2.0
Antimony Similar to the SBML functions above, you can also use the functions getCurrentAntimony and exportToAntimony to get or export the current Antimony representation.
import tellurium as te import tempfile # load model r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10') # file for export f_antimony = tempfile.NamedTemporaryFile(suffix=".txt") # export current model state r.exportToAntimony(f_antimony.name) # to export the initial state when the model was loaded # set the current a...
examples/notebooks/core/tellurium_export.ipynb
kirichoi/tellurium
apache-2.0
CellML Tellurium also has functions for exporting the current model state to CellML. These functionalities rely on using Antimony to perform the conversion.
import tellurium as te import tempfile # load model r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10') # file for export f_cellml = tempfile.NamedTemporaryFile(suffix=".cellml") # export current model state r.exportToCellML(f_cellml.name) # to export the initial state when the model was loaded # set the current argu...
examples/notebooks/core/tellurium_export.ipynb
kirichoi/tellurium
apache-2.0
Matlab To export the current model state to MATLAB, use getCurrentMatlab.
import tellurium as te import tempfile # load model r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10') # file for export f_matlab = tempfile.NamedTemporaryFile(suffix=".m") # export current model state r.exportToMatlab(f_matlab.name) # to export the initial state when the model was loaded # set the current argument ...
examples/notebooks/core/tellurium_export.ipynb
kirichoi/tellurium
apache-2.0
Using Antimony Directly The above examples rely on Antimony as in intermediary between formats. You can use this functionality directly using e.g. antimony.getCellMLString. A comprehensive set of functions can be found in the Antimony API documentation.
import antimony antimony.loadAntimonyString('''S1 -> S2; k1*S1; k1 = 0.1; S1 = 10''') ant_str = antimony.getCellMLString(antimony.getMainModuleName()) print(ant_str)
examples/notebooks/core/tellurium_export.ipynb
kirichoi/tellurium
apache-2.0
Performing scripts with python-fmrest This is a short example on how to perform scripts with python-fmrest. Import the module
import fmrest
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
Create the server instance
fms = fmrest.Server('https://10.211.55.15', user='admin', password='admin', database='Contacts', layout='Demo', verify_ssl=False )
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
Login The login method obtains the access token.
fms.login()
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
Setup scripts You can setup scripts to run prerequest, presort, and after the action and sorting are executed. The script setup is passed to a python-fmrest method as an object that contains the types of script executions, followed by a list containing the script name and parameter.
scripts={ 'prerequest': ['name_of_script_to_run_prerequest', 'script_parameter'], 'presort': ['name_of_script_to_run_presort', None], # parameter can also be None 'after': ['name_of_script_to_run_after_actions', '1234'], #FMSDAPI expects all parameters to be string }
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
You only need to specify the scripts you actually want to execute. So if you only have an after action, just build a scripts object with only the 'after' key. Call a standard method Scripts are always executed as part of a standard request to the server. These requests are the usual find(), create_record(), delete_reco...
fms.find( query=[{'name': 'David'}], scripts={ 'after': ['testScriptWithError', None], } )
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
Get the last script error and result Via the last_script_result property, you can access both last error and script result for all scripts that were called.
fms.last_script_result
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
We see that we had 3 as last error, and our script result was '1'. The FMS Data API only returns strings, but error numbers are automatically converted to integers, for convenience. The script result, however, will always be a string or None, even if you exit your script in FM with a number or boolean. Another example ...
fms.find( query=[{'name': 'David'}], scripts={ 'prerequest': ['demoScript (id)', 'abc-1234'], } )
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
... and here is the result (error 0 means no error):
fms.last_script_result
examples/performing_scripts.ipynb
davidhamann/python-fmrest
mit
Data Split Idealy, we'd perform stratified 5x4 fold cross validation, however, given the timeframe, we'll stick with a single split. We'll use an old chunck of data as training, a more recent as validation, and finally, the most recent data as test set. Don't worry, we'll use K-fold cross-validation in the next noteboo...
l1 = int(df.shape[0]*0.6) l2 = int(df.shape[0]*0.8) df_tra = df.loc[range(0,l1)] df_val = df.loc[range(l1,l2)] df_tst = df.loc[range(l2, df.shape[0])] df_tra.shape, df_val.shape, df_tst.shape, df.shape
notebooks/2016-11-01-dvro-feature-selection.ipynb
dvro/sf-open-data-analysis
mit
checking data distribution, we see that this is a good split (considering the porportion of targets)
fig, axs = plt.subplots(1,3, sharex=True, sharey=True, figsize=(12,3)) axs[0].hist(df_tra.target, bins=2) axs[1].hist(df_val.target, bins=2) axs[2].hist(df_tst.target, bins=2) axs[0].set_title('Training') axs[1].set_title('Validation') axs[2].set_title('Test') X_tra = df_tra.drop(labels=['target'], axis=1, inplace=Fal...
notebooks/2016-11-01-dvro-feature-selection.ipynb
dvro/sf-open-data-analysis
mit