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
Pre-processing: Feature selection/extraction Lets look at the day of the week people get the loan
df['dayofweek'] = df['effective_date'].dt.dayofweek bins = np.linspace(df.dayofweek.min(), df.dayofweek.max(), 10) g = sns.FacetGrid(df, col="Gender", hue="loan_status", palette="Set1", col_wrap=2) g.map(plt.hist, 'dayofweek', bins=bins, ec="k") g.axes[-1].legend() plt.show()
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
We see that people who get the loan at the end of the week dont pay it off, so lets use Feature binarization to set a threshold values less then day 4
df['weekend'] = df['dayofweek'].apply(lambda x: 1 if (x>3) else 0) df.head()
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Convert Categorical features to numerical values Lets look at gender:
df.groupby(['Gender'])['loan_status'].value_counts(normalize=True)
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
86 % of female pay there loans while only 73 % of males pay there loan Lets convert male to 0 and female to 1:
df['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True) df.head()
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
One Hot Encoding How about education?
df.groupby(['education'])['loan_status'].value_counts(normalize=True)
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Feature befor One Hot Encoding
df[['Principal','terms','age','Gender','education']].head()
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Use one hot encoding technique to conver categorical varables to binary variables and append them to the feature Data Frame
Feature = df[['Principal','terms','age','Gender','weekend']] Feature = pd.concat([Feature,pd.get_dummies(df['education'])], axis=1) Feature.drop(['Master or Above'], axis = 1,inplace=True) Feature.head()
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Feature selection Lets defind feature sets, X:
X = Feature X[0:5]
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
What are our lables?
y = df['loan_status'].values y[0:5]
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Normalize Data Data Standardization give data zero mean and unit variance (technically should be done after train test split )
X= preprocessing.StandardScaler().fit(X).transform(X) X[0:5]
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Classification Now, it is your turn, use the training set to build an accurate model. Then use the test set to report the accuracy of the modelYou should use the following algorithm:- K Nearest Neighbor(KNN)- Decision Tree- Support Vector Machine- Logistic Regression__ Notice:__ - You can go above and change the pre-...
#Importing library for KNN from sklearn.neighbors import KNeighborsClassifier # Train Test Split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_tes...
The best accuracy was with 0.7857142857142857 with k= 7 Train set Accuracy: 0.7898550724637681 Test set Accuracy: 0.7571428571428571
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Decision Tree
#Import library of DecisionTreeClassifier from sklearn.tree import DecisionTreeClassifier #Modeling drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 5) drugTree # it shows the default parameters drugTree.fit(X_train,y_train) #Prediction predTree = drugTree.predict(X_test) print (predTree [0:10]) print...
['COLLECTION' 'COLLECTION' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'COLLECTION' 'COLLECTION' 'PAIDOFF' 'PAIDOFF'] ['PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF' 'PAIDOFF']
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Support Vector Machine
#Importing library for SVM from sklearn import svm #Modeling clf = svm.SVC(kernel='rbf') clf.fit(X_train, y_train) #Prediction yhat_SVM = clf.predict(X_test) yhat_SVM [0:5]
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Logistic Regression
#Importing library for Logistic Regression from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix #Modeling LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train) LR #Prediction yhat_L = LR.predict(X_test) yhat_prob = LR.predict_proba(X_test) yhat_prob
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Model Evaluation using Test set
from sklearn.metrics import jaccard_similarity_score from sklearn.metrics import f1_score from sklearn.metrics import log_loss
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
First, download and load the test set:
#!wget -O loan_test.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv url='https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv'
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
Load Test set for evaluation
test_df = pd.read_csv(url) test_df.head() #Test set for y y_for_test=test_df[['loan_status']] #Feature test_df['due_date'] = pd.to_datetime(test_df['due_date']) test_df['effective_date'] = pd.to_datetime(test_df['effective_date']) test_df['dayofweek'] = test_df['effective_date'].dt.dayofweek test_df['weekend'] = tes...
_____no_output_____
MIT
Course 8: Machine Learning with Python/The best classifier.ipynb
jonathanyeh0723/Coursera_IBM-Data-Science
ClusteringIn contrast to *supervised* machine learning, *unsupervised* learning is used when there is no "ground truth" from which to train and validate label predictions. The most common form of unsupervised learning is *clustering*, which is simllar conceptually to *classification*, except that the the training data...
import pandas as pd # load the training dataset data = pd.read_csv('data/seeds.csv') # Display a random sample of 10 observations (just the features) features = data[data.columns[0:6]] features.sample(10)
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
As you can see, the dataset contains six data points (or *features*) for each instance (*observation*) of a seed. So you could interpret these as coordinates that describe each instance's location in six-dimensional space.Now, of course six-dimensional space is difficult to visualise in a three-dimensional world, or on...
from sklearn.preprocessing import MinMaxScaler from sklearn.decomposition import PCA # Normalize the numeric features so they're on the same scale scaled_features = MinMaxScaler().fit_transform(features[data.columns[0:6]]) # Get two principal components pca = PCA(n_components = 2).fit(scaled_features) features_2d = p...
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
Now that we have the data points translated to two dimensions, we can visualize them in a plot:
import matplotlib.pyplot as plt %matplotlib inline plt.scatter(features_2d[:,0],features_2d[:,1]) plt.xlabel('Dimension 1') plt.ylabel('Dimension 2') plt.title('Data') plt.show()
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
Hopefully you can see at least two, arguably three, reasonably distinct groups of data points; but here lies one of the fundamental problems with clustering - without known class labels, how do you know how many clusters to separate your data into?One way we can try to find out is to use a data sample to create a serie...
#importing the libraries import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans %matplotlib inline # Create 10 models with 1 to 10 clusters wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i) # Fit the data points kmeans.fit(features.values) # kmeans.fit(scal...
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
The plot shows a large reduction in WCSS (so greater *tightness*) as the number of clusters increases from one to two, and a further noticable reduction from two to three clusters. After that, the reduction is less pronounced, resulting in an "elbow" in the chart at around three clusters. This is a good indication that...
from sklearn.cluster import KMeans # Create a model based on 3 centroids model = KMeans(n_clusters=3, init='k-means++', n_init=100, max_iter=1000) # Fit to the data and predict the cluster assignments for each data point km_clusters = model.fit_predict(features.values) # View the cluster assignments km_clusters
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
Let's see those cluster assignments with the two-dimensional data points.
def plot_clusters(samples, clusters): col_dic = {0:'blue',1:'green',2:'orange'} mrk_dic = {0:'*',1:'x',2:'+'} colors = [col_dic[x] for x in clusters] markers = [mrk_dic[x] for x in clusters] for sample in range(len(clusters)): plt.scatter(samples[sample][0], samples[sample][1], color = color...
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
Hopefully, the the data has been separated into three distinct clusters.So what's the practical use of clustering? In some cases, you may have data that you need to group into distict clusters without knowing how many clusters there are or what they indicate. For example a marketing organization might want to separate ...
seed_species = data[data.columns[7]] plot_clusters(features_2d, seed_species.values)
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
There may be some differences between the cluster assignments and class labels, but the K-Means model should have done a reasonable job of clustering the observations so that seeds of the same species are generally in the same cluster. Hierarchical ClusteringHierarchical clustering methods make fewer distributional as...
from sklearn.cluster import AgglomerativeClustering agg_model = AgglomerativeClustering(n_clusters=3) agg_clusters = agg_model.fit_predict(features.values) agg_clusters
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
So what do the agglomerative cluster assignments look like?
import matplotlib.pyplot as plt %matplotlib inline def plot_clusters(samples, clusters): col_dic = {0:'blue',1:'green',2:'orange'} mrk_dic = {0:'*',1:'x',2:'+'} colors = [col_dic[x] for x in clusters] markers = [mrk_dic[x] for x in clusters] for sample in range(len(clusters)): plt.scatter(...
_____no_output_____
MIT
04 - Clustering.ipynb
jschevers/ml-basics
These are a couple of functions I've always kept handy because I end up using them more often than I even expect. They both work off of an iterable, so I'll define one here to use as an example:
my_iter = [x for x in range(20)]
_____no_output_____
MIT
Notebooks/Batch Process and Sliding Windows.ipynb
agbs2k8/python_FAQ
Batch ProcessingThis is a function that will yield small subsets of an iterable and allow you to work with smaller parts at once. I've used this when I have too much data to process all of it at once, so I could process it in chuncks.
def batch(iterable, n: int = 1): """ Return a dataset in batches (no overlap) :param iterable: the item to be returned in segments :param n: length of the segments :return: generator of portions of the original data """ for ndx in range(0, len(iterable), n): yield iterable[ndx:max(nd...
[0, 1, 2] [3, 4, 5] [6, 7, 8] [9, 10, 11] [12, 13, 14] [15, 16, 17] [18, 19]
MIT
Notebooks/Batch Process and Sliding Windows.ipynb
agbs2k8/python_FAQ
You can see that it just split my iterable up into smaller parts. It still gave me back all of it, and did not repeat any portions. Sliding WindowDifferent from the batch, this gives me overlapping sections of the iterable. You define a window size, and it will give you back each window, in order of that size.
from itertools import islice def window(sequence, n: int = 5): """ Returns a sliding window of width n over the iterable sequence :param sequence: iterable to yield segments from :param n: number of items in the window :return: generator of windows """ _it = iter(sequence) result = tup...
(0, 1, 2, 3) (1, 2, 3, 4) (2, 3, 4, 5) (3, 4, 5, 6) (4, 5, 6, 7) (5, 6, 7, 8) (6, 7, 8, 9) (7, 8, 9, 10) (8, 9, 10, 11) (9, 10, 11, 12) (10, 11, 12, 13) (11, 12, 13, 14) (12, 13, 14, 15) (13, 14, 15, 16) (14, 15, 16, 17) (15, 16, 17, 18) (16, 17, 18, 19)
MIT
Notebooks/Batch Process and Sliding Windows.ipynb
agbs2k8/python_FAQ
QUBO and basic calculation Here we are going to check the way how to create QUBO matrix and solve it. First we prepare the wildqat sdk and create an instance.
import wildqat as wq a = wq.opt()
_____no_output_____
Apache-2.0
examples_en/tutorial001_qubo_en.ipynb
mori388/annealing
Next we make a matrix called QUBO like below.
a.qubo = [[4,-4,-4],[0,4,-4],[0,0,4]]
_____no_output_____
Apache-2.0
examples_en/tutorial001_qubo_en.ipynb
mori388/annealing
And then calculate with algorithm. This time we use SA algorithm to solve the matrix.
a.sa()
1.412949800491333
Apache-2.0
examples_en/tutorial001_qubo_en.ipynb
mori388/annealing
And we got the result. Upper value show the time to aquire the result. The array is the list of result of the bit. The QUBO matrix once converted to Ising Model so called Jij matrix. If we want to check it we can easily aquire is by printing a.J
print(a.J)
[[0, -1, -1], [0, 0, -1], [0, 0, 0]]
Apache-2.0
examples_en/tutorial001_qubo_en.ipynb
mori388/annealing
Component GraphsEvalML component graphs represent and describe the flow of data in a collection of related components. A component graph is comprised of nodes representing components, and edges between pairs of nodes representing where the inputs and outputs of each component should go. It is the backbone of the featu...
from evalml.pipelines import ComponentGraph component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'OHE': ['One Hot Encoder', 'X', 'y'], 'RF Classifier': ['Random Forest Classifier', 'My Imputer.x', 'OHE.x', 'y'] # takes in multiple feature inputs } cg_simple = ComponentGraph(component_dict)
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
All component graphs must end with one final or terminus node. This can either be a transformer or an estimator. Below, the component graph is invalid because has two terminus nodes: the "RF Classifier" and the "EN Classifier".
# Can't instantiate a component graph with more than one terminus node (here: RF Classifier, EN Classifier) component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'RF Classifier': ['Random Forest Classifier', 'My Imputer.x', 'y'], 'EN Classifier': ['Elastic Net Classifier', 'My Imputer.x', 'y'] }
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
Once we have defined a component graph, we can instantiate the graph with specific parameter values for each component using `.instantiate(parameters)`. All components in a component graph must be instantiated before fitting, transforming, or predicting.Below, we instantiate our graph and set the value of our Imputer's...
cg_simple.instantiate({'My Imputer': {'numeric_impute_strategy': 'most_frequent'}})
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
Components in the Component GraphYou can use `.get_component(name)` and provide the unique component name to access any component in the component graph. Below, we can grab our Imputer component and confirm that `numeric_impute_strategy` has indeed been set to "most_frequent".
cg_simple.get_component('My Imputer')
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
You can also `.get_inputs(name)` and provide the unique component name to to retrieve all inputs for that component.Below, we can grab our 'RF Classifier' component and confirm that we use `"My Imputer.x"` as our features input and `"y"` as target input.
cg_simple.get_inputs('RF Classifier')
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
Component Graph Computation OrderUpon initalization, each component graph will generate a topological order. We can access this generated order by calling the `.compute_order` attribute. This attribute is used to determine the order that components should be evaluated during calls to `fit` and `transform`.
cg_simple.compute_order
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
Visualizing Component Graphs We can get more information about an instantiated component graph by calling `.describe()`. This method will pretty-print each of the components in the graph and its parameters.
# Using a more involved component graph with more complex edges component_dict = { "Imputer": ["Imputer", "X", "y"], "Target Imputer": ["Target Imputer", "X", "y"], "OneHot_RandomForest": ["One Hot Encoder", "Imputer.x", "Target Imputer.y"], "OneHot_ElasticNet": ["One Hot Encoder", "Impu...
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
We can also visualize a component graph by calling `.graph()`.
cg_with_estimators.graph()
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
Component graph methodsSimilar to the pipeline structure, we can call `fit`, `transform` or `predict`. We can also call `fit_features` which will fit all but the final component and `compute_final_component_features` which will transform all but the final component. These two methods may be useful in cases where you w...
from evalml.demos import load_breast_cancer X, y = load_breast_cancer() component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'OHE': ['One Hot Encoder', 'My Imputer.x', 'y'] } cg_with_final_transformer = ComponentGraph(component_dict) cg_with_final_transformer.instantiate({}) cg_with_final_transformer.fit(X,...
_____no_output_____
BSD-3-Clause
docs/source/user_guide/component_graphs.ipynb
peterataylor/evalml
![alt text](https://github.com/callysto/callysto-sample-notebooks/blob/master/notebooks/images/Callysto_Notebook-Banner_Top_06.06.18.jpg?raw=true) Basics of PythonThis notebook will provide basics of python and introduction to DataFrames.To enter code in Colab we are going to use **Code Cells**. Click on `+Code` in t...
# Anything in a code cell after a pound sign is a comment! # You can type anything here and it will not be excecuted # Variables are defined with an equals sign (=) my_variable = 10 # You cannot put spaces in variable names. other_variable = "some text" # variables need not be numbers! # Print will ou...
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
--- Exercise 11. In the cell below, assign variable **z** to your name and run the cell. 2. In the cell below, write a comment on the same line where you define z. Run the cell to make sure the comment is not changing anything.---
## Enter your code in the line below z = "your name here" ## print(z, "is loving Python!")
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Basics of DataFrames and pandas **DataFrame** - two-dimentional data structure, similar to a table or a spreadsheet.In Python there is a library of pre-defined functions to work with DataFrames - **pandas**.
#load "pandas" library under short name "pd" import pandas as pd
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
To read file in csv format the **read_csv()** function is used, it can read a file or a file from a URL.
#we have csv file stored in the cloud - it is 10 rows of data related to Titanic url = "https://swift-yeg.cloud.cybera.ca:8080/v1/AUTH_d22d1e3f28be45209ba8f660295c84cf/hackaton/titanic_short.csv" #read csv file from url and save it as dataframe titanic = pd.read_csv(url) #shape shows number of rows and number of colum...
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Basic operations with DataFrames Select rows/colums by name and index
#Getting column names titanic.columns #Selecting one column titanic[['survived']] #Selecting multiple columns titanic[['survived','age']] #Selecting first 5 rows #try changin to head(10) or head(2) titanic.head() #Getting index (row names) - note that row names start at 0 titanic.index.tolist() #Selecting one row ti...
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
--- Exercise 21. In the cell below, uncomment the code2. Change "column1", "column2", and "column3" to "fare", "age", and "class" to get these 3 columns---
#titanic[["column1","column2","column3"]]
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Add a new column using existing one
#creating new column - age in months by multiplying "age" column by 12 titanic['age_months'] = titanic['age']*12 #look at the very last column 'age_months' titanic
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Select specific colums by condition
#create a condition: for example sex equals female condition = titanic['sex']=="female" #note == sign checks rather than assigns condition #it shows True for rows where sex is equal to female #select only rows where condition is True (all female) titanic[condition] #other examples of conditions: #Not equal condition1...
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
--- Exercise 31. Change the cell below to subset data where sex is "female" and embark_town is "Cherbourg"---
condition5 = (titanic['sex']=="female") | (titanic['class']=="First") #change the condition here titanic[condition5]
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Sorting
#sorting by pclass - note the ascending paramater, try changing it to False titanic.sort_values("pclass", ascending=True) #sort by two columns - first by pclass and then by age titanic.sort_values(["pclass","age"])
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Grouping and calculating summaries on groups
#split data into groups based on all unique values in "survived" column - #first group is survived(1), second groups is not survived(0) #calculate average(mean) for every column for both groups titanic.groupby("survived").mean() #another operations you can do on groups are # min(), max(), sum() #you can do multiple...
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
--- Exercise 41. Modify the cell below to calculate **max()** for every column grouped by "class"---
titanic.groupby("survived").mean() ##modify this cell
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Calculating number of rows by group
#using size() function to calculate number of rows by group row_counts = titanic.groupby("sex").size() #create new column "count" - to store row numbers row_counts = row_counts.reset_index(name="count") row_counts
_____no_output_____
CC-BY-4.0
Prep_materials/Python and pandas basics solutions.ipynb
lgfunderburk/hackathon
Univariate Process Kalman Filtering ExampleIn this Jypyter notebook we implement the example given on pages 11-15 of [An Introduction to the Kalman Filter](http://www.cs.unc.edu/~welch/kalman/kalmanIntro.html) by Greg Welch and Gary Bishop. It is written in the spirit of Andrew Straw's [SciPy cookbook](http://scipy-co...
import os, sys sys.path.append(os.path.abspath('../../main/python')) import numpy as np import matplotlib.pyplot as plt from thalesians.tsa.distrs import NormalDistr as N import thalesians.tsa.filtering as filtering import thalesians.tsa.filtering.kalman as kalman import thalesians.tsa.processes as proc import thalesi...
_____no_output_____
BSD-3-Clause
tsa/src/jupyter/python/welchbishopkalmanfilteringtutorial.ipynb
mikimaus78/ml_monorepo
- Combine all data
import pandas as pd from os import listdir path = '../data/' files = listdir('../data/') df = pd.DataFrame(columns=["url", "query", "text"]) for f in files: temp = pd.read_csv(path + f) if 'article-name' in temp.columns: temp.rename(columns={'article-name':'name','article-url':'url','content':'text','...
_____no_output_____
MIT
doc2vec/Word2Vec to cyber security data.ipynb
sagar1993/NLP_cyber_security
- data preprocessing 1. stop word removal 2. lower case letters 3. non ascii character removal
from nltk.corpus import stopwords import re stop = stopwords.words('english') def normalize_text(text): norm_text = text.lower() # Replace breaks with spaces norm_text = norm_text.replace('<br />', ' ') # Pad punctuation with spaces on both sides norm_text = re.sub(r"([\.\",\(\)!\?;:])", " \\1 ", n...
_____no_output_____
MIT
doc2vec/Word2Vec to cyber security data.ipynb
sagar1993/NLP_cyber_security
- a simple word2vec model In this section we apply simple word to vec model to tokenized data.
from gensim.models import Word2Vec from nltk import word_tokenize df['tokenized_text'] = df.apply(lambda row: word_tokenize(row['text']), axis=1) model = Word2Vec(df['tokenized_text'], size=100) for num in [1, 3, 5, 10, 12, 16, 17, 18, 19, 28, 29, 30, 32, 33, 34, 37, 38]: term = "apt%s"%str(num) if term in mode...
Most similar words for apt1 ('mandiant', 0.9992831349372864) ('according', 0.9988211989402771) ('china', 0.9986724257469177) ('defense', 0.9986507892608643) ('kaspersky', 0.9986412525177002) ('iranian', 0.9985784888267517) ('military', 0.9983772039413452) ('lab', 0.9978839159011841) ('detected', 0.997614860534668) ('pu...
MIT
doc2vec/Word2Vec to cyber security data.ipynb
sagar1993/NLP_cyber_security
here we got one interesting result for apt17 as apt28 but for all other word2vec results we observe that we are getting names like malware, attackers, groups, backdoor in the most similar items. It might be the case that the names of attacker groups are ommited because they are phrases instead simple words. -...
from gensim.models import Phrases from collections import Counter bigram = Phrases() bigram.add_vocab(df['tokenized_text']) bigram_counter = Counter() for key in bigram.vocab.keys(): if len(key.split("_")) > 1: bigram_counter[key] += bigram.vocab[key] for key, counts in bigram_counter.most_common(20): ...
Most similar words for apt1 (u'different', 0.99991774559021) (u'likely', 0.9999154806137085) (u'well', 0.9999152421951294) (u'says', 0.9999047517776489) (u'multiple', 0.9999043941497803) (u'threat_actors', 0.9998949766159058) (u'network', 0.9998934268951416) (u'according', 0.9998912811279297) (u'compromised', 0.9998894...
MIT
doc2vec/Word2Vec to cyber security data.ipynb
sagar1993/NLP_cyber_security
After applying bigram phrases still we cannot see the desired results. Word2Vec model topic by topic using bigram phrases
df_doc = df[['query', 'text']] df_doc df_doc = df_doc.groupby(['query'],as_index=False).first() df_doc from nltk.corpus import stopwords import re stop = stopwords.words('english') + ['fireeye', 'crowdstrike', 'symantec', 'rapid7', 'securityweek', 'kaspersky'] def normalize_text(text): norm_text = text.lower() ...
_____no_output_____
MIT
doc2vec/Word2Vec to cyber security data.ipynb
sagar1993/NLP_cyber_security
Logistic Regression Project In this project we will be working with a fake advertising data set, indicating whether or not a particular internet user clicked on an Advertisement. We will try to create a model that will predict whether or not they will click on an ad based off the features of that user.This data set co...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import warnings warnings.filterwarnings("ignore")
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Get the Data**Read in the advertising.csv file and set it to a data frame called ad_data.**
ad_data = pd.read_csv("advertising.csv")
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
**Check the head of ad_data**
ad_data.head()
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
** Use info and describe() on ad_data**
ad_data.info() ad_data.describe()
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Exploratory Data AnalysisLet's use seaborn to explore the data!Try recreating the plots shown below!** Create a histogram of the Age**
sns.set_style('whitegrid') ad_data['Age'].hist(bins=30) plt.xlabel("Age")
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
**Create a jointplot showing Area Income versus Age.**
sns.jointplot(x='Age',y='Area Income',data=ad_data)
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
**Create a jointplot showing the kde distributions of Daily Time spent on site vs. Age.**
sns.jointplot(x='Age',y='Daily Time Spent on Site',data=ad_data,color='red',kind='kde')
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
** Create a jointplot of 'Daily Time Spent on Site' vs. 'Daily Internet Usage'**
sns.jointplot(x="Daily Time Spent on Site",y="Daily Internet Usage",data=ad_data,color='green')
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
** Finally, create a pairplot with the hue defined by the 'Clicked on Ad' column feature.**
sns.pairplot(ad_data,hue='Clicked on Ad',palette='bwr')
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Logistic RegressionNow it's time to do a train test split, and train our model!You'll have the freedom here to choose columns that you want to train on! ** Split the data into training set and testing set using train_test_split**
from sklearn.model_selection import train_test_split X = ad_data[['Daily Time Spent on Site', 'Age', 'Area Income','Daily Internet Usage', 'Male']] y = ad_data['Clicked on Ad'] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33,random_state = 42)
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
** Train and fit a logistic regression model on the training set.**
from sklearn.linear_model import LogisticRegression logmodel = LogisticRegression() logmodel.fit(X_train,y_train)
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Predictions and Evaluations** Now predict values for the testing data.**
predictions = logmodel.predict(X_test)
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
** Create a classification report for the model.**
from sklearn.metrics import classification_report print(classification_report(y_test,predictions)) from sklearn.metrics import confusion_matrix confusion_matrix(y_test,predictions)
_____no_output_____
MIT
Logistic Regression/17.4 Logistic Regression Project.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Forecasting - Facebook Prophet
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline mpl.rcParams['figure.figsize'] = (16, 10) pd.set_option('display.max_rows', 500) import plotly.graph_objects as go #from fbprophet import Prophet %matplotlib inline plt.style.use('fivethirtyeight') #def ...
_____no_output_____
MIT
notebooks/Modelling_Forecast.ipynb
MayuriKalokhe/Data_Science_Covid-19
Trivial Forecast (rolling mean)
df = pd.DataFrame({'X': np.arange(0,10)}) # generate an input df df['y']=df.rolling(3).mean() df #trying over small data set first df_new = pd.read_csv('../data/processed/COVID_small_flat_table.csv',sep=';') df=df_new[['date','India']] df=df.rename(columns={'date': 'ds', 'India': 'y'}) ax = df.s...
_____no_output_____
MIT
notebooks/Modelling_Forecast.ipynb
MayuriKalokhe/Data_Science_Covid-19
Cross Validation
from fbprophet.diagnostics import cross_validation df_cv = cross_validation(my_model, initial='40 days', # we take the first 40 days for training period='1 days', # every days a new prediction run horizon = '7 days') #we predict 7days into th...
_____no_output_____
MIT
notebooks/Modelling_Forecast.ipynb
MayuriKalokhe/Data_Science_Covid-19
Diagonalplot
## to understand comparison/under and over estimation wrt. actual values horizon='7 days' df_cv['horizon']=df_cv.ds-df_cv.cutoff date_vec=df_cv[df_cv['horizon']==horizon]['ds'] y_hat=df_cv[df_cv['horizon']==horizon]['yhat'] y=df_cv[df_cv['horizon']==horizon]['y'] df_cv_7=df_cv[df_cv['horizon']==horizon] df_cv_7.tail()...
_____no_output_____
MIT
notebooks/Modelling_Forecast.ipynb
MayuriKalokhe/Data_Science_Covid-19
Trivial Forecast
def mean_absolute_percentage_error(y_true, y_pred): ''' MAPE calculation ''' y_true, y_pred = np.array(y_true), np.array(y_pred) return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 parse_dates=['date'] df_all = pd.read_csv('../data/processed/COVID_small_flat_table.csv',sep=';',parse_dates=parse_dates)...
MAPE: 134.06143093647987
MIT
notebooks/Modelling_Forecast.ipynb
MayuriKalokhe/Data_Science_Covid-19
Causes of Death in the United States (2011)To visualize the causes of death in the United States, we look at data from the [Centers for Disease Control](http://www.cdc.gov/).To get the most recent information, we start with [data from 2015 (PDF)](http://www.cdc.gov/nchs/data/hus/hus15.pdf019). Table 7 inclues data on ...
%matplotlib inline import pandas as pd from altair import * df = pd.read_excel('2011_causes_of_death.xlsx') df.head() df = df.ix[1:] df.plot(kind="bar",x=df["Cause"], title="United SttCauses of Death", legend=False) c = Chart(df).mark_bar().encode( x=X('Number:Q',axis=Axis(ti...
_____no_output_____
MIT
us-deaths.ipynb
mkudija/US-Causes-of-Death
Monte Carlo MethodsIn this notebook, you will write your own implementations of many Monte Carlo (MC) algorithms. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. Part 0: Explore BlackjackEnvWe begin by importing the necessary packages.
import sys import gym import numpy as np from collections import defaultdict from plot_utils import plot_blackjack_values, plot_policy
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Use the code cell below to create an instance of the [Blackjack](https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py) environment.
env = gym.make('Blackjack-v0')
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Each state is a 3-tuple of:- the player's current sum $\in \{0, 1, \ldots, 31\}$,- the dealer's face up card $\in \{1, \ldots, 10\}$, and- whether or not the player has a usable ace (`no` $=0$, `yes` $=1$).The agent has two potential actions:``` STICK = 0 HIT = 1```Verify this by running the code cell below.
print(env.observation_space) print(env.action_space)
Tuple(Discrete(32), Discrete(11), Discrete(2)) Discrete(2)
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Execute the code cell below to play Blackjack with a random policy. (_The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to get some experience with the output that is returned as the agent interacts with the environment._)
for i_episode in range(3): state = env.reset() while True: print(state) action = env.action_space.sample() state, reward, done, info = env.step(action) if done: print('End game! Reward: ', reward) print('You won :)\n') if reward > 0 else print('You lost :(...
(17, 2, False) End game! Reward: -1 You lost :( (20, 5, False) End game! Reward: -1 You lost :( (20, 7, False) End game! Reward: 1.0 You won :)
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Part 1: MC PredictionIn this section, you will write your own implementation of MC prediction (for estimating the action-value function). We will begin by investigating a policy where the player _almost_ always sticks if the sum of her cards exceeds 18. In particular, she selects action `STICK` with 80% probability ...
def generate_episode_from_limit_stochastic(bj_env): episode = [] state = bj_env.reset() while True: probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8] action = np.random.choice(np.arange(2), p=probs) next_state, reward, done, info = bj_env.step(action) episode.append((state,...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Execute the code cell below to play Blackjack with the policy. (*The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to gain some familiarity with the output of the `generate_episode_from_limit_stochastic` function.*)
for i in range(3): print(generate_episode_from_limit_stochastic(env))
[((17, 2, True), 0, 1.0)] [((17, 5, False), 1, 0), ((18, 5, False), 1, 0), ((20, 5, False), 1, -1)] [((10, 9, False), 0, -1.0)]
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Now, you are ready to write your own implementation of MC prediction. Feel free to implement either first-visit or every-visit MC prediction; in the case of the Blackjack environment, the techniques are equivalent.Your algorithm has three arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episo...
def mc_prediction_q(env, num_episodes, generate_episode, gamma=1.0): # initialize empty dictionaries of arrays returns_sum = defaultdict(lambda: np.zeros(env.action_space.n)) N = defaultdict(lambda: np.zeros(env.action_space.n)) Q = defaultdict(lambda: np.zeros(env.action_space.n)) # loop over episo...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Use the cell below to obtain the action-value function estimate $Q$. We have also plotted the corresponding state-value function.To check the accuracy of your implementation, compare the plot below to the corresponding plot in the solutions notebook **Monte_Carlo_Solution.ipynb**.
# obtain the action-value function Q = mc_prediction_q(env, 500000, generate_episode_from_limit_stochastic) # obtain the corresponding state-value function V_to_plot = dict((k,(k[0]>18)*(np.dot([0.8, 0.2],v)) + (k[0]<=18)*(np.dot([0.2, 0.8],v))) \ for k, v in Q.items()) # plot the state-value function plot_b...
Episode 500000/500000.
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Part 2: MC ControlIn this section, you will write your own implementation of constant-$\alpha$ MC control. Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`: Th...
def epsilon_soft_policy(Qs, epsilon, nA): policy = np.ones(nA)*epsilon/nA Q_arg_max = np.argmax(Qs) policy[Q_arg_max] = 1 - epsilon + epsilon/nA return policy def generate_episode_with_Q(env, Q, epsilon, nA): episode = [] state = env.reset() while True: probs = epsilon_soft_policy(Q...
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Use the cell below to obtain the estimated optimal policy and action-value function. Note that you should fill in your own values for the `num_episodes` and `alpha` parameters.
# obtain the estimated optimal policy and action-value function policy, Q = mc_control(env, 500000, 1/50)
Episode 500000/500000.
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Next, we plot the corresponding state-value function.
# obtain the corresponding state-value function V = dict((k,np.max(v)) for k, v in Q.items()) # plot the state-value function plot_blackjack_values(V)
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Finally, we visualize the policy that is estimated to be optimal.
# plot the policy plot_policy(policy)
_____no_output_____
MIT
monte-carlo/Monte_Carlo.ipynb
dmitrylosev/deep-reinforcement-learning
Figure 4 - Effective variablesCreate the figure panels describing the model's effective variables dependencies on US frequency, US amplitude and sonophore radius. Imports
import os import matplotlib.pyplot as plt from PySONIC.plt import plotEffectiveVariables from PySONIC.utils import logger from PySONIC.neurons import getPointNeuron from utils import saveFigsAsPDF
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Plot parameters
figindex = 4 fs = 12 lw = 2 ps = 15 figs = {}
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Simulation parameters
pneuron = getPointNeuron('RS') a = 32e-9 # m Fdrive = 500e3 # Hz Adrive = 50e3 # Pa
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Panel A: dependence on acoustic amplitude
fig = plotEffectiveVariables(pneuron, a=a, f=Fdrive, cmap='Oranges', zscale='log') figs['a'] = fig
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Panel B: dependence on US frequency
fig = plotEffectiveVariables(pneuron, a=a, A=Adrive, cmap='Greens', zscale='log') figs['b'] = fig
28/04/2020 22:17:14: Rounding f value (4000000.000000001) to interval upper bound (4000000.0)
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Panel C: dependence on sonophore radius
fig = plotEffectiveVariables(pneuron, f=Fdrive, A=Adrive, cmap='Blues', zscale='log') figs['c'] = fig
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Save figure panelsSave figure panels as **pdf** in the *figs* sub-folder:
saveFigsAsPDF(figs, figindex)
_____no_output_____
MIT
figure_04.ipynb
tjjlemaire/JNE1685
Thresh - Binary
res , thresh = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV) plt.imshow(thresh)
_____no_output_____
MIT
Notebooks/.ipynb_checkpoints/Character Segmentation Model -checkpoint.ipynb
swapnilmarathe007/Handwriting-Recognition