markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
调整gamma参数
svm = SVC(kernel='rbf', random_state=0, gamma=100.0, C=1.0) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.show()
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
1.5 使用sklearn决策树实现分类器   如果我们关心的是模型的可解释性,决策树是有用的模型,通过不断问问题走向不同的分支,最终得到类型
from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0) tree.fit(X_train, y_train) X_combined = np.vstack((X_train, X_test)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X_combined, y_combined, classifier=tree, test_idx=range(105...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
1.6 使用随机森林实现分类器   随机森林由于在实现分类时效果良好,可伸缩,易用的特性比较受欢迎。随机森林可以看作决策树的组合,弱弱联合组成更健壮的模型,降低决策树的过拟合。随机森林算法可以总结为4步: * 从样本集中通过重采样的方式产生n个样本 * 假设样本特征数目为a,对n个样本选择a中的k个特征,用建立决策树的方式获得最佳分割点 * 重复m次,产生m棵决策树 * 多数投票机制来进行预测   随机森林的优势在于无需考虑如何选择超参数,模型足够健壮无需剪枝,只需要考虑决策树的个数k,k越大表现越良好但是计算成本就越大。
from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(criterion='entropy', n_estimators=10, random_state=1, n_jobs=2) forest.fit(X_train, y_train) plot_decision_regions(X_combined, y_combined, classifier=forest, test_idx=range(105,150)) plt.xlabel('petal length') plt.ylabel('petal width') ...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
1.7 K近邻算法实现分类器   这是一个监督机器学习算法(KNN),KNN是典型的懒惰学习算法,他会记忆训练数据集而不是从数据集得到判断函数 参数模型和非参数模型   机器学习算法可分为参数模型和非参数模型。参数模型用于从训练集估计参数,产生的函数无需用到以前的数据就可以为新数据分类,典型的例子是感知器、逻辑回归、线性SVM;非参数模型无法从固定参数集合获取特征,且参数数量随着训练集增加而增加,典型的例子是决策树、随机森林和核函数SVM、K近邻
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski') knn.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=knn, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]'...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
减小过拟合 收集更多数据 通过正规化引入复杂度惩罚(L1正规化) 使用更少参数构建简单一些的模型 降维(序列化特征选择) 使用L1正规化
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash',...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
使用SBS序列化特征选择
from sklearn.base import clone from itertools import combinations import numpy as np from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score class SBS(): def __init__(self, estimator, k_features, scoring=accuracy_score, test_size=0.25, random_state=1): self.scoring =...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
我们挑选5个特征检查是否带来改善,从结果可以看出,使用更少的属性,测试集的准确率提高了2%
k5 = list(sbs.subsets_[8]) print(df_wine.columns[1:][k5]) knn.fit(X_train_std, y_train) print('Training accuracy:', knn.score(X_train_std, y_train)) print('Test accuracy:', knn.score(X_test_std, y_test)) knn.fit(X_train_std[:, k5], y_train) print('Training accuracy(select 5):', knn.score(X_train_std[:, k5], y_train)) p...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
使用随机森林评估特征重要程度   前面我们用L1标准化去除不相关特征,用SBS算法选择特征。另一种选择相关特性的方式是随机森林。
from sklearn.ensemble import RandomForestClassifier feat_labels = df_wine.columns[1:] forest = RandomForestClassifier(n_estimators=10000, random_state=0, n_jobs=-1) forest.fit(X_train, y_train) importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] for f in range(X_train.shape[1]): print(...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
2.1 通过降维压缩数据 主特征分析(PCA),压缩非监督学习数据 线性判别分析(PDA),降维监督学习数据 核心主特征分析(KPCA),降维非线性数据 Sklearn PCA
from matplotlib.colors import ListedColormap from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA import matplotlib.pyplot as plt import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler def plot_decision_regions(X, ...
jupyter/machine_learning_1.ipynb
lichao890427/lichao890427.github.io
mit
Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest...
import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a bach of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return None def neural_net_label_input(n_classes): """ Return a Tensor...
project2/files/dlnd_image_classification_instruction.ipynb
myfunprograms/deep_learning
gpl-3.0
Import packages
# Import from __future__ import absolute_import, division, print_function import calendar import hashlib import json import math import os import random import time import uuid from datetime import datetime import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from google.cloud ...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Authenticate your GCP account If you are using AI Platform Notebooks, you are already authenticated so there is no need to run this step.
import sys if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user()
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Analyze dataset Some charts might use a log scale. Quantity This sections shows how to use the BigQuery ML BUCKETIZE preprocessing function to create buckets of data for quantity and display a log scaled distribution of the qty field.
%%bigquery df_histo_qty --project $PROJECT_ID WITH min_max AS ( SELECT MIN(qty) min_qty, MAX(qty) max_qty, CEIL((MAX(qty) - MIN(qty)) / 100) step FROM `ltv_ecommerce.10_orders` ) SELECT COUNT(1) c, bucket_same_size AS bucket FROM ( SELECT -- Creates (1000-100)/100 + 1 buckets of data. ...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Unit price
%%bigquery df_histo_unit_price --project $PROJECT_ID WITH min_max AS ( SELECT MIN(unit_price) min_unit_price, MAX(unit_price) max_unit_price, CEIL((MAX(unit_price) - MIN(unit_price)) / 10) step FROM `ltv_ecommerce.10_orders` ) SELECT COUNT(1) c, bucket_same_size AS bucket FROM ( SELECT ...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Set parameters for LTV Some parameters useful to run some of the queries in this tutorial: WINDOW_STEP: How many days between threshold dates. WINDOW_STEP_INITIAL: How many days between the first order and the first threshold date. A threshold date is when BigQuery computes inputs and targets. WINDOW_LENGTH: How many ...
LTV_PARAMS = { "WINDOW_LENGTH": 0, "WINDOW_STEP": 30, "WINDOW_STEP_INITIAL": 90, "LENGTH_FUTURE": 30, "MAX_STDV_MONETARY": 500, "MAX_STDV_QTY": 100, "TOP_LTV_RATIO": 0.2, } LTV_PARAMS
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Check distributions This tutorial does minimum data cleansing and focuses mostly on transforming a list of transactions into workable inputs for the model. This section checks that data is generally usable. Per date
%%bigquery df_dist_dates --project $PROJECT_ID SELECT count(1) c, SUBSTR(CAST(order_day AS STRING), 0, 7) as yyyy_mm FROM `ltv_ecommerce.20_aggred` WHERE qty_articles > 0 GROUP BY yyyy_mm ORDER BY yyyy_mm plt.figure(figsize=(12, 5)) sns.barplot(x="yyyy_mm", y="c", data=df_dist_dates)
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Orders are quite well distributed across the year despite a lower number in the early days of the dataset. You can keep this in mind when choosing a value for WINDOW_STEP_INITIAL. Per customer
%%bigquery df_dist_customers --params $LTV_PARAMS --project $PROJECT_ID SELECT customer_id, count(1) c FROM `ltv_ecommerce.20_aggred` GROUP BY customer_id plt.figure(figsize=(12, 4)) sns.distplot(df_dist_customers["c"], hist_kws=dict(ec="k"), kde=False)
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
The number of transactions per customer is distributed across a few discrete values with no clear outliers. Per quantity This section looks at the general distribution of the number of articles per orders and check if there are some outliers.
%%bigquery df_dist_qty --params $LTV_PARAMS --project $PROJECT_ID SELECT qty_articles, count(1) c FROM `ltv_ecommerce.20_aggred` GROUP BY qty_articles plt.figure(figsize=(12, 4)) sns.distplot(df_dist_qty["qty_articles"], hist_kws=dict(ec="k"), kde=False)
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Dataset
%%bigquery --project $PROJECT_ID -- Shows all data for a specific customer and some other random records. SELECT * FROM `ltv_ecommerce.30_featured` WHERE customer_id = "10" UNION ALL (SELECT * FROM `ltv_ecommerce.30_featured` LIMIT 5) ORDER BY customer_id, frequency, T %%bigquery df_featured --project $PROJECT_ID lt...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Seems like for most values, there is a long tail of records. This is something that might required additional feature preparation even if AutoML already provides some automatic engineering. You can investigate this if you want to improve the base model. Train the model This tutorial uses an AutoML regressor to predict ...
# You can run this query using the magic cell but the cell would run for hours. # Although stopping the cell would not stop the query, using the Python client # also enables you to add a custom parameter for the model name. suffix_now = datetime.now().strftime("%Y%m%d_%H%M%S") train_model_jobid = f"train_model_{suffix_...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
This is an example of a model evaluation Predict LTV Predicts LTV for all customers. It uses the overall monetary value for each customer to predict a future one.
%%bigquery --params $LTV_PARAMS --project $PROJECT_ID -- TODO(developer): -- 1. Update the model name to the one you want to use. -- 2. Update the table where to output predictions. -- How many days back for inputs transactions. 0 means from the start. DECLARE WINDOW_LENGTH INT64 DEFAULT @WINDOW_LENGTH; -- Date at w...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
The monetary distribution analysis shows small monetary amounts for the next month compare to the overall historical value. The difference is about 3 to 4 orders of magnitude. One reason is that the model is trained to predict the value for the next month (LENGTH_FUTURE = 30). You can play around with that value to tr...
%%bigquery df_top_ltv --params $LTV_PARAMS --project $PROJECT_ID DECLARE TOP_LTV_RATIO FLOAT64 DEFAULT @TOP_LTV_RATIO; SELECT p.customer_id, monetary_future, c.email AS email FROM ( SELECT customer_id, monetary_future, PERCENT_RANK() OVER (ORDER BY monetary_future DESC) AS percent_rank_monetary ...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Setup Adwords client Creates the configuration YAML file for the Google Ads client. You need to: 1. Create Client ID and Secret using the Cloud Console 2. Follow these steps
# Sets your variables. if "google.colab" in sys.modules: from google.colab import files ADWORDS_FILE = "/tmp/adwords.yaml" DEVELOPER_TOKEN = "[YOUR_DEVELOPER_TOKEN]" OAUTH_2_CLIENT_ID = "[YOUR_OAUTH_2_CLIENT_ID]" CLIENT_SECRET = "[YOUR_CLIENT_SECRET]" REFRESH_TOKEN = "[YOUR_REFRESH_TOKEN]" # Creates a local YAML...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
Create an AdWords user list Using emails of the top LTV customers, you create an AdWords list. If more than 5000 of the users are matched with AdWords email, a similar audience list will be created. Note that this guide uses fake emails so running these steps is not going to work but you can leverage this code with em...
ltv_emails = list(set(df_top_ltv["email"])) # https://developers.google.com/adwords/api/docs/samples/python/remarketing#create-and-populate-a-user-list # https://github.com/googleads/googleads-python-lib/blob/7c41584c65759b6860572a13bde65d7395c5b2d8/examples/adwords/v201809/remarketing/add_crm_based_user_list.py # ""...
notebooks/community/analytics-componetized-patterns/retail/ltv/bqml/notebooks/bqml_automl_ltv_activate_lookalike.ipynb
GoogleCloudPlatform/bigquery-notebooks
apache-2.0
SWAP
swap()
examples/quantum-gates.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
ISWAP
iswap()
examples/quantum-gates.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
From QuTiP 4.4, we can also add gate at arbitrary position in a circuit.
qc1.add_gate("CSIGN", index=1) qc1.png
examples/quantum-gates.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Adding gate in the middle of a circuit From QuTiP 4.4 one can add a gate at an arbitrary position of a circuit. All one needs to do is to specify the parameter index. With this, we can also add the same gate at multiple positions at the same time.
qc = QubitCircuit(1) qc.add_gate("RX", targets=1) qc.add_gate("RX", targets=1) qc.add_gate("RY", targets=1, index=[1,0]) qc.gates
examples/quantum-gates.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
If If statements can be use to execute some lines or block of code if a particular condition is satisfied. E.g. Let's print something based on the entries in the list.
for instructor in instructors: if not "Clown" in instructor: print(instructor) else: pass for instructor in instructors: if "Clown" in instructor: pass else: print(instructor) for instructor in instructors: if not "Clown" in instructor: print(instructor) ...
week_1/procedural_python/flow_of_control.ipynb
UWSEDS/LectureNotes
bsd-2-clause
You can combine loops and conditionals:
for instructor in instructors: if instructor.endswith('Clown'): print(instructor + " doesn't sound like a real instructor name!") else: print(instructor + " is so smart... all those gooey brains!") # Loops can be nested for i in range(1, 4): for j in range(1, 4): print('%d * %d = %d...
week_1/procedural_python/flow_of_control.ipynb
UWSEDS/LectureNotes
bsd-2-clause
Programming Example Write a script that finds the first N prime numbers.
4 % 2 N = 100 for candidate in range(2, N): # n is candidate prime. Check if n is prime is_prime = True for m in range(2, candidate): if (candidate % m) == 0: is_prime = False break if is_prime: print("%d is prime!" % candidate)
week_1/procedural_python/flow_of_control.ipynb
UWSEDS/LectureNotes
bsd-2-clause
With the model loaded, you can process text like this:
doc = nlp("Tea is healthy and calming, don't you think?")
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
There's a lot you can do with the doc object you just created. Tokenizing This returns a document object that contains tokens. A token is a unit of text in the document, such as individual words and punctuation. SpaCy splits contractions like "don't" into two tokens, "do" and "n't". You can see the tokens by iterating ...
for token in doc: print(token)
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
Iterating through a document gives you token objects. Each of these tokens comes with additional information. In most cases, the important ones are token.lemma_ and token.is_stop. Text preprocessing There are a few types of preprocessing to improve how we model with words. The first is "lemmatizing." The "lemma" of a w...
print(f"Token \t\tLemma \t\tStopword".format('Token', 'Lemma', 'Stopword')) print("-"*40) for token in doc: print(f"{str(token)}\t\t{token.lemma_}\t\t{token.is_stop}")
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
Why are lemmas and identifying stopwords important? Language data has a lot of noise mixed in with informative content. In the sentence above, the important words are tea, healthy and calming. Removing stop words might help the predictive model focus on relevant words. Lemmatizing similarly helps by combining multiple ...
from spacy.matcher import PhraseMatcher matcher = PhraseMatcher(nlp.vocab, attr='LOWER')
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
The matcher is created using the vocabulary of your model. Here we're using the small English model you loaded earlier. Setting attr='LOWER' will match the phrases on lowercased text. This provides case insensitive matching. Next you create a list of terms to match in the text. The phrase matcher needs the patterns as ...
terms = ['Galaxy Note', 'iPhone 11', 'iPhone XS', 'Google Pixel'] patterns = [nlp(text) for text in terms] matcher.add("TerminologyList", patterns)
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
Then you create a document from the text to search and use the phrase matcher to find where the terms occur in the text.
# Borrowed from https://daringfireball.net/linked/2019/09/21/patel-11-pro text_doc = nlp("Glowing review overall, and some really interesting side-by-side " "photography tests pitting the iPhone 11 Pro against the " "Galaxy Note 10 Plus and last year’s iPhone XS and Google Pixel 3.") matc...
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
The matches here are a tuple of the match id and the positions of the start and end of the phrase.
match_id, start, end = matches[0] print(nlp.vocab.strings[match_id], text_doc[start:end])
notebooks/nlp/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
We initialize the simulation and generate the grid in the complex plane.
size = 200 iterations = 100
4_Cython.ipynb
thewtex/ieee-nss-mic-scipy-2014
apache-2.0
Pure Python
def mandelbrot_python(m, size, iterations): for i in range(size): for j in range(size): c = -2 + 3./size*j + 1j*(1.5-3./size*i) z = 0 for n in range(iterations): if np.abs(z) <= 10: z = z*z + c m[i, j] = n ...
4_Cython.ipynb
thewtex/ieee-nss-mic-scipy-2014
apache-2.0
Cython versions We first import Cython.
%load_ext cythonmagic
4_Cython.ipynb
thewtex/ieee-nss-mic-scipy-2014
apache-2.0
Take 1 First, we just add the %%cython magic.
%%cython -a import numpy as np def mandelbrot_cython(m, size, iterations): for i in range(size): for j in range(size): c = -2 + 3./size*j + 1j*(1.5-3./size*i) z = 0 for n in range(iterations): if np.abs(z) <= 10: z = z*z + c ...
4_Cython.ipynb
thewtex/ieee-nss-mic-scipy-2014
apache-2.0
Virtually no speedup. Take 2 Now, we add type information, using memory views for NumPy arrays.
%%cython -a import numpy as np def mandelbrot_cython(int[:,::1] m, int size, int iterations): cdef int i, j, n cdef complex z, c for i in range(size): for j in range(size): c = -2 + 3./size*j + 1j*(1.5-3./size*i) z = 0 ...
4_Cython.ipynb
thewtex/ieee-nss-mic-scipy-2014
apache-2.0
Vertex client library: Custom training image classification model with custom container for online prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_custom_image_classification_online_c...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/custom/showcase_custom_image_classification_online_container.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train a model There are two ways you can train a custom model using a container image: Use a Google Cloud prebuilt container. If you use a prebuilt container, you will additionally specify a Python package to install into the container image. This Python package contains your code for training a custom model. Use y...
# Make folder for Python training script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow...
notebooks/community/gapic/custom/showcase_custom_image_classification_online_container.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Select seeds for search networks I select small (1000-1500) sized bot network and pick 4 random members from it
seeds = ['volya_belousova', 'egor4rgurev', 'kirillfrolovdw', 'ilyazhuchhj'] auth = tweepy.OAuthHandler(OAUTH_KEY, OAUTH_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) graph = Graph(user=NEO4J_USER, password=NEO4J_SECRET) ...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Now search for friends of seed users
friend_ids = {} for account in seeds: friend_ids[account] = get_friends(account) commons = {} for first in seeds: for second in seeds: if first != second: commons[(first, second)] = list(set(friend_ids[first]) & set(friend_ids[second])) all_users = friend_ids[seeds[0]] for name in see...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Show common users in total and per seed user
display("Common users: {0}".format(len(all_users))) html = ["<table width=100%>"] html.append('<tr><td></td>') for name in seeds: html.append('<td>{0}</td>'.format(name)) html.append('</tr>') for first in seeds: html.append('<tr><td>{0}</td>'.format(first)) for second in seeds: if first != second:...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Now search and populate neo4j database
graph.run("CREATE CONSTRAINT ON (u:UserRes) ASSERT u.id IS UNIQUE") processed_users = [] for user_id in all_users: if user_id not in processed_users: user = Node("UserRes", id=user_id) graph.merge(user) try: for friend_id in get_follwers_by_id(user_id): if friend...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Get all users from neo4j and build graph
query = """ MATCH (user1:UserRes)-[:FRIEND_OF]->(user2:UserRes), (user2:UserRes)-[:FRIEND_OF]->(user1) RETURN user1.id, user2.id """ data = graph.run(query) ig = IGraph.TupleList(data, weights=False) ig.es["width"] = 1 ig.simplify(combine_edges={ "width": "sum" })
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Let's cluster graph and search for communities
clusters = IGraph.community_fastgreedy(ig) clusters = clusters.as_clustering() print("Found %d clusters" % len(clusters))
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Let's make clusters dataframe
nodes = [{"id": node.index, "name": node["name"]} for node in ig.vs] for node in nodes: node["cluster"] = clusters.membership[node["id"]] nodes_df = pd.DataFrame(nodes) edges = [{"source": x[0], "target": x[1]} for x in ig.get_edgelist()] edges_df = pd.DataFrame(edges) edges_counts = edges_df.groupby('source'...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Let's look to all clusters closely
nodes_df.groupby('cluster').count()
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
We have only two clusters with significant user count. Let's check first
first_cluster = nodes_df[nodes_df["cluster"] == 0][["id", "name"]]
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Join edges to users
first_cluster_counts = first_cluster.set_index('id').join(edges_counts.set_index('source')).reset_index() first_cluster_counts["count"].hist()
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Let's look to all groups
for group in range(20): start = group * 100 stop = (group + 1) * 100 users_slice = first_cluster_counts[(first_cluster_counts["count"] > start) & (first_cluster_counts["count"] < stop)] print("Users from %d to %d has %d" %(start, stop, users_slice.count()[0])) display(users_slice[:10])
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Looks like most bot accounts has followers/follows count from 1200 to 1900 Let's filter it
filtered_bots = first_cluster_counts[(first_cluster_counts["count"] > 1200) & (first_cluster_counts["count"] < 1900)] print("We found %s bots in first approximation" % filtered_bots.count()[0])
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Now collect all information from these accounts and search for corellations
first_cluster_bots = [] for group in chunks(filtered_bots["name"].values, 100): for user in api.lookup_users(user_ids=list(group)): first_cluster_bots.append(user) locations = [user.location for user in first_cluster_bots] first_cluster_bots[0].favourites_count possible_bot_users = pd.DataFrame([{'name':...
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Ok, we have two significant values. Moscow and New York. Let's split dataset
moscow_users = possible_bot_users[possible_bot_users["location"] == u'Москва'] moscow_users.hist() moscow_users[:10]
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Now check NY users
ny_users = possible_bot_users[possible_bot_users["location"] == u'New York, USA'] ny_users.hist() ny_users[:10]
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Conclusion We have one twitter bot network on two languages: Russian and English. All bots have deep linking and posts random sentences every hour.
print("Moscow bots: %d, NY bots: %d, Total: %d" % (moscow_users.count()[0], ny_users.count()[0], moscow_users.count()[0] + ny_users.count()[0]))
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Now export moscow and ny users to csv
ny_users.append(moscow_users).to_csv("./moscow_ny_bots.csv", encoding='utf8')
Twitter bots/Botnet search.ipynb
UserAd/data_science
mit
Loading and visualizing the input data
# read the peaks flt = columnfile('sma_261N.flt.new') # peaks indexed to phase 1 phase1 = flt.copy() phase1.filter( phase1.labels > -1 ) # unindexed peaks (phase 2 + unindexed phase 1?) phase2 = flt.copy() phase2.filter( phase2.labels == -1 ) #plot radial transform for phase 1 plt.plot( phase1.tth_per_grain, phase1....
sandbox/weighted_kde/3DXRD diffractogram from filtered peaks.ipynb
jonwright/ImageD11
gpl-2.0
Plotting the diffraction profile
# Probability density function (pdf) of 2theta # weighted by the peak intensity and using default 2theta bandwidth I_phase1 = phase1.sum_intensity * phase1.Lorentz_per_grain pdf = wkde.gaussian_kde( phase1.tth_per_grain, weights = I_phase1) # Plotting it over 2theta range x = np.linspace( min(flt.tth), max(flt.tth), 5...
sandbox/weighted_kde/3DXRD diffractogram from filtered peaks.ipynb
jonwright/ImageD11
gpl-2.0
The profile showed above is highly smoothed and the hkl peaks are merged.<br> $\to$ A Smaller bandwidth should be used. Choosing the right bandwidth of the estimator The bandwidth can be passed as argument to the gaussian_kde() object or set afterward using the later set_badwidth() method. For example, the bandwidth ca...
pdf_phase1 = wkde.gaussian_kde( phase1.tth, weights = phase1.sum_intensity ) pdf_phase2 = wkde.gaussian_kde( phase2.tth, weights = phase2.sum_intensity ) frac_phase1 = np.sum( phase1.sum_intensity ) / np.sum( flt.sum_intensity ) frac_phase2 = np.sum( phase2.sum_intensity ) / np.sum( flt.sum_intensity ) from ipywidgets...
sandbox/weighted_kde/3DXRD diffractogram from filtered peaks.ipynb
jonwright/ImageD11
gpl-2.0
Read some data
df1 = pd.read_csv('/Users/atma6951/Documents/code/pychakras/pychakras/udemy_ml_bootcamp/Python-for-Data-Visualization/Pandas Built-in Data Viz/df1', index_col=0) df2 = pd.read_csv('/Users/atma6951/Documents/code/pychakras/pychakras/udemy_ml_bootcamp/Python-for-Data-Visualization/Pandas Built-in Data Viz/df2') df1.head...
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
3 ways of calling plot from a DataFrame df.plot() and specify the plot type, the X and Y columns etc df.plot.hist() calling plot in OO fashion. Only specify teh X and Y and color or size columns df['column'].plot.plotname() - calling plot on a series Types of plot that can be called: area, bar, line, scatter, box, he...
df1.plot(x='A', kind='hist') df1['A'].plot.hist(bins=30)
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Plotting a histogram of all numeric columns in the dataframe:
df1.hist()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
In reality, you have a lot more columns. You can prettify the above by creating a layout and figsize:
ax_list = df1.hist(bins=25, layout=(2,2), figsize=(7,7)) plt.tight_layout()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Plotting histogram of all columns and sharing axes The chart above might make more sense if you shared the X as well as Y axes for different columns. This helps in comparing the distribution of values visually.
ax_list = df1.hist(bins=25, sharex=True, sharey=True, layout=(1,4), figsize=(15,4)) ax_list = df1.hist(bins=25, sharex=True, sharey=True, layout=(2,2), figsize=(8,8))
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Backgrounds You can specify dark or white background and style info to the matplotlib that is used behind the scenes. Area plot
plt.style.use('dark_background') df2.plot.area()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Bar chart Another style is fivethirtyeight
plt.style.use('fivethirtyeight') df2.plot.bar()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Line plot This is suited for time series data
#reset the style plt.style.use('default') # pass figsize to the matplotlib backend engine and `lw` is line width df1.plot.line(x=df1.index, y='A', figsize=(12,2), lw=1)
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Scatter plot Use colormap or size to bring in a visualize a 3rd variable in your scatter
df1.plot.scatter(x='A', y='B',c='C', cmap='coolwarm') # you could specify size s='c' however the points come out tiny. # had to scale it by 100, hence using actual series data and not the column name df2.plot.scatter(x='a',y='b', s=df2['c']*100)
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
KDE plots To visualize the density of data
df1['A'].plot.kde()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Visualize the density of all columns in one plot
df1.plot.kde() df2.plot.density() #I think density is an alias to KDE
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Making wordclouds from text fields Word clouds are a great way to visualize frequency of certain terms that appear in the data set. This is accomplished using the library wordcloud. You can install it as conda install -c conda-forge wordcloud
registrant_df = pd.read_csv('./registrant.csv') registrant_df.head()
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Now, let us plot the responses from the column What would you like to learn? as a word cloud. First, we need to turn the series into a paragraph.
obj_series = registrant_df['What would you like to learn?'].dropna() obj_list = list(obj_series) obj_string = ' '.join(obj_list) obj_string from wordcloud import WordCloud wc = WordCloud(width=1000, height=600, background_color='white') obj_wc_img = wc.generate_from_text(obj_string) plt.figure(figsize=(20,10)) plt.i...
python_crash_course/pandas_data_viz_1.ipynb
AtmaMani/pyChakras
mit
Create a DataFrame object Creat DataFrame by reading a file
mtcars = spark.read.csv(path='../../data/mtcars.csv', sep=',', encoding='UTF-8', comment=None, header=True, inferSchema=True) mtcars.show(n=5, truncate=False)
notebooks/01-data-strcture/1.2-dataframe.ipynb
MingChen0919/learning-apache-spark
mit
Actuators A multiprocessing block may need to interact asynchronously with some external device. To do so, the block puts data into a queue and uses threads responsible for interfacing between the queue and the device. This simple example illustrates the simplest actuator: a printer. Indeed printing can be done synchro...
import threading from IoTPy.agent_types.sink import stream_to_queue def f(in_streams, out_streams): map_element(lambda v: v+100, in_streams[0], out_streams[0]) def source_thread_target(procs): for i in range(3): extend_stream(procs, data=list(range(i*2, (i+1)*2)), stream_name='x') time.sleep(0...
examples/ExamplesOfMulticorePartTwo.ipynb
AssembleSoftware/IoTPy
bsd-3-clause
Example of Process Structure with Feedback The example shows a process structure with feedback. This example creates an echo from a spoken sound. (You can write more efficient and succinct code to compute echoes. The code in this example is here merely because it illustrates a concept.) <br> Streams <ol> <li><b>sou...
from IoTPy.agent_types.basics import * def example_echo_two_cores(): # This is the delay from when the made sound hits a # reflecting surface. delay = 4 # This is the attenuation of the reflected wave. attenuation = 0.5 # The results are put in this queue. A thread reads this # queue and ...
examples/ExamplesOfMulticorePartTwo.ipynb
AssembleSoftware/IoTPy
bsd-3-clause
Example source and actuator thread with single process This example is the same as the previous one except that the computation is carried out in a single process rather in two processes. The example illustrates an actuator thread and a source thread in the same process.
def example_echo_single_core(): # This is the delay from when the made sound hits a # reflecting surface. delay = 4 # This is the attenuation of the reflected wave. attenuation = 0.5 # The results are put in this queue. A thread reads this # queue and feeds a speaker or headphone. q = ...
examples/ExamplesOfMulticorePartTwo.ipynb
AssembleSoftware/IoTPy
bsd-3-clause
Example of a grid computation Grid computations are used in science, for example in computing the temperature of a metal plate. The grid is partitioned into regions with a process assigned to simulate each region. On the n-th step, each process reads the values of relevant parts of the grid and updates its own value. <...
from IoTPy.core.stream import _no_value def test_grid(): # N is the size of the grid N = 5 # M is the number of steps of execution. M = 5 # DELTA is the deviation from the final solution. DELTA = 0.01 # even, odd are the grids that will be returned # by this computation even = multip...
examples/ExamplesOfMulticorePartTwo.ipynb
AssembleSoftware/IoTPy
bsd-3-clause
let us avaluate a function of 3 variables on relatively large mesh
T = 1.618033988749895 from numpy import sin,cos,pi r = 4.77 zmin,zmax = -r,r xmin,xmax = -r,r ymin,ymax = -r,r Nx,Ny,Nz = 80,80,80 x = np.linspace(xmin,xmax,Nx) y = np.linspace(ymin,ymax,Ny) z = np.linspace(zmin,zmax,Nz) x,y,z = np.meshgrid(x,y,z,indexing='ij') %time p = 2 - (cos(x + T*y) + cos(x - T*y) + cos(y + T*z...
examples/SageDays74/implicit_plot3d_interactive.ipynb
K3D-tools/K3D-jupyter
mit
isolevel can be changed from Python side:
p3d_1.level=-0.1 from ipywidgets import interact, interactive, fixed import ipywidgets as widgets @interact(l=widgets.FloatSlider(value=-.1,min=-3,max=1.1)) def g(l): p3d_1.level=-l
examples/SageDays74/implicit_plot3d_interactive.ipynb
K3D-tools/K3D-jupyter
mit
to avoid recentering one can disable camera auto fit:
plot.camera_auto_fit = False plot.grid_auto_fit = False
examples/SageDays74/implicit_plot3d_interactive.ipynb
K3D-tools/K3D-jupyter
mit
one can add other plots to the same scene:
%%time p =(x**2+y**2+z**2+2*y-1)*((x**2+y**2+z**2-2*y-1)**2-8*z**2)+16*x*z*(x**2+y**2+z**2-2*y-1) plot += k3d.marching_cubes(p,xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax, zmin=zmin, zmax=zmax, level=0.0,color=0xff0000) %%time p = x**2 + y**2 - z**2 -0. plot += k3d.marching_cubes(p,xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax...
examples/SageDays74/implicit_plot3d_interactive.ipynb
K3D-tools/K3D-jupyter
mit
Config
import nlpaug.augmenter.char as nac import nlpaug.augmenter.word as naw import nlpaug.augmenter.sentence as nas import nlpaug.flow as naf from nlpaug.util import Action text = 'The quick brown fox jumps over the lazy dog .' print(text)
example/flow.ipynb
makcedward/nlpaug
mit
Flow <a class="anchor" id="flow"> To make use of multiple augmentation, sequential and sometimes pipelines are introduced to connect augmenters. Sequential Pipeline<a class="anchor" id="seq_pipeline"> Apply different augmenters sequentially
aug = naf.Sequential([ nac.RandomCharAug(action="insert"), naw.RandomWordAug() ]) aug.augment(text)
example/flow.ipynb
makcedward/nlpaug
mit
Generate mulitple synthetic data
aug = naf.Sequential([ nac.RandomCharAug(action="insert"), naw.RandomWordAug() ]) aug.augment(text, n=3)
example/flow.ipynb
makcedward/nlpaug
mit
Sometimes Pipeline<a class="anchor" id="sometimes_pipeline"> Apply some augmenters randomly
aug = naf.Sometimes([ nac.RandomCharAug(action="delete"), nac.RandomCharAug(action="insert"), naw.RandomWordAug() ]) aug.augment(text)
example/flow.ipynb
makcedward/nlpaug
mit
$$ v(s) = \min_x(cost(x,s) + v(new state(x,s))) $$
class DynamicProgram(object): """ Generate a dynamic program to find a set of optimal descissions using the HJB. define the program by: Setting intial states via: set_inital_state(list or int) Setting the number of steps via: set_step_number(int) Add a set of desc...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
We can also solve classic dynamic programming problems such as the knapsack problem, hannoi towers or the fibonacci number calculation. Blank functions are outlined below. The functions must fulfill a range of conditions: $$ f:\mathcal{S}^n\times x \rightarrow \mathbb{R} $$ where $\mathcal{S}$ is the set of permissab...
#help(DynamicProgram) def cost(x,s): """Return a float or integer""" pass def new_state(x,s): """Return a tuple""" pass def val_T(s,settings): """Return a float or int""" pass
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
We can solve a very simple pump optimsiation where the state of water in a tank is given by h and described by: $$ s_{new} = \begin{cases} (t+1,h-1) & \text{if } x = 0 \ (t+1,h+1) & \text{if } x = 1 \ (t+1,h+1.5) & \text{if } x = 2\end{cases} $$ The operating cost are described by: $$ cost = tarrif(t)\times x $$ where...
def simple_cost(x,s): tariff = [19, 8, 20, 3, 12, 14, 0, 4, 3, 13, 11, 13, 13, 11, 16, 14, 16, 19, 1, 8, 0, 4, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 12, 3, 18, 15, 3, 10, 12, 6, 3, 5, 11, 0, 11, 8, 10, 11, 5, 15, 8, 2, 0., 0., 0., 0., 0., 0....
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
We can have more than one state variable. For example we can add a second tank and now pump to either of them: Here they have similar equations, but they can be completly independant, of each other. Any cost and state function that meets the requirments above is allowed. $$ s_{new} = \begin{cases} (t+1,h_1-1,h_2-1) & \...
def simple_state2(x,s): if x == 0: return (s[0]+1,s[1]-1,s[2]-1) elif x == 1: return (s[0]+1,s[1]+1,s[2]) elif x == 2: return (s[0]+1,s[1] ,s[2]+2) # We also need to update the final value function. def val_T2(s,settings): if s[1] < settings['Initial state'][1] or s[2] < settin...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
One final example is the checkerboard problem as outlined here: https://en.wikipedia.org/wiki/Dynamic_programming#Checkerboard
board = np.array([[1,3,4,6], [2,6,2,1], [7,3,2,1], [0,4,2,9]]) def cost(x,s): """Return a float or integer""" global board return board[s[0],s[1]] def new_state(x,s): """Return a tuple""" global board return (int(s[0]+1),int(s[1]+x)) ...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
An example we can solve is the water allocation problem from the tutorial sheets: Consider a water supply allocation problem. Suppose that a quantity Q can be allocated to three water users (indices j=1, 2 and 3), what is allocation x4 which maximises the total net benefits? The gross benefit resulting from the allocat...
Costs = np.array([[100,0.1, 10,0.6], [50, 0.4, 10,0.8], [100,0.2, 25,0.4]]) def value(x,s): global Costs return Costs[s[0],0]*(1-math.exp(-Costs[s[0],1]*x)) def cost(x,s): """Return a float or integer""" global Costs if return ...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
Stochastic Programming $$ v(s,i) = \min_x( cost(x,s,i)+\sum_j (p_{i,j} \times v(newstate(x,s,j))) ) $$ Where the probability $p_{i,j}$ is the probaility of jumping from state $i$ to state $j$. Currently the transition matrix is invariate, however this can be easily implimented with P as a list of lists.
class StochasticProgram(DynamicProgram): """ Adds a stochastic component to the dynamic program. state now is: s where s[0] is the step s[1:-1] is the states of the system and s[-1] is the stochastic state The transition matrix for the markov chain describing the stochastic bhavior is added by...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
The cost of operating a pump with a given wind turbine power input given by a certain state is given by: $$ cost(x,t,h,j) := \begin{cases} T(t) \times (x \times P_p - W(t,j)) & \text{if} +ve \ E_{xp} \times (x \times P_p - W(t,j)) & \text{if} -ve\end{cases} $$ where $W(t,j)$ is the wind power output at time $t$ with a...
# Convention s = t,h,j def stoch_simple_state(x,s): #print s if x == 0: return (s[0]+1,s[1]-1,s[2]) elif x == 1: return (s[0]+1,s[1]+1,s[2]) elif x == 2: return (s[0]+1,s[1]+1.5,s[2]) def err_corr_wind_power_cost(x,s): Tariff = [5,5,5,5,5,8,8,8,8,8,12,12,12,12,1...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0
The cost of operating a pump with a given wind turbine power input is given by: $$ cost(x,t,h) := \begin{cases} T(t) \times (x \times P_p - W(t)) & \text{if} +ve \ E_{xp} \times (x \times P_p - W(t)) & \text{if} -ve\end{cases} $$ where $x$ is the descision variable, $W(t)$ is the wind turbine output in time step $t$. ...
def wind_power_cost(x,s): """Very simple cost function for a pump with wind turbine power""" Tariff = [5,5,5,5,5,8,8,8,8,8,12,12,12,12,12,50,50,50,50,20,20,6,5,5] Wind = [46, 1, 3, 36, 30, 19, 9, 26, 35, 5, 49, 3, 6, 36, 43, 36, 14, 34, 2, 0, 0, 30, 13, 36] Export_price = 5.5 ...
Dynamic programming class.ipynb
icfly2/hjb_solvers
gpl-3.0